query
stringlengths
7
9.55k
document
stringlengths
10
363k
metadata
dict
negatives
listlengths
0
101
negative_scores
listlengths
0
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
GET /projects GET /projects.json
def index q_param = params[:q] page = params[:page] per_page = params[:per_page] || 100 @q = Account.ransack q_param @accounts = @q.result.page(page).per(per_page) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def listprojects\n get('listprojects.json')['projects']\n end", "def list\n get 'projects'\n end", "def projects\n request(method: 'getAllProjects')\n end", "def projects\n resource 'projects'\n end", "def projects(params = {})\n make_get_request('/account/projects', params)\n end", "def projects\n Sifter.\n get(\"/api/projects\").\n parsed_response[\"projects\"].\n map { |p| Sifter::Project.new(p) }\n end", "def index\n @projects = Project.all\n render json: @projects\n end", "def index\n # @projects = @current_user.projects\n @projects = Project.all\n json_response(@projects)\n end", "def index\n @projects = Project.all\n render json: @projects, status: :ok\n end", "def get_projects\n me = request('/services/v5/me')\n me['projects']\n end", "def index\n @projects = current_user.projects\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def get\n CircleCi.request(conf, '/projects').get\n end", "def projects\n return forbidden unless current_account # already returns a 401 if credentials aren't supplied\n opts = { :include_document_ids => params[:include_document_ids] != 'false' }\n @response = {'projects' => Project.accessible(current_account).map {|p| p.canonical(opts) } }\n render_cross_origin_json\n end", "def projects\n records \"project\", \"/project/list\"\n end", "def index\n @projects = current_user.projects.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def index\n @projects = Project.all\n render json: @projects, layout: false\n end", "def projects(params = {})\n fetch_all('projects', 'projects', params)\n end", "def index\n @projects = Project.all_for_user(current_user.id)\n render json: @projects.to_json(include: :project_detail), status: 200\n end", "def index\n @projects = Project.visible\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def index\n @user = User.find_by(id: params[:user_id])\n @project = @user.projects\n if @project \n render :json => @project\n else\n render :json => 422\n end\n end", "def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @projects }\n end\n end", "def all_projects()\n @endpoint = \"/projects.json?limit=100\"\n setup_get\n res = @http.request(@req)\n return JSON.load(res.body)[\"projects\"].sort_by { |proj| proj[\"name\"] }\n end", "def index\n \n @workspaces = current_user.workspaces\n # debugger\n @projects = Project.where(:workspace_id => @workspace)\n\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def projects(options = {})\n get(\"projects\", options).projects\n end", "def list_projects\n handle_action_exceptions(__method__) do\n cmd_line = ['listprojects']\n cmd_line << 'json' if @json\n\n handle_return(@toolshck_ether.cmd(cmd_line.join(' ')))\n end\n end", "def index\n @projects = Project.includes(:user).all\n respond_with(@projects) do |format|\n format.json { render :json => {:list => @projects.as_json, :current_user => current_user.as_json} }\n format.html\n end\n end", "def projects(req_params = {})\n name = 'Projects'\n params = { req: req_params }\n\n data = endpoint(name: name, params: params).do_get\n\n collection name, data\n end", "def index \n\n @projects = Project.all\n respond_to do |format|\n format.html {render :template => \"projects/index\"}\n format.json { render json: @projects }\n end\n end", "def index\n @projects = Project.with_permissions_to(:read)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def projects\n @projects ||= Harvest::API::Projects.new(credentials)\n end", "def show\n @project = @client.projects.find(params[:id])\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end", "def index\n @projects = Project.where user: current_user\n render json: @projects, each_serializer: Projects::IndexSerializer\n end", "def index\n @projects = Project.order_by_company_and_project.paginate(page: params[:page] || 1, per_page: helpers.pager_per_page)\n respond_to do |format|\n message = @projects.present? ? \"\" : \"There are no projects available at this time\"\n format.json do\n status = @projects.present? ? :ok : :not_found\n render json: { response: @projects, status: status, message: message }\n end\n format.html do\n # Only authorize html format, json is okay because we use it as\n # an api.\n authorize(:project)\n flash[:alert] = message unless message.blank?\n @projects\n end\n end\n end", "def index\n if signed_in?\n @projects = current_user.projects\n respond_to do |format|\n format.html { render 'projects/index' }\n format.json { render template: 'projects/index.json.jbuilder' }\n end\n else\n redirect_to :projects\n end\n end", "def get_projects_of_user\n respond_to do |format|\n format.json {\n #param = params[:payload]\n #@user = User.find_by_id(param[:id])\n @projects = Project.where(:user_id => @current_user.id)\n if @projects\n render :json => @projects\n else\n render :nothing => true, :status => 200, :content_type => 'text/html'\n end\n }\n end\n end", "def get_projects_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ProjectsApi.get_projects ...'\n end\n # resource path\n local_var_path = '/projects'\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 = nil\n auth_names = ['Token']\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 => 'Projects')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ProjectsApi#get_projects\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def show_all_projects\r\n json = GoodData.get GoodData.profile.projects\r\n puts \"You have this project available:\"\r\n json[\"projects\"].map do |project|\r\n pid = project[\"project\"][\"links\"][\"roles\"].to_s\r\n puts \"Project name: #{project[\"project\"][\"meta\"][\"title\"].bright} Project PID: #{pid.match(\"[^\\/]{32}\").to_s.bright}\"\r\n end\r\n end", "def init_projects\n @projects = []\n\n response = @conn.get do |req|\n req.url \"/api/v1/projects\"\n req.headers = rest_headers\n end\n\n @projects = json(response.body)[:projects]\n end", "def projects\n @projects ||= begin\n http = Net::HTTP.new(API_HOST, API_PORT)\n http.use_ssl = true\n http.ca_file = (Twigg.root + 'files' + 'github.pem').to_s\n http.verify_mode = OpenSSL::SSL::VERIFY_PEER\n uri = ORG_REPOS_ENDPOINT % Config.github.organization\n headers = { 'Authorization' => \"token #{Config.github.token}\" }\n\n [].tap do |names|\n begin # loop: page through project list\n request = Net::HTTP::Get.new(uri, headers)\n response = http.request(request)\n raise \"Bad response #{response.inspect}\" unless response.is_a?(Net::HTTPOK)\n names.concat JSON[response.body].map { |repo| repo['name'] }\n uri = parse_link(response['Link'])\n end until uri.nil?\n end\n end\n end", "def projects\n @projects = Project.order(created_at: :desc).page(@page).per(10)\n respond_to do |format|\n format.html\n format.js { render :projects}\n end\n end", "def list_project(optional={})\n\t\targs = self.class.new_params\n\t\targs[:method] = 'GET'\n\t\targs[:pattern] = '/projects'\n\t\targs[:query]['Action'] = 'ListProject'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\targs[:scheme] = 'http'\n\t\tif optional.key? :page\n\t\t\targs[:query]['Page'] = optional[:page]\n\t\tend\n\t\tif optional.key? :page_size\n\t\t\targs[:query]['PageSize'] = optional[:page_size]\n\t\tend\n\t\tif optional.key? :project_owner\n\t\t\targs[:query]['ProjectOwner'] = optional[:project_owner]\n\t\tend\n\t\tself.run(args)\n\tend", "def project(project_id, options={})\n response_body = nil\n begin\n response = connection.get do |req|\n req.url \"/api/v1/projects/#{project_id}\", options\n end\n response_body = response.body\n rescue MultiJson::DecodeError => e\n #p 'Unable to parse JSON.'\n end\n \n response_body\n end", "def index\n\t\tif present_user.role? 'admin'\n\t\t\t@projects = Project.all\n\t\telse\n\t\t\t@projects = present_user.projects\n\t\tend\n\t\tmake_breadcrumbs\n\n\t\trespond_to do |format|\n\t\t\tformat.html # index.html.erb\n\t\t\tformat.json { render json: @projects }\n\t\tend\n\tend", "def show\n @projects = find_projects\n end", "def index\n projects = current_user.admin_projects.paginate(:page => params[:page])\n render json: projects\n end", "def list\r\n @projects = Project.where(user:current_user).order(created_at: :desc).page(params[:page])\r\n respond_with(@projects)\r\n end", "def index\n @user = User.find_by_id(session[:userid])\n @projects = current_user_projects\n respond_to do |format|\n format.html # index.html.erb\n format.json\n end\n end", "def index\n @user = get_user\n @projects = Project.all\n # render :inline => @projects.to_json\n end", "def project\n request :project\n end", "def show\n\n render json: Project.all\n\n end", "def listProjects \n uri = URI(RUNDECKSERVER + ':' + RUNDECKPORT + '/api/1/projects')\n http = Net::HTTP.new(uri.host, uri.port)\n headers = {\n 'Content-Type'=> 'application/json',\n 'X-RunDeck-Auth-Token'=> API_KEY \n}\n r = http.get(uri.path, headers)\n return r.body.force_encoding(\"UTF-8\")\n\nend", "def available_projects_list\n uri = \"#{@api_url}?access_token=#{@access_token}\"\n get uri\n end", "def index\n @projects = current_user.active_projects.includes(:project_errors)\n @project_invitations = current_user.user_projects.pending\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def project(project_id, params = {})\n make_get_request(\"/projects/#{project_id}\", params)\n end", "def list_projects # :nologin:\n query = create_query(:Project, :all, :by => :title)\n show_selected_projects(query)\n end", "def index\n @projects = Project.includes(:participants).all\n\n render json: @projects, include: :participants, status: 200\n end", "def show\n render json: @project\n end", "def projects\n @projects\n end", "def index\n @projects = @projects.includes(:latest_iteration).where(:tenant_id => current_user.tenant).order(\"name\").page(params[:page]).per(DEFAULT_ROWS_PER_PAGE)\n\n respond_with @projects\n end", "def index\n @projects = Service::JIRA.projects\n respond_with(@projects) do |format|\n format.json { render json: @projects.to_a.sort_by(&:name).map(&:attrs).to_json }\n end\n end", "def projects\n Harvest::Resources::Project\n end", "def project(project_id, query_params = nil)\n get(\"/projects/#{project_id}\", query_params)\n end", "def get_projects_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: ProjectsApi#get_projects ...\"\n end\n \n # resource path\n path = \"/Projects\".sub('{format}','json')\n\n # query parameters\n query_params = {}\n query_params[:'brief'] = opts[:'brief'] if opts[:'brief']\n query_params[:'skip'] = opts[:'skip'] if opts[:'skip']\n query_params[:'top'] = opts[:'top'] if opts[:'top']\n query_params[:'count_total'] = opts[:'count_total'] if opts[:'count_total']\n\n # header parameters\n header_params = {}\n\n # HTTP header 'Accept' (if needed)\n _header_accept = ['application/json']\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']\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(: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<APIProject>')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ProjectsApi#get_projects\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def index\n @projects = @namespace.projects.all\n end", "def projects\n tmp = client.get @json['user']['links']['projects']\n tmp['projects'].map do |project_meta|\n project_uri = project_meta['project']['links']['self']\n project = client.get project_uri\n client.factory.create(GoodData::Project, project)\n end\n end", "def get_projects_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ProjectApi.get_projects ...'\n end\n # resource path\n local_var_path = '/v1/project'\n\n # query parameters\n query_params = opts[:query_params] || {}\n query_params[:'name'] = opts[:'name'] if !opts[:'name'].nil?\n query_params[:'excludeInactive'] = opts[:'exclude_inactive'] if !opts[:'exclude_inactive'].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[:body] \n\n # return_type\n return_type = opts[:return_type] || 'Array<Project>' \n\n # auth_names\n auth_names = opts[:auth_names] || ['X-Api-Key']\n\n new_options = opts.merge(\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ProjectApi#get_projects\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def index\n\t\t@projects = Project.all\n\tend", "def index\n #@projects = []\n if current_user\n #@projects = current_user.projects.where(\"memberships.status >= ?\", 1)\n end\n\n if params[:id]\n @project = Project.find(params[:id])\n authorize! :read, @project\n else\n @project = @projects.first\n end\n\n respond_to do |format|\n format.html # index.html.erb\n format.js { render :action => 'show'}\n format.json { render json: @projects }\n end\n end", "def index_participating\n projects = current_user.projects.paginate(:page => params[:page])\n render json: projects\n end", "def list_project(optional={})\n\t\targs = self.class.new_params\n\t\targs[:method] = 'GET'\n\t\targs[:query]['Action'] = 'ListProject'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\targs[:scheme] = 'http'\n\t\tif optional.key? :page\n\t\t\targs[:query]['Page'] = optional[:page]\n\t\tend\n\t\tif optional.key? :page_size\n\t\t\targs[:query]['PageSize'] = optional[:page_size]\n\t\tend\n\t\tif optional.key? :project_owner\n\t\t\targs[:query]['ProjectOwner'] = optional[:project_owner]\n\t\tend\n\t\tself.run(args)\n\tend", "def project\n return forbidden unless current_account and params[:id] and (request.format.json? || request.format.js? || request.format.text?)\n project = Project.accessible(current_account).find(params[:id].to_i)\n return not_found unless project\n opts = { :include_document_ids => params[:include_document_ids] != 'false' }\n @response = {'project' => project.canonical(opts)}\n render_cross_origin_json\n end", "def show \n project= Project.find(params[:id])\n\n render json: project\n end", "def list_projects(company_id: )\n url = \"#{@base_url}/vapid/projects?company_id=#{company_id}\"\n HTTParty.get(url, headers: procore_headers(token: @customer_info[:token], company_id: @customer_info[:company_id] )).parsed_response\n end", "def index\n @projects = current_user.projects\n end", "def index\n @projects = current_user.projects\n end", "def index\n @projects = current_user.projects\n end", "def index\n @projects = current_user.projects\n end", "def index\n @projects = current_user.projects\n end", "def index\n @projects = current_user.projects\n end", "def index\n @projects = current_user.projects\n end", "def index\n @projects = current_user.projects\n end", "def index\n @projects_people = ProjectsPerson.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects_people }\n end\n end", "def index\r\n @projects = current_user.projects\r\n end", "def projects\n PivotalTracker::Project.all\n end", "def show\n render json: Project.where(id: params.fetch(:id))\n end", "def get_projects\n @params=task_params\n @client=current_user.clients.find(@params[:client_id])\n counter=0\n @res=[]\n @client.projects.each do |c|\n if c.users.include? current_user\n @res[counter]={\n project_id: c.id, \n name: c.name\n }\n counter+=1\n end\n end\n respond_to do |format|\n format.json {render json: @res.uniq}\n end\n end", "def show\n @projects = Project.all\n end", "def projects\n @projects ||= begin\n user = api('user')\n api(\"users/#{user['id']}/projects\").sort_by { |p| p['id'] }\n end\nend", "def list_projects_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: QcApi.list_projects ...\"\n end\n # resource path\n local_var_path = \"/projects.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 # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['api_key']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'Array<Project>')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: QcApi#list_projects\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def getProjectID()\n result = RestClient.get GITHUB_API + PROJECTS_PATH, :accept => 'application/vnd.github.inertia-preview+json', :'Authorization' => 'token ' + CONFIG['OAUTH']\n result = JSON.parse(result) \n end", "def index\n @projects = Project.all\n end", "def index\n @projects = Project.all\n end", "def index\n @projects = Project.all\n end" ]
[ "0.8574897", "0.8386689", "0.8355737", "0.8062607", "0.80368364", "0.8002139", "0.78593457", "0.7834634", "0.78324", "0.7799698", "0.77792805", "0.7748103", "0.77139485", "0.7700251", "0.7696023", "0.7695487", "0.7695487", "0.7695487", "0.7695487", "0.7695487", "0.7695487", "0.7695487", "0.7695384", "0.7677249", "0.7659848", "0.76413786", "0.7627596", "0.76157665", "0.76007134", "0.75998086", "0.7599048", "0.755127", "0.75476474", "0.7504184", "0.7464399", "0.7463047", "0.74520797", "0.7440121", "0.74273944", "0.74115896", "0.74086154", "0.7406792", "0.73953074", "0.73152006", "0.72899425", "0.7288984", "0.727693", "0.72592014", "0.725888", "0.72443324", "0.72430474", "0.7232267", "0.7224122", "0.7218089", "0.7194763", "0.7187098", "0.71705997", "0.7170378", "0.7167435", "0.7164896", "0.71607876", "0.7140332", "0.7130536", "0.7128779", "0.7127035", "0.7124004", "0.7118136", "0.711526", "0.7114364", "0.71083033", "0.71005213", "0.7098299", "0.70919305", "0.70723647", "0.70523155", "0.70496404", "0.70492387", "0.7042553", "0.70393467", "0.7036608", "0.7033363", "0.7031996", "0.7031996", "0.7031996", "0.7031996", "0.7031996", "0.7031996", "0.7031996", "0.7031996", "0.70277584", "0.7026879", "0.7022911", "0.70143616", "0.70081574", "0.70047146", "0.70036596", "0.7003546", "0.7002825", "0.69961166", "0.69961166", "0.69961166" ]
0.0
-1
GET /projects/1 GET /projects/1.json
def show end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def list\n get 'projects'\n end", "def listprojects\n get('listprojects.json')['projects']\n end", "def show\n @project = @client.projects.find(params[:id])\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end", "def projects\n resource 'projects'\n end", "def index\n @projects = Project.all\n render json: @projects, status: :ok\n end", "def index\n @projects = Project.all\n render json: @projects\n end", "def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def index\n @user = User.find_by(id: params[:user_id])\n @project = @user.projects\n if @project \n render :json => @project\n else\n render :json => 422\n end\n end", "def projects\n request(method: 'getAllProjects')\n end", "def project(project_id, params = {})\n make_get_request(\"/projects/#{project_id}\", params)\n end", "def index\n @projects = Project.visible\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def index\n @projects = Project.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @projects }\n end\n end", "def show\n render json: Project.where(id: params.fetch(:id))\n end", "def show \n project= Project.find(params[:id])\n\n render json: project\n end", "def index\n @projects = Project.all_for_user(current_user.id)\n render json: @projects.to_json(include: :project_detail), status: 200\n end", "def project(project_id, options={})\n response_body = nil\n begin\n response = connection.get do |req|\n req.url \"/api/v1/projects/#{project_id}\", options\n end\n response_body = response.body\n rescue MultiJson::DecodeError => e\n #p 'Unable to parse JSON.'\n end\n \n response_body\n end", "def index\n @projects = current_user.projects\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end", "def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end", "def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end", "def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end", "def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end", "def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end", "def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end", "def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end", "def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end", "def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end", "def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end", "def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end", "def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end", "def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end", "def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end", "def project(project_id, query_params = nil)\n get(\"/projects/#{project_id}\", query_params)\n end", "def project(project_id)\n resource \"projects/#{project_id}\"\n end", "def index\n @projects = Project.all\n render json: @projects, layout: false\n end", "def getProjectID()\n result = RestClient.get GITHUB_API + PROJECTS_PATH, :accept => 'application/vnd.github.inertia-preview+json', :'Authorization' => 'token ' + CONFIG['OAUTH']\n result = JSON.parse(result) \n end", "def show\n @project = Project.find(params[:id])\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end", "def get\n CircleCi.request(conf, '/projects').get\n end", "def index\n # @projects = @current_user.projects\n @projects = Project.all\n json_response(@projects)\n end", "def projects\n records \"project\", \"/project/list\"\n end", "def projects\n Sifter.\n get(\"/api/projects\").\n parsed_response[\"projects\"].\n map { |p| Sifter::Project.new(p) }\n end", "def index \n\n @projects = Project.all\n respond_to do |format|\n format.html {render :template => \"projects/index\"}\n format.json { render json: @projects }\n end\n end", "def index\n @projects = current_user.projects.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def index\n \n @workspaces = current_user.workspaces\n # debugger\n @projects = Project.where(:workspace_id => @workspace)\n\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def show\n @project = Project.find(params[:id])\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @project }\n end\n end", "def show\n render json: @project\n end", "def show\n repo = ProjectRepo.new current_user\n @v_project = repo.get(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @v_project }\n end\n end", "def find_project(name)\n get(\"/projects/#{name}\")\n end", "def find_project(name)\n get(\"/projects/#{name}\")\n end", "def show\n @project = Project.find_by(id: params[:id])\n if @project\n render :json => @project\n else\n render :json => 422\n end\n end", "def projects(params = {})\n make_get_request('/account/projects', params)\n end", "def project\n request :project\n end", "def project\n return forbidden unless current_account and params[:id] and (request.format.json? || request.format.js? || request.format.text?)\n project = Project.accessible(current_account).find(params[:id].to_i)\n return not_found unless project\n opts = { :include_document_ids => params[:include_document_ids] != 'false' }\n @response = {'project' => project.canonical(opts)}\n render_cross_origin_json\n end", "def show \n render :json => Project.find_by_id(params[:id])\n end", "def show\n @ourproject = Ourproject.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @ourproject }\n end\n end", "def get_project(project_id)\n http = Net::HTTP.new(@city_db_url, @port)\n http.read_timeout = 1000\n if @city_db_is_https\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n end\n\n request = Net::HTTP::Get.new(\"/projects/#{project_id}.json\")\n request.add_field('Content-Type', 'application/json')\n request.add_field('Accept', 'application/json')\n request.basic_auth(ENV['URBANOPT_USERNAME'], ENV['URBANOPT_PASSWORD'])\n\n response = http.request(request)\n if response.code != '200' # success\n @runner.registerError(\"Bad response #{response.code}\")\n @runner.registerError(response.body)\n @result = false\n return {}\n end\n\n result = JSON.parse(response.body, symbolize_names: true)\n return result\n end", "def index\n @projects = Project.with_permissions_to(:read)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end", "def show\n @projectresource = Projectresource.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @projectresource }\n end\n end", "def index\n @projects = Project.where user: current_user\n render json: @projects, each_serializer: Projects::IndexSerializer\n end", "def show \n respond_to do |format|\n format.json {\n\n @project = Project.find_by_id(params[:id])\n\n if @project\n render :json => @project\n else\n render :nothing => true, :status => 200, :content_type => 'text/html'\n end\n }\n end\n end", "def show\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end", "def show\n @current_project = CurrentProject.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @current_project }\n end\n end", "def show\n respond_with(@project) do |format|\n format.json { render json: @project.as_json }\n format.html\n end\n end", "def show\n @show_project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @show_project }\n end\n end", "def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end", "def show\n respond_with @project do |format|\n format.json do\n render json: @project.as_json.merge(\n commits_url: project_commits_url(@project, format: 'json'),\n commits: @project.commits.order('committed_at DESC').limit(10).map { |commit|\n commit.as_json.merge(\n percent_done: commit.fraction_done.nan? ? 0.0 : commit.fraction_done*100,\n translations_done: commit.translations_done,\n translations_total: commit.translations_total,\n strings_total: commit.strings_total,\n import_url: import_project_commit_url(@project, commit, format: 'json'),\n sync_url: sync_project_commit_url(@project, commit, format: 'json'),\n url: project_commit_url(@project, commit),\n status_url: project_commit_url(@project, commit),\n )\n }\n )\n end\n end\n end", "def show\n # turn ruby database into json\n # route to the project 3 page with this json\n # id = 1\n end", "def show\n\n render json: Project.all\n\n end", "def projects(params = {})\n fetch_all('projects', 'projects', params)\n end", "def index\n @about_projects = AboutProject.last(1)\n\n respond_to do |format|\n format.json {render json: @about_projects[0], :only => [:description]}\n end\n end", "def show\n set_surrogate_key_header \"api/platforms/#{@platform.id}/projects\"\n set_cache_control_headers 3600\n end", "def show\n @projects = find_projects\n end", "def get_project(optional={})\n\t\targs = self.class.new_params\n\t\targs[:method] = 'GET'\n\t\targs[:pattern] = '/projects/[ProjectName]'\n\t\targs[:query]['Action'] = 'GetProject'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\targs[:scheme] = 'http'\n\t\tif optional.key? :project_name\n\t\t\targs[:path]['ProjectName'] = optional[:project_name]\n\t\tend\n\t\tself.run(args)\n\tend", "def show_by_gitpath\n @project = Project.includes(:users).includes(:technos).find_by_gitpath(params[:gitpath])\n\n respond_to do |format|\n format.json { render json: @project, status: 200 }\n end\n end", "def project\n @client.project(:id => project_id)\n end", "def list_projects\n handle_action_exceptions(__method__) do\n cmd_line = ['listprojects']\n cmd_line << 'json' if @json\n\n handle_return(@toolshck_ether.cmd(cmd_line.join(' ')))\n end\n end", "def index\n #@projects = []\n if current_user\n #@projects = current_user.projects.where(\"memberships.status >= ?\", 1)\n end\n\n if params[:id]\n @project = Project.find(params[:id])\n authorize! :read, @project\n else\n @project = @projects.first\n end\n\n respond_to do |format|\n format.html # index.html.erb\n format.js { render :action => 'show'}\n format.json { render json: @projects }\n end\n end", "def projects\n return forbidden unless current_account # already returns a 401 if credentials aren't supplied\n opts = { :include_document_ids => params[:include_document_ids] != 'false' }\n @response = {'projects' => Project.accessible(current_account).map {|p| p.canonical(opts) } }\n render_cross_origin_json\n end", "def get_projects_of_user\n respond_to do |format|\n format.json {\n #param = params[:payload]\n #@user = User.find_by_id(param[:id])\n @projects = Project.where(:user_id => @current_user.id)\n if @projects\n render :json => @projects\n else\n render :nothing => true, :status => 200, :content_type => 'text/html'\n end\n }\n end\n end", "def get\n render json: Project.select(:id, \"name as label\")\n end", "def index\n @projects = Project.includes(:user).all\n respond_with(@projects) do |format|\n format.json { render :json => {:list => @projects.as_json, :current_user => current_user.as_json} }\n format.html\n end\n end", "def details\n get(\"project/details\")[\"project\"]\n end", "def show\n @unfinished_project = UnfinishedProject.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @unfinished_project }\n end\n end", "def show\n @workspaces = current_user.workspaces\n @project = Project.find(params[:id])\n @workspace = Workspace.find(params[:workspace_id])\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end", "def index\n @user = User.find_by_id(session[:userid])\n @projects = current_user_projects\n respond_to do |format|\n format.html # index.html.erb\n format.json\n end\n end", "def get(project_name)\n response = get_request(\"/projects/#{project_name}/\")\n TheShiningSource::Project.new(response)\n end", "def show_project\r\n @project = Project.find(params[:id])\r\n @id = @project.id\r\n respond_to do |format|\r\n format.html { render 'project_control/view' }\r\n format.json { render json: @project }\r\n end\r\n end", "def getProject(project)\r\n\t\t\t\tproject_json = JSON.parse project\r\n\t\t\t\tproject_array = project_json[\"projects\"]\r\n\t\t\t\treturn jsonToProject(project_array[0])\r\n\t\t\tend", "def show\n @project = Project.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @projects }\n #format.json { render json: @project.as_json(:include => [:client, :project_participants] ) }\n end\n end", "def index\n if signed_in?\n @projects = current_user.projects\n respond_to do |format|\n format.html { render 'projects/index' }\n format.json { render template: 'projects/index.json.jbuilder' }\n end\n else\n redirect_to :projects\n end\n end", "def index\n @projects = @projects.includes(:latest_iteration).where(:tenant_id => current_user.tenant).order(\"name\").page(params[:page]).per(DEFAULT_ROWS_PER_PAGE)\n\n respond_with @projects\n end", "def show\n respond_to do |format|\n format.html {render :show}\n format.json {render json: @project}\n end\n end", "def show\n @project = Project.find(params[:id])\n\t@user = User.find(@project.user_id)\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @project }\n end\n end", "def find(project_id)\n raw_response = get_request(\"projects/#{project_id}\")\n parse_response(raw_response, :project)\n end" ]
[ "0.7868971", "0.76979554", "0.7680216", "0.7611453", "0.75334454", "0.75258976", "0.74926496", "0.74926496", "0.74926496", "0.74926496", "0.74926496", "0.74926496", "0.74926496", "0.74924207", "0.7484109", "0.7479275", "0.7444873", "0.74294627", "0.74224764", "0.7414947", "0.7385035", "0.7380203", "0.7379937", "0.7375317", "0.7361155", "0.7361155", "0.7361155", "0.7361155", "0.7361155", "0.7361155", "0.7361155", "0.7361155", "0.7361155", "0.7361155", "0.7361155", "0.7361155", "0.7361155", "0.7361155", "0.7361155", "0.73572785", "0.7352506", "0.73521084", "0.73436445", "0.73410857", "0.73250616", "0.7303016", "0.72884965", "0.72734356", "0.72727096", "0.72536707", "0.7251402", "0.72502863", "0.72433484", "0.7241812", "0.7228012", "0.7228012", "0.7213682", "0.7210143", "0.72031206", "0.71956533", "0.7184686", "0.71557546", "0.71509594", "0.71480834", "0.7120158", "0.71123755", "0.7106823", "0.70865124", "0.7084294", "0.7079523", "0.705198", "0.70506", "0.7044681", "0.70423746", "0.70259416", "0.70248544", "0.70047486", "0.70040953", "0.70025414", "0.7000689", "0.6987457", "0.6984701", "0.69802356", "0.6979858", "0.69780463", "0.69780076", "0.6970507", "0.6966368", "0.69646454", "0.69622666", "0.6961776", "0.6961545", "0.69614834", "0.69565344", "0.6943089", "0.6936655", "0.69335127", "0.69173217", "0.69125015", "0.6909762", "0.69050795" ]
0.0
-1
POST /projects POST /projects.json
def create end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.json { render :json => @project, :status => :created, :location => @project }\n format.html { redirect_to(projects_path) }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @project.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create_project(name)\n post('projects', {:name => name})[\"project\"]\n end", "def create\n @project = Project.new(project_params)\n\n if @project.save\n render json: @project, status: 200\n else\n render json: { errors: @project.errors.messages }, status: 200\n end\n end", "def create\n @project = Project.new(project_params)\n\n if @project.save\n render json: @project, status: :created\n else\n render json: @project.errors, status: :unprocessable_entity\n end\n end", "def create\n @urlroot = Designax::Application.config.urlroot\n if params[:pk] == \"new\" and params[:name] == \"project_name\"\n project_name = params[:value]\n @project = Project.new()\n @project.project_name = project_name\n else\n @project = Project.new(params[:project])\n end\n\n respond_to do |format|\n if @project.save\n redirect_url = @urlroot + \"/projects\"\n response_url = { \"url\" => redirect_url }\n format.json { render json: response_url, status: 200 }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(params[:project] || JSON.parse(request.body.read))\n\n if (params[:id])\n @project.id = params[:id]\n end\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to(@project, :notice => 'Project was successfully created.') }\n format.xml { render :xml => @project, :status => :created, :location => @project }\n format.json { render :json => @project }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @project.errors, :status => :unprocessable_entity }\n format.json { render :text => \"error creating project via http/json\" }\n end\n end\n end", "def test_should_create_project_via_API_JSON\r\n get \"/logout\"\r\n post \"/projects.json\", :api_key => 'testapikey',\r\n :project => {:user_id => 1,\r\n :url => 'http://www.apiproject.com',\r\n :name => 'API Project',\r\n :description => 'API Project Desc' }\r\n assert_response :created\r\n project = JSON.parse(response.body)\r\n check_new_project(project) \r\n end", "def create\n\t\t@project = current_user.projects.new(project_params)\n\n\t\trespond_to do |format|\n\t\t\tif @project.save\n\t\t\t\tformat.json { render :show, status: :created }\n\t\t\telse\n\t\t\t\tformat.json { render json: @project.errors, status: :unprocessable_entity }\n\t\t\tend\n\t\tend\n\tend", "def create\n @projects = current_user.projects\n @project = current_user.projects.new(project_params)\n\n respond_to do |format|\n if @projects << @project\n format.html { redirect_to user_projects_path(current_user), notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.json { render json: @project, status: :created, location: @project }\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n else\n format.json { render json: @project.errors, status: :unprocessable_entity }\n format.html { render action: \"new\" }\n end\n end\n end", "def create\n @project = current_user.projects.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create(attributes={})\n raw_response = post_request('projects', project: attributes)\n parse_response(raw_response, :project)\n end", "def create\n #byebug\n @project = Project.new(create_params)\n @project.user_id = @current_user.id\n @project.save\n #@project = Project.create(name_project: \"prueba\", subsidy: true, parking: true, user_id: @current_user.id)\n #byebug\n render json: @project, status: :created\n end", "def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to(@project, :notice => 'Project was successfully created.') }\n format.json { render :json => @project, :status => :created, :location => @project }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @project.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to projects_path, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n if @project.save\n render json: @project, status: :ok\n else\n render json: {error: @project.errors.full_messages.to_sentence } , status: :unprocessable_entity\n end\n end", "def create\n @user = current_user\n @project = @user.projects.build(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = current_user.projects.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html {redirect_to \"/projects\", notice: \"Project was successfully created.\"}\n format.json {render :show, status: :created, location: @project}\n else\n format.html {render :new, status: :unprocessable_entity}\n format.json {render json: @project.errors, status: :unprocessable_entity}\n end\n end\n end", "def create\n @project = current_user.projects.build(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: \"Project was successfully created.\" }\n User.find(current_user.id).projects << Project.find(@project.id)\n @projects_user = ProjectsUser.find_by(user_id: current_user.id, project_id: @project.id)\n format.json { render :show, status: :created, location: @project }\n\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: t('models.project.create') }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @api_project = Project.new(api_project_params)\n\n respond_to do |format|\n if @api_project.save\n format.html { redirect_to @api_project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @api_project }\n else\n format.html { render :new }\n format.json { render json: @api_project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to projects_path, notice: \"Project was successfully created.\" }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to projects_path, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = @client.projects.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @client, notice: 'Project was successfully created.' }\n else\n format.html { render action: \"new\" }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.json { render json: @project, status: 200 }\n else\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = current_user.projects.build(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to projects_path, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n @project.user_id = @user.id\n if @project.save\n render json: {status: :success, project: @project}\n else\n render json: {status: :failed, project: @project}\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to projects_path, notice: 'Project was successfully created.' }\n format.json { render action: 'show', status: :created, location: @project }\n else\n format.html { render action: 'new' }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n respond_to do |format|\n if project.save\n format.html { redirect_to project, notice: 'Project was successfully created.' }\n format.json { render json: project, status: ':created', location: project }\n else\n format.html { render action: 'new' }\n format.json { render json: project.errors, status: ':unprocessable_entity' }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: 'new' }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = current_user.projects.new(project_params)\n if @project.save\n render :show\n else\n render json: { errors: @project.errors }\n end\n end", "def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to admin_projects_url, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, flash: {success: 'Project was successfully created.'} }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n # authenticate_user!\n @project = Project.new\n @project[:category] = params[:category]\n @project[:title] = params[:title]\n @project[:body] = params[:body]\n @project[:location] = params[:location]\n @project[:image_link] = params[:image_link]\n @project[:project_url] = params[:project_url]\n @project[:year] = params[:year]\n @project[:likes] = params[:likes]\n @project.save\n\n render json: @project\n end", "def create\n @project = Project.new(project_params.merge(user_id: current_user.id))\n\n respond_to do |format|\n if @project.save\n format.json { render :show, status: :created, location: @project }\n else\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n \n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @client = Client.find(params[:client_id])\n @project = @client.projects.build(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to client_projects_path(@client), notice: 'Project was successfully created.' }\n format.json { render json: client_projects_path(@client), status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: client_projects_path(@client).errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = current_user.projects.build(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to root_path, notice: 'Enhorabuena! Tienes un nuevo proyecto. A trabajar!' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.create project_params\n current_user.memberships.create(\n project_id: @project.id,\n owner_at: Time.now\n )\n\n if @project.save\n render 'projects/create', status: 201\n else\n render 'projects/error', status: 422\n end\n end", "def create\n @project = @client.projects.build(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to(client_projects_url(@client), notice: 'Project was successfully created.') }\n format.xml { render xml: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.xml { render xml: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @create_project = current_user.projects.build(params[:project])\n flash[:notice] = \"Project #{@create_project.description} successfully created\" if @create_project.save\n respond_with(@create_project, layout: !request.xhr?)\n end", "def new_project\n @request = Request.new(data_type: :project)\n @request.build_contact\n @request.build_project\n @request.build_general_information\n\n render 'new'\n end", "def create\t\t\t\t\t\t\t\t\t# Creates record in db and redirects (porbably to index)\n\t\t@project = Project.new(projects_params)\t# Passes only title and desc.\n\n \trespond_to do |format|\t\t\t\t\t# All this is doing is rendering stuff in case of json\n \t\tif @project.save\n \t\tformat.html { redirect_to @project, notice: 'Created a new project!' }\n \t\tformat.json { render :show, status: :created, location: @project }\n \t\telse\n \t\tformat.html { render :new }\n \t\t\tformat.json { render json: @project.errors, status: :unprocessable_entity }\n \t\tend\n \tend\n\tend", "def create\n if params[:project_id]\n cloned_from = Project.find(params[:project_id])\n @project = cloned_from.clone(params, @cur_user.id)\n else\n @cloned_project = nil\n @project = Project.new project_params\n @project.user_id = @cur_user.id\n end\n\n respond_to do |format|\n if @project.save\n format.html do\n redirect_to @project, notice: 'Project was successfully created.'\n end\n format.json do\n render json: @project.to_hash(false),\n status: :created, location: @project\n end\n else\n flash[:error] = @project.errors.full_messages\n format.html { redirect_to projects_path }\n format.json do\n render json: @project.errors, status: :unprocessable_entity\n end\n end\n end\n end", "def create_project(key, name, params = {})\n params[:key] = key\n params[:name] = name\n post('projects', params)\n end", "def create\n @project = Project.new(project_params)\n @project.owner = current_user unless @project.owner\n if @project.save\n render :show, status: :created, location: @project\n else\n render json: @project.errors, status: :unprocessable_entity\n end\n end", "def create_project(optional={})\n\t\targs = self.class.new_params\n\t\targs[:method] = 'POST'\n\t\targs[:pattern] = '/projects'\n\t\targs[:query]['Action'] = 'CreateProject'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\targs[:scheme] = 'http'\n\t\tif optional.key? :project\n\t\t\targs[:body]['Project'] = optional[:project]\n\t\tend\n\t\tself.run(args)\n\tend", "def projects\n resource 'projects'\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n build_projects_user\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n project_attrs = params[:project].merge(validate_repo_connectivity: true)\n @project = current_user.owned_projects.create(project_attrs, as: :owner)\n respond_with @project do |format|\n format.json do\n if @project.valid?\n render json: decorate(@project).to_json, status: :created\n else\n render json: {project: @project.errors.as_json}.to_json, status: :unprocessable_entity\n end\n end\n end\n end", "def create\n @project = Project.new(params[:project])\n\t\t@project.user_id =current_user.id\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(params[:project])\n @project.skills = params[:skills]\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.create(project_params)\n if @project.errors.blank?\n flash[:success] = t('controllers.projects.create.success', project: @project.name)\n else\n flash.now[:alert] = @project.errors.full_messages.unshift(t('controllers.projects.create.failure'))\n end\n respond_with @project, location: projects_url\n end", "def create\n @new_nav = true;\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n if params[:project_attachments]\n create_attachments\n end\n\n if params[:project_fields]\n create_fields\n end\n\n if params[:slider_objects]\n create_slider_objects\n end\n\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n @project.user = current_user\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n begin\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors.full_messages, status: :unprocessable_entity }\n end\n end\n rescue Exception => e\n @project.destroy\n respond_to do |format|\n format.html { render :new }\n format.json { render json: e.as_json, status: :service_unavailable }\n end\n end\n end", "def project_create(global_options, options)\n result = Excon.post(\n \"#{global_options[:fenton_server_url]}/projects.json\",\n body: project_json(options),\n headers: { 'Content-Type' => 'application/json' }\n )\n\n [result.status, JSON.parse(result.body)]\n end", "def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n @project.user_projects.create(:user_id => current_user.id, :status => true, :role => 1)\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n respond_to do |format|\n if @project.save\n flash[:alert] = \"Project created successfully.\"\n format.html { redirect_back(fallback_location: root_path) }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n if is_organization_admin? and @project.save\n @project.team_members.create(user_id: @project.organization.owner_id)\n render json: {\n name: @project.name,\n organization: @project.organization.name,\n url: project_dashboard_path(@project.id)\n }\n else\n render json: @project.errors, status: :unprocessable_entity\n end\n end", "def create\n @project = Project.new(project_params)\n\n if params[\"project\"][\"client_id\"] != \"\"\n @project.client = Client.find params[\"project\"][\"client_id\"]\n end\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Novo projeto cadastrado com sucesso.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = current_user.projects.create(params[:project])\n \n if @project.save\n record_activity(\"created new project: \" + @project.id.to_s)\n redirect_to root_path, :notice => \"Project created successfully\"\n else\n render 'new'\n end\n end", "def create\n find_projects(params[:api_key])\n end", "def create\n\n @project = Project.new(project_params)\n @project.user_id = current_user.id\n\n respond_to do |format|\n if @project.save\n\n format.html { redirect_to @project, success: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(:project_title => params[:project_title], :start_date => params[:startDate], :end_date => params[:endDate],\n :status => params[:project_status])\n\n @project.user_id = current_user.id\n\n\n respond_to do |format|\n if @project.save\n p \"pass on projects controller\"\n format.html { redirect_to @project}\n format.json { render json: \"ok\" }\n else\n p \"fail on projects controller\"\n end\n end\n\n\n end", "def create_project_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ProjectApi.create_project ...'\n end\n # resource path\n local_var_path = '/projects'\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/json'])\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\n # http body (model)\n post_body = opts[:debug_body] || @api_client.object_to_http_body(opts[:'create_project_body'])\n\n # return_type\n return_type = opts[:debug_return_type] || 'Project'\n\n # auth_names\n auth_names = opts[:debug_auth_names] || ['oryAccessToken']\n\n new_options = opts.merge(\n :operation => :\"ProjectApi.create_project\",\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ProjectApi#create_project\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to :projects, notice: \"Project was successfully created.\" }\n format.json { render :show, status: :created, location: @project }\n else\n format.html do\n @teams = Team.order(:name)\n render :new\n end\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n @project.team.touch\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n render_errors(format, @project.errors, :new)\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to [:user, @project], notice: 'Project temp was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n\n render text: params[:project].inspect\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to projects_path, notice: 'Proyecto creado sastifactoriamente' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(params[:project])\n @project.status = \"Etat zero\"\n creator = current_user\n ProjectUser.create(:project => @project, :user => creator, :admin => true)\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.new(project_params)\n @project.user_id = current_user.id\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = @projectable.projects.new(params[:project])\n\n respond_to do |format|\n if @project.save\n track_activity @project\n format.html { redirect_to [@projectable, @project], notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render layout: 'form', action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\n #Acá se retorna de la vista New (o de cualquier lugar que llame a create con POST). Le llega el hash project_params con \n # los datos que retornó la vista.\n\n #Crea el nuevo usuario.\n @project = Project.new(project_params)\n\n respond_to do |format| #Esta linea es curiosa. Si el request le llegó por HTML, entonces fue un navegador. Si le llego\n #por JSON, entonces probablemente fue otra cosa, un app movil por ejemplo.\n if @project.save #Esto guarda el proyecto nuevo en la base de datos y retorna True si no hubo problema, y False si hubo un error.\n # Es importante notar que al llamar .save, primero pasa por el modelo, el cual revisa que no falte ningún dato.\n # Por ejemplo, si el modelo necesita que se incluya el nombre del proyecto, si o si, y no se le pasó el nombre,\n # Entonces el modelo va a guardar ese error en un hash llamado errors, dentro de el mismo (@projects.errors)\n # y va a hacer que .save retorne False.\n\n\n format.html { redirect_to :controller => \"misc\", :action =>\"about\", notice: 'Project was successfully created.' }\n format.json { render :show, status: :created, location: @project }\n else\n format.html { render :new }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end" ]
[ "0.7338948", "0.73139244", "0.7308003", "0.7299582", "0.7227503", "0.7225945", "0.71982473", "0.71170384", "0.7104803", "0.7095263", "0.7070636", "0.70408624", "0.70358187", "0.7024969", "0.70191896", "0.7009597", "0.698481", "0.697517", "0.6963753", "0.6963096", "0.6948756", "0.6948756", "0.6948756", "0.6948756", "0.6948756", "0.6948756", "0.6948756", "0.6948756", "0.6948756", "0.6944626", "0.69397265", "0.6938008", "0.69204897", "0.6911497", "0.6908809", "0.6907813", "0.6894293", "0.689054", "0.68847734", "0.6879909", "0.68794346", "0.6879012", "0.68784195", "0.6868972", "0.68664163", "0.68660194", "0.68657774", "0.68657774", "0.68657774", "0.68657774", "0.68657774", "0.68657774", "0.68657774", "0.68657774", "0.68657774", "0.68657774", "0.68657774", "0.68657774", "0.68657774", "0.68657774", "0.68657774", "0.6865554", "0.68598175", "0.6858278", "0.6846567", "0.6828604", "0.68193066", "0.6806436", "0.678643", "0.6784763", "0.6773288", "0.675545", "0.6750235", "0.67379624", "0.6718913", "0.6716745", "0.67009157", "0.66877806", "0.6686259", "0.668621", "0.66856426", "0.66838706", "0.6680505", "0.66770595", "0.6670888", "0.6668133", "0.66572726", "0.66528344", "0.66518456", "0.66511416", "0.6649628", "0.6649045", "0.6642436", "0.6638429", "0.6634081", "0.66324985", "0.6629944", "0.6628171", "0.66263485", "0.66259176", "0.66255814" ]
0.0
-1
PATCH/PUT /projects/1 PATCH/PUT /projects/1.json
def update end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update\n if @project.update(project_params)\n render json: @project, status: 200\n else\n render json: { errors: @project.errors.messages }, status: 200\n end\n end", "def update\n authorize! :update, @project\n\n if @project.update(project_params)\n head :no_content\n else\n render 'projects/error', status: 422\n end\n end", "def update\n @project = Project.find(params[:id])\n\n if params[:name] == \"project_name\"\n project_name = params[:value]\n @project.project_name = project_name\n end\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n\n @projects = Project.all\n format.html {\n render :action => \"index\"\n }\n format.json { render json: @project }\n else\n logMessage = self.class.to_s + \"#\" + __method__.to_s + \" \" + current_user.username + \" errors:\" + @project.errors.full_messages.to_s\n logger.info logMessage\n\n format.html {\n flash[:error] = 'Project was not successfully updated.'\n redirect_to action: \"index\"\n }\n errorMsg = @project.errors.full_messages.to_s.split(\"\\\"\")\n format.json { render json: errorMsg[1], status: 500 }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, :notice => 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @project.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to projects_path, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to(@project, :notice => 'Project was successfully updated.') }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @project.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update_project\n\t\t@project = Project.find(params[:id])\n\n\t \trespond_to do |format|\n\t\t if @project.update_attributes(project_update_params)\n\t\t format.html { redirect_to(@project, :notice => 'Entry was successfully updated.') }\n\t\t format.json { respond_with_bip(@project) }\n\t\t else\n\t\t format.html { render :action => \"edit\" }\n\t\t format.json { respond_with_bip(@project) }\n\t\t end\n\n \t end\n\tend", "def update\t\t\t\t\t\t\t\t\t# Actually modifies the data and redirects (probably to index or show? depends)\n\t\t#@project = Project.find(params[:id])\t# Taken out because of the before action GENIUS!\n\n\t\trespond_to do |format|\n \t\t if @project.update(projects_params)\n \t\tformat.html { redirect_to @project, notice: 'Project was successfully updated.' }\n \t\tformat.json { render :show, status: :ok, location: @project }\n \t\telse\n \t\tformat.html { render :edit }\n \t\tformat.json { render json: @project.errors, status: :unprocessable_entity }\n \t\tend\n \tend\n\tend", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = current_user.projects.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = @client.projects.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(project_params)\n format.html { redirect_to([@client, @project], notice: 'Project was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render action: \"edit\" }\n format.xml { render xml: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.json { render :show, status: :ok, location: @project }\n else\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.json { render json: @project, status: 200 }\n else\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\t\trespond_to do |format|\n\t\t\tif @project.update(project_params)\n\t\t\t\tformat.json { render :show, status: :ok }\n\t\t\telse\n\t\t\t\tformat.json { render json: @project.errors, status: :unprocessable_entity }\n\t\t\tend\n\t\tend\n\tend", "def update\n @client = Client.find(params[:client_id])\n @project = Project.find(params[:id])\n \n respond_to do |format|\n if @project.update_attributes(project_params)\n format.html { redirect_to client_projects_path(@client), notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: client_projects_path(@client).errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render json: @project.as_json(:include => [:client, :project_participants ] ) }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if project.update(project_params)\n format.html { redirect_to project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: project.errors, status: ':unprocessable_entity' }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to projects_path, notice: 'project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :ok }\n else\n @main_projects = Project.roots.where(creator_id: @project.creator_id)\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if @project.update(project_params)\n render json: {status: :success, project: @project}\n else\n render json: {status: :failed, project: @project}\n end\n end", "def update\n @edit_project = Project.find(params[:id])\n\n respond_to do |format|\n if @edit_project.update_attributes(params[:project])\n format.html { redirect_to @edit_project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @edit_project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @api_project.update(api_project_params)\n format.html { redirect_to @api_project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @api_project }\n else\n format.html { render :edit }\n format.json { render json: @api_project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def project_update(project)\n raise Client::FileboundClientException.new('Id is required', 0) unless project[:projectId].greater_than_zero?\n put('/projects', nil, project)\n end", "def update\n\t\t@project = Project.find(params[:id])\n\t\tmake_breadcrumbs\n\t\t\n\t\trespond_to do |format|\n\t\t\tif @project.update_attributes(params[:project])\n\t\t\t\tformat.html { redirect_to @project, notice: t('app.projects.updated') }\n\t\t\t\tformat.json { head :ok }\n\t\t\telse\n\t\t\t\tformat.html { render action: \"edit\" }\n\t\t\t\tformat.json { render json: @project.errors, status: :unprocessable_entity }\n\t\t\tend\n\t\tend\n\tend", "def update\n if @project.update(project_params)\n render :show, status: :ok, location: api_v1_project_url(@project)\n else\n render json: @project.errors, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n \t\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to add_path(@project), notice: 'Project was successfully updated.' }\n format.json { render :add, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project = Project.find(params[:id])\n params[:project][:problem_ids] ||= []\n params[:project][:target_ids] ||= []\n params[:project][:factor_ids] ||= []\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to(projects_path, :notice => 'Project was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @project.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to projects_path, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: projects_path }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\r\n respond_to do |format|\r\n if @project.update(project_params)\r\n format.html { redirect_to @project }\r\n format.json { respond_with_bip(@project) }\r\n else\r\n format.html { render action: 'edit' }\r\n format.json { respond_with_bip(@project) }\r\n end\r\n end\r\n end", "def update\n authenticate_user!\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to(@project, :notice => 'Project was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @project.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update_project(optional={})\n\t\targs = self.class.new_params\n\t\targs[:method] = 'PUT'\n\t\targs[:pattern] = '/projects/[ProjectName]'\n\t\targs[:query]['Action'] = 'UpdateProject'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\targs[:scheme] = 'http'\n\t\tif optional.key? :project\n\t\t\targs[:body]['Project'] = optional[:project]\n\t\tend\n\t\tif optional.key? :project_name\n\t\t\targs[:path]['ProjectName'] = optional[:project_name]\n\t\tend\n\t\tself.run(args)\n\tend", "def update\n @project = Project.find(params[:id])\n\n respond_to do |format|\n if @project.update_attributes(params[:project])\n format.html { redirect_to projects_path() }\n format.xml { head :ok }\n else\n @edit_mode = true\n @tasks = Task.find_all_by_project_id(@project.id)\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @project.errors, :status => :unprocessable_entity }\n end\n end\n end", "def project_updates\n @project = Project.find(params[:id])\n end", "def update\n if @project.update(project_params)\n render :show, status: :ok\n else\n render json: @project.errors, status: :unprocessable_entity\n end\n end", "def update\n if @project.update(project_params)\n render :show, status: :ok\n else\n render json: @project.errors, status: :unprocessable_entity\n end\n end", "def update\n @project = Project.find(params[:id])\n<<<<<<< HEAD:app/controllers/projects_controller.rb\n handle_disciplines_projects\n \n=======\n\n>>>>>>> 336471e6be257cf55c9afa2a65f928fde34e41fe:app/controllers/projects_controller.rb\n respond_to do |format|\n if @project.update_attributes(params[:project])\n flash[:notice] = 'Project was successfully updated.'\n format.html { redirect_to(@project) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @project.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to projects_path, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to projects_path, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def patch_project_with_http_info(project_id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ProjectApi.patch_project ...'\n end\n # verify the required parameter 'project_id' is set\n if @api_client.config.client_side_validation && project_id.nil?\n fail ArgumentError, \"Missing the required parameter 'project_id' when calling ProjectApi.patch_project\"\n end\n # resource path\n local_var_path = '/projects/{project_id}'.sub('{' + 'project_id' + '}', CGI.escape(project_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/json'])\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\n # http body (model)\n post_body = opts[:debug_body] || @api_client.object_to_http_body(opts[:'json_patch'])\n\n # return_type\n return_type = opts[:debug_return_type] || 'SuccessfulProjectUpdate'\n\n # auth_names\n auth_names = opts[:debug_auth_names] || ['oryAccessToken']\n\n new_options = opts.merge(\n :operation => :\"ProjectApi.patch_project\",\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(:PATCH, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ProjectApi#patch_project\\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 @project.update(project_params)\n format.html { redirect_to projects_path, notice: \"Project was successfully updated.\" }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors.full_messages, status: :unprocessable_entity }\n end\n end\n end", "def update\n if @project\n if @project.update(project_params)\n render json: @project, status: :ok\n else\n render json: {error: @project.errors.full_messages.to_sentence } , status: :unprocessable_entity\n end\n else\n render json: {error: \"Project does not exist\"} , status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @project.update(project_params)\n format.html { redirect_to @project, notice: 'Project was successfully updated.' }\n format.json { render :show, status: :ok, location: @project }\n else\n format.html { render :edit }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end" ]
[ "0.70004326", "0.69119745", "0.6911138", "0.6889052", "0.6888448", "0.6878091", "0.68675476", "0.6857582", "0.685334", "0.685334", "0.68503886", "0.68503886", "0.68503886", "0.68503886", "0.68503886", "0.68503886", "0.68503886", "0.68503886", "0.68503886", "0.68503886", "0.68503886", "0.68503886", "0.68503886", "0.68503886", "0.6850255", "0.6842495", "0.684057", "0.684057", "0.684057", "0.684057", "0.68398464", "0.68397754", "0.6839175", "0.6829714", "0.6829413", "0.68209535", "0.68173355", "0.6808719", "0.68025875", "0.68025875", "0.6780633", "0.6771888", "0.67589355", "0.67586994", "0.67586994", "0.67561215", "0.6746647", "0.6735708", "0.67201793", "0.6706241", "0.6702684", "0.66779363", "0.66752994", "0.66677266", "0.6659675", "0.66557306", "0.66467226", "0.6633223", "0.6633223", "0.66229934", "0.66225135", "0.66225135", "0.6615703", "0.661438", "0.66133374", "0.66015583", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113", "0.6600113" ]
0.0
-1
DELETE /projects/1 DELETE /projects/1.json
def destroy end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n @project.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n \n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n # @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :ok }\n end\n end", "def destroy\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :ok }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to(projects_url) }\n format.json { head :ok }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :ok }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :ok }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :ok }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :ok }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.delete\n\n respond_to do |format|\n format.html { redirect_to request.referer }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.status = 'deleted'\n @project.save!\n\n respond_to do |format|\n format.json { render :json => \"success\" }\n end\n end", "def delete\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_path }\n format.json { head :no_content }\n end\n end", "def destroy\n project = Project.find(params[:id])\n project.destroy\n\n respond_to do |format|\n format.html { redirect_to root_path }\n format.json { head :no_content }\n end\n end", "def destroy\n name = @project.name\n @project.destroy\n render json: [\"You have successfullly deleted '#{name}''\"], status: 200\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to admin_projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\r\n @project.destroy\r\n respond_to do |format|\r\n format.html { redirect_to projects_url }\r\n format.json { head :no_content }\r\n end\r\n end", "def delete(projects)\n project_ids = projects.collect { |project| project.id } \n args = {ids: project_ids.to_json}\n return @client.api_helper.command(args, \"project_delete\")\n end", "def delete\r\n\t\t\trender json: Project.delete_by_id(params[:id])\r\n\t\tend", "def destroy\n\t\t@project.destroy\n\t\trespond_to do |format|\n\t\t\tformat.json { head :no_content }\n\t\tend\n\tend", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to administration_projects_path }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = current_user.projects.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { render :json => {:message=>\"OK\",:id=>@project.id}, :staus=>:ok}\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n head :no_content\n end", "def destroy\t\t\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Successfully deleted project.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: t('models.project.destroy') }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = @client.projects.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to @client }\n end\n end", "def destroy\n @project.destroy\n\n head :no_content\n end", "def destroy\n @ourproject = Ourproject.find(params[:id])\n @ourproject.destroy\n\n respond_to do |format|\n format.html { redirect_to ourprojects_url }\n format.json { head :ok }\n end\n end", "def destroy\n authorize @project\n @project.destroy\n render json: [\"Deleted successfully.\"], status: :ok\n end", "def destroy\n @project.destroy_all\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'The project was successfully removed.' }\n format.json { head :no_content }\n end\n end", "def delete_project(project)\n handle_action_exceptions(__method__) do\n cmd_line = [\"deleteproject '#{project}'\"]\n cmd_line << 'json' if @json\n\n handle_return(@toolshck_ether.cmd(cmd_line.join(' ')))\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { render :json => {:valid => true} }\n end\n end", "def destroy\n @api_project.destroy\n respond_to do |format|\n format.html { redirect_to api_projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_path, notice: 'Project was successfully deleted.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully deleted.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully deleted.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find_by_permalink(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def delproject(project)\n post('delproject.json', project: project)\n end", "def destroy\n authorize! :destroy, @project\n @project.destroy\n\n head :no_content\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_back(fallback_location: root_path) }\n format.json { head :no_content }\n end\n end", "def destroy\n Rails.logger.info \"We are deleting project\"\n @todo_project.destroy\n respond_to do |format|\n format.html { redirect_to todo_projects_url, notice: 'Project was successfully deleted.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = @projectable.projects.find(params[:id])\n @project.destroy\n track_activity @project\n\n respond_to do |format|\n format.html { redirect_to [@projectable, :projects] }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find(params[:id])\n @project.destroy\n @project.users.delete_all\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n \t@project = Project.find(params[:id])\n \t#ap @project\n \t#abort\n \n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to :back }\n format.json { head :no_content }\n end\n end", "def destroy\n authenticate_user!\n @project = Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to(projects_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @project.destroy\n render json: {message: 'Projeto Excluido'}, status: :ok\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to root_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to root_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Project.find_by_slug(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :ok }\n end\n end", "def destroy\n\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: \"Project was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: \"#{I18n.t 'project.project_destoy'}\"}\n format.json { head :no_content }\n end\n end", "def destroy\n @project = Admin::Project.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_projects_url) }\n format.xml { head :ok }\n end\n end", "def delete_project(optional={})\n\t\targs = self.class.new_params\n\t\targs[:method] = 'DELETE'\n\t\targs[:pattern] = '/projects/[ProjectName]'\n\t\targs[:query]['Action'] = 'DeleteProject'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\targs[:scheme] = 'http'\n\t\tif optional.key? :project_name\n\t\t\targs[:path]['ProjectName'] = optional[:project_name]\n\t\tend\n\t\tself.run(args)\n\tend", "def destroy\n @project = current_user.active_projects.find(params[:id])\n @project.destroy\n\n respond_to do |format|\n format.html { redirect_to projects_url }\n format.json { head :no_content }\n end\n end", "def destroy\n standard_destroy(Project, params[:id])\n end", "def destroy\n authorize! :delete, @project\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: \"Project was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: \"Project was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: \"Project was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @project.destroy\n respond_to do |format|\n format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }\n format.json { head :no_content }\n end\n end" ]
[ "0.78951", "0.78593713", "0.7778056", "0.7771693", "0.77585995", "0.7730887", "0.77305084", "0.77305084", "0.77305084", "0.77305084", "0.77305084", "0.77244985", "0.7718401", "0.7718401", "0.7718401", "0.7718401", "0.7704753", "0.7704753", "0.7704753", "0.7704753", "0.7704753", "0.7704753", "0.7704753", "0.7704753", "0.7704753", "0.7704753", "0.7704753", "0.7704753", "0.7704753", "0.7704753", "0.7704753", "0.7704753", "0.7704753", "0.7704753", "0.7704753", "0.7704753", "0.7704753", "0.7704753", "0.7700103", "0.76993084", "0.7682566", "0.7669082", "0.7659675", "0.764973", "0.76495475", "0.7641442", "0.763269", "0.761519", "0.76147044", "0.7611191", "0.76066136", "0.7605034", "0.7598783", "0.75986093", "0.7593673", "0.7591231", "0.75896156", "0.7571706", "0.7571697", "0.7561333", "0.7543007", "0.7537952", "0.75324875", "0.75302756", "0.75237787", "0.75237787", "0.75189", "0.75063527", "0.7504202", "0.7499374", "0.7494583", "0.7487019", "0.74810386", "0.74776345", "0.7469382", "0.74652857", "0.7460907", "0.7460907", "0.74520767", "0.7448516", "0.744649", "0.74448746", "0.74421936", "0.7441719", "0.74374086", "0.7437005", "0.74365294", "0.74365294", "0.74365294", "0.7436244", "0.7436244", "0.7436244", "0.7436244", "0.7436244", "0.7436244", "0.7436244", "0.7436244", "0.7436244", "0.7436244", "0.7436244", "0.7436244" ]
0.0
-1
Use callbacks to share common setup or constraints between actions.
def set_project @project = Project.find(params[:id]) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_required_actions\n # TODO: check what fields change to asign required fields\n end", "def action_hook; end", "def run_actions; end", "def define_action_hook; end", "def actions; end", "def define_action_helpers\n if super && action == :save\n @instance_helper_module.class_eval do\n define_method(:valid?) do |*args|\n self.class.state_machines.fire_event_attributes(self, :save, false) { super(*args) }\n end\n end\n end\n end", "def add_actions; end", "def callbacks; end", "def callbacks; end", "def setup *actions, &proc\n (@setup_procs ||= []) << [proc, actions.size > 0 ? actions : [:*]]\n end", "def define_action_helpers; end", "def post_setup\n end", "def action_methods; end", "def action_methods; end", "def action_methods; end", "def before_setup; end", "def action_run\n end", "def execute(setup)\n @action.call(setup)\n end", "def define_action_helpers?; end", "def set_actions\n actions :all\n end", "def action_done(action)\n dispatch = { :migrate => :done_migrating, :map => :done_mapping, :reduce =>\n :done_reducing, :finalize => :done_finalizing } \n self.send dispatch[action[:action]], action\n end", "def dependencies action, &block\n @actions.each do |other|\n if action[:requires].include? other[:provide]\n block.call other\n end\n end\n end", "def setup!\n return unless @setup_procs\n http_actions = actions\n @setup_procs.each do |setup_proc|\n proc, actions = setup_proc\n @setup__actions = actions.map do |action|\n\n action.is_a?(Regexp) ?\n http_actions.select { |a| a.to_s =~ action } :\n action.is_a?(String) && action =~ /\\A\\./ ?\n http_actions.map { |a| a.to_s << action if format?(a).include?(action) }.compact :\n action\n\n end.flatten\n self.class_exec &proc\n @setup__actions = nil\n end\n @setup_procs = nil\n end", "def before_actions(*logic)\n self.before_actions = logic\n end", "def setup_handler\n end", "def set_action(opts)\n opts = check_params(opts,[:actions])\n super(opts)\n end", "def setup(action)\n @targets.clear\n unless action.item.target_filters.empty?\n @targets = SES::TargetManager.make_targets(action)\n else\n item = action.item\n if item.for_opponent?\n @targets = $game_troop.alive_members\n elsif item.for_dead_friend?\n @targets = $game_party.battle_members.select { |actor| actor.dead? }\n else\n $game_party.battle_members.select { |actor| actor.alive? }\n end\n end\n @item_max = @targets.size\n create_contents\n refresh\n show\n activate\n end", "def action; end", "def action; end", "def action; end", "def action; end", "def action; end", "def workflow\n end", "def revisable_shared_setup(args, block)\n class << self\n attr_accessor :revisable_options\n end\n options = args.extract_options!\n self.revisable_options = Options.new(options, &block)\n \n self.send(:include, Common)\n self.send(:extend, Validations) unless self.revisable_options.no_validation_scoping?\n self.send(:include, WithoutScope::QuotedColumnConditions)\n end", "def setup\n @action = SampleActionAndroid.new(os_name: 'android',\n app_name: APP_PATH)\n end", "def before(action)\n invoke_callbacks *self.class.send(action).before\n end", "def process_action(...)\n send_action(...)\n end", "def before_dispatch(env); end", "def after_actions(*logic)\n self.after_actions = logic\n end", "def setup\n # override and do something appropriate\n end", "def setup(client)\n return unless @setup\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n actions.each do |action|\n action.execute(client)\n end\n self\n end", "def setup(_context)\n end", "def setup(resources) ; end", "def validate_actions\n errors.add(:base, :should_give_at_least_one_action) if !manage? && !forecasting? && !read? && !api?\n end", "def setup\n @resource_config = {\n :callbacks => {\n :before_create => nil,\n :after_create => nil,\n :before_update => nil,\n :after_update => nil,\n :before_destroy => nil,\n :after_destroy => nil,\n },\n :child_assoc => nil,\n :model => nil,\n :parent => nil,\n :path => nil,\n :permission => {},\n :properties => {},\n :relation => {\n :create => nil,\n :delete => nil,\n },\n :roles => nil,\n }\n end", "def determine_valid_action\n\n end", "def process_shared\n handle_taxes\n handle_shippings\n create_adjustments_from_params\n handle_status\n handle_inventory_refunds\n handle_payment_transactions\n order.updater.update\n end", "def startcompany(action)\n @done = true\n action.setup\n end", "def init_actions\n am = action_manager()\n am.add_action(Action.new(\"&Disable selection\") { @selection_mode = :none; unbind_key(32); bind_key(32, :scroll_forward); } )\n am.add_action(Action.new(\"&Edit Toggle\") { @edit_toggle = !@edit_toggle; $status_message.value = \"Edit toggle is #{@edit_toggle}\" })\n end", "def event_callbacks(event, metadata={})\n case event\n when :reset, :review\n if confirmed\n update_attributes(confirmed: false)\n end\n when :confirm\n confirm\n # trigger :order for all applicable items\n # NOTE: :order event is common to both physical and digital items\n items.each do |i|\n if i.event_permitted(:order)\n user_id = last_transition.user_id\n i.trigger!(:order, { order_id: id, user_id: user_id })\n end\n end\n when :complete_work\n request = metadata[:request]\n work_complete_notification(request)\n when :close\n close\n end\n if event != :close && !open\n reopen\n end\n end", "def setup_action\n return unless PONY::ERRNO::check_sequence(current_act)\n new_sequence = @action_sequence[@sequence_index+1...@action_sequence.size]\n @sequence_index = 0\n new_sequence = DND::SkillSequence::ACTS[@acts[1]] + new_sequence\n execute_sequence\n end", "def define_tasks\n define_weave_task\n connect_common_tasks\n end", "def setup(&block)\n define_method(:setup, &block)\n end", "def setup\n transition_to(:setup)\n end", "def setup\n transition_to(:setup)\n end", "def action\n end", "def setup( *args )\n\t\t\tself.class.setupBlocks.each {|sblock|\n\t\t\t\tdebugMsg \"Calling setup block method #{sblock}\"\n\t\t\t\tself.send( sblock )\n\t\t\t}\n\t\t\tsuper( *args )\n\t\tend", "def config(action, *args); end", "def setup\n @setup_proc.call(self) if @setup_proc\n end", "def before_action \n end", "def setup_callbacks\n defined_callbacks.each do |meth|\n unless respond_to?(\"call_#{meth}_callbacks\".to_sym)\n self.class.module_eval <<-EOE\n def call_#{meth}_callbacks(*args)\n plugin_store.each {|a| a.call_#{meth}_callbacks(*args) } if respond_to?(:plugin_store) && plugin_store\n self.send :#{meth}, *args if respond_to?(:#{meth})\n end\n EOE\n end\n end\n end", "def action\n end", "def matt_custom_action_begin(label); end", "def setup\n # override this if needed\n end", "def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend", "def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend", "def action(options,&callback)\n new_action = Action===options ? options : Action.new(options,&callback)\n # replace any with (shared name/alias or both default) + same arity\n @actions.delete_if do |existing_action|\n ((existing_action.names & new_action.names).size > 0 ||\n existing_action.default? && new_action.default?) &&\n existing_action.required.size == new_action.required.size &&\n existing_action.optional.size <= new_action.optional.size\n end\n @actions = (@actions + [new_action]).sort\n new_action\n end", "def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action\n end", "def after(action)\n invoke_callbacks *options_for(action).after\n end", "def pre_task\n end", "def setup(server)\n server.on('beforeMethod', method(:before_method), 10)\n end", "def add_actions\n attribute = machine.attribute\n name = self.name\n \n owner_class.class_eval do\n define_method(name) {self.class.state_machines[attribute].events[name].fire(self)}\n define_method(\"#{name}!\") {self.class.state_machines[attribute].events[name].fire!(self)}\n define_method(\"can_#{name}?\") {self.class.state_machines[attribute].events[name].can_fire?(self)}\n end\n end", "def init_actions\n @select_action = SelectAction.new\n @endpoint_mouse_action = EndpointMouseAction.new\n @move_action = MoveAction.new\n end", "def setup_signals; end", "def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend", "def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend", "def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action.respond_to?('weak!') ? action.weak! : action\n end", "def initialize(*args)\n super\n @action = :set\nend", "def after_set_callback; end", "def setup\n #implement in subclass;\n end", "def lookup_action; end", "def setup &block\n if block_given?\n @setup = block\n else\n @setup.call\n end\n end", "def setup_action\n return TSBS.error(@acts[0], 1, @used_sequence) if @acts.size < 2\n actions = TSBS::AnimLoop[@acts[1]]\n if actions.nil?\n show_action_error(@acts[1])\n end\n @sequence_stack.push(@acts[1])\n @used_sequence = @acts[1]\n actions.each do |acts|\n @acts = acts\n execute_sequence\n break if @break_action\n end\n @sequence_stack.pop\n @used_sequence = @sequence_stack[-1]\n end", "def release_actions; end", "def around_hooks; end", "def save_action; end", "def setup(easy)\n super\n easy.customrequest = @verb\n end", "def action_target()\n \n end", "def setup\n callback(:setup) do\n notify(:setup)\n migration_check.last_deployed_commit\n end\n end", "def setup\n return unless @setup\n\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n run_actions_and_retry(actions)\n self\n end", "def before_setup\n # do nothing by default\n end", "def my_actions(options)\n @setup = false\n get_template_part(\"custom_used\",\"action_users\",true)\n end", "def default_action; end", "def setup(&blk)\n @setup_block = blk\n end", "def callback_phase\n super\n end", "def advice\n end", "def _handle_action_missing(*args); end", "def duas1(action)\n action.call\n action.call\nend", "def shared_action(name, &block)\n @controller.shared_actions[name] = block\n end", "def before_action action, &block\n @audience[:before][action] ||= Set.new\n @audience[:before][action] << block\n end", "def setup_initial_state\n\n state_a = State.new(\"a\", 0)\n state_b = State.new(\"b\", 0)\n state_c = State.new(\"c\", 10)\n\n move_to_b = Action.new(\"move_to_b\", 1, state_b)\n\n move_to_c = Action.new(\"move_to_c\", 1, state_c)\n\n state_a.actions = [move_to_b, move_to_c]\n\n return state_a\n \nend" ]
[ "0.6163163", "0.6045976", "0.5946146", "0.591683", "0.5890051", "0.58349305", "0.5776858", "0.5703237", "0.5703237", "0.5652805", "0.5621621", "0.54210985", "0.5411113", "0.5411113", "0.5411113", "0.5391541", "0.53794575", "0.5357573", "0.53402257", "0.53394014", "0.53321576", "0.53124547", "0.529654", "0.5296262", "0.52952296", "0.52600986", "0.52442724", "0.52385926", "0.52385926", "0.52385926", "0.52385926", "0.52385926", "0.5232394", "0.523231", "0.5227454", "0.52226824", "0.52201617", "0.5212327", "0.52079266", "0.52050185", "0.51754695", "0.51726824", "0.51710224", "0.5166172", "0.5159343", "0.51578903", "0.51522785", "0.5152022", "0.51518047", "0.51456624", "0.51398855", "0.5133759", "0.5112076", "0.5111866", "0.5111866", "0.5110294", "0.5106169", "0.509231", "0.50873137", "0.5081088", "0.508059", "0.50677156", "0.50562143", "0.5050554", "0.50474834", "0.50474834", "0.5036181", "0.5026331", "0.5022976", "0.5015441", "0.50121695", "0.5000944", "0.5000019", "0.4996878", "0.4989888", "0.4989888", "0.49864885", "0.49797225", "0.49785787", "0.4976161", "0.49683493", "0.4965126", "0.4958034", "0.49559742", "0.4954353", "0.49535993", "0.4952725", "0.49467874", "0.49423352", "0.49325448", "0.49282882", "0.49269363", "0.49269104", "0.49252945", "0.4923091", "0.49194667", "0.49174926", "0.49173003", "0.49171105", "0.4915879", "0.49155936" ]
0.0
-1
Never trust parameters from the scary internet, only allow the white list through.
def project_params params.require(:account).permit(:is_eligable, :is_registered) 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
get this would normally have a form view to make a new url
def new @url = Url.new end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def url\n end", "def to(url); end", "def edit\n session[:return_to] ||= request.referer\n @Urlmaster = Urlmaster.find(params[:id])\n end", "def new\n @page_title = 'New URL'\n @url = ShortenUrl.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @url }\n end\n end", "def url; end", "def url; end", "def url; end", "def url; end", "def url; end", "def url; end", "def url; end", "def url; end", "def url; end", "def url; end", "def url; end", "def url; end", "def url; end", "def url; end", "def url; end", "def url; end", "def url; end", "def url; end", "def url; end", "def new\n\t\t@shortened_url = ShortenedUrl.new\n\t\t@url = shorten_urls_path\n\tend", "def form_url\n URL\n end", "def new\n @rails_url = RailsUrl.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @rails_url }\n end\n end", "def url\n end", "def show\n @url = @oi.urls.new\n end", "def new\n @url = ShortenedUrl.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @url }\n end\n end", "def GET; end", "def new\n @admin_enter_url = Admin::EnterUrl.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @admin_enter_url }\n end\n end", "def new\n @url = Url.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @url }\n end\n end", "def url_template; end", "def url_template; end", "def redirect(url); end", "def new\n redirect_to '/new_course'\n end", "def new\n # Set variables\n @snop = Snop.new\n @default_uri = params[:uri]\n\n respond_to do |format|\n format.html # new.html.erb\n end\n end", "def quest_new_page\n \"/#{user_path}/#{objective_path}/#{controller}/new\"\n end", "def new\n redirect_to root_url\n end", "def show\n@url=geturl(@registro)\n respond_to do |format|\n format.html\n\n end\n\n\n end", "def new\n redirect_to static_pages_home_url\n end", "def show\n redirect_to(\"http://www.tuanao.com/today\")\n end", "def new\n @employee = Employee.new\n @url = { controller: '/employees', action: :create }\n render :form\n end", "def create\n @url = Url.create_update_with(url_params)\n @short_url = \"#{request.host_with_port}/#{@url.short_url}\"\n redirect_to root_path(short_url: @short_url)\n end", "def set_url\n # @url = Url.find(params[:id])\n end", "def new\n geoname = Geoname.find(rand(Geoname.count))\n\n respond_to do |format|\n format.html { redirect_to travel_path(geoname.name)}\n end\n end", "def url=(_); end", "def current_url(new_params)\n url_for params: params.permit!.merge(new_params) # allow all params already passed\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => new_vurl }\n end\n end", "def url=(_arg0); end", "def url=(_arg0); end", "def url=(_arg0); end", "def url=(_arg0); end", "def url=(_arg0); end", "def url=(_arg0); end", "def url=(_arg0); end", "def create\n @url = Url.new(url_params)\n\n if @url.save\n redirect_to @url\n else\n render 'new'\n end\n end", "def new\n @url = Url.new\n end", "def new\n @url = Url.new\n end", "def index\n @url = Url.new\n end", "def view\n\t\tbinding.pry\n\t\t# @offer = Offer.find params[:referral_id]\n\t\t# company = @offer.company\n\t\t# @offer.build_referral\n\t\t# @referral = Referral.new\n\t\t@tags = @offer.tag_list\n\t\trender 'new'\n\tend", "def new\n render\n end", "def new\n render\n end", "def new\n render\n end", "def new\n render\n end", "def new\n @address = Address.new\n @url = { controller: '/addresses', action: :create }\n end", "def new\n url = params[:long_url] || params[:url]\n if !url.present?\n render :text => \"URL not passed as a variable\" \n else\n # check to see if there's an existing short url\n short_url = @site.urls.find_by_long_url(url)\n\n if short_url\n respond_to do |format|\n format.html { render text: short_url.full_short_link }\n format.json { respond_with short_url }\n end\n else\n @url = @site.urls.create!(long_url: url, title: params[:title])\n\n respond_to do |format|\n format.html { render text: @url.full_short_link }\n format.json { respond_with @url }\n end\n end\n\n end\n rescue\n render text: \"Error saving short link\"\n end", "def show\n redirect_to @url_builder.short_url_info\n end", "def new_site\n \n end", "def new\n redirect_to :action => 'index'\n end", "def new\n @video = Video.new\n @title = \"Video Submission\"\n \n @url = params[:url]\n \n respond_to do |format|\n format.html # new.html.erb\n end\n end", "def new\n redirect_to root_path\n end", "def new\n redirect_to root_path\n end", "def new\n\t\t# no code needed here; all handled in the view\n\tend", "def url\n super\n end", "def create\n referrer = Rails.application.routes.recognize_path(request.referrer)\n \n @url = Url.new(url_params)\n @error = nil\n result_url = Url.find_by(:long_url => @url[:long_url])\n\n respond_to do |format|\n if result_url.nil?\n max_id = Url.maximum(:id) || 0\n num = START_OFFSET + max_id + 1\n short_key = encode(num) \n @url[:short_url] = short_key\n\n if @url.save\n @new_url = @url\n @url = Url.new(:long_url => @new_url[:long_url], :short_url => @new_url[:short_url])\n if referrer[:action] == 'index'\n format.html { render :index }\n else\n format.html { redirect_to @new_url, notice: \"URL was successfully created.\"}\n end\n else\n @error = @url.errors.full_messages\n if referrer[:action] == 'index'\n format.html { render :index }\n else\n format.html { render :new }\n format.json { render json: @url.errors, status: :unprocessable_entity }\n end\n end\n else\n if referrer[:action] == 'index'\n @url[:short_url] = result_url[:short_url]\n format.html { render :index }\n else\n format.html { redirect_to result_url, notice: \"Existing URL. No URL is created.\" }\n end\n end\n end\n end", "def new #given to config/routes.rb\n end", "def set_url\n @url = Url.get_from_short(params[:id])\n end", "def new\n respond_with(page)\n end", "def new_form_url\n if params[:firm_id]\n @information[:form_url] = firm_trades_path(@parent, trade_type: params[:trade_type])\n @information[:back_path] = firm_path(@parent)\n @information[:subtitle] = if params[:trade_type] == 'sells'\n t('view.trades.new_trade_sold_by_firm_title', firm: @parent.name)\n elsif params[:trade_type] == 'buys'\n t('view.trades.new_trade_sold_to_firm_title', firm: @parent.name)\n end\n elsif params[:product_id]\n @information[:form_url] = product_trades_path(@parent, trade_type: params[:trade_type])\n @information[:back_path] = product_path(@parent)\n @information[:subtitle] = if params[:trade_type] == 'sells'\n t('view.trades.new_product_traded_by_title', product: @parent.name)\n elsif params[:trade_type] == 'buys'\n t('view.trades.new_product_traded_to_title', product: @parent.name)\n end\n end\n end", "def new\n redirect_to edit_page_path(find_or_create_page)\n end", "def url_for_main; end", "def url_for_main; end", "def create\n \turl = Url.create(params[:url])\n \t\n \tredirect_to urls_path\n end", "def new\n render \"new\"\n end", "def new\n render \"new\"\n end", "def new\n redirect_to orders_path\n end", "def new_question_url\n view_context.new_question_url\n end", "def link() url; end", "def link() url; end", "def show\n self.redirect\n end", "def new\n render 'new'\n end", "def update\n redirect_to new_vurl_path\n end", "def getViewLink(request)\r\n viewid = request.getParameter(\"viewid\")\r\n if !viewid.nil? \r\n newviewid = KeywordProcessor.filterAlphaNumeric(viewid)\r\n end\r\n return nil if newviewid.nil?\r\n # Use alpha-numeric viewid\r\n newviewid\r\n end", "def new\n @url_search = UrlSearch.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @url_search }\n end\n end", "def new\n @cv = Cv.new\n @url = { controller: '/cvs', action: :create }\n end", "def redirects; end", "def set_url\n @url = Url.find(params[:id])\n end", "def retrieve_short_url_to_long_url\n if params[:short_url]==\"\"\n flash[:Error] = \"Please Enter all Details\"\n redirect_to urls_short_url_to_long_url_path\n else\n params[:short_url] = params[:short_url].strip\n @result = short_url(url_params)\n render '/urls/show'\n end\n end", "def new\n redirect_to lato_pages.pages_path\n end" ]
[ "0.65918636", "0.6569572", "0.6503145", "0.6468078", "0.6433631", "0.6433631", "0.6433631", "0.6433631", "0.6433631", "0.6433631", "0.6433631", "0.6433631", "0.6433631", "0.6433631", "0.6433631", "0.6433631", "0.6433631", "0.6433631", "0.6433631", "0.6433631", "0.6433631", "0.6433631", "0.6433631", "0.642689", "0.64247376", "0.6422422", "0.6394193", "0.63294625", "0.6318236", "0.63024485", "0.6276751", "0.6252171", "0.62321913", "0.62321913", "0.6224255", "0.62185293", "0.61963356", "0.6186674", "0.617942", "0.6172006", "0.6162843", "0.613902", "0.61378884", "0.6135471", "0.6122072", "0.6117411", "0.6106482", "0.61019737", "0.6100737", "0.6098244", "0.6098244", "0.6098244", "0.6098244", "0.6098244", "0.6098244", "0.6098244", "0.6094934", "0.609241", "0.609241", "0.6091571", "0.6090533", "0.6085949", "0.6085949", "0.6085949", "0.6085949", "0.60770285", "0.60600287", "0.60586673", "0.60543704", "0.60503876", "0.6042318", "0.5999396", "0.5999396", "0.5997933", "0.59861225", "0.5979617", "0.5975618", "0.59751517", "0.5970985", "0.5969621", "0.5969202", "0.5966564", "0.5966564", "0.59630126", "0.5962187", "0.5962187", "0.5960765", "0.5954217", "0.59534836", "0.59534836", "0.5953204", "0.5948059", "0.5947009", "0.5944353", "0.59437054", "0.5929089", "0.59282696", "0.59246665", "0.5921283", "0.5921087" ]
0.6122127
44
post would accept form data from the new view
def create url = Url.create(params[:url]) redirect_to urls_path end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def POST; end", "def new\n respond_with(@post)\n end", "def new\n respond_with @post\n end", "def post\r\n end", "def form_view\n end", "def form\n end", "def post\n end", "def post; end", "def create \n #render plain: params[:post].inspect\n @post = Post.new(post_params) #Capture paramters from the View\n @post.save #Save the new Post object to the DV\n redirect_to @post #Display the new post once saved\n end", "def form; end", "def new\n render\n end", "def new\n render\n end", "def new\n render\n end", "def new\n render\n end", "def new\n\t\t# no code needed here; all handled in the view\n\tend", "def create\n post\n end", "def form_data?; end", "def post_data; end", "def new\n @post = flash[:form_data] || Post.new\n @title = 'New post'\n\n render_view(:form)\n end", "def post_form\n @post = Post.new(post_params)\n unless @post.valid?\n render :new\n else\n redirect_to :action => \"create_confirm\", title: @post.title, description: @post.description\n end\n end", "def create\n # render plain: params[:post].inspect #get the inspected parameters filled by the user in the form\n @post = Post.new(post_params) #Create a new post with the supplied post parameters\n if(@post.save) #Saves the post to the database\n redirect_to @post #Redirects to the show method\n else\n render 'new' #If got any errors while saving, render the new.html.erb page and show the error \n end\n end", "def post\n frm.button(:name=>\"post\").click\n AssignmentsList.new(@browser)\n end", "def new\n @post = Post.new\n respond_with(@post)\n end", "def new\n @post = Post.new\n respond_with(@post)\n end", "def employee_post\n if params[\"new\"] \n redirect_to \"/employee/new\" and return\n else\n redirect_to \"/employee/#{params[\"edit\"]}\" and return\n end\n end", "def new #http://localhost:3000/posts/new\n\t@post = Post.new #creates a new empty post,if a form is created for it, it will be empty as well \n end", "def post\n frm.button(:value=>\"Post\").click\n AssignmentsList.new(@browser)\n end", "def create\n #render plain: params[:post].inspect\n # to display the paramerters that are coming in the form\n\n # @post = Post.new(params.require(:post).permit(:title, :text))\n @post = Post.new(posts_params)\n if @post.save\n redirect_to @post\n else\n render 'new'\n end\n end", "def post!\n request! :post\n end", "def onSubmit(request, response, form, errors) \r\n return form\r\n end", "def onSubmit(request, response, form, errors) \r\n return form\r\n end", "def onSubmit(request, response, form, errors) \r\n return form\r\n end", "def onSubmit(request, response, form, errors) \r\n return form\r\n end", "def new\n @post = session[:post] || @contest.posts.build\n @post.subject = @contest.name #|| params[:subject] if params[:subject]\n @post.url = @contest.url #|| params[:url] if params[:url]\n @post.description = @contest.description \n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @post }\n end\n end", "def new\n render :new\n end", "def submit\n @new = New.new\n end", "def new\n # render(:new) => this whole action could also be implicit\n end", "def new\n respond_to do |format|\n format.html\n end\n end", "def create\n #binding.pry\n # saving the post w/the form values into the database\n @post = Post.new(post_params) #call a new method as params - post in memory\n if @post.save #making active record call to see if we saved in db\n redirect_to post_path(@post) #look at rake routes bundle exec rake routes read right left; rails is smart enough that u don't need @post.id\n else\n # unsuccessful create attempt\n render :new #render new page (most basic flow here)\n end\n end", "def onSubmit(request, response, form, errors)\r\n\treturn form\r\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @post }\n end\n end", "def new\n render 'new'\n end", "def new\n #just show me the form\nend", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @post }\n end\n end", "def onSubmit(request, response, form, errors)\r\n return form\r\n end", "def onSubmit(request, response, form, errors)\r\n return form\r\n end", "def moip_post\n @nasp_rail = NaspRail.new(params[:nasp_rail])\n\n format.html { redirect_to @nasp_rail, :notice => 'Nova entrada criada com sucesso.' }\n format.json { render :json => @nasp_rail, :status => :created, :location => @nasp_rail }\n end", "def new\n @post = Post.new\n\n respond_to do |format|\n format.html\n end\n end", "def new\n @post = Post.new\nend", "def new\n get_user\n @submission = Submission.new\n end", "def create\n render :new\n end", "def create\n # displays post information in JSON format\n # render([current,] :text => params[:post].inspect )\n# render text: params[:post].inspect\n\n # get post form data from params as new Post\n# Rails 4.0\n# @post = Post.new(params[:post].permit(:title, :text))\n @post = Post.new(params[:post])\n\n # save post in sqlite db; save returns false if invalid\n if @post.save\n # send GET request to post, conveying post id => posts#show\n redirect_to @post\n else # invalid form\n # same form => posts#new\n render 'new'\n end\n end", "def new\n render \"new\"\n end", "def new\n render \"new\"\n end", "def new\n @post = Post.new\n\n respond_to do |format|\n format.html #{ redirect_to '/' }\n format.json { render json: @post }\n end\n end", "def new\n\n end", "def new\n\n end", "def new\n\n end", "def new\n\n end", "def new\n\n end", "def new\n\n end", "def new\n\n end", "def new\n\n end", "def new\n\n end", "def new\n\n end", "def new\n\n end", "def new\n respond_with @proveedor\n end", "def forms; end", "def create\n @post = Post.new(params[:post])\n\n respond_to do |format|\n if @post.save\n format.html { redirect_to @post, notice: 'Post creado con éxito.' }\n else\n format.html { render action: \"new\" }\n end\n end\n end", "def new\n @post305 = Post305.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @post305 }\n end\n end", "def onSubmit(request, response, form, errors) \n return form\n end", "def new\n @todo = Todo.new\n respond_with @todo\n end", "def new\n redirect_to '/404.html' and return if params[:auth_token].nil? || not_allowed_user\n @form = Form.new\n @form.user_id = user.id\n end", "def new\n @post377 = Post377.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @post377 }\n end\n end", "def post(data = \"\")\n submit :Post, data\n end", "def create\n @post = Post.new\n @post.title = params[:title]\n @post.description = params[:description]\n @post.save\n\n #each route will automatically check for a matching view..\n # since we don't need a view for create, we must redirect\n # after we are done saving the post... in order to avoid errors.\n \n redirect_to post_path(@post)\n end", "def create\n @post = Post.new(params[:post])\n @post.researcher = logged_in_researcher \n\n respond_to do |format|\n if @post.save\n format.html { redirect_to(@post, :notice => 'Post was successfully created.') }\n format.xml { render :xml => @post, :status => :created, :location => @post }\n format.json { render :json => @post, :status => :created, :location => @post }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @post.errors, :status => :unprocessable_entity }\n format.json { render :json => @post.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @mypost = Mypost.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @mypost }\n end\n end", "def new\n @form_of_receits = FormOfReceipt.new\n\n respond_to do |format|\n format.html # new.html.erb\n end\n end", "def new\n @post445 = Post445.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @post445 }\n end\n end", "def new\n @post405 = Post405.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @post405 }\n end\n end", "def new\n redirect_to posting_types_path\n end", "def new\n\n\t\t\n\tend", "def new\n @post13 = Post13.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @post13 }\n end\n end", "def new\n @test_post = TestPost.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @test_post }\n end\n end", "def new\n @post335 = Post335.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @post335 }\n end\n end", "def new\n respond_with(@task = Task.new)\nend", "def new\n @dos = CreateDo.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @dos }\n end \n end", "def new\n @post453 = Post453.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @post453 }\n end\n end", "def new\n @view = View.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @view }\n end\n end", "def postNews\n @new = New.new\n @new.headline = params[\"headline\"]\n @new.content = params[\"content\"]\n @new.user_id = session[:user_id]\n if @new.save\n flash[:success] = \"News submitted successfully\"\n redirect_to :action => 'index'\n else\n flash[:warning] = \"Fail to submit news\"\n redirect_to :action => 'submit' \n end\n end", "def new\n # render new.html\n end", "def new\n # @post = Post.new\n\n respond_to do |format|\n format.html # new.html.erb\n # format.json { render json: @post }\n end\n end", "def new\n \trespond_with @rubro\n end", "def create\n Post.create(params[:post])\n redirect_to new_post_path\n end", "def new\n @post366 = Post366.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @post366 }\n end\n end", "def new\n @post326 = Post326.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @post326 }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n end\n end" ]
[ "0.72150147", "0.70573664", "0.7024402", "0.6957369", "0.6776068", "0.6742947", "0.66835546", "0.66584283", "0.650927", "0.64824015", "0.64713037", "0.64713037", "0.64713037", "0.64713037", "0.64462554", "0.6421328", "0.63944113", "0.6359852", "0.63273907", "0.63062555", "0.62791127", "0.62684846", "0.6262936", "0.6262936", "0.6260467", "0.6202939", "0.6191139", "0.61520463", "0.6149551", "0.6147209", "0.6147209", "0.6147209", "0.6147209", "0.61350083", "0.6123021", "0.6121203", "0.61142135", "0.6112769", "0.61062515", "0.6104841", "0.6096184", "0.6095033", "0.6094859", "0.6091355", "0.608258", "0.608258", "0.6078857", "0.60639024", "0.6043604", "0.6023553", "0.6004518", "0.60019255", "0.5992154", "0.5992154", "0.5981942", "0.5975151", "0.5975151", "0.5975151", "0.5975151", "0.5975151", "0.5975151", "0.5975151", "0.5975151", "0.5975151", "0.5975151", "0.5975151", "0.59681106", "0.5967561", "0.5967458", "0.59638435", "0.5952355", "0.5947227", "0.59454614", "0.5944656", "0.593565", "0.59323263", "0.5930835", "0.5928155", "0.5926894", "0.5925792", "0.5922465", "0.59189975", "0.5918617", "0.5909268", "0.5908727", "0.5901369", "0.59007055", "0.59000325", "0.5898451", "0.58968", "0.5894509", "0.58925307", "0.58888006", "0.58865356", "0.5885742", "0.58842474", "0.58841395", "0.58840126", "0.58840126", "0.58840126", "0.58840126" ]
0.0
-1
Only allow a list of trusted parameters through.
def document_params params.require(:doc_file).permit(:data) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def allowed_params\n ALLOWED_PARAMS\n end", "def strong_params\n params.require(:listing_member).permit(param_whitelist)\n end", "def parameters_list_params\n params.require(:parameters_list).permit(:name, :description, :is_user_specific)\n end", "def param_whitelist\n [:role, :title]\n end", "def param_whitelist\n whitelist = [\n :username, :name,\n :parent_id,\n :headline, :description, :video,\n :policy, :signup_mode, :category,\n :website, :facebook, :twitter, :linkedin,\n :founded_at,\n privacy: [\n :events,\n :resources\n ],\n permission: [\n :profile,\n :members,\n :children,\n :statistics,\n :posts,\n :listings,\n :resources,\n :events\n ],\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:parent_id)\n unless current_user.role_in(@community) === 'owner'\n whitelist.delete(:privacy)\n whitelist.delete(:permission)\n end\n end\n \n whitelist\n end", "def strong_params\n params.require(:user).permit(param_whitelist)\n end", "def param_whitelist\n if @user.present? && current_user != @user\n return [:followed]\n end\n \n whitelist = [\n :username, :email, :password,\n :first_name, :last_name,\n :birthday, :gender,\n :headline, :biography, :ask_about, :focus,\n :website, :facebook, :linkedin, :twitter, :github,\n roles: [],\n skills: [],\n interests: [],\n privacy: { contact: [] },\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:email)\n whitelist.delete(:password)\n end\n \n whitelist\n end", "def allow_params_authentication!; end", "def whitelisted_args\n args.select &:allowed\n end", "def safe_list_sanitizer; end", "def safe_list_sanitizer; end", "def safe_list_sanitizer; end", "def filtered_parameters; end", "def sanitize_params_for user, params, allowed_params\n params.each do |key, val|\n #if allowed_params.include?(key)\n #sanitize!(user, params, key) if key =~ /_attributes|_ids$/\n #else\n #params.delete(key)\n #end\n params.delete(key) unless allowed_params.include?(key.to_sym)\n end\n end", "def strong_params\n params.require(:team_member).permit(param_whitelist)\n end", "def expected_permitted_parameter_names; end", "def sanitize_parameters!(sanitizer, params)\n # replace :readwrite with :onlyif\n if params.has_key?(:readwrite)\n warn \":readwrite is deprecated. Replacing with :onlyif\"\n params[:onlyif] = params.delete(:readwrite)\n end\n\n # add default parameters\n bindata_default_parameters.each do |k,v|\n params[k] = v unless params.has_key?(k)\n end\n\n # ensure mandatory parameters exist\n bindata_mandatory_parameters.each do |prm|\n if not params.has_key?(prm)\n raise ArgumentError, \"parameter ':#{prm}' must be specified \" +\n \"in #{self}\"\n end\n end\n\n # ensure mutual exclusion\n bindata_mutually_exclusive_parameters.each do |param1, param2|\n if params.has_key?(param1) and params.has_key?(param2)\n raise ArgumentError, \"params #{param1} and #{param2} \" +\n \"are mutually exclusive\"\n end\n end\n end", "def strong_params\n params.require(:education).permit(param_whitelist)\n end", "def safe_list_sanitizer=(_arg0); end", "def safe_list_sanitizer=(_arg0); end", "def safe_list_sanitizer=(_arg0); end", "def safe_params\n resurce_name = self.class.resource_name\n params_method_name = \"#{resurce_name}_params\".to_sym\n if params[resurce_name]\n if respond_to?(params_method_name) || private_methods.include?(params_method_name)\n send(params_method_name)\n else\n raise ActiveModel::ForbiddenAttributesError, \"Please, define the '#{params_method_name}' method in #{self.class.name}\"\n end\n end\n end", "def param_whitelist\n [:rating, :review]\n end", "def check_params; true; end", "def strong_params\n params.require(:experience).permit(param_whitelist)\n end", "def validate_search_inputs\n @whitelisted = params.fetch(:user, nil)\n if @whitelisted.blank?\n render_error(400, \"#{I18n.t('general_error.params_missing_key')}\": [I18n.t('general_error.params_missing_value', model: \"review\")])\n return\n else\n @whitelisted = @whitelisted.permit(:name, :uen, :description)\n end\n end", "def allowed?(*_)\n true\n end", "def param_whitelist\n [\n :title,\n :description,\n :organization,\n :team_id,\n :started_at,\n :finished_at,\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n end", "def allowed_params(parameters)\n parameters.select do |name, values|\n values.location != \"path\"\n end\n end", "def secure_params\n return @secure_params if @secure_params\n\n defn = implementation_class.definition\n field_list = [:master_id] + defn.field_list_array\n\n res = params.require(controller_name.singularize.to_sym).permit(field_list)\n res[implementation_class.external_id_attribute.to_sym] = nil if implementation_class.allow_to_generate_ids?\n @secure_params = res\n end", "def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end", "def permitir_parametros\n \t\tparams.permit!\n \tend", "def strong_params\n params.require(:community).permit(param_whitelist)\n end", "def permit( params, whitelist, name = nil )\n raise 'Parametrization not yet configured' unless @configured\n whitelist ||= []\n px = params.respond_to?( :permit ) ? params : ActionController::Parameters.new( params )\n px = dig(px, name)\n px.permit( *whitelist )\n end", "def valid_params?; end", "def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end", "def url_allowlist=(_arg0); end", "def param_whitelist\n whitelist = [\n :description,\n :progress,\n :kpi_id\n ]\n \n unless action_name === 'create'\n whitelist.delete(:kpi_id)\n end\n \n whitelist\n end", "def restricted_params\n #params.require(self.controller_name.classify.underscore.to_sym).permit([])\n raise(\"No strong params set, override restricted_params method in your controller. E.g. params.require(:model).permit(:attribute1, :attribute2)\")\n end", "def list_params\n params.permit(:list_name)\n end", "def valid_params_request?; end", "def safe_params\n params.permit(:id, :name, :origin, :emails => []); #emails is an array\n end", "def param_list(param_type, name, type, required, description = nil, allowed_values = [], hash = {})\n hash.merge!({allowable_values: {value_type: \"LIST\", values: allowed_values}})\n param(param_type, name, type, required, description, hash)\n end", "def safelists; end", "def authorize_own_lists\n authorize_lists current_user.lists\n end", "def listed_params\n params.permit(:listed, :list_id, :listable_id, :listable_type, :campsite_id)\n end", "def lists_params\n params.require(:list).permit(:name)\n\n end", "def list_params\n params.require(:list).permit(:name, :user_id)\n end", "def list_params\n params.require(:list).permit(:name, :description, :type, :privacy, :allow_edit, :rating, :votes_count, :user_id)\n end", "def check_params\n true\n end", "def authorize_own_or_shared_lists\n authorize_lists current_user.all_lists\n end", "def user_pref_list_params\n\t\tparams.require(:user).permit(:preference_list)\n\tend", "def may_contain!(*keys)\n self.allow_only_permitted = true\n self.permitted_keys = [*permitted_keys, *keys].uniq\n end", "def filter_parameters; end", "def filter_parameters; end", "def whitelist; end", "def article_params_whitelist\n params.require(:article).permit(:title, :description, category_ids: [])\n end", "def list_params\n params.require(:list).permit(:name)\n end", "def list_params\n params.permit(:name)\n end", "def recipient_list_params\n params.require(:recipient_list).permit(:name, :list, :references)\n end", "def cancan_parameter_sanitizer\n resource = controller_name.singularize.to_sym\n method = \"#{resource}_params\"\n params[resource] &&= send(method) if respond_to?(method, true)\n end", "def list_params\n params.require(:list).permit(:name).merge(user_id: current_user.id)\n end", "def whitelist_place_params\n params.require(:place).permit(:place_name, :unlock, :auth, :is_deep_checked, :parent_ADM4, :parent_ADM3, :parent_ADM2, :parent_ADM1, :parent_country, feature_code: [], same_as: [], related_authority: [], altlabel: [], note: []) # Note - arrays need to go at the end or an error occurs!\n end", "def list_params\n params.fetch(:list, {}).permit(:user_id, :name, :active)\n end", "def permitted_strong_parameters\n :all #or an array of parameters, example: [:name, :email]\n end", "def secure_params(require_param, permit_keys)\n params.require(require_param).permit(*permit_keys)\n end", "def grant_params\n @whitelisted = params.require(:grant).permit(:name, :description, :agency_id, :acronym)\n end", "def permitted_params\n []\n end", "def price_list_params\n params.fetch(:price_list, {}).permit(:name, :valid_from, :valid_to, :active,\n :all_warehouses, :all_users, :all_contact_groups,\n warehouse_ids: [], price_lists_user_ids: [], contact_group_ids: [])\n end", "def params(list)\n @declared_params = list\n end", "def admin_review_params\n params.fetch(:review, {}).permit(whitelisted_params)\n end", "def saved_list_params\n params.require(:saved_list).permit(:user_id)\n end", "def allow(ids); end", "def list_params\n params.require(:list).permit(:name)\n end", "def list_params\n params.require(:list).permit(:name)\n end", "def list_params\n params.require(:list).permit(:name)\n end", "def filter_params(param_set, **kwargs)\r\n begin\r\n key = kwargs[:key]\r\n params.require(key).permit(*param_set)\r\n rescue Exception\r\n params.permit(*param_set)\r\n end\r\n end", "def valid_parameters\n sort_symbols(@interface.allowed_parameters)\n end", "def validate_paramified_params\n self.class.paramify_methods.each do |method|\n params = send(method)\n transfer_errors_from(params, TermMapper.scope(params.group)) if !params.valid?\n end\n end", "def list_params\n params.require(:list).permit(:name)\n end", "def secure_params\n return @secure_params if @secure_params\n\n @implementation_class = implementation_class\n resname = @implementation_class.name.ns_underscore.gsub('__', '_').singularize.to_sym\n @secure_params = params.require(resname).permit(*permitted_params)\n end", "def refine_permitted_params(param_list)\n res = param_list.dup\n\n ms_keys = res.select { |a| columns_hash[a.to_s]&.array }\n ms_keys.each do |k|\n res.delete(k)\n res << { k => [] }\n end\n\n res\n end", "def recipient_list_params\n params.require(:recipient_list).permit(:name, :description, recipient_id_array: [])\n end", "def safelist; end", "def sponsor_params\n params.require(:sponsor).permit(WHITE_LIST)\n end", "def valid_for_params_auth?; end", "def default_param_whitelist\n [\"mode\"]\n end", "def devise_filter\r\n logger.debug(\"In devise_filter =>PARAMS: #{params.inspect}\")\r\n\r\n # White list for sign_up\r\n devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(user_whitelist) }\r\n\r\n # White list for account update\r\n devise_parameter_sanitizer.for(:account_update) { |u| u.permit(user_whitelist, :current_password) }\r\n\r\n # White list for Invitation creation\r\n devise_parameter_sanitizer.for(:invite) { |u| u.permit(:account_type, :email, :invitation_token)}\r\n\r\n # White list for accept invitation\r\n devise_parameter_sanitizer.for(:accept_invitation) { |u| u.permit(user_whitelist, :invitation_token)}\r\n\r\n end", "def shopping_list_params\n params.require(:shopping_list).permit!\n end", "def permitted_params\n declared(params, include_missing: false)\n end", "def permitted_params\n declared(params, include_missing: false)\n end", "def safe_params\n params.except(:host, :port, :protocol).permit!\n end", "def permitters\n @_parametrizr_permitters || {}\n end", "def allow_params(action, keys: nil, except: nil, &blk)\n keys &&= Array.wrap(keys)\n keys ||= User.field_names\n except &&= Array.wrap(except)\n except ||= %i[id email]\n devise_parameter_sanitizer.permit(action, keys: keys, except: except, &blk)\n end", "def list_params\n if current_user && current_user.role == 'admin'\n params.require(:list).permit(:name, :url, :description, :user_id,\n ideas_attributes: [:id, :list_id, :body, :due_date, :completion_status, :_destroy])\n else\n params.require(:list).permit(:name, :description,\n ideas_attributes: [:body, :due_date, :completion_status]) \n end\n end", "def whitelist(params)\n send_request_of_type(GlobalConstant::PrivateOpsApi.private_ops_api_type, 'post', '/token-sale/whitelist', params)\n end", "def valid_access_params\n params.require(:valid_access).permit(:wish_list_id, :user_id)\n end", "def url_allowlist; end", "def ensure_redirected_params_are_safe!(passed_params)\n unless passed_params.is_a?(ActionController::Parameters) && passed_params.permitted?\n error_message = if passed_params.is_a?(ActionController::Parameters)\n unsafe_parameters = passed_params.send(:unpermitted_keys, params)\n \"[Rails::Prg] Error - Must use permitted strong parameters. Unsafe: #{unsafe_parameters.join(', ')}\"\n else\n \"[Rails::Prg] Error - Must pass strong parameters.\"\n end\n raise error_message\n end\n end", "def data_collection_params\n allow = [:name,:description,:institution,:collection_name,:country_id,:province_id,:city_id]\n params.require(:data_collection).permit(allow)\n end", "def quote_params\n params.permit!\n end" ]
[ "0.69497335", "0.6812623", "0.6803639", "0.6795365", "0.67448795", "0.67399913", "0.6526815", "0.6518771", "0.64931697", "0.6430388", "0.6430388", "0.6430388", "0.63983387", "0.6356042", "0.63535863", "0.63464934", "0.63444513", "0.6337208", "0.6326454", "0.6326454", "0.6326454", "0.63140553", "0.6299814", "0.62642586", "0.626006", "0.62578833", "0.6236823", "0.6227561", "0.6221758", "0.62200165", "0.620879", "0.61983657", "0.6195055", "0.6172993", "0.6156856", "0.61558664", "0.61521494", "0.6135789", "0.6121145", "0.61118174", "0.60736513", "0.6071645", "0.60632104", "0.60549796", "0.6043906", "0.6034662", "0.60207325", "0.6018568", "0.6016575", "0.60103434", "0.60084206", "0.600763", "0.6007443", "0.6003619", "0.6003619", "0.5995791", "0.5993301", "0.5993231", "0.5984926", "0.597122", "0.5968121", "0.5965808", "0.59640145", "0.59632224", "0.59602356", "0.59332967", "0.5927556", "0.5922805", "0.5909745", "0.5905083", "0.5904304", "0.5893434", "0.58888215", "0.58823985", "0.58823985", "0.58823985", "0.5873434", "0.58619875", "0.58533794", "0.5845531", "0.58426666", "0.58360124", "0.583218", "0.5828041", "0.5827927", "0.5816121", "0.5814705", "0.5812719", "0.581121", "0.5803423", "0.5803423", "0.57995003", "0.5794207", "0.5784923", "0.5781365", "0.5776385", "0.5774859", "0.57671493", "0.5766998", "0.57618684", "0.5758038" ]
0.0
-1
GET /relations GET /relations.json
def index if session[:user] != nil if (User.where(name: session[:user]).first).role != 0 me = User.where(name: session[:user]).first @relations = Relation.where('user1_id = ? OR user2_id = ?', me, me) else @relations = Relation.all end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_relations_referring_to_object(type, id)\n api_call_with_type(type, id, \"#{type}/#{id}/relations\")\n end", "def relations\n _relations\n end", "def relations\n _relations\n end", "def relations\n @relations ||= {}\n end", "def get_relation(args)\n\tapi_url = \"#{@base_url}/#{args[:collection]}/#{args[:key]}/relations/#{args[:relation]}\"\n\tdo_the_get_call( url: api_url, user: @user )\nend", "def relations\n @relations ||= process_rels\n end", "def get_relations(service)\n\t\treturn @transport.get_path(\"relations\",service)\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 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 get_relationship_by_id id\n headers = {\n 'Accept' => 'application/json; charset=UTF-8',\n }\n get_request 'relationship/' + id, headers\n end", "def relations\n self.class.relations\n end", "def relations\n return @artist_data[\"relations\"]\n end", "def list_relationships\n end", "def index\n @relations = Relation.all\n end", "def find_relations\n puts '2nd pass: find relations'\n find :relations\n self\n end", "def resource_relations\n @resource_relations ||= Relation.from_links(client,\n decoded_body[:links])\n end", "def show\n @relation = Relation.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @relation }\n end\n end", "def show\n @relation = Relation.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @relation }\n end\n end", "def get_relations\n # Descobrir as relacoes:\n # Orientados\n # Projetos de Pesquisa\n # Producoes Bibliograficas\n # Consultar o RP de cada uma\n # Somar os RPs e retornar\n orientados = self.get_relations_of_orientados\n projetos = self.get_relations_of_projetos_pesquisa\n producoes = self.get_relations_of_producoes_bibliograficas\n\n relations = (orientados | projetos | producoes).delete self.id\n return relations.to_a\n end", "def relations_info\n self::RELATIONS_INFO\n end", "def index\n respond_with Relationships.all\n end", "def get_relation(id)\n get_object('relation', id)\n end", "def relationships(*ids)\n perform_request_with_collection(:get, '/api/v1/accounts/relationships',\n array_param(:id, ids),\n Mastodon::Relationship)\n end", "def relationships\n model.relationships(repository.name)\n end", "def relationships\n @relationships ||= {}\n end", "def relationship\n response[\"relationship\"]\n end", "def related\n request('related')\n end", "def get_relation(id)\n @relations[id.to_i]\n end", "def index\n @relationships = Relationship.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @relationships }\n end\n end", "def related_data\n @resource.related_identifiers.where(verified: true).where(hidden: false).map do |ri|\n { relation: ri.relation_type_friendly&.camelize(:lower), identifier: ri.related_identifier }\n end || []\n end", "def get_user_relationships_info\n id = params[\"id\"]\n error_list = []\n status = 1\n json_response = {}\n user = User.find_by(id: id)\n\n if user.nil?\n error_list.append(\"Error: The specified user doesn't exist.\")\n status = -1\n else\n json_response[\"relationships\"] = user.get_relationship_json_data\n end\n\n if status == -1\n json_response[\"errors\"] = error_list\n end\n\n json_response[\"status\"] = status\n\n # Format the json_response into proper JSON and respond with it\n json_response = json_response.to_json\n\n respond_to do |format|\n format.json { render json: json_response }\n end\n end", "def rels\n @rels ||= root.data._rels\n end", "def relations; enum_relations.to_a end", "def related\n Birdman::Requester.get(\"movies/#{id}/related\")\n end", "def get_relationship user_id\n url = API + \"users/#{user_id}/relationship?access_token=\" + @access_token\n get(url)\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 get_related(**params)\n related = get(\"/related/#{id}.json\", params).body[1]\n client.object_from_body(related)\n end", "def printout_relations\n @relations.each do |shape, relations|\n relations.each do |relation|\n relation.each do |key, value|\n puts \"\\\"#{shape}\\\" #{value} \\\"#{key}\\\"\"\n end\n end\n end\n end", "def get_relations(type, options)\n configure_twitter\n result = case type\n when :follows\n Twitter.friend_ids(options)\n when :followers\n Twitter.follower_ids(options)\n end\n # next_cursor = result.next_cursor\n ids = result.ids\n options[:page] = 0 if options[:page].nil?\n offset = options[:page].to_i * USERS_PER_PAGE\n users = Twitter.users(result.collection[offset, USERS_PER_PAGE+1]).index_by(&:id)\n data = []\n ids.each {|id|\n data << users[id] unless users[id].nil?\n }\n data\n end", "def index\n @relationships = @relationships.order(created_at: :desc).page(params[:page])\n\n respond_to do |format|\n format.html { @relationships = @relationships.includes(:follower, :followed) }\n format.json {}\n end\n end", "def target_relations\n query = \"at:link[@rel = '#{Rel[repository.cmis_version][:relationships]}']/@href\"\n link = data.xpath(query, NS::COMBINED)\n if link.length == 1\n link = Internal::Utils.append_parameters(link.text, \"relationshipDirection\" => \"target\", \"includeSubRelationshipTypes\" => true)\n Collection.new(repository, link)\n else\n raise \"Expected exactly 1 relationships link for #{key}, got #{link.length}, are you sure this is a document/folder?\"\n end\n end", "def related_to(*args)\n@relations = args.map(&:to_s)\nend", "def relations\n Relations::RelationTraverser.new(@internal_node)\n end", "def resource_relations_names\n resource_handler.resource_relations.collect { |_k, v| v[:name].to_sym }\n end", "def relation_params\n _relation_params\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 nices\n Relation.where(relationship: 'nice', related_id: id)\n end", "def new\n @relation = Relation.new\n @personnages = Personnage.all\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @relation }\n end\n end", "def relationships_with_name(input, name)\n input.relations(name)\n end", "def show\n @oma_relation_type = OmaRelationType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @oma_relation_type }\n end\n end", "def contains_relations?\n resource_handler.resource_relations.present?\n end", "def rels\n @traversal_result = :rels\n self\n end", "def source_relations\n query = \"at:link[@rel = '#{Rel[repository.cmis_version][:relationships]}']/@href\"\n link = data.xpath(query, NS::COMBINED)\n if link.length == 1\n link = Internal::Utils.append_parameters(link.text, \"relationshipDirection\" => \"source\", \"includeSubRelationshipTypes\" => true)\n Collection.new(repository, link)\n else\n raise \"Expected exactly 1 relationships link for #{key}, got #{link.length}, are you sure this is a document/folder?\"\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 index\n @relationships = Relationship.all\n end", "def index\n @relationships = Relationship.all\n end", "def relationship_data\n data = @objects.try(:map) { |o| o.try(:relationship_data) }\n data.try(:compact!) || data\n end", "def related(id, options={})\n get_request(\"articles/#{id}/related\", options)\n end", "def index\n @csrelations = Csrelation.all\n end", "def index\n @tag_relations = TagRelation.all\n end", "def read_relation_list(node)\n target_type = Utils.add_namespace(node.attributes['target-type'], Model::NS_REL_1)\n node.elements.each('relation') {|child|\n yield create_relation(child, target_type)\n }\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 jsonapi_relationships\n\t\t\t\t\tjsonapi_model_class.reflect_on_all_associations.collect do |association|\n\t\t\t\t\t\t#type = nil\n\n\t\t\t\t\t\ttype = :to_one if [\n\t\t\t\t\t\t\tActiveRecord::Reflection::HasOneReflection, \n\t\t\t\t\t\t\tActiveRecord::Reflection::BelongsToReflection\n\t\t\t\t\t\t].include? association.class\n\n\t\t\t\t\t\ttype = :to_many if [\n\t\t\t\t\t\t\tActiveRecord::Reflection::HasManyReflection, \n\t\t\t\t\t\t\tActiveRecord::Reflection::HasAndBelongsToManyReflection\n\t\t\t\t\t\t].include? association.class\n\n\t\t\t\t\t\tnext unless type\n\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tname: association.name,\n\t\t\t\t\t\t\ttype: type,\n\t\t\t\t\t\t\treceiver: {\n\t\t\t\t\t\t\t\ttype: association.klass.to_s.underscore.pluralize.to_sym,\n\t\t\t\t\t\t\t\tclass: association.klass.to_s.constantize\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\tend.compact\n\t\t\t\tend", "def owned\n @relations = @user.owned.paginate(page: params[:page], per_page: 10)\n respond_to do |format|\n format.html\n format.amp\n format.json\n format.js\n end\n end", "def show\n\t\t@relation = Relation.find(params[:id])\n\t\trespond_to do |format|\n\t\t\tformat.html # show.html.erb\n\t\t\tformat.xml { render :xml => @relation }\n\t\tend\n\tend", "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 index\n @relationships = Relationship.first\n end", "def relationship_get_all_props id\n headers = {\n 'Accept' => 'application/json; charset=UTF-8',\n }\n get_request 'relationship/' + id + '/properties', headers\n end", "def each_relation\n\t for rel in relations\n\t\tyield(rel)\n\t end\n\tend", "def relations_by_type\n relations = {}\n for i in 0..(self.relations.count-1)\n type = self.relations(i).type.first\n relations[type] ||= []\n relations[type] += self.relations(i).id\n end\n relations\n end", "def jsonapi_received_relationships\n\t\t\t\t\t# Relationship definitions for current model\n\t\t\t\t\trels = jsonapi_relationships\n\n\t\t\t\t\t# Consider only current relationship for relationship actions\n\t\t\t\t\t# (params[:relationship] contains the relationship name)\n\t\t\t\t\tif params[:relationship] \n\n\t\t\t\t\t\trels.select! do |rel|\n\t\t\t\t\t\t\trel[:name].to_sym == params[:relationship].to_sym\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\t# If no relationship is received, then return the definition only\n\t\t\t\t\t\tif request.method == \"GET\"\n\t\t\t\t\t\t\treturn rels.collect do |rel|\n\t\t\t\t\t\t\t\t{definition: rel}\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\n\t\t\t\t\tend\n\n\t\t\t\t\trels.collect do |relationship|\n\t\t\t\t\t\tbegin\n\t\t\t\t\t\t\treceived_params = nil\n\n\t\t\t\t\t\t\t# Relationship action\n\t\t\t\t\t\t\tif params[:relationship]\n\t\t\t\t\t\t\t\treceived_params = params.permit({\n\t\t\t\t\t\t\t\t\tdata: [\n\t\t\t\t\t\t\t\t\t\t:type, :id\n\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t# Object action\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\treceived_params = params.require( \n\t\t\t\t\t\t\t\t\t:data\n\t\t\t\t\t\t\t\t).require(\n\t\t\t\t\t\t\t\t\t:relationships\n\t\t\t\t\t\t\t\t).require(\n\t\t\t\t\t\t\t\t\trelationship[:name]\n\t\t\t\t\t\t\t\t).permit({\n\t\t\t\t\t\t\t\t\tdata: [\n\t\t\t\t\t\t\t\t\t\t:type, :id\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\tend\n\t\t\t\t\t\t\t# => {\"data\"=>{\"type\"=>\"users\", \"id\"=>1}} # sample value for a to-one association\n\t\t\t\t\t\t\t# => {\"data\"=>[{\"type\"=>\"properties\", \"id\"=>1}, {\"type\"=>\"properties\", \"id\"=>2}]} # sample value for a to-many association\n\n\t\t\t\t\t\t\t# is received data conformant to the database schema? \n\t\t\t\t\t\t\tconformant = true\n\t\t\t\t\t\t\tloop do\n\t\t\t\t\t\t\t\t# to-many\n\t\t\t\t\t\t\t\tif received_params[:data].kind_of? Array\n\t\t\t\t\t\t\t\t\tif relationship[:type] != :to_many\n\t\t\t\t\t\t\t\t\t\tconformant = false\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\t\t\treceived_params[:data].each do |item|\n\t\t\t\t\t\t\t\t\t\tnext if item[:type].to_sym == relationship[:receiver][:type]\n\t\t\t\t\t\t\t\t\t\tconformant = false\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\tend\n\n\t\t\t\t\t\t\t\t# to-one\n\t\t\t\t\t\t\t\tif relationship[:type] != :to_one\n\t\t\t\t\t\t\t\t\tconformant = false\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\t\tconformant = false unless received_params[:data][:type].to_sym == relationship[:receiver][:type]\n\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\tnext unless conformant\n\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tdefinition: relationship,\n\t\t\t\t\t\t\t\tparams: received_params\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\trescue ActionController::ParameterMissing => e\n\n\t\t\t\t\t\t\t# nil assignment to to-one relationship?\n\t\t\t\t\t\t\tif relationship[:type] == :to_one\n\t\t\t\t\t\t\t\tbegin\n\t\t\t\t\t\t\t\t\tif params[:relationship] # relationship action\n\t\t\t\t\t\t\t\t\t\treceived_params = params.permit(\n\t\t\t\t\t\t\t\t\t\t\t:data\n\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\treceived_params = params.require( \n\t\t\t\t\t\t\t\t\t\t\t:data\n\t\t\t\t\t\t\t\t\t\t).require(\n\t\t\t\t\t\t\t\t\t\t\t:relationships\n\t\t\t\t\t\t\t\t\t\t).require(\n\t\t\t\t\t\t\t\t\t\t\trelationship[:name]\n\t\t\t\t\t\t\t\t\t\t).permit(\n\t\t\t\t\t\t\t\t\t\t\t:data\n\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\tend\n\n\t\t\t\t\t\t\t\t\t# received nil?\n\t\t\t\t\t\t\t\t\tnext if received_params[:data] # TODO: should return error to client?\n\n\t\t\t\t\t\t\t\t\tnext {\n\t\t\t\t\t\t\t\t\t\tdefinition: relationship,\n\t\t\t\t\t\t\t\t\t\tparams: received_params\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\trescue ActionController::ParameterMissing => e\n\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\tend\n\n\t\t\t\t\t\t\tnil\n\t\t\t\t\t\tend\n\t\t\t\t\tend.compact\n\t\t\t\tend", "def get_relations_hash(project_id = nil, base_ids = nil, sort = false)\n\t\treturn [] if base_ids == []\n\t\tget_relations(project_id, base_ids, sort).as_json\n\tend", "def included_relationship_json(name)\n return if relationships[name].blank? ||\n relationships[name]['data'].blank?\n\n type = relationships[name]['data']['type']\n id = relationships[name]['data']['id']\n included_data = last_result_set.included.data[type]\n return if included_data.blank?\n\n included_data[id.to_i] || included_data[id.to_s]\n end", "def relations_in_holder\n if (@user = User.find_by_id(params[:id]))\n\n if (params[:role] == 'following')\n @relations = Relation.where(:user_id => @user.id)\n else\n @relations = Relation.where(:user_relation_id => @user.id)\n end\n\n respond_to do |format|\n format.html { redirect_to root_path }\n format.js { render }\n end\n\n else\n error404\n end\n end", "def included_relationship_json(name)\n return if relationships[name].blank? ||\n relationships[name]['data'].blank?\n type = relationships[name]['data']['type']\n id = relationships[name]['data']['id']\n included_data = last_result_set.included.data[type]\n return if included_data.blank?\n included_data[id.to_i] || included_data[id.to_s]\n end", "def rels(node)\n @batch_inserter.getRelationships(node)\n end", "def as_jsonld(opts = { related: Ladder::Config.settings[:with_relations] })\n JSON.parse update_resource(opts.slice :related).dump(:jsonld, { standard_prefixes: true }.merge(opts))\n end", "def elastic_relations(relations = [])\n @elastic_relations ||= relations\n end", "def show\n\t\tshow_\n\t\trespond_to do |format|\n\t\t\tformat.html # show.html.erb\n\t\t\tformat.xml { render :xml => @relation }\n\t\tend\n\tend", "def load_relations\n @revisions = @app.\n app_series.\n accessible_revisions(@context).\n select(:title, :id, :uid, :revision, :version)\n\n @notes = @app.\n notes.\n real_notes.\n accessible_by(@context).\n order(id: :desc).\n page(unsafe_params[:notes_page])\n\n @answers = @app.\n notes.\n accessible_by(@context).\n answers.order(id: :desc).\n page(unsafe_params[:answers_page])\n\n @discussions = @app.\n notes.\n accessible_by(@context).\n discussions.\n order(id: :desc).page(unsafe_params[:discussions_page])\n\n @assigned_challenges = Challenge.\n where(app_id: @app.id).\n order(created_at: :desc)\n\n @assignable_challenges = Challenge.\n all.\n order(created_at: :desc).\n select { |c| c.can_assign_specific_app?(@context, @app) }\n end", "def relationships\n @relationships ||= Relationship.from_associations(self, associations)\n end", "def index\n @references = Reference.all\n\n render json: @references\n end", "def load_relations\n relations = Relation.registry(gateways, relation_classes)\n RelationRegistry.new(relations)\n end", "def relationships\n return [] if empty?\n\n map { |table| Relationship.new(table, TABLE_R, \"../#{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 path_rels(*args)\n options = args.extract_options!\n rel = relationship(:raise_on_multiple => true) # TODO: Handle multiple nodes with a way to detect which node you want\n rels = rel.nil? ? [relationship_for_isolated_root] : rel.path\n Relationship.filter_by_resource_type(rels, options)\n end", "def decorate_relations(attributes = {}, options = {})\n inclusions = options[:decorated_include]\n relation_names(inclusions).each do |name|\n metadata = relations[name.to_s]\n relation = send(metadata.name)\n if relation\n attributes[metadata.name.to_s] =\n relation.as_json(relation_options(inclusions, options, name))\n end\n end\n end", "def index\n @expression_relationships = ExpressionRelationship.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @expression_relationships }\n end\n end", "def model_relationships; end", "def index\n @tag_relationships = TagRelationship.all\n end", "def index_relations(exclude_relations: []); end", "def all\n @data_adapter.relations\n end", "def index\n @reforganism = Reforganism.find(params[:id])\n @referents = @reforganism.referents\n end", "def links\n json_hyperschema[\"links\"] || []\n end", "def show\n @relation = Relation.find(params[:id])\n return redirect_to root_url, notice: \"Vous n'avez pas accès à cette ressource.\" if !permition?(@user, @relation)\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @relation }\n end\n end", "def new\n @relation = Relation.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @relation }\n end\n end", "def id\n _relation_json.fetch(\"id\", nil)\n end", "def index\n @npc_relations = @campaign.npc_relations\n end", "def relation\n\t\tbegin\n\t\t\tRelation.find(relation_id)\n\t\trescue Exception => e\n\t\t\tfname= \"#{self.class.name}.#{__method__}\"\n\t\t\tLOG.error (fname) {\"relation not found:#{e}\"}\n\t\t\tnil\n\t\tend\n\tend", "def child_rels(*args)\n options = args.extract_options!\n rels = relationships.flat_map(&:children).uniq\n Relationship.filter_by_resource_type(rels, options)\n end" ]
[ "0.76649773", "0.73452705", "0.73452705", "0.7206631", "0.71788263", "0.71153605", "0.7097382", "0.7040563", "0.6891425", "0.6833073", "0.67859524", "0.67443615", "0.67295223", "0.6718496", "0.67149585", "0.6706494", "0.6630044", "0.6630044", "0.65891963", "0.6551609", "0.6504556", "0.6460412", "0.64276874", "0.6412114", "0.63388926", "0.6287125", "0.62663484", "0.6216514", "0.6168323", "0.61676854", "0.61280173", "0.6118223", "0.6106489", "0.6084467", "0.6074811", "0.6055509", "0.6050293", "0.602468", "0.6011381", "0.5991455", "0.59866405", "0.59864444", "0.59686804", "0.59357446", "0.5933539", "0.5907963", "0.590454", "0.58910066", "0.5885805", "0.5872327", "0.5867728", "0.586513", "0.5860737", "0.58379096", "0.58250266", "0.58250266", "0.58157814", "0.58154166", "0.58069855", "0.58038056", "0.5794881", "0.5781947", "0.5775818", "0.57685995", "0.5757346", "0.5744829", "0.57347834", "0.5720016", "0.5719472", "0.5714928", "0.5713099", "0.57118124", "0.5711523", "0.5710025", "0.5707771", "0.5696254", "0.569607", "0.5681123", "0.56596375", "0.5653798", "0.5643673", "0.56322795", "0.5618944", "0.5611437", "0.5603618", "0.5585374", "0.5580078", "0.5571702", "0.55667084", "0.5566647", "0.55651385", "0.5564318", "0.55643076", "0.5561561", "0.5558837", "0.5543131", "0.55418074", "0.5540766", "0.55345696", "0.55262536", "0.55198044" ]
0.0
-1
GET /relations/1 GET /relations/1.json
def show end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_relations_referring_to_object(type, id)\n api_call_with_type(type, id, \"#{type}/#{id}/relations\")\n end", "def get_relation(args)\n\tapi_url = \"#{@base_url}/#{args[:collection]}/#{args[:key]}/relations/#{args[:relation]}\"\n\tdo_the_get_call( url: api_url, user: @user )\nend", "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 show\n @relation = Relation.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @relation }\n end\n end", "def show\n @relation = Relation.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @relation }\n end\n end", "def get_relations_from_api(api=Rosemary::API.new)\n api.get_relations_referring_to_object(type, self.id.to_i)\n end", "def get_relation(id)\n get_object('relation', id)\n end", "def get_relations(service)\n\t\treturn @transport.get_path(\"relations\",service)\n\tend", "def index\n @relations = Relation.all\n end", "def get_relation(id)\n @relations[id.to_i]\n end", "def relations\n _relations\n end", "def relations\n _relations\n end", "def relations\n @relations ||= {}\n end", "def find_relations\n puts '2nd pass: find relations'\n find :relations\n self\n end", "def relations\n @relations ||= process_rels\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 show\n @oma_relation_type = OmaRelationType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @oma_relation_type }\n end\n end", "def index\n respond_with Relationships.all\n end", "def index\n @relationships = Relationship.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @relationships }\n end\n end", "def relationship\n response[\"relationship\"]\n end", "def relations\n return @artist_data[\"relations\"]\n end", "def show\n\t\t@relation = Relation.find(params[:id])\n\t\trespond_to do |format|\n\t\t\tformat.html # show.html.erb\n\t\t\tformat.xml { render :xml => @relation }\n\t\tend\n\tend", "def related\n request('related')\n end", "def related\n Birdman::Requester.get(\"movies/#{id}/related\")\n end", "def get_related(**params)\n related = get(\"/related/#{id}.json\", params).body[1]\n client.object_from_body(related)\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 get_relationship user_id\n url = API + \"users/#{user_id}/relationship?access_token=\" + @access_token\n get(url)\n end", "def list_relationships\n end", "def new\n @relation = Relation.new\n @personnages = Personnage.all\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @relation }\n end\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 index\n @relationships = Relationship.first\n end", "def id\n _relation_json.fetch(\"id\", nil)\n end", "def relations\n self.class.relations\n end", "def relations_info\n self::RELATIONS_INFO\n end", "def new\n @relation = Relation.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @relation }\n end\n end", "def nices\n Relation.where(relationship: 'nice', related_id: id)\n end", "def resource_relations\n @resource_relations ||= Relation.from_links(client,\n decoded_body[:links])\n end", "def get_user_relationships_info\n id = params[\"id\"]\n error_list = []\n status = 1\n json_response = {}\n user = User.find_by(id: id)\n\n if user.nil?\n error_list.append(\"Error: The specified user doesn't exist.\")\n status = -1\n else\n json_response[\"relationships\"] = user.get_relationship_json_data\n end\n\n if status == -1\n json_response[\"errors\"] = error_list\n end\n\n json_response[\"status\"] = status\n\n # Format the json_response into proper JSON and respond with it\n json_response = json_response.to_json\n\n respond_to do |format|\n format.json { render json: json_response }\n end\n end", "def show\n\t\tshow_\n\t\trespond_to do |format|\n\t\t\tformat.html # show.html.erb\n\t\t\tformat.xml { render :xml => @relation }\n\t\tend\n\tend", "def show\n @relation = Relation.find(params[:id])\n return redirect_to root_url, notice: \"Vous n'avez pas accès à cette ressource.\" if !permition?(@user, @relation)\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @relation }\n end\n end", "def included_relationship_json(name)\n return if relationships[name].blank? ||\n relationships[name]['data'].blank?\n\n type = relationships[name]['data']['type']\n id = relationships[name]['data']['id']\n included_data = last_result_set.included.data[type]\n return if included_data.blank?\n\n included_data[id.to_i] || included_data[id.to_s]\n end", "def relationships(*ids)\n perform_request_with_collection(:get, '/api/v1/accounts/relationships',\n array_param(:id, ids),\n Mastodon::Relationship)\n end", "def included_relationship_json(name)\n return if relationships[name].blank? ||\n relationships[name]['data'].blank?\n type = relationships[name]['data']['type']\n id = relationships[name]['data']['id']\n included_data = last_result_set.included.data[type]\n return if included_data.blank?\n included_data[id.to_i] || included_data[id.to_s]\n end", "def index\n @relationships = @relationships.order(created_at: :desc).page(params[:page])\n\n respond_to do |format|\n format.html { @relationships = @relationships.includes(:follower, :followed) }\n format.json {}\n end\n end", "def related(id, options={})\n get_request(\"articles/#{id}/related\", options)\n end", "def index\n @relationships = Relationship.all\n end", "def index\n @relationships = Relationship.all\n end", "def one_relationship(name)\n end", "def relation\n\t\tbegin\n\t\t\tRelation.find(relation_id)\n\t\trescue Exception => e\n\t\t\tfname= \"#{self.class.name}.#{__method__}\"\n\t\t\tLOG.error (fname) {\"relation not found:#{e}\"}\n\t\t\tnil\n\t\tend\n\tend", "def relationships\n model.relationships(repository.name)\n end", "def show\n begin\n @resource = get_relation(params[:id], params[:entity_id])\n render :response => :GET\n rescue Exception => e\n @error = process_exception(e)\n render :response => @error\n end\n \n \n\n end", "def relationship(*args)\n options = args.extract_options!\n if options[:raise_on_multiple]\n rels = relationships.take(2)\n raise _(\"Multiple relationships found\") if rels.length > 1\n rels.first\n else\n relationships.first\n end\n end", "def related_to(*args)\n@relations = args.map(&:to_s)\nend", "def get_relations\n # Descobrir as relacoes:\n # Orientados\n # Projetos de Pesquisa\n # Producoes Bibliograficas\n # Consultar o RP de cada uma\n # Somar os RPs e retornar\n orientados = self.get_relations_of_orientados\n projetos = self.get_relations_of_projetos_pesquisa\n producoes = self.get_relations_of_producoes_bibliograficas\n\n relations = (orientados | projetos | producoes).delete self.id\n return relations.to_a\n end", "def relationships\n @relationships ||= {}\n end", "def relationships_with_name(input, name)\n input.relations(name)\n end", "def jsonapi_received_relationships\n\t\t\t\t\t# Relationship definitions for current model\n\t\t\t\t\trels = jsonapi_relationships\n\n\t\t\t\t\t# Consider only current relationship for relationship actions\n\t\t\t\t\t# (params[:relationship] contains the relationship name)\n\t\t\t\t\tif params[:relationship] \n\n\t\t\t\t\t\trels.select! do |rel|\n\t\t\t\t\t\t\trel[:name].to_sym == params[:relationship].to_sym\n\t\t\t\t\t\tend\n\n\t\t\t\t\t\t# If no relationship is received, then return the definition only\n\t\t\t\t\t\tif request.method == \"GET\"\n\t\t\t\t\t\t\treturn rels.collect do |rel|\n\t\t\t\t\t\t\t\t{definition: rel}\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\n\t\t\t\t\tend\n\n\t\t\t\t\trels.collect do |relationship|\n\t\t\t\t\t\tbegin\n\t\t\t\t\t\t\treceived_params = nil\n\n\t\t\t\t\t\t\t# Relationship action\n\t\t\t\t\t\t\tif params[:relationship]\n\t\t\t\t\t\t\t\treceived_params = params.permit({\n\t\t\t\t\t\t\t\t\tdata: [\n\t\t\t\t\t\t\t\t\t\t:type, :id\n\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t# Object action\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\treceived_params = params.require( \n\t\t\t\t\t\t\t\t\t:data\n\t\t\t\t\t\t\t\t).require(\n\t\t\t\t\t\t\t\t\t:relationships\n\t\t\t\t\t\t\t\t).require(\n\t\t\t\t\t\t\t\t\trelationship[:name]\n\t\t\t\t\t\t\t\t).permit({\n\t\t\t\t\t\t\t\t\tdata: [\n\t\t\t\t\t\t\t\t\t\t:type, :id\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\tend\n\t\t\t\t\t\t\t# => {\"data\"=>{\"type\"=>\"users\", \"id\"=>1}} # sample value for a to-one association\n\t\t\t\t\t\t\t# => {\"data\"=>[{\"type\"=>\"properties\", \"id\"=>1}, {\"type\"=>\"properties\", \"id\"=>2}]} # sample value for a to-many association\n\n\t\t\t\t\t\t\t# is received data conformant to the database schema? \n\t\t\t\t\t\t\tconformant = true\n\t\t\t\t\t\t\tloop do\n\t\t\t\t\t\t\t\t# to-many\n\t\t\t\t\t\t\t\tif received_params[:data].kind_of? Array\n\t\t\t\t\t\t\t\t\tif relationship[:type] != :to_many\n\t\t\t\t\t\t\t\t\t\tconformant = false\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\t\t\treceived_params[:data].each do |item|\n\t\t\t\t\t\t\t\t\t\tnext if item[:type].to_sym == relationship[:receiver][:type]\n\t\t\t\t\t\t\t\t\t\tconformant = false\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\tend\n\n\t\t\t\t\t\t\t\t# to-one\n\t\t\t\t\t\t\t\tif relationship[:type] != :to_one\n\t\t\t\t\t\t\t\t\tconformant = false\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\t\tconformant = false unless received_params[:data][:type].to_sym == relationship[:receiver][:type]\n\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\tnext unless conformant\n\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tdefinition: relationship,\n\t\t\t\t\t\t\t\tparams: received_params\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\trescue ActionController::ParameterMissing => e\n\n\t\t\t\t\t\t\t# nil assignment to to-one relationship?\n\t\t\t\t\t\t\tif relationship[:type] == :to_one\n\t\t\t\t\t\t\t\tbegin\n\t\t\t\t\t\t\t\t\tif params[:relationship] # relationship action\n\t\t\t\t\t\t\t\t\t\treceived_params = params.permit(\n\t\t\t\t\t\t\t\t\t\t\t:data\n\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\treceived_params = params.require( \n\t\t\t\t\t\t\t\t\t\t\t:data\n\t\t\t\t\t\t\t\t\t\t).require(\n\t\t\t\t\t\t\t\t\t\t\t:relationships\n\t\t\t\t\t\t\t\t\t\t).require(\n\t\t\t\t\t\t\t\t\t\t\trelationship[:name]\n\t\t\t\t\t\t\t\t\t\t).permit(\n\t\t\t\t\t\t\t\t\t\t\t:data\n\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\tend\n\n\t\t\t\t\t\t\t\t\t# received nil?\n\t\t\t\t\t\t\t\t\tnext if received_params[:data] # TODO: should return error to client?\n\n\t\t\t\t\t\t\t\t\tnext {\n\t\t\t\t\t\t\t\t\t\tdefinition: relationship,\n\t\t\t\t\t\t\t\t\t\tparams: received_params\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\trescue ActionController::ParameterMissing => e\n\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\tend\n\n\t\t\t\t\t\t\tnil\n\t\t\t\t\t\tend\n\t\t\t\t\tend.compact\n\t\t\t\tend", "def related_data\n @resource.related_identifiers.where(verified: true).where(hidden: false).map do |ri|\n { relation: ri.relation_type_friendly&.camelize(:lower), identifier: ri.related_identifier }\n end || []\n end", "def show\n @relationship = Relationship.find(params[:id])\n end", "def show\n @comment_relationship = CommentRelationship.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @comment_relationship }\n end\n end", "def [](name)\n relations.fetch(name)\n end", "def show\n @through_reference = ThroughReference.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @through_reference }\n end\n end", "def show\n\t\tid = params[:id]\n\t\tlang = params[:lang] || I18n.locale\n\n\t\tif is_a_number?(id)\n\t\t\tmodel = entity.with_relationships.find_by(id: params[:id])\n\t\telse\n\t\t\tmodel = entity.with_relationships.lang(lang).find_by(slug: params[:id])\n\t\tend\n\n\t\trender json: model.to_json(:except => [:keywords],\n\t\t\t:include => [\n\t\t\t\t:translations,\n\t\t\t\t:translation,\n\t\t\t\t{:categories => {:except => [:description]} },\n\t\t\t\t:lawyers,\n\t\t\t\t:gallery\n\t\t])\n\n\tend", "def set_relation\n @relation = Relation.find(params[:id])\n end", "def load_type\n :relation\n end", "def relations; enum_relations.to_a end", "def relationship_get_property id, name\n headers = {\n 'Accept' => 'application/json; charset=UTF-8',\n }\n\n get_request 'relationship/' + id + '/properties/' + name, headers\n end", "def new\n @relation = Relation.new(user_id: session[:user_id])\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @relation }\n end\n end", "def _load_relation name\n relation = self.relations.select { |rel| rel.name == name }.first\n if relation.type == :has_many\n _load_has_many relation\n elsif relation.type == :belongs_to\n _load_belongs_to relation\n else\n raise \"Unkown relation type\"\n end\n end", "def as_jsonld(opts = { related: Ladder::Config.settings[:with_relations] })\n JSON.parse update_resource(opts.slice :related).dump(:jsonld, { standard_prefixes: true }.merge(opts))\n end", "def get_relation(relation_id, entity_id = nil)\n if entity_id\n relation = Relation.find(:first, :conditions => \n [\"id = ? and child_id = ? or parent_id = ?\", relation_id, entity_id, entity_id])\n else\n relation = Relation.find(:first, :conditions => \n [\"id = ?\", relation_id])\n end\n return relation\n end", "def index\n @expression_relationships = ExpressionRelationship.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @expression_relationships }\n end\n end", "def relation_params\n _relation_params\n end", "def owned\n @relations = @user.owned.paginate(page: params[:page], per_page: 10)\n respond_to do |format|\n format.html\n format.amp\n format.json\n format.js\n end\n end", "def set_relation\n @relation = Relation.find(params[:id])\n end", "def set_relation\n @relation = Relation.find(params[:id])\n end", "def related(r)\n relation_set(r).first\n end", "def index\n @relationships = Relationship.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @relationships }\n end\n end", "def index\n @csrelations = Csrelation.all\n end", "def rels\n @rels ||= root.data._rels\n end", "def show\n @expression_relationship = ExpressionRelationship.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @expression_relationship }\n end\n end", "def printout_relations\n @relations.each do |shape, relations|\n relations.each do |relation|\n relation.each do |key, value|\n puts \"\\\"#{shape}\\\" #{value} \\\"#{key}\\\"\"\n end\n end\n end\n end", "def destroy\n @relation = Relation.find(params[:id])\n @relation.destroy\n\n respond_to do |format|\n format.html { redirect_to relations_url }\n format.json { head :no_content }\n end\n end", "def show\n @expression_relationship_type = ExpressionRelationshipType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @expression_relationship_type }\n end\n end", "def get_relations(type, options)\n configure_twitter\n result = case type\n when :follows\n Twitter.friend_ids(options)\n when :followers\n Twitter.follower_ids(options)\n end\n # next_cursor = result.next_cursor\n ids = result.ids\n options[:page] = 0 if options[:page].nil?\n offset = options[:page].to_i * USERS_PER_PAGE\n users = Twitter.users(result.collection[offset, USERS_PER_PAGE+1]).index_by(&:id)\n data = []\n ids.each {|id|\n data << users[id] unless users[id].nil?\n }\n data\n end", "def relation(*fields)\n inline_keys = fields.extract_options!\n if api_response?\n fields.each do |column|\n raise ArgumentError, \"You specify relation with `_id` on the end.\" if column.end_with?(\"_id\")\n\n property column, inline_keys do\n key :type, \"object\"\n key :readOnly, true\n property \"id\", type: \"integer\"\n property \"name\", type: \"string\"\n end\n end\n else\n fields.each do |column|\n property \"#{column}_id\", inline_keys do\n key :type, \"integer\"\n end\n end\n end\n end", "def source_relations\n query = \"at:link[@rel = '#{Rel[repository.cmis_version][:relationships]}']/@href\"\n link = data.xpath(query, NS::COMBINED)\n if link.length == 1\n link = Internal::Utils.append_parameters(link.text, \"relationshipDirection\" => \"source\", \"includeSubRelationshipTypes\" => true)\n Collection.new(repository, link)\n else\n raise \"Expected exactly 1 relationships link for #{key}, got #{link.length}, are you sure this is a document/folder?\"\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.xml { render :xml => @relationship }\n end\n end", "def index\n @relatories = Relatory.all\n end", "def relationship_links(source)\n {}\n end", "def index\n @references = Reference.all\n\n render json: @references\n end", "def index\n @reforganism = Reforganism.find(params[:id])\n @referents = @reforganism.referents\n end", "def relations_in_holder\n if (@user = User.find_by_id(params[:id]))\n\n if (params[:role] == 'following')\n @relations = Relation.where(:user_id => @user.id)\n else\n @relations = Relation.where(:user_relation_id => @user.id)\n end\n\n respond_to do |format|\n format.html { redirect_to root_path }\n format.js { render }\n end\n\n else\n error404\n end\n end", "def relationship_get_all_props id\n headers = {\n 'Accept' => 'application/json; charset=UTF-8',\n }\n get_request 'relationship/' + id + '/properties', headers\n end", "def relation\n Proxy\n end", "def relation\n Proxy\n end", "def relation\n Proxy\n end", "def index\n @relationships = @character.relationships.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @relationships }\n end\n end", "def read_relation_list(node)\n target_type = Utils.add_namespace(node.attributes['target-type'], Model::NS_REL_1)\n node.elements.each('relation') {|child|\n yield create_relation(child, target_type)\n }\n end", "def relation_params\n params.require(:relation).permit(:user_id, :friend_id)\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" ]
[ "0.7504887", "0.73537993", "0.720369", "0.7179545", "0.7179545", "0.6951257", "0.68535554", "0.6713202", "0.6704042", "0.6693183", "0.6654969", "0.6654969", "0.6635389", "0.65769684", "0.65248525", "0.6416955", "0.6393167", "0.6384109", "0.6350153", "0.6346643", "0.6325167", "0.6317032", "0.62741274", "0.6243522", "0.62418115", "0.6236963", "0.6213532", "0.6211326", "0.6206255", "0.620447", "0.61989", "0.61721635", "0.6128931", "0.61111945", "0.60775733", "0.6058222", "0.6057302", "0.60450745", "0.60380864", "0.6016913", "0.5967071", "0.59618866", "0.5956582", "0.5939087", "0.5933986", "0.5918768", "0.5918768", "0.5917354", "0.59166545", "0.59038055", "0.5898577", "0.5897726", "0.58800423", "0.587687", "0.58762246", "0.5872336", "0.58575755", "0.5825053", "0.58048624", "0.5803026", "0.5797056", "0.579399", "0.5792385", "0.57588345", "0.574511", "0.5732331", "0.5730715", "0.5730665", "0.57251483", "0.5721014", "0.56914234", "0.5680452", "0.5679426", "0.567549", "0.5660836", "0.5660836", "0.5658205", "0.5657326", "0.56449854", "0.5636667", "0.562906", "0.5612418", "0.5610417", "0.56012845", "0.5596945", "0.5593508", "0.55926955", "0.55886143", "0.5579609", "0.55792385", "0.5578745", "0.5578712", "0.5573721", "0.5570793", "0.5545336", "0.5545336", "0.5545336", "0.55444366", "0.553708", "0.5534762", "0.5523764" ]
0.0
-1
POST /relations POST /relations.json
def create @relation = Relation.new(relation_params) name1 = @relation.user1_id name2 = @relation.user2_id user1 = User.where(name: name1).first user2 = User.where(name: name2).first @relation = Relation.create(user1_id: user1.id, user2_id: user2.id, status: 0) respond_to do |format| if @relation.save format.html { redirect_to @relation, notice: 'Relation was successfully created.' } format.json { render :show, status: :created, location: @relation } else format.html { render :new } format.json { render json: @relation.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add_relation\n #add relation\n @word.word_roots.create(@word_root)\n respond_to do |format|\n format.js\n end\n end", "def relation_params\n params.require(:relation).permit(:user_id, :friend_id)\n end", "def create\n @relation = Relation.new(relation_params)\n\n respond_to do |format|\n if @relation.save\n format.html { redirect_to edit_relation_path(@relation), notice: 'Relation was successfully created.' }\n format.json { render :show, status: :created, location: @relation }\n else\n format.html { render :new }\n format.json { render json: @relation.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @relation = Relation.new(params[:relation])\n\n respond_to do |format|\n if @relation.save\n format.html { redirect_to \"/users/#{session[:user_id]}\", notice: 'Relation was successfully created.' }\n format.json { render json: @relation, status: :created, location: @relation }\n else\n format.html { render action: \"new\" }\n format.json { render json: @relation.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @tag_relation = TagRelation.new(tag_relation_params)\n\n respond_to do |format|\n if @tag_relation.save\n format.html { redirect_to @tag_relation, notice: 'Tag relation was successfully created.' }\n format.json { render :show, status: :created, location: @tag_relation }\n else\n format.html { render :new }\n format.json { render json: @tag_relation.errors, status: :unprocessable_entity }\n end\n end\n end", "def relation_params\n params.require(:relation).permit(:document_id, :type, :nodes, :ref_id, :order_no)\n end", "def get_relations_referring_to_object(type, id)\n api_call_with_type(type, id, \"#{type}/#{id}/relations\")\n end", "def attach_relationship(data) #FIXME: Method doesn't work, RelationshipManager cannot access to id attribute.\n return @client.raw(\"post\", \"/config/relationships/attach\", nil, data)\n end", "def save_relations(relations)\n current_relations = sobject.relations_as_from\n added_relations = []\n unless relations.nil?\n elements = relations.split(\",\")\n elements.each do |element|\n to_sobject_id = element.split(\"-\")[0]\n relation_id = element.split(\"-\")[1]\n added_relations << add_relation_unless(to_sobject_id,relation_id)\n end\n end\n # remove removed relationships\n (current_relations - added_relations).each { |relation| relation.destroy }\n # fix positions\n added_relations.each_with_index { |relation,index| relation.update_attribute :position, index if relation.valid? }\n end", "def create\n @relation = Relation.new(params[:relation])\n @relation.secret = false if !@user.admin?\n respond_to do |format|\n if @relation.save\n format.html { redirect_to @relation, notice: 'Relation a été crée avec succès.' }\n format.json { render json: @relation, status: :created, location: @relation }\n else\n format.html { render action: \"new\" }\n format.json { render json: @relation.errors, status: :unprocessable_entity }\n end\n end\n end", "def get_or_create_relationship(conn, node_start, node_end, type)\n data = <<\"EOS\"\n{\n \"to\" : \"#{node_end}\",\n \"max_depth\" : 1,\n \"relationships\" : {\n \"type\" : \"#{type}\",\n \"direction\" : \"out\"\n },\n \"algorithm\" : \"shortestPath\"\n}\nEOS\n r = conn.post(\"#{node_start}/paths\", data, HEADER)\n length = (JSON.parse(r.body).first || {})['length'] if r.status == 200\n if length != 1\n conn.post(\"#{node_start}/relationships\", JSON.unparse({ :to => node_end, :type => type }), HEADER)\n $load_r += 1\n else\n $skip_r += 1\n end\nend", "def relations\n @relations ||= {}\n end", "def relation_params\n params.require(:relation).permit(:user1_id, :user2_id, :status)\n end", "def create\n begin\n @resource = Relation.new(params[:relation])\n @resource.save!\n render :response => :POST\n rescue Exception => e\n @error = process_exception(e)\n render :response => :error\n end\n \n \n \n end", "def create \n if InfoNode.duplicate_key?(params[:info_types])\n redirect_to :back, :alert => \"Key in the additional information shoud be unique\"\n return\n end\n\n unless params[:rid].nil?\n @rid = params[:rid].strip\n end\n\n @type = params[:type] \n\n @refs = []\n\n params[:refids].each_with_index do |ref_id, idx|\n @refs << {:ref_id => ref_id, :role => params[:labels][idx]}\n end unless params[:refids].nil?\n\n if @refs.empty?\n redirect_to :back, :alert => \"Please add references for a new relation\"\n return\n end\n\n @info_nodes = {}\n (0...params[:info_types].size).each do |i|\n key = params[:info_types][i]\n value = params[:info_values][i]\n if !key.nil? && !key.strip.blank? && !value.nil? && !value.strip.blank?\n @info_nodes[key] = value\n end\n end\n\n begin\n @collection = current_user.collections.find(params[:collection_id])\n raise \"Cannot find the collection No. #{params[:collection_id]}\" if @collection.nil?\n \n @document = @collection.documents.find_by_pmid(params[:document_id])\n raise \"Cannot find the document No. #{params[:document_id]}\" if @document.nil?\n \n @rid = @document.create_new_relation_id if @rid.blank?\n \n @relation = @document.create_relation(@rid, @type, @refs, @info_nodes)\n\n respond_to do |format|\n format.html { redirect_to \"/collections/#{@collection.id}/documents/#{@document.pmid}?tab=relation\", :notice => 'Relation was successfully created.' }\n format.json { render :json => @relation, :status => :created, :location => @relation }\n end\n rescue Exception => e\n logger.debug(e.backtrace)\n respond_to do |format|\n format.html { redirect_to :back, :alert => e.message}\n format.json { render json: @relation.errors, status: :unprocessable_entity }\n end\n end\n end", "def relationship_params\n params.require(:relationship).permit(:character_id, :relative_id, :relation_type)\n end", "def create\n @item = Item.new(params[:item])\n\n get_relations_from_params\n\n respond_to do |format|\n if @item.save\n format.html { redirect_to @item, notice: 'Item was successfully created.' }\n format.json { render json: @item, status: :created }\n else\n format.html { render action: \"new\" }\n format.json { render json: @item.errors, status: :unprocessable_entity }\n end\n end\n end", "def add_relationship(rel_attr); 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_task_relation(opts={})\n visit '/task_relations/new'\n if opts[:public]\n check 'public'\n end\n\n click_button 'Nova lista de tarefas'\n expect(page).to have_content 'Lista de tarefa salva.'\n end", "def rel(rels)\n # rel must be an array.\n data[:rel] = Array(rels)\n end", "def process_relations\n pending_relations.each_pair do |name, value|\n association = relations[name]\n if value.is_a?(Hash)\n association.nested_builder(value, {}).build(self)\n else\n send(\"#{name}=\", value)\n end\n end\n end", "def put_relation(args)\n\tapi_url = \"#{@base_url}/#{args[:coll_A]}/#{args[:key_A]}/relation/\" +\n\t \"#{args[:relation]}/#{args[:coll_B]}/#{key_B}\"\n\tputs do_the_put_call( url: api_url, user: @user, json: '{}')\nend", "def relation_params\n params.require(:relation).permit(:link_id, :ally_id, :candidate_id, :relation_type_id,link_attributes: [:title,:content,:journal,:author,:url])\n end", "def relations\n @relations ||= process_rels\n end", "def new\n @relation = Relation.new\n @personnages = Personnage.all\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @relation }\n end\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 new_relations_data(personality)\n new_relations_data = {}\n new_relations_data[:personality_id] = personality.id\n new_relations_data[:related_content_data] = personality.content\n new_relations_data\n end", "def relation_type_params\n params.require(:relation_type).permit(:name, :color, :num_nodes, :project_id, :entity_type => [])\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 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 create\n @tag_relationship = TagRelationship.new(tag_relationship_params)\n\n respond_to do |format|\n if @tag_relationship.save\n format.html { redirect_to @tag_relationship, notice: 'Tag relationship was successfully created.' }\n format.json { render action: 'show', status: :created, location: @tag_relationship }\n else\n format.html { render action: 'new' }\n format.json { render json: @tag_relationship.errors, status: :unprocessable_entity }\n end\n end\n end", "def op_add_relation!(field, objects = [])\n objects = [objects] unless objects.is_a?(Array)\n return false if objects.empty?\n relation_action = Parse::RelationAction.new(field, polarity: true, objects: objects)\n operate_field! field, relation_action\n end", "def relationship_params\n params.require(:relationship).permit(:donor_id, :target, :link_description)\n end", "def new\n @relation = Relation.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @relation }\n end\n end", "def create\n @npc_relation = NpcRelation.new(npc_relation_params)\n\n respond_to do |format|\n if @npc_relation.save\n format.html { redirect_to @npc_relation, notice: 'Npc relation was successfully created.' }\n format.json { render :show, status: :created, location: @npc_relation }\n else\n format.html { render :new }\n format.json { render json: @npc_relation.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_field_rel(params)\n post('fieldRels', fieldRel: params)\n end", "def create_relation(ways_list)\n puts 'Creating relation...'\n relation = Rosemary::Relation.new(visible: 'true')\n ways_list.each do |way_id|\n relation.members << Rosemary::Member.new('way', way_id)\n end\n relation.add_tags(route: 'bus', type: 'route')\n relation\n 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 create\n @public_relation = PublicRelation.new(public_relation_params)\n\n respond_to do |format|\n if @public_relation.save\n format.html { redirect_to @public_relation, notice: 'Public relation was successfully created.' }\n format.json { render :show, status: :created, location: @public_relation }\n else\n format.html { render :new }\n format.json { render json: @public_relation.errors, status: :unprocessable_entity }\n end\n end\n end", "def add_relationship ( user , country_list, rel_type )\n country_list.each do |country_node|\n rel_instance = get_rel_instance rel_type\n rel_instance.from_node = user\n rel_instance.to_node = country_node\n rel_instance.save\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 related_to(*args)\n@relations = args.map(&:to_s)\nend", "def relations\n _relations\n end", "def relations\n _relations\n end", "def relationships\n @relationships ||= {}\n end", "def target_relations\n query = \"at:link[@rel = '#{Rel[repository.cmis_version][:relationships]}']/@href\"\n link = data.xpath(query, NS::COMBINED)\n if link.length == 1\n link = Internal::Utils.append_parameters(link.text, \"relationshipDirection\" => \"target\", \"includeSubRelationshipTypes\" => true)\n Collection.new(repository, link)\n else\n raise \"Expected exactly 1 relationships link for #{key}, got #{link.length}, are you sure this is a document/folder?\"\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 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 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 @csrelation = Csrelation.new(csrelation_params)\n\n respond_to do |format|\n if @csrelation.save\n format.html { redirect_to @csrelation, notice: 'Csrelation was successfully created.' }\n format.json { render :show, status: :created, location: @csrelation }\n else\n format.html { render :new }\n format.json { render json: @csrelation.errors, status: :unprocessable_entity }\n end\n end\n end", "def relation_params\n _relation_params\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_params\n params.require(:relationship).permit(:followed_id)\n end", "def follow_artist\n relationship = Relationship.create(params.require(:relationship).permit(:follower_id, :followed_id))\n render json: relationship\n end", "def tag_relation_params\n params.require(:tag_relation).permit(:tag_id, :pile_id, :deck_id, :synergy_id)\n end", "def create\n @table_relation = TableRelation.new(table_relation_params)\n respond_to do |format|\n if @table_relation.save\n auto_field\n format.html { redirect_to edit_database_table_path(@database, @table), notice: 'Table relation was successfully created.' }\n format.json { render :show, status: :created, location: @table_relation }\n else\n format.html { render :new }\n format.json { render json: @table_relation.errors, status: :unprocessable_entity }\n end\n end\n end", "def resource_relations\n @resource_relations ||= Relation.from_links(client,\n decoded_body[:links])\n end", "def relationships_with_name(input, name)\n input.relations(name)\n end", "def populate_relation(args)\n\targs[:keys_B].each do |key_B|\n\t\tapi_url = \"#{@base_url}/#{args[:coll_A]}/#{args[:key_A]}/relation/\" +\n\t\t \"#{args[:relation]}/#{args[:coll_B]}/#{key_B}\"\n\t\tputs do_the_put_call({ url: api_url, user: @user, json: '{}' })\n\tend\nend", "def set_relation\n @relation = Relation.find(params[:id])\n end", "def post_relation\n if user = current_user\n respond_with PostRelation.find_or_create(post_id:params[:id],user_id:user.id)\n else\n head :unauthorized\n end\n end", "def create\n @products_purposes_relation = ProductsPurposesRelation.new(products_purposes_relation_params)\n\n respond_to do |format|\n if @products_purposes_relation.save\n format.html { redirect_to @products_purposes_relation, notice: t('create_success') }\n format.json { render :show, status: :created, location: @products_purposes_relation }\n else\n format.html { render :new }\n format.json { render json: @products_purposes_relation.errors, status: :unprocessable_entity }\n end\n end\n end", "def relationship_params\n params.require(:relationship).permit(:follower_user_id, :followed_act_id)\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 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 index\n @relations = Relation.all\n end", "def get_relations(service)\n\t\treturn @transport.get_path(\"relations\",service)\n\tend", "def new\n @relation = Relation.new(user_id: session[:user_id])\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @relation }\n end\n end", "def table_relation_params\n params.require(:table_relation).permit(:table_id, :relationship, :through, :table_to)\n end", "def set_relation\n @relation = Relation.find(params[:id])\n end", "def set_relation\n @relation = Relation.find(params[:id])\n end", "def create\n @ingredient = Ingredient.new(ingredient_params)\n @ingredient.recipe = Recipe.find(ingredient_params[:recipe])\n @ingredient.recipe.ingredients << @ingredient\n save_relations\n \n respond_to do |format|\n if @ingredient.save\n format.html { redirect_to @ingredient.recipe, notice: 'Ingredient was successfully added.' }\n format.json { render :show, status: :created, location: @ingredient }\n else\n format.html { render :new }\n format.json { render json: @ingredient.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_relations\n # relational saves require an id\n return false unless @id.present?\n # verify we have relational changes before we do work.\n return true unless relation_changes?\n raise \"Unable to update relations for a new object.\" if new?\n # get all the relational changes (both additions and removals)\n additions, removals = relation_change_operations\n\n responses = []\n # Send parallel Parse requests for each of the items to update.\n # since we will have multiple responses, we will track it in array\n [removals, additions].threaded_each do |ops|\n next if ops.empty? #if no operations to be performed, then we are done\n responses << client.update_object(parse_class, @id, ops, session_token: _session_token)\n end\n # check if any of them ended up in error\n has_error = responses.any? { |response| response.error? }\n # if everything was ok, find the last response to be returned and update\n #their fields in case beforeSave made any changes.\n unless has_error || responses.empty?\n result = responses.last.result #last result to come back\n set_attributes!(result)\n end #unless\n has_error == false\n end", "def get_relations_from_api(api=Rosemary::API.new)\n api.get_relations_referring_to_object(type, self.id.to_i)\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 generate_person_and_task_relations(relations)\n relations.each_pair { |person_id, values|\n values.each { |task_id|\n @db_base.map_task_to_person(person_id, task_id)\n }\n }\n end", "def read_relation_list(node)\n target_type = Utils.add_namespace(node.attributes['target-type'], Model::NS_REL_1)\n node.elements.each('relation') {|child|\n yield create_relation(child, target_type)\n }\n end", "def relationship_params\n params.require(:relationship).permit( :following_id, :created_at, :updated_at)\n end", "def create\n @course = Course.new(params[:course])\n\n respond_to do |format|\n if @course.save && @course.update_relations(params[:course])\n format.html { redirect_to(@course, :notice => 'Course was successfully created.') }\n format.xml { render :xml => @course, :status => :created, :location => @course }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @course.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @oma_relation_type = OmaRelationType.new(params[:oma_relation_type])\n\n respond_to do |format|\n if @oma_relation_type.save\n format.html { redirect_to @oma_relation_type, notice: 'Oma relation type was successfully created.' }\n format.json { render json: @oma_relation_type, status: :created, location: @oma_relation_type }\n else\n format.html { render action: \"new\" }\n format.json { render json: @oma_relation_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def npc_relation_params\n params.require(:npc_relation).permit(:campaign_id, :npc1_id, :npc2_id, :status, :notes)\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 new\n @dependent_relationship = DependentRelationship.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @dependent_relationship }\n end\n end", "def create\n child = Assembly.find(params[:child_id])\n @relationship = @assembly.relationships.build(child: child)\n child = @relationship.child\n child.used = true\n child.save\n\n respond_to do |format|\n if @relationship.save\n format.html { redirect_to [@plan, @assembly], notice: 'Relationship was successfully created.' }\n format.json { render json: @relationship, status: :created, location: @relationship }\n else\n format.html { render action: \"new\" }\n format.json { render json: @relationship.errors, status: :unprocessable_entity }\n end\n end\n end", "def relationships(*ids)\n perform_request_with_collection(:get, '/api/v1/accounts/relationships',\n array_param(:id, ids),\n Mastodon::Relationship)\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 as_jsonld(opts = { related: Ladder::Config.settings[:with_relations] })\n JSON.parse update_resource(opts.slice :related).dump(:jsonld, { standard_prefixes: true }.merge(opts))\n end", "def adding_plan_relation(transaction, parent, child, relations, info); end", "def create_relation(node, target_type)\n relation = @factory.new_relation\n \n # Read all defined data fields\n if node.attributes['direction']\n relation.direction = node.attributes['direction'].to_sym\n else\n relation.direction = Model::Relation::DIR_BOTH\n end\n \n if node.attributes['type']\n relation.type = Utils.add_namespace(node.attributes['type'], Model::NS_REL_1)\n end\n \n relation.begin_date = read_date_attribute(node, 'begin')\n relation.end_date = read_date_attribute(node, 'end')\n \n if node.attributes['attributes']\n node.attributes['attributes'].split(' ').each {|attribute|\n relation.attributes << Utils.add_namespace(attribute, Model::NS_REL_1)\n }\n end\n \n # Set the target. Either use the target included in the relation\n # or create a new target according to the target type if no target\n # is present.\n case target_type\n when Model::Relation::TO_ARTIST\n if node.elements['artist']\n target = create_artist node.elements['artist']\n else\n target = @factory.new_artist\n target.id = Model::MBID.parse(node.attributes['target'], :artist)\n end\n when Model::Relation::TO_RELEASE\n if node.elements['release']\n target = create_release node.elements['release']\n else\n target = @factory.new_release\n target.id = Model::MBID.parse(node.attributes['target'], :release)\n end\n when Model::Relation::TO_TRACK\n if node.elements['track']\n target = create_track node.elements['track']\n else\n target = @factory.new_track\n target.id = Model::MBID.parse(node.attributes['target'], :track)\n end\n when Model::Relation::TO_LABEL\n if node.elements['label']\n target = create_label node.elements['label']\n else\n target = @factory.new_label\n target.id = Model::MBID.parse(node.attributes['target'], :label)\n end\n when Model::Relation::TO_URL\n target = node.attributes['target']\n end\n \n relation.target = target\n \n return relation\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 save_related\n if self.links.present?\n self.links.each do | link |\n link.parent_type = :action_item\n link.parent_key = self.key\n link.save!\n end\n end\n end", "def create\r\n @relatorio = Relatorio.new(relatorio_params)\r\n\r\n respond_to do |format|\r\n if @relatorio.save\r\n format.html { redirect_to @relatorio, notice: 'Relatório criado com sucesso.' }\r\n format.json { render :show, status: :created, location: @relatorio }\r\n else\r\n format.html { render :new }\r\n format.json { render json: @relatorio.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def contains_relations?\n resource_handler.resource_relations.present?\n end", "def relationship_params\n params.require(:relationship).permit(:country_id, :friend_id, :score)\n end", "def make_relation(actionable, relation, magnitude=1)\n if actionable.is_a?(Sociographer::Actionable) && relation.present? && relation\n # @@neo = Neography::Rest.new\n self_node = self.get_node\n actionable_node = actionable.get_node\n if self_node && actionable_node\n if magnitude\n magnitude = magnitude.try(:to_f).try(:round)\n if magnitude < 0\n magnitude = -1\n else\n magnitude = 1\n end\n else\n magnitude = 1\n end\n node_property = \"#{relation.to_s.parameterize.underscore.to_s}_count\"\n self_node_property = self_node[node_property]\n if self_node_property\n self_node[node_property] = self_node_property+1\n elsif\n self_node[node_property] = 1\n end\n relation = relation.to_s.parameterize.underscore.to_sym\n relation_relationship = Neography::Relationship.create(relation, self_node, actionable_node)\n @@neo.set_relationship_properties(relation_relationship, {\"magnitude\" => magnitude, \"created_at\" => DateTime.now.to_i})\n # self.update_actions_cache(self_node, relation_relationship, 1) #removed will be set to -1\n return true\n else\n false\n end\n else\n false\n end\n end", "def relations_info\n self::RELATIONS_INFO\n end" ]
[ "0.6698783", "0.6452547", "0.6425456", "0.6410771", "0.6223413", "0.61852455", "0.61304104", "0.6125933", "0.61115205", "0.6019417", "0.6008763", "0.59798807", "0.5969094", "0.596323", "0.5960743", "0.589646", "0.58872426", "0.5861519", "0.57996064", "0.57966375", "0.57899326", "0.5781399", "0.5769767", "0.5748311", "0.57214016", "0.5693914", "0.56803405", "0.56801003", "0.56801003", "0.56801003", "0.5679775", "0.5679252", "0.56669503", "0.56636715", "0.56590164", "0.56582254", "0.56446964", "0.5639848", "0.5630132", "0.5622055", "0.561319", "0.56032765", "0.55921763", "0.55878276", "0.557245", "0.5557347", "0.55483115", "0.55483115", "0.5546037", "0.5541131", "0.55221957", "0.5507773", "0.5497139", "0.5490664", "0.54884076", "0.54851043", "0.546573", "0.546288", "0.5455952", "0.5455921", "0.5416738", "0.5392209", "0.53840166", "0.5374635", "0.53685594", "0.53653497", "0.5347199", "0.5340834", "0.53363097", "0.53340435", "0.5323631", "0.53182614", "0.53100926", "0.5300426", "0.5300426", "0.529758", "0.52974606", "0.5293495", "0.5288292", "0.528807", "0.52872044", "0.52866566", "0.52795196", "0.5275371", "0.526981", "0.5265696", "0.5262689", "0.52540034", "0.52534175", "0.5250559", "0.5247231", "0.5242397", "0.5235053", "0.52221316", "0.5217223", "0.52061194", "0.52016336", "0.5193866", "0.5187365", "0.51772755" ]
0.6018088
10
PATCH/PUT /relations/1 PATCH/PUT /relations/1.json
def update respond_to do |format| if @relation.update(relation_params) format.html { redirect_to @relation, notice: 'Relation was successfully updated.' } format.json { render :show, status: :ok, location: @relation } else format.html { render :edit } format.json { render json: @relation.errors, status: :unprocessable_entity } end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update\n begin\n @resource = Relation.find params[:id]\n @resource.update_attributes!(params[:relation])\n render :response => :PUT\n rescue Exception => e\n @error = process_exception(e)\n render :response => :error\n end\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 update\n @relation = Relation.find(params[:id])\n\n respond_to do |format|\n if @relation.update_attributes(params[:relation])\n format.html { redirect_to @relation, notice: 'Relation was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @relation.errors, status: :unprocessable_entity }\n end\n end\n end", "def put_relation(args)\n\tapi_url = \"#{@base_url}/#{args[:coll_A]}/#{args[:key_A]}/relation/\" +\n\t \"#{args[:relation]}/#{args[:coll_B]}/#{key_B}\"\n\tputs do_the_put_call( url: api_url, user: @user, json: '{}')\nend", "def update\n respond_to do |format|\n if @relation.update(relation_params)\n format.html { redirect_to edit_relation_path(@relation), notice: 'Relation was successfully updated.' }\n format.json { render :show, status: :ok, location: @relation }\n else\n format.html { render :edit }\n format.json { render json: @relation.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_relations\n # relational saves require an id\n return false unless @id.present?\n # verify we have relational changes before we do work.\n return true unless relation_changes?\n raise \"Unable to update relations for a new object.\" if new?\n # get all the relational changes (both additions and removals)\n additions, removals = relation_change_operations\n\n responses = []\n # Send parallel Parse requests for each of the items to update.\n # since we will have multiple responses, we will track it in array\n [removals, additions].threaded_each do |ops|\n next if ops.empty? #if no operations to be performed, then we are done\n responses << client.update_object(parse_class, @id, ops, session_token: _session_token)\n end\n # check if any of them ended up in error\n has_error = responses.any? { |response| response.error? }\n # if everything was ok, find the last response to be returned and update\n #their fields in case beforeSave made any changes.\n unless has_error || responses.empty?\n result = responses.last.result #last result to come back\n set_attributes!(result)\n end #unless\n has_error == false\n end", "def update\n @item = Item.find(params[:id])\n\n get_relations_from_params\n\n respond_to do |format|\n if @item.update_attributes(params[:item])\n format.html { redirect_to @item, notice: 'Item was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @item.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @relation = Relation.find(params[:id])\n params[:relation][:secret] = false if !@user.admin?\n respond_to do |format|\n if @relation.update_attributes(params[:relation])\n format.html { redirect_to @relation, notice: 'Relation a été édité avec succès.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @relation.errors, status: :unprocessable_entity }\n end\n end\n end", "def update!(**args)\n @relation = args[:relation] if args.key?(:relation)\n end", "def update\n\n if InfoNode.duplicate_key?(params[:info_types])\n redirect_to :back, :alert => \"Key in the additional information shoud be unique\"\n return\n end\n\n @relation = Node.find(params[:id])\n @collection = current_user.collections.find(params[:collection_id])\n if @relation.nil? || @collection.nil? || @relation.document.collection.id != @collection.id\n redirect_to :back, :alert => \"Cannot find an relation\"\n return\n end \n\n @document = @relation.document\n @collection = @document.collection\n\n unless params[:rid].nil?\n @rid = params[:rid].strip\n end\n\n @rid = @document.create_new_relation_id if @rid.blank?\n @relation.entity_type = params[:type] \n @refs = []\n\n params[:refids].each_with_index do |ref_id, idx|\n @refs << {:ref_id => ref_id, :role => params[:labels][idx]}\n end unless params[:refids].nil?\n\n if @refs.empty?\n redirect_to :back, :alert => \"Please add references for a new relation\"\n return\n end\n \n @relation.update_references(@refs)\n\n keyset = []\n (0...params[:info_types].size).each do |i|\n key = params[:info_types][i]\n value = params[:info_values][i]\n if !key.nil? && !key.strip.blank? && !value.nil? && !value.strip.blank?\n keyset << key\n @relation.set_info_node(key, value)\n end\n end\n\n @relation.remove_info_node_except(keyset)\n\n\n respond_to do |format|\n if @relation.save\n format.html { redirect_to \"/collections/#{@collection.id}/documents/#{@document.pmid}?tab=relation\", notice: 'Relation was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { redirect_to :back, :alert => \"Cannot update relation: #{@relation.errors.full_messages}\" }\n format.json { render json: @relation.errors, status: :unprocessable_entity }\n end\n end\n\n \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 respond_to do |format|\n if @table_relation.update(table_relation_params)\n format.html { redirect_to edit_database_table_path(@database, @table), notice: 'Table relation was successfully updated.' }\n format.json { render :show, status: :ok, location: @table_relation }\n else\n format.html { render :edit }\n format.json { render json: @table_relation.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n save_relations\n if @recipe.update(recipe_params)\n format.html { redirect_to @recipe, notice: 'Recipe was successfully updated.' }\n format.json { render :show, status: :ok, location: @recipe }\n else\n format.html { render :edit }\n format.json { render json: @recipe.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\t\t @tree = current_user.trees.find(params[:tree_id])\n\n\t if @tree.nil?\n\t \trender json: { errors: [\"No such tree found\"], success: false }, status: :bad_request\n\t end\n\n\t @person = @tree.people.find(params[:id])\n\n \tif @person.nil?\n \t\trender json: { errors: [\"No such person found\"], success: false }, status: :bad_request\n \tend\n\n \tparams.delete :_id\n\n\t relations = {}\n\t\t \tmodified_people = []\n\n\t\t \tif params[:person][:spouses]\n\t\t \t\trelations[:spouses] = params[:person][:spouses]\n\t\t \t\tparams[:person].delete :spouses\n\t\t \tend\n\n\t\t \tif params[:person][:children]\n\t\t \t\trelations[:children] = params[:person][:children]\n\t\t \t\tparams[:person].delete :children\n\t\t \tend\n\n\t\t \tif params[:person][:parents]\n\t\t \t\trelations[:parents] = params[:person][:parents]\n\t\t \t\tparams[:person].delete :parents\n\t\t \tend\n\n \tif @person.update_attributes(params[:person])\n \t\tmodified_people << @person\n\n \t\trelations.each do |k,v|\n\t\t \t\tv.each do |p|\n\t\t \t\t\tputs \"RELATIONS\", relations\n\t\t \t\t\tputs \"HERE\", k, v, p\n\t\t \t\t\trelative = @tree.people.find(p)\n\t\t \t\t\tputs \"THERE\", relative[k], relative.to_json\n\t\t \t\t\trelative.send(k) << @person\n\t\t \t\t\trelative.save\n\t\t \t\t\tmodified_people << relative\n\t\t \t\tend\n\t\t \tend\n\n \trender json: { person: @person, people: modified_people }, status: :accepted\n \telse\n \trender json: { errors: @person.errors, success: false }, status: :unprocessable_entity\n \tend\n\t\t end", "def update_from_relation(field_name, related = Ladder::Config.settings[:with_relations])\n objects = send(field_name).to_a\n\n if related || embedded_relations[field_name]\n # Force autosave of related documents to ensure correct serialization\n methods.select { |i| i[/autosave_documents/] }.each { |m| send m }\n\n # update inverse relation properties\n relation = relations[field_name]\n objects.each { |object| object.resource.set_value(relation.inverse, rdf_subject) } if relation.inverse\n objects.map(&:update_resource)\n else\n # remove inverse relation properties\n objects.each { |object| resource.delete [object.rdf_subject] }\n objects.map(&:rdf_subject)\n end\n end", "def update\n @oma_relation_type = OmaRelationType.find(params[:id])\n\n respond_to do |format|\n if @oma_relation_type.update_attributes(params[:oma_relation_type])\n format.html { redirect_to @oma_relation_type, notice: 'Oma relation type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @oma_relation_type.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 { 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 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 update(attrs)\n @attrs ||= {}\n @attrs.update(attrs[:relationship]) unless attrs[:relationship].nil?\n self\n end", "def relationship_set_props id, data\n headers = {\n 'Accept' => 'application/json; charset=UTF-8',\n 'Content-Type' => 'application/json',\n }\n\n put_request 'relationship/' + id + '/properties', data, headers\n end", "def update(context={})\n self.pre_cast_attributes\n m2o = @relations.reject{|k, v| !self.class.many2one_relations.has_key?(k)}\n vals = @attributes.reject {|key, value| key == 'id'}.merge(m2o.merge(m2o){|k, v| v.is_a?(Array) ? v[0] : v})\n self.class.rpc_execute('write', self.id, vals, context)\n reload_from_record!(self.class.find(self.id, :context => context))\n end", "def update!(**args)\n @object_id_prop = args[:object_id_prop] if args.key?(:object_id_prop)\n @relation = args[:relation] if args.key?(:relation)\n @subject_id = args[:subject_id] if args.key?(:subject_id)\n end", "def update(attrs)\n @attrs.update(attrs[:relationship]) unless attrs[:relationship].nil?\n self\n end", "def patch options\n rest_request({ method: :patch }.merge(options))\n end", "def patch options\n rest_request({ method: :patch }.merge(options))\n end", "def update\n respond_to do |format|\n save_relations\n if @ingredient.update(ingredient_params)\n format.html { redirect_to @ingredient.recipe, notice: 'Ingredient was successfully updated.' }\n format.json { render :show, status: :ok, location: @ingredient }\n else\n format.html { render :edit }\n format.json { render json: @ingredient.errors, status: :unprocessable_entity }\n end\n end\n end", "def rest_edit(path, options={}, &blk)\n callback = Proc.new { |*args|\n @object = yield(*args) or pass\n rest_params.each { |k, v| @object.send :\"#{k}=\", v unless k == 'id' }\n\n return 400, @object.errors.to_json unless @object.valid?\n\n @object.save\n rest_respond @object\n }\n\n # Make it work with `Backbone.emulateHTTP` on.\n put path, &callback\n post path, &callback\n end", "def rest_edit(path, options={}, &blk)\n callback = Proc.new { |*args|\n @object = yield(*args) or pass\n rest_params.each { |k, v| @object.send :\"#{k}=\", v unless k == 'id' }\n\n return 400, @object.errors.to_json unless @object.valid?\n\n @object.save\n rest_respond @object\n }\n\n # Make it work with `Backbone.emulateHTTP` on.\n put path, &callback\n post path, &callback\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 update\n respond_to do |format|\n if @tag_relation.update(tag_relation_params)\n format.html { redirect_to @tag_relation, notice: 'Tag relation was successfully updated.' }\n format.json { render :show, status: :ok, location: @tag_relation }\n else\n format.html { render :edit }\n format.json { render json: @tag_relation.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\t\t@relation = Relation.find(params[:id])\n\t\t@datas=@relation.datas\n\t\t@views = View.all\n\t\t@relation.update_accessor(current_user)\n\t\trespond_to do |format|\n\t\t\tif @relation.update_attributes(params[:relation])\n\t\t\t\tflash[:notice] = t(:ctrl_object_updated,:typeobj =>t(:ctrl_relation),:ident=>@relation.ident)\n\t\t\t\tformat.html { redirect_to(@relation, :notice => 'Relation was successfully updated.') }\n\t\t\t\tformat.xml { head :ok }\n\t\t\telse\n\t\t\t\tflash[:error] = t(:ctrl_object_not_updated,:typeobj =>t(:ctrl_relation),:ident=>@relation.ident)\n\t\t\t\tformat.html { render :action => \"edit\" }\n\t\t\t\tformat.xml { render :xml => @relation.errors, :status => :unprocessable_entity }\n\t\t\tend\n\t\tend\n\tend", "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 update\n\t\t@relation = Relation.find(params[:id])\n\t\t@views = View.all\n\t\t@types = Typesobject.get_types(\"relation\")\n\t\t@status = Statusobject.get_status(\"relation\")\n\t\t@relation.update_accessor(current_user)\n\t\trespond_to do |format|\n\t\t\tif @relation.update_attributes(params[:relation])\n\t\t\t\tflash[:notice] = t(:ctrl_object_updated,:typeobj =>t(:ctrl_relation),:ident=>@relation.ident)\n\t\t\t\tshow_\n\t\t\t\tformat.html { render :action => \"show\" }\n\t\t\t\t#format.html { redirect_to(@relation, :notice => 'Relation was successfully updated.') }\n\t\t\t\tformat.xml { head :ok }\n\t\t\telse\n\t\t\t\tflash[:error] = t(:ctrl_object_not_updated,:typeobj =>t(:ctrl_relation),:ident=>@relation.ident, :error => @object_plm.errors.full_messages)\n\t\t\t\tformat.html { render :action => \"edit\" }\n\t\t\t\tformat.xml { render :xml => @relation.errors, :status => :unprocessable_entity }\n\t\t\tend\n\t\tend\n\tend", "def update\n respond_to do |format|\n if @tag_relationship.update(tag_relationship_params)\n format.html { redirect_to @tag_relationship, notice: 'Tag relationship was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @tag_relationship.errors, status: :unprocessable_entity }\n end\n end\n end", "def populate_relation(args)\n\targs[:keys_B].each do |key_B|\n\t\tapi_url = \"#{@base_url}/#{args[:coll_A]}/#{args[:key_A]}/relation/\" +\n\t\t \"#{args[:relation]}/#{args[:coll_B]}/#{key_B}\"\n\t\tputs do_the_put_call({ url: api_url, user: @user, json: '{}' })\n\tend\nend", "def update!(**args)\n @relation_descriptor = args[:relation_descriptor] if args.key?(:relation_descriptor)\n end", "def update\n Neo4j::Transaction.run do\n @q_resource = QResource.find(params[:id])\n @q_resource.update_attributes!(params[:q_resource])\n respond_to do |format|\n if @q_resource.update_attributes(params[:q_resource])\n format.html { redirect_to @q_resource, :notice => 'Q resource was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @q_resource.errors, :status => :unprocessable_entity }\n end\n end\n end\n end", "def update!(**args)\n @related_feature_index = args[:related_feature_index] if args.key?(:related_feature_index)\n @relation_type = args[:relation_type] if args.key?(:relation_type)\n end", "def update!(**args)\n @related_feature_index = args[:related_feature_index] if args.key?(:related_feature_index)\n @relation_type = args[:relation_type] if args.key?(:relation_type)\n end", "def update\n @survey = Survey.find(params[:id])\n json = params[:survey]\n json[:questions] = JSON.parse(json[:questions])\n json[:questions].each_with_index do |question, idx|\n json[:questions][idx]['id'] = idx + 1\n end\n\n respond_to do |format|\n if @survey.update_attributes(json)\n format.html { redirect_to @survey, notice: 'Survey was successfully updated.' }\n format.json { render json: @survey }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @survey.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_relations\n self.reload\n logger.info '*****************************************'\n if self.parent_issue_id.to_i > 0\n logger.info 'Update parent (id %d) status...' % self.parent_issue_id.to_i\n update_parent_status\n end\n if self.relations.to_s != ''\n logger.info 'Update relation statuses...'\n update_relation_issues_status\n end\n if self.children.count.to_i > 0\n logger.info 'Update children status from parent (id %d) ...' % self.parent_issue_id.to_i\n update_children_status\n end\n logger.info '*****************************************'\n end", "def patch\n headers = {\"If-Match\" => @version}\n response = @context.request :patch, \"#{@path}/#{@id}\", @data.to_json, headers\n @version += 1\n response\n # 'X-HTTP-Method-Override' => 'PATCH'\n end", "def get_relations_referring_to_object(type, id)\n api_call_with_type(type, id, \"#{type}/#{id}/relations\")\n end", "def update_relation(field_name, *obj)\n # Should be an Array of RDF::Term objects\n return unless obj\n\n obj.map! { |item| item.is_a?(RDF::URI) ? Ladder::Resource.from_uri(item) : item }\n relation = send(field_name)\n\n if Mongoid::Relations::Targets::Enumerable == relation.class\n obj.map { |item| relation.send(:push, item) unless relation.include? item }\n else\n send(\"#{field_name}=\", obj.size > 1 ? obj : obj.first)\n end\n end", "def update options={}\n client.put(\"/#{id}\", options)\n end", "def update\n respond_to do |format|\n if @taxon_name_relationship.update(taxon_name_relationship_params)\n format.html { redirect_to @taxon_name_relationship.metamorphosize, notice: 'Taxon name relationship was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @taxon_name_relationship.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 render json: Company.update(params[\"id\"], params[\"company\"])\n end", "def update\n @student_relation = StudentRelation.find(params[:id])\n\n respond_to do |format|\n if @student_relation.update_attributes(params[:student_relation])\n flash[:notice] = 'Relative was successfully updated.'\n format.html { redirect_to(@student_relation) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @student_relation.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update!(**args)\n @annotated_relationship = args[:annotated_relationship] if args.key?(:annotated_relationship)\n @annotations = args[:annotations] if args.key?(:annotations)\n @collections = args[:collections] if args.key?(:collections)\n @entity_join = args[:entity_join] if args.key?(:entity_join)\n @id = args[:id] if args.key?(:id)\n @mrf = args[:mrf] if args.key?(:mrf)\n end", "def test_putrelation_update_valid\n relation = create(:relation)\n create(:relation_member, :relation => relation)\n user = relation.changeset.user\n cs_id = relation.changeset.id\n\n assert_not_equal({ \"test\" => \"ok\" }, relation.tags)\n amf_content \"putrelation\", \"/1\", [\"#{user.email}:test\", cs_id, relation.version, relation.id, { \"test\" => \"ok\" }, relation.members, true]\n post :amf_write\n assert_response :success\n amf_parse_response\n result = amf_result(\"/1\")\n\n assert_equal 5, result.size\n assert_equal 0, result[0]\n assert_equal \"\", result[1]\n assert_equal relation.id, result[2]\n assert_equal relation.id, result[3]\n assert_equal relation.version + 1, result[4]\n\n new_relation = Relation.find(relation.id)\n assert_equal relation.version + 1, new_relation.version\n assert_equal relation.members, new_relation.members\n assert_equal({ \"test\" => \"ok\" }, new_relation.tags)\n assert_equal true, new_relation.visible\n end", "def update!(**args)\n @relation = args[:relation] if args.key?(:relation)\n @source = args[:source] if args.key?(:source)\n @target = args[:target] if args.key?(:target)\n end", "def update\n respond_to do |format|\n if @resource.update(resource_params)\n format.html { redirect_to referential_resource_path(@referential, @resource), notice: 'Resource was successfully updated.' }\n format.json { render :show, status: :ok, location: @resource }\n else\n format.html { render :edit }\n format.json { render json: @resource.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @hackplatformrelation = Hackplatformrelation.find(params[:id])\n\n respond_to do |format|\n if @hackplatformrelation.update_attributes(params[:hackplatformrelation])\n format.html { redirect_to @hackplatformrelation, :notice => 'Hackplatformrelation was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @hackplatformrelation.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update # PATCH\n raise NotImplementedError\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 respond_to do |format|\n if @npc_relation.update(npc_relation_params)\n format.html { redirect_to @npc_relation, notice: 'Npc relation was successfully updated.' }\n format.json { render :show, status: :ok, location: @npc_relation }\n else\n format.html { render :edit }\n format.json { render json: @npc_relation.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @expression_relationship = ExpressionRelationship.find(params[:id])\n\n respond_to do |format|\n if @expression_relationship.update_attributes(params[:expression_relationship])\n format.html { redirect_to @expression_relationship, notice: 'Expression relationship was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @expression_relationship.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @relationship_status.update(relationship_status_params)\n format.html { redirect_to @relationship_status, notice: 'Relationship status was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @relationship_status.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @protocol_relationship.update(protocol_relationship_params)\n format.html { redirect_to @protocol_relationship, notice: 'Protocol relationship was successfully updated.' }\n format.json { render :show, status: :ok, location: @protocol_relationship }\n else\n format.html { render :edit }\n format.json { render json: @protocol_relationship.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n exit_if_not_manager and return\n respond_to do |format|\n if @relation_type.update(relation_type_params)\n format.html { redirect_to project_relation_types_path(@project), notice: 'Relation type was successfully updated.' }\n format.json { render :show, status: :ok, location: @relation_type }\n else\n format.html { render :edit }\n format.json { render json: @relation_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def reindex_relations\n ids = solr_relation_ids + relation_ids\n yield\n ids.uniq.map { |id| ActiveFedora::Base.find(id).update_index }\n end", "def update\n @meant_it_rel = MeantItRel.find(params[:id])\n\n respond_to do |format|\n if @meant_it_rel.update_attributes(params[:meant_it_rel])\n format.html { redirect_to(@meant_it_rel, :notice => 'Meant it rel was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @meant_it_rel.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @doc = Doc.find(params[:id])\n \n respond_to do |format|\n if @doc.update_attributes(params[:doc])\n save_object_relationship\n format.html { redirect_to(@doc, :notice => 'Doc was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @doc.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 relationship_set_property id, name, value\n headers = {\n 'Accept' => 'application/json; charset=UTF-8',\n }\n\n put_request 'relationship/' + id + '/properties/' + name, value, headers\n end", "def patch_relation_tuples_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: WriteApi.patch_relation_tuples ...'\n end\n # resource path\n local_var_path = '/relation-tuples'\n\n # query parameters\n query_params = opts[:query_params] || {}\n\n # header parameters\n header_params = opts[:header_params] || {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:debug_body] || @api_client.object_to_http_body(opts[:'payload'])\n\n # return_type\n return_type = opts[:debug_return_type]\n\n # auth_names\n auth_names = opts[:debug_auth_names] || []\n\n new_options = opts.merge(\n :operation => :\"WriteApi.patch_relation_tuples\",\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(:PATCH, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: WriteApi#patch_relation_tuples\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def do_related(verb, guid, name, other_guid, parent_model=model)\n logger.debug \"cc.association.#{verb}\", guid: guid, association: name, other_guid: other_guid\n\n singular_name = name.to_s.singularize\n\n @request_attrs = { singular_name => other_guid, verb: verb, relation: name, related_guid: other_guid }\n\n obj = find_guid(guid, parent_model)\n\n before_update(obj)\n\n parent_model.db.transaction do\n read_validation = verb == 'remove' ? :can_remove_related_object : :read_related_object_for_update\n validate_access(read_validation, obj, request_attrs)\n obj.send(\"#{verb}_#{singular_name}_by_guid\", other_guid)\n end\n\n after_update(obj)\n\n return [HTTP::NO_CONTENT] if verb == 'remove'\n\n [HTTP::CREATED, object_renderer.render_json(self.class, obj, @opts)]\n end", "def patch!\n request! :patch\n end", "def update\n respond_to_update({thing: @author})\n end", "def jsonapi_update!(attributes)\n assign_jsonapi_attributes(attributes)\n save!\n end", "def update\n @node = Node.find(params[:id])\n \n #params[:incoming_edges_attributes] and params[:incoming_edges_attributes].each { |i| i[:node_id_B] = @node.id and i[:edgetype] = Edgetype.find_by_name('dependent') }\n #params[:outgoing_edges_attributes] and params[:outgoing_edges_attributes].each { |i| i[:node_id_A] = @node.id and i[:edgetype] = Edgetype.find_by_name('dependent') }\n\n respond_to do |format|\n if @node.update_attributes(params[:node])\n Action.log :controller => params[:controller], :action => params[:action], :target_id => params[:id], :user => current_user\n format.html { redirect_to @node, notice: 'Node was successfully updated.' }\n format.json { head :no_content }\n else\n @node.related_edges_B.build\n @node.incoming_edges.build\n @node.outgoing_edges.build\n format.html { render action: \"edit\", :layout => !request.xhr? }\n format.json { render json: @node.errors, status: :unprocessable_entity }\n end\n end\n end", "def relation_params\n params.require(:relation).permit(:user_id, :friend_id)\n end", "def api_patch(path, data = {})\n api_request(:patch, path, :data => data)\n end", "def update\n respond_to do |format|\n if @public_relation.update(public_relation_params)\n format.html { redirect_to @public_relation, notice: 'Public relation was successfully updated.' }\n format.json { render :show, status: :ok, location: @public_relation }\n else\n format.html { render :edit }\n format.json { render json: @public_relation.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if request.content_type == \"application/json\"\n # .update is like a \"update people set ...\" in sql\n if @person.update(person_params)\n render json: @person\n else\n render json: @person.errors, status: :not_found\n end\n else\n render status: :bad_request\n end\n end", "def relation_params\n params.require(:relation).permit(:user1_id, :user2_id, :status)\n end", "def update\n @person = Person.find(params[:id])\n\n populate_attributes(@person, params[:person])\n respond_to do |format|\n \n if @person.save && @person.identifiable_entries.each(&:save!)\n format.html { redirect_to @person, notice: 'Person was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @person.errors, status: :unprocessable_entity }\n end\n end\n end", "def patch(path, data)\n request 'PATCH', path, body: data.to_json\n end", "def update\n current_user.new_relation_with(@user, params[:relation])\n render partial: 'follow', locals: { user: @user }\n end", "def patch_relation_tuples(opts = {})\n patch_relation_tuples_with_http_info(opts)\n nil\n end", "def update\n @expression_relationship_type = ExpressionRelationshipType.find(params[:id])\n\n respond_to do |format|\n if @expression_relationship_type.update_attributes(params[:expression_relationship_type])\n format.html { redirect_to @expression_relationship_type, notice: 'Expression relationship type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @expression_relationship_type.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 apply_relationships(obj, json, opts, new_record = false)\n delete_existing_relationships(obj) if !new_record\n\n @relationships.each do |relationship_name, relationship_defn|\n property_name = relationship_defn.json_property\n\n # If there's no property name, the relationship is just read-only\n next if !property_name\n\n # For each record reference in our JSON data\n ASUtils.as_array(json[property_name]).each_with_index do |reference, idx|\n record_type = parse_reference(reference['ref'], opts)\n\n referent_model = relationship_defn.participating_models.find {|model|\n model.my_jsonmodel.record_type == record_type[:type]\n } or raise \"Couldn't find model for #{record_type[:type]}\"\n\n referent = referent_model[record_type[:id]]\n\n if !referent\n raise ReferenceError.new(\"Can't relate to non-existent record: #{reference['ref']}\")\n end\n\n # Create a new relationship instance linking us and them together, and\n # add the properties from the JSON request to the relationship\n properties = reference.clone.tap do |properties|\n properties.delete('ref')\n end\n\n properties[:aspace_relationship_position] = idx\n properties[:system_mtime] = Time.now\n properties[:user_mtime] = Time.now\n\n relationship_defn.relate(obj, referent, properties)\n\n # If this is a reciprocal relationship (defined on both participating\n # models), update the referent's lock version to ensure that a\n # concurrent update to that object won't clobber our changes.\n\n if referent_model.find_relationship(relationship_name, true) && !opts[:system_generated]\n DB.increase_lock_version_or_fail(referent)\n end\n end\n end\n end", "def update\n @one = One.find(params[:id])\n\n respond_to do |format|\n if @one.update_attributes(params[:one])\n format.html { redirect_to @one, notice: 'One was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @one.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @recipe = Recipe.find(params[:id])\n @recipe.ingrediences = Ingredience.find(params[:ingredience_ids]) if params[:ingredience_ids] \n respond_to do |format|\n if @recipe.update_attributes(params[:recipe])\n flash[:notice] = 'Recipe was successfully updated.'\n format.html { redirect_to(@recipe) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @recipe.errors, :status => :unprocessable_entity }\n end\n end\n end", "def set_relation\n @relation = Relation.find(params[:id])\n end", "def update\n @person = Person.find(params[:id]) \n respond_to do |format|\n if @person.update(person_params)\n format.json { render json: @person, status: :ok }\n else\n format.json { render json: @person.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @csrelation.update(csrelation_params)\n format.html { redirect_to @csrelation, notice: 'Csrelation was successfully updated.' }\n format.json { render :show, status: :ok, location: @csrelation }\n else\n format.html { render :edit }\n format.json { render json: @csrelation.errors, status: :unprocessable_entity }\n end\n end\n end", "def update!(**args)\n @place_id = args[:place_id] if args.key?(:place_id)\n @relation_type = args[:relation_type] if args.key?(:relation_type)\n end", "def save_relations(relations)\n current_relations = sobject.relations_as_from\n added_relations = []\n unless relations.nil?\n elements = relations.split(\",\")\n elements.each do |element|\n to_sobject_id = element.split(\"-\")[0]\n relation_id = element.split(\"-\")[1]\n added_relations << add_relation_unless(to_sobject_id,relation_id)\n end\n end\n # remove removed relationships\n (current_relations - added_relations).each { |relation| relation.destroy }\n # fix positions\n added_relations.each_with_index { |relation,index| relation.update_attribute :position, index if relation.valid? }\n end", "def update\n question = Question.find_by!(id: params[:id])\n if question\n question.name = params[:name]\n question.description = params[:description]\n question.user_id = params[:user_id]\n question.category_id = params[:category_id]\n question.zavrseno = params[:zavrseno]\n question.uposlenik_id = params[:uposlenik_id]\n question.save\n render json: question, status: 200 \n else\n render json: { errors: \"This link is invalid.\"}, status: 404\n end\n end", "def update\n if params[:resource][:document].present?\n @resource.document.purge\n @resource.document.attach(params[:resource][:document])\n end\n if params[:resource][:sample].present?\n @resource.sample.purge\n @resource.sample.attach(params[:resource][:sample])\n end\n respond_to do |format|\n if @resource.update(resource_params)\n format.html { redirect_to @resource, notice: 'Resource was successfully updated.' }\n format.json { render :show, status: :ok, location: @resource }\n else\n format.html { render :edit }\n format.json { render json: @resource.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_radios_for_array(args = {}) \n put(\"/radios.json/#{args[:arrayId]}\", args)\nend", "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 update(attrs, path=nil)\n resp = api_client.put(path || url, JSON.dump(attrs))\n refresh(JSON.load(resp.body))\n end", "def update!(**args)\n @json_schemas = args[:json_schemas] if args.key?(:json_schemas)\n @schema = args[:schema] if args.key?(:schema)\n end", "def update(&block)\n validate_request()\n\n # Params includes all of the PATCH data at the top level along with other\n # other Rails-injected params like 'id', 'action', 'controller'. These\n # are harmless given no namespace collision and we're only interested in\n # the 'Operations' key for the actual patch data.\n #\n render(json: yield(self.safe_params()[:id], self.safe_params().to_hash()))\n end" ]
[ "0.6880368", "0.6605103", "0.65462255", "0.63583416", "0.6325468", "0.63048434", "0.616476", "0.6092026", "0.60556364", "0.60269153", "0.5955914", "0.59391123", "0.59208995", "0.5866268", "0.5860552", "0.5818152", "0.5790238", "0.5784563", "0.5773039", "0.5761265", "0.5721474", "0.5718242", "0.57111955", "0.56992567", "0.56992567", "0.56759536", "0.56631154", "0.56631154", "0.5638797", "0.5638797", "0.5638797", "0.5633821", "0.5629118", "0.5618489", "0.56044054", "0.55994254", "0.55671275", "0.5566759", "0.5558855", "0.5558303", "0.5558303", "0.5520685", "0.5519603", "0.5515578", "0.5495365", "0.54937947", "0.5479441", "0.5477563", "0.54761744", "0.54760605", "0.5463702", "0.5453287", "0.5450906", "0.54457337", "0.5440825", "0.5422728", "0.5406713", "0.5401364", "0.53968364", "0.5396207", "0.53931445", "0.5391265", "0.5387649", "0.5385411", "0.5382859", "0.537946", "0.53693813", "0.536404", "0.5361902", "0.53508943", "0.53506273", "0.5347759", "0.5346925", "0.5345826", "0.5339922", "0.5333659", "0.5328784", "0.53045535", "0.5293501", "0.52907926", "0.5283468", "0.52787685", "0.5275133", "0.526853", "0.52559185", "0.52554464", "0.5248268", "0.52455795", "0.52373827", "0.5236213", "0.5235127", "0.52337724", "0.5230127", "0.5226095", "0.5223989", "0.521394", "0.5212781", "0.52115655", "0.5206677", "0.52038956" ]
0.63545454
4
DELETE /relations/1 DELETE /relations/1.json
def destroy if @relation.user1_id == @currentUser.id or @currentUser.role == 0 @relation.destroy respond_to do |format| format.html { redirect_to relations_url, notice: 'Relation was successfully destroyed.' } format.json { head :no_content } end else redirect_to relations_url, notice: 'You cant revoke anothers users queries' end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n @relation = Relation.find(params[:id])\n @relation.destroy\n\n respond_to do |format|\n format.html { redirect_to relations_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @relation.destroy\n respond_to do |format|\n format.html { redirect_to relations_url, notice: 'Relation was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n relationship = Relationships.find(params[:id])\n relationship.destroy\n head 204\n end", "def destroy\n @subrelation = Subrelation.find(params[:id])\n @subrelation.destroy\n\n respond_to do |format|\n format.html { redirect_to(subrelations_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @oma_relation_type = OmaRelationType.find(params[:id])\n @oma_relation_type.destroy\n\n respond_to do |format|\n format.html { redirect_to oma_relation_types_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @relation = Node.find(params[:id])\n @collection = current_user.collections.find(params[:collection_id])\n\n if @relation.nil? || @collection.nil? || @relation.document.collection.id != @collection.id\n redirect_to :back, :alert => \"Cannot find an relation\"\n return\n end\n\n @document = @relation.document\n @collection = @document.collection\n\n logger.debug @relation.errors.inspect\n respond_to do |format|\n if @relation.destroy\n format.html { redirect_to \"/collections/#{@collection.id}/documents/#{@document.pmid}?tab=relation\", :notice => \"Relation was successfully deleted.\" }\n format.json { head :no_content }\n else\n format.html { redirect_to :back, :alert => \"Cannot delete relation: #{@relation.errors.full_messages}\" }\n format.json { render json: @relation.errors, status: :unprocessable_entity }\n end\n end\n end", "def destroy\n @npc_relation.destroy\n respond_to do |format|\n format.html { redirect_to npc_relations_url, notice: 'Npc relation was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @table_relation.destroy\n respond_to do |format|\n format.html { redirect_to edit_database_table_path(@database, @table), notice: 'Table relation was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @dependent_relationship = DependentRelationship.find(params[:id])\n @dependent_relationship.destroy\n\n respond_to do |format|\n format.html { redirect_to dependent_relationships_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @tag_relation.destroy\n respond_to do |format|\n format.html { redirect_to tag_relations_url, notice: 'Tag relation was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete_relationship(id)\n return @client.raw(\"delete\", \"/config/relationships/#{id}\")\n end", "def destroy\n\t\t@relation = Relation.find(params[:id])\n\t\tif @relation.destroy\n\t\t\tflash[:notice] = t(:ctrl_object_deleted, :typeobj => t(:ctrl_relation), :ident => @relation.ident)\n\t\telse\n\t\t\tflash[:error] = t(:ctrl_object_not_deleted, :typeobj => t(:ctrl_relation), :ident => @project.ident)\n\t\tend\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to(relations_url) }\n\t\t\tformat.xml { head :ok }\n\t\tend\n\tend", "def destroy\n @orphan.destroy\n respond_to do |format|\n format.html { redirect_to orphans_url }\n format.json { head :no_content }\n end\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 destroy\n @relationship.destroy\n respond_to do |format|\n format.html { redirect_to relationships_url, notice: 'Relationship was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @relationship.destroy\n respond_to do |format|\n format.html { redirect_to relationships_url, notice: 'Relationship was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @public_relation.destroy\n respond_to do |format|\n format.html { redirect_to public_relations_url, notice: 'Public relation was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @hackplatformrelation = Hackplatformrelation.find(params[:id])\n @hackplatformrelation.destroy\n\n respond_to do |format|\n format.html { redirect_to hackplatformrelations_url }\n format.json { head :ok }\n end\n end", "def destroy\n @csrelation.destroy\n respond_to do |format|\n format.html { redirect_to csrelations_url, notice: 'Csrelation was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @tag_relationship.destroy\n respond_to do |format|\n format.html { redirect_to tag_relationships_url }\n format.json { head :no_content }\n end\n end", "def destroy_relations\n begin\n File.delete FRIENDS_IDS_PATH + self.twitter_id.to_s\n File.delete FOLLOWER_IDS_PATH + self.twitter_ids.to_s\n rescue\n puts \"Didnt find the corresponding files.\"\n end \n end", "def destroy\n @taxon_name_relationship.destroy\n respond_to do |format|\n format.html { redirect_to taxon_name_relationships_url }\n format.json { head :no_content }\n end\n end", "def delete\n client.delete(\"/#{id}\")\n end", "def delete\n @relationship = Relationship.find(params[:relationship_id])\n end", "def destroy\n @expression_relationship = ExpressionRelationship.find(params[:id])\n @expression_relationship.destroy\n\n respond_to do |format|\n format.html { redirect_to expression_relationships_url }\n format.json { head :no_content }\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", "def destroy\n @jido_guardian_rel = JidoGuardianRel.find(params[:id])\n @jido_guardian_rel.destroy\n\n respond_to do |format|\n format.html { redirect_to(jido_guardian_rels_url) }\n format.xml { head :ok }\n end\n end", "def destroy \n Link.connection.execute(\"delete from links where id in (#{params[:id].join(',')})\") unless params[:id].blank?\n respond_to do |format|\n format.html { redirect_to(links_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @student_relation = StudentRelation.find(params[:id])\n @student_relation.destroy\n\n respond_to do |format|\n format.html { redirect_to(student_relations_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @firend_relationship.destroy\n respond_to do |format|\n format.html { redirect_to user_firend_relationships_url, notice: 'Firend relationship was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @meant_it_rel = MeantItRel.find(params[:id])\n @meant_it_rel.destroy\n\n respond_to do |format|\n format.html { redirect_to(meant_it_rels_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @relationship_status.destroy\n respond_to do |format|\n format.html { redirect_to relationship_statuses_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @wx_relationship.destroy\n respond_to do |format|\n format.html { redirect_to wx_relationships_url }\n format.json { head :no_content }\n end\n end", "def delete_relation_for association\n @relations.reject!{ |r| r.association == association || r.association == association.singularize}\n end", "def destroy\n @expression_relationship_type = ExpressionRelationshipType.find(params[:id])\n @expression_relationship_type.destroy\n\n respond_to do |format|\n format.html { redirect_to expression_relationship_types_url }\n format.json { head :no_content }\n end\n end", "def delete\n render json: Alien.delete(params[\"id\"])\n end", "def destroy\n @through_reference = ThroughReference.find(params[:id])\n @through_reference.destroy\n\n respond_to do |format|\n format.html { redirect_to through_references_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @comment_relationship = CommentRelationship.find(params[:id])\n @comment_relationship.destroy\n\n respond_to do |format|\n format.html { redirect_to comment_relationships_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @protocol_relationship.destroy\n respond_to do |format|\n format.html { redirect_to protocol_relationships_url, notice: 'Protocol relationship was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @products_purposes_relation.destroy\n respond_to do |format|\n format.html { redirect_to products_purposes_relations_url, notice: t('destroy_success') }\n format.json { head :no_content }\n end\n end", "def destroy\n @child_guardian_relationship = ChildGuardianRelationship.find(params[:id])\n @child_guardian_relationship.destroy\n\n respond_to do |format|\n format.html { redirect_to child_guardian_relationships_url }\n format.json { head :no_content }\n end\n end", "def delete\n render json: Item.delete(params[\"id\"])\n end", "def destroy\n @relatory.destroy\n respond_to do |format|\n format.html { redirect_to relatories_url, notice: 'Relatório deletado.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @biological_relationship.destroy\n respond_to do |format|\n format.html { redirect_to biological_relationships_url, notice: 'Biological relationship was successfully destroyed.' }\n format.json { head :no_content }\n end\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 delete; rest_delete(link('self')); end", "def delete; rest_delete(link('self')); end", "def delete(key)\n @relation.delete(key)\n end", "def destroy\n @player_relationship.destroy\n respond_to do |format|\n format.html { redirect_to player_relationships_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @one = One.find(params[:id])\n @one.destroy\n\n respond_to do |format|\n format.html { redirect_to ones_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @referent.destroy\n respond_to do |format|\n format.html { redirect_to referents_url, notice: 'Referent was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @subject_courses_relation.destroy\n respond_to do |format|\n format.html { redirect_to subject_courses_relations_url, notice: 'Subject courses relation was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @foreign_key.destroy\n respond_to do |format|\n format.html { redirect_to foreign_keys_url, notice: 'Foreign key was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @recurso = Recurso.find(params[:id])\n @recurso.destroy\n\n respond_to do |format|\n format.html { redirect_to recursos_url }\n format.json { head :no_content }\n end\n end", "def delete\n CONNECTION.execute(\"DELETE FROM links WHERE id = #{self.id};\")\n end", "def destroy\n @relatorios = Relatorio.find(params[:id])\n @relatorios.destroy\n\n respond_to do |format|\n format.html { redirect_to(homes_path) }\n format.xml { head :ok }\n end\n end", "def delete\n render json: Post.delete(params[\"id\"])\n end", "def destroy\n @relation = Relation.find(params[:id])\n relation_id=params[:id]\n #relation_email=@relation.email\n #@user=User.find(session[:user_id])\n #message=Message.new :subject=>\"This isn't working\", :body=>\"Sorry this just isn't working. We are done.\"\n #MessageMailer.mail_message(@user, relation_email, message).deliver\n Message.delete_all(['relation_id= ?', relation_id])\n @relation.destroy\n\n respond_to do |format|\n format.html { redirect_to user_url(session[:user_id]) }\n format.json { head :no_content }\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 delete\n render json: Company.delete(params[\"id\"])\n end", "def delete(rel)\n @relations.delete_if do |x|\n x === rel\n end\n @graph[rel.from].delete(rel.to)\n @graph[rel.to].delete(rel.from) if @undirected\n end", "def destroy_old\n\t\t@relation = Relation.find(params[:id])\n\t\tif @relation.destroy\n\t\t\tflash[:notice] = t(:ctrl_object_deleted, :typeobj => t(:ctrl_relation), :ident => @relation.ident)\n\t\telse\n\t\t\tflash[:error] = t(:ctrl_object_not_deleted, :typeobj => t(:ctrl_relation), :ident => @relation.ident)\n\t\tend\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to(relations_url) }\n\t\t\tformat.xml { head :ok }\n\t\tend\n\tend", "def destroy\n @user_relationship.destroy\n respond_to do |format|\n format.html { redirect_to user_relationships_url, notice: 'User relationship was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @vendor_relationship = VendorRelationship.find(params[:id])\n @vendor_relationship.destroy\n\n respond_to do |format|\n format.html { redirect_to vendor_relationships_url }\n format.json { head :no_content }\n end\n end", "def delete(options={})\n connection.delete(\"/\", @name)\n end", "def remove_relation\n @word.word_roots.delete(@word_root)\n respond_to do |format|\n format.js\n end\n end", "def destroy\n @referent.destroy\n respond_to do |format|\n format.html { redirect_to referents_url(:id => params[:refId]), notice: 'Referent was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @manifestation_relationship_type = ManifestationRelationshipType.find(params[:id])\n @manifestation_relationship_type.destroy\n\n respond_to do |format|\n format.html { redirect_to manifestation_relationship_types_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @agency_relationship = AgencyRelationship.find(params[:id])\n @agency_relationship.destroy\n\n respond_to do |format|\n format.html { redirect_to(agency_relationships_url) }\n end\n end", "def destroy\n @creator_accession_relationship = CreatorAccessionRelationship.find(params[:id])\n @creator_accession_relationship.destroy\n\n respond_to do |format|\n format.html { redirect_to creator_accession_relationships_url }\n format.json { head :no_content }\n end\n end", "def delete\n render json: Users.delete(params[\"id\"])\n end", "def destroy\n @obj = Node.find(params[:id])\n @obj.destroy\n\n respond_to do |format|\n format.html { redirect_to :back}\n format.json { head :no_content }\n end\n end", "def destroy\n @relatorio = Relatorio.find(params[:id])\n @relatorio.destroy\n\n respond_to do |format|\n format.html { redirect_to(home_path) }\n format.xml { head :ok }\n end\n end", "def delete\n\t\tdb.execute{ \"delete edge #{ref_name} #{rrid}\" }\n\tend", "def destroy\n @project = @relation_type.project\n exit_if_not_manager and return\n @relation_type.destroy\n respond_to do |format|\n format.html { redirect_to project_relation_types_path(@project), notice: 'Relation type was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n bef_delete = Before::Delete.new\n respond_to do |format|\n if bef_delete.child_of_relation(@cliente, :lotes)\n format.json { render json: \"Algunos lotes dependen de este cliente. No se puede eliminar.\", status: :conflict }\n else\n @cliente.destroy\n format.json { render json: {message: \"Cliente eliminado con éxito\"} }\n end\n end\n end", "def delete\n render json: Like.delete(params[\"id\"])\n end", "def remove_relation(rel)\n relations.delete(rel)\n Roby.remove_relation(rel)\n end", "def destroy\n @relation_industry.destroy\n respond_to do |format|\n format.html { redirect_to relation_industries_url }\n format.json { head :no_content }\n end\n end", "def test_urls_cascade_delete\n\t\tres = DB.exec(\"SELECT person_id FROM urls WHERE id=8\")\n\t\tassert_equal '5', res[0]['person_id']\n\t\tDB.exec(\"DELETE FROM people WHERE id=5\")\n\t\tres = DB.exec(\"SELECT person_id FROM urls WHERE id=8\")\n\t\tassert_equal 0, res.ntuples\n\tend", "def destroy\n @agent_relationship_type.destroy\n\n respond_to do |format|\n format.html { redirect_to agent_relationship_types_url, notice: t('controller.successfully_deleted', model: t('activerecord.models.agent_relationship_type')) }\n format.json { head :no_content }\n end\n end", "def orchio_delete_graph(kind, to_collection, to_key)\n response = client.send_request(\n :delete,\n inst_args(\n kind: kind,\n to_collection: to_collection,\n to_key: to_key,\n path: \"?purge=true\"\n ))\n orchio_status response, 204\n end", "def detach_relationship(data) #FIXME: Method doesn't work, RelationshipManager cannot access to id attribute.\n return @client.raw(\"post\", \"/config/relationships/detach\", nil, data)\n end", "def destroy\n @reltype.destroy\n respond_to do |format|\n format.html { redirect_to reltypes_url, notice: 'Reltype was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete\n render json: User.delete(params[\"id\"])\n end", "def destroy\n @relative.destroy\n respond_to do |format|\n format.html { redirect_to [:admin, :relatives], notice: 'Relative was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @resource.destroy\n respond_to do |format|\n format.html { redirect_to referential_resources_path(@referential), notice: 'Resource was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @program_relationship.destroy\n respond_to do |format|\n format.html { redirect_to program_relationships_url, notice: 'Program relationship was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @medicine_patient_relationship = MedicinePatientRelationship.find(params[:id])\n @medicine_patient_relationship.destroy\n\n respond_to do |format|\n format.html { redirect_to medicine_patient_relationships_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @three.destroy\n respond_to do |format|\n format.html { redirect_to threes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @campaign_user_relationship = CampaignUserRelationship.find(params[:id])\n @campaign_user_relationship.destroy\n\n respond_to do |format|\n format.html { redirect_to @campaign_user_relationship.campaign }\n format.json { head :no_content }\n end\n end", "def deletes_to(path,opts={},&block) #:nodoc: \n crud_to(:delete,path,opts[:params] || {},opts,&block)\n end", "def cascade\n if relation\n if relation.is_a?(Enumerable)\n relation.entries\n relation.each { |doc| doc.destroy }\n else\n relation.destroy\n end\n end\n end", "def destroy\n @recur.destroy\n respond_to do |format|\n format.html { redirect_to recurs_url, notice: 'Recur was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @referer = Referer.find(params[:id])\n @referer.destroy\n\n respond_to do |format|\n format.html { redirect_to referers_url }\n format.json { head :no_content }\n end\n end", "def destroy\r\n @relatorio.destroy\r\n respond_to do |format|\r\n format.html { redirect_to relatorios_url, notice: 'Relatório excluído com sucesso.' }\r\n format.json { head :no_content }\r\n end\r\n end", "def destroy\n @xlink = Xlink.find(params[:id])\n @xlink.destroy\n\n respond_to do |format|\n format.html { redirect_to xlinks_url }\n format.json { head :no_content }\n end\n end", "def delete\n request(:delete)\n end", "def destroy\n @anything.destroy\n respond_to do |format|\n format.html { redirect_to anythings_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @graph = Graph.find(params[:id])\n @graph.destroy\n \n Action.log :controller => params[:controller], :action => params[:action], :target_id => params[:id], :user => current_user\n\n respond_to do |format|\n format.html { redirect_to :root, notice: 'Graph was successfully deleted.' }\n format.json { head :no_content }\n end\n end" ]
[ "0.76680166", "0.7349601", "0.71940434", "0.6980938", "0.6924732", "0.6881415", "0.67720175", "0.67577136", "0.667264", "0.6663593", "0.6651822", "0.66421074", "0.6634024", "0.6624969", "0.66126865", "0.66126865", "0.6562891", "0.65532494", "0.6552323", "0.6551405", "0.65280384", "0.65242475", "0.6499035", "0.6469829", "0.6459659", "0.645272", "0.64398843", "0.64330447", "0.64101774", "0.64018977", "0.63911563", "0.6375125", "0.6372958", "0.6367671", "0.63320214", "0.632557", "0.6319655", "0.6304756", "0.6298148", "0.6297509", "0.62943655", "0.6276802", "0.6272596", "0.626317", "0.6252086", "0.6243619", "0.6243619", "0.6239094", "0.62389135", "0.6235043", "0.6232706", "0.6221463", "0.6217338", "0.62163144", "0.62065196", "0.6202123", "0.618866", "0.61871415", "0.6185403", "0.6180861", "0.6174143", "0.61647683", "0.6157026", "0.6153716", "0.613839", "0.61260986", "0.6109549", "0.61078686", "0.6107208", "0.61048657", "0.6103144", "0.609929", "0.6090814", "0.6089502", "0.6086645", "0.6077999", "0.6077729", "0.6072761", "0.60704315", "0.60594404", "0.6058096", "0.60573614", "0.60514134", "0.6050681", "0.60505074", "0.6048027", "0.6045362", "0.6043376", "0.6037813", "0.6034012", "0.6027192", "0.6022166", "0.60075724", "0.60052395", "0.6002031", "0.5999724", "0.5992863", "0.59885746", "0.5984709", "0.59819436" ]
0.63310724
35
Use callbacks to share common setup or constraints between actions.
def set_relation @relation = Relation.find(params[:id]) @currentUser = User.where(name: session[:user]).first end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_required_actions\n # TODO: check what fields change to asign required fields\n end", "def action_hook; end", "def run_actions; end", "def define_action_hook; end", "def actions; end", "def define_action_helpers\n if super && action == :save\n @instance_helper_module.class_eval do\n define_method(:valid?) do |*args|\n self.class.state_machines.fire_event_attributes(self, :save, false) { super(*args) }\n end\n end\n end\n end", "def add_actions; end", "def callbacks; end", "def callbacks; end", "def setup *actions, &proc\n (@setup_procs ||= []) << [proc, actions.size > 0 ? actions : [:*]]\n end", "def define_action_helpers; end", "def post_setup\n end", "def action_methods; end", "def action_methods; end", "def action_methods; end", "def before_setup; end", "def action_run\n end", "def execute(setup)\n @action.call(setup)\n end", "def define_action_helpers?; end", "def set_actions\n actions :all\n end", "def action_done(action)\n dispatch = { :migrate => :done_migrating, :map => :done_mapping, :reduce =>\n :done_reducing, :finalize => :done_finalizing } \n self.send dispatch[action[:action]], action\n end", "def dependencies action, &block\n @actions.each do |other|\n if action[:requires].include? other[:provide]\n block.call other\n end\n end\n end", "def setup!\n return unless @setup_procs\n http_actions = actions\n @setup_procs.each do |setup_proc|\n proc, actions = setup_proc\n @setup__actions = actions.map do |action|\n\n action.is_a?(Regexp) ?\n http_actions.select { |a| a.to_s =~ action } :\n action.is_a?(String) && action =~ /\\A\\./ ?\n http_actions.map { |a| a.to_s << action if format?(a).include?(action) }.compact :\n action\n\n end.flatten\n self.class_exec &proc\n @setup__actions = nil\n end\n @setup_procs = nil\n end", "def before_actions(*logic)\n self.before_actions = logic\n end", "def setup_handler\n end", "def set_action(opts)\n opts = check_params(opts,[:actions])\n super(opts)\n end", "def setup(action)\n @targets.clear\n unless action.item.target_filters.empty?\n @targets = SES::TargetManager.make_targets(action)\n else\n item = action.item\n if item.for_opponent?\n @targets = $game_troop.alive_members\n elsif item.for_dead_friend?\n @targets = $game_party.battle_members.select { |actor| actor.dead? }\n else\n $game_party.battle_members.select { |actor| actor.alive? }\n end\n end\n @item_max = @targets.size\n create_contents\n refresh\n show\n activate\n end", "def action; end", "def action; end", "def action; end", "def action; end", "def action; end", "def workflow\n end", "def revisable_shared_setup(args, block)\n class << self\n attr_accessor :revisable_options\n end\n options = args.extract_options!\n self.revisable_options = Options.new(options, &block)\n \n self.send(:include, Common)\n self.send(:extend, Validations) unless self.revisable_options.no_validation_scoping?\n self.send(:include, WithoutScope::QuotedColumnConditions)\n end", "def setup\n @action = SampleActionAndroid.new(os_name: 'android',\n app_name: APP_PATH)\n end", "def before(action)\n invoke_callbacks *self.class.send(action).before\n end", "def process_action(...)\n send_action(...)\n end", "def before_dispatch(env); end", "def after_actions(*logic)\n self.after_actions = logic\n end", "def setup\n # override and do something appropriate\n end", "def setup(client)\n return unless @setup\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n actions.each do |action|\n action.execute(client)\n end\n self\n end", "def setup(_context)\n end", "def setup(resources) ; end", "def validate_actions\n errors.add(:base, :should_give_at_least_one_action) if !manage? && !forecasting? && !read? && !api?\n end", "def setup\n @resource_config = {\n :callbacks => {\n :before_create => nil,\n :after_create => nil,\n :before_update => nil,\n :after_update => nil,\n :before_destroy => nil,\n :after_destroy => nil,\n },\n :child_assoc => nil,\n :model => nil,\n :parent => nil,\n :path => nil,\n :permission => {},\n :properties => {},\n :relation => {\n :create => nil,\n :delete => nil,\n },\n :roles => nil,\n }\n end", "def determine_valid_action\n\n end", "def process_shared\n handle_taxes\n handle_shippings\n create_adjustments_from_params\n handle_status\n handle_inventory_refunds\n handle_payment_transactions\n order.updater.update\n end", "def startcompany(action)\n @done = true\n action.setup\n end", "def init_actions\n am = action_manager()\n am.add_action(Action.new(\"&Disable selection\") { @selection_mode = :none; unbind_key(32); bind_key(32, :scroll_forward); } )\n am.add_action(Action.new(\"&Edit Toggle\") { @edit_toggle = !@edit_toggle; $status_message.value = \"Edit toggle is #{@edit_toggle}\" })\n end", "def event_callbacks(event, metadata={})\n case event\n when :reset, :review\n if confirmed\n update_attributes(confirmed: false)\n end\n when :confirm\n confirm\n # trigger :order for all applicable items\n # NOTE: :order event is common to both physical and digital items\n items.each do |i|\n if i.event_permitted(:order)\n user_id = last_transition.user_id\n i.trigger!(:order, { order_id: id, user_id: user_id })\n end\n end\n when :complete_work\n request = metadata[:request]\n work_complete_notification(request)\n when :close\n close\n end\n if event != :close && !open\n reopen\n end\n end", "def setup_action\n return unless PONY::ERRNO::check_sequence(current_act)\n new_sequence = @action_sequence[@sequence_index+1...@action_sequence.size]\n @sequence_index = 0\n new_sequence = DND::SkillSequence::ACTS[@acts[1]] + new_sequence\n execute_sequence\n end", "def define_tasks\n define_weave_task\n connect_common_tasks\n end", "def setup(&block)\n define_method(:setup, &block)\n end", "def setup\n transition_to(:setup)\n end", "def setup\n transition_to(:setup)\n end", "def action\n end", "def setup( *args )\n\t\t\tself.class.setupBlocks.each {|sblock|\n\t\t\t\tdebugMsg \"Calling setup block method #{sblock}\"\n\t\t\t\tself.send( sblock )\n\t\t\t}\n\t\t\tsuper( *args )\n\t\tend", "def config(action, *args); end", "def setup\n @setup_proc.call(self) if @setup_proc\n end", "def before_action \n end", "def setup_callbacks\n defined_callbacks.each do |meth|\n unless respond_to?(\"call_#{meth}_callbacks\".to_sym)\n self.class.module_eval <<-EOE\n def call_#{meth}_callbacks(*args)\n plugin_store.each {|a| a.call_#{meth}_callbacks(*args) } if respond_to?(:plugin_store) && plugin_store\n self.send :#{meth}, *args if respond_to?(:#{meth})\n end\n EOE\n end\n end\n end", "def action\n end", "def matt_custom_action_begin(label); end", "def setup\n # override this if needed\n end", "def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend", "def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend", "def action(options,&callback)\n new_action = Action===options ? options : Action.new(options,&callback)\n # replace any with (shared name/alias or both default) + same arity\n @actions.delete_if do |existing_action|\n ((existing_action.names & new_action.names).size > 0 ||\n existing_action.default? && new_action.default?) &&\n existing_action.required.size == new_action.required.size &&\n existing_action.optional.size <= new_action.optional.size\n end\n @actions = (@actions + [new_action]).sort\n new_action\n end", "def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action\n end", "def after(action)\n invoke_callbacks *options_for(action).after\n end", "def pre_task\n end", "def setup(server)\n server.on('beforeMethod', method(:before_method), 10)\n end", "def add_actions\n attribute = machine.attribute\n name = self.name\n \n owner_class.class_eval do\n define_method(name) {self.class.state_machines[attribute].events[name].fire(self)}\n define_method(\"#{name}!\") {self.class.state_machines[attribute].events[name].fire!(self)}\n define_method(\"can_#{name}?\") {self.class.state_machines[attribute].events[name].can_fire?(self)}\n end\n end", "def init_actions\n @select_action = SelectAction.new\n @endpoint_mouse_action = EndpointMouseAction.new\n @move_action = MoveAction.new\n end", "def setup_signals; end", "def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend", "def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend", "def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action.respond_to?('weak!') ? action.weak! : action\n end", "def initialize(*args)\n super\n @action = :set\nend", "def after_set_callback; end", "def setup\n #implement in subclass;\n end", "def lookup_action; end", "def setup &block\n if block_given?\n @setup = block\n else\n @setup.call\n end\n end", "def setup_action\n return TSBS.error(@acts[0], 1, @used_sequence) if @acts.size < 2\n actions = TSBS::AnimLoop[@acts[1]]\n if actions.nil?\n show_action_error(@acts[1])\n end\n @sequence_stack.push(@acts[1])\n @used_sequence = @acts[1]\n actions.each do |acts|\n @acts = acts\n execute_sequence\n break if @break_action\n end\n @sequence_stack.pop\n @used_sequence = @sequence_stack[-1]\n end", "def release_actions; end", "def around_hooks; end", "def save_action; end", "def setup(easy)\n super\n easy.customrequest = @verb\n end", "def action_target()\n \n end", "def setup\n callback(:setup) do\n notify(:setup)\n migration_check.last_deployed_commit\n end\n end", "def setup\n return unless @setup\n\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n run_actions_and_retry(actions)\n self\n end", "def before_setup\n # do nothing by default\n end", "def my_actions(options)\n @setup = false\n get_template_part(\"custom_used\",\"action_users\",true)\n end", "def default_action; end", "def setup(&blk)\n @setup_block = blk\n end", "def callback_phase\n super\n end", "def advice\n end", "def _handle_action_missing(*args); end", "def duas1(action)\n action.call\n action.call\nend", "def shared_action(name, &block)\n @controller.shared_actions[name] = block\n end", "def before_action action, &block\n @audience[:before][action] ||= Set.new\n @audience[:before][action] << block\n end", "def setup_initial_state\n\n state_a = State.new(\"a\", 0)\n state_b = State.new(\"b\", 0)\n state_c = State.new(\"c\", 10)\n\n move_to_b = Action.new(\"move_to_b\", 1, state_b)\n\n move_to_c = Action.new(\"move_to_c\", 1, state_c)\n\n state_a.actions = [move_to_b, move_to_c]\n\n return state_a\n \nend" ]
[ "0.6163163", "0.6045976", "0.5946146", "0.591683", "0.5890051", "0.58349305", "0.5776858", "0.5703237", "0.5703237", "0.5652805", "0.5621621", "0.54210985", "0.5411113", "0.5411113", "0.5411113", "0.5391541", "0.53794575", "0.5357573", "0.53402257", "0.53394014", "0.53321576", "0.53124547", "0.529654", "0.5296262", "0.52952296", "0.52600986", "0.52442724", "0.52385926", "0.52385926", "0.52385926", "0.52385926", "0.52385926", "0.5232394", "0.523231", "0.5227454", "0.52226824", "0.52201617", "0.5212327", "0.52079266", "0.52050185", "0.51754695", "0.51726824", "0.51710224", "0.5166172", "0.5159343", "0.51578903", "0.51522785", "0.5152022", "0.51518047", "0.51456624", "0.51398855", "0.5133759", "0.5112076", "0.5111866", "0.5111866", "0.5110294", "0.5106169", "0.509231", "0.50873137", "0.5081088", "0.508059", "0.50677156", "0.50562143", "0.5050554", "0.50474834", "0.50474834", "0.5036181", "0.5026331", "0.5022976", "0.5015441", "0.50121695", "0.5000944", "0.5000019", "0.4996878", "0.4989888", "0.4989888", "0.49864885", "0.49797225", "0.49785787", "0.4976161", "0.49683493", "0.4965126", "0.4958034", "0.49559742", "0.4954353", "0.49535993", "0.4952725", "0.49467874", "0.49423352", "0.49325448", "0.49282882", "0.49269363", "0.49269104", "0.49252945", "0.4923091", "0.49194667", "0.49174926", "0.49173003", "0.49171105", "0.4915879", "0.49155936" ]
0.0
-1
Never trust parameters from the scary internet, only allow the white list through.
def relation_params params.require(:relation).permit(:user1_id, :user2_id, :status) 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
Interview Problem Candidate given two intervals described each by two numbers on a number line, find the intersect and the section of each interval with no overlap let a range be [l, r] for [left, right]
def valid?(range) range[0] < range[1] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def intersection_of(range_a, range_b)\n range_a, range_b = [range_a, range_b].sort_by(&:begin)\n return if range_a.end < range_b.begin\n heads_and_tails = [range_a.begin, range_b.begin, range_a.end, range_b.end].sort\n middle = heads_and_tails[1..-2]\n middle[0]..middle[1]\n end", "def rec_intersection(r1, r2)\n p1 = [[r1[0][0],r2[0][0]].max , [r1[0][1],r2[0][1]].max]\n p2 = [[r1[1][0],r2[1][0]].min , [r1[1][1],r2[1][1]].min]\n if p1[0] < p2[0] && p1[1] < p2[1]\n return [p1,p2]\n else\n return nil\n end\nend", "def intersect?(range1,range2)\nif range1.begin < range2.begin\n if range1.end < range2.begin\n nil\n else\n (range2.begin..range1.end)\n end\nelse\n if range2.end < range1.begin\n nil\n else\n (range1.begin..range2.end)\n end\nend\nend", "def rec_intersection(rect1, rect2)\n\tx_min = [rect1[0][0],rect2[0][0]].max \n\tx_max = [rect1[1][0],rect2[1][0]].min \n\ty_min = [rect1[0][1],rect2[0][1]].max \n\ty_max = [rect1[1][1],rect2[1][1]].min \n\n\t(x_max < x_min) || (y_max < y_min) ? nil : [[x_min, y_min], [x_max, y_max]]\nend", "def intersect? (range1,range2)\n if range1.begin < range2.begin\n if range1.end < range2.begin\n nil\n else\n (range2.begin..range1.end)\n end\n else\n if range2.end < range1.begin\n nil\n else\n (range1.begin..range2.end)\n end\n end\nend", "def rec_intersection(rect1, rect2)\n x_min = [rect1[0][0], rect2[0][0]].max\n x_max = [rect1[1][0], rect2[1][0]].min\n\n y_min = [rect1[0][1], rect2[0][1]].max\n y_max = [rect1[1][1], rect2[1][1]].min\n\n return nil if ((x_max < x_min) || (y_max < y_min)) # no overlap\n return [[x_min, y_min], [x_max, y_max]]\nend", "def rec_intersection(rect1, rect2)\n x1 = [rect1[0][0],rect2[0][0]].max\n y1 = [rect1[0][1],rect2[0][1]].max\n y2 = [rect2[1][1],rect1[1][1]].min\n x2 = [rect2[1][0],rect1[1][0]].min\n if rect2[0][0] > rect1[1][0] || rect2[0][1] > rect1[1][1]\n return nil\n else\n return [[x1,y1],[x2,y2]]\n end\nend", "def intersection(range)\n int_a = (self.to_a & range.to_a) \n int_a.empty? ? nil : Range.new(int_a.min, int_a.max)\n end", "def rec_intersection(rect1, rect2)\n\txmin = rect1[0][0] > rect2[0][0] ? rect1[0][0] : rect2[0][0]\n\txmax = rect1[1][0] > rect2[1][0] ? rect2[1][0] : rect1[1][0]\n\tymin = rect1[0][1] > rect2[0][1] ? rect1[0][1] : rect2[0][1]\n\tymax = rect1[1][1] > rect2[1][1] ? rect2[1][1] : rect1[1][1]\n\nreturn nil if ((xmax < xmin) || (ymax < ymin))\nreturn [ [xmin, ymin], [xmax, ymax] ]\nend", "def find_range_overlap(point1, length1, point2, length2)\n # find the highest start point and lowest end point. The highest\n # (\"rightmost\" or \"upmost\") start point is the start point of overlap.\n # The lowest end point is the end point of the overlap.\n highest_start_point = [point1, point2].max\n lowest_end_point = [point1 + length1, point2 + length2].min\n \n # return nil if no overlap\n if highest_start_point >= lowest_end_point\n return [nil, nil]\n end\n \n # compute the overlap length\n overlap_length = lowest_end_point - highest_start_point\n \n return [highest_start_point, overlap_length]\nend", "def e123_include_intersect (n, min, max)\n ranges = []\n # loop i=1 a N\n (1..n).each { |i|\n # generate Ri with start = rand(min, max), end = (start, max) -> Note if start == max, then Range.length = 1\n start = rand(max - min) + min\n finish = rand(max - start) + start\n range = start..finish\n ranges.push(range)\n }\n\n intersected = []\n contained = []\n # loop Ri to Rn, i=1 to N\n ranges.each_with_index { |range_i, i|\n # loop Rj to Rn, j=i+1 to N\n ranges.drop(i+1).each { |range_j|\n # Ri intersects Rj?\n if range_i.intersects? range_j\n # push [Ri,Rj] to I\n intersected.push([range_i, range_j])\n # Ri contains? Rj or Rj contains? Ri\n if range_i.contains? range_j or range_i.is_contained_by? range_j\n # push [Ri, Rj] to C\n contained.push([range_i, range_j])\n end\n end\n }\n }\n\n return ranges, intersected, contained\n end", "def rec_intersection(rect1, rect2)\n bot_x, bot_y = [rect1[0][0], rect2[0][0]].max, [rect1[0][1], rect2[0][1]].max\n top_x, top_y = [rect1[1][0], rect2[1][0]].min, [rect1[1][1], rect2[1][1]].min\n return nil if bot_x > top_x || bot_y > top_y\n [[bot_x, bot_y], [top_x, top_y]]\nend", "def find_range_overlap(point1, length1, point2, length2)\n\n # find the highest start point and lowest end point.\n # the highest (\"rightmost\" or \"upmost\") start point is\n # the start point of the overlap.\n # the lowest end point is the end point of the overlap.\n highest_start_point = [point1, point2].max\n lowest_end_point = [point1 + length1, point2 + length2].min\n\n # return nil overlap if there is no overlap\n if highest_start_point >= lowest_end_point\n return [nil, nil]\n end\n\n # compute the overlap length\n overlap_length = lowest_end_point - highest_start_point\n\n return [highest_start_point, overlap_length]\nend", "def intersect(other_interval)\n if self.end <= other_interval.start || other_interval.end <= start\n nil\n else\n Interval.new([start, other_interval.start].max, [self.end, other_interval.end].min)\n end\n end", "def intersection(other)\n [first, other.begin].max..[last, other.end].min\n end", "def overlapInterval (array1, array2)\n\t@answer = false\n\t@a = array1[0] <= array2[0]\n\t@b = array1[1] > array2[0]\n\t@c = array1[0] > array2[0]\n\t@d = array1[0] < array2[1]\n\tif ((@a&&@b)||(@c&&@d))\n\t\t@answer = true\n\tend\n\t@answer\n\t\nend", "def conjunctionRangeExtd(r1, r2)\n\n [r1, r2].each do |er|\n return er if er.is_none?\n end\n\n r = *( sort_ranges_core([RangeExtd(r1), RangeExtd(r2)]) )\t# => Rangeary.sort_ranges\n\n ## Note: the end product will be (cBeg(:stBeg), cEnd(:stEnd))\n # where :stBeg and :stEnd mean exclude_(begin|end)?\n\n # Set the candidate begin value.\n cBeg = r[1].begin\n if r[0].begin == r[1].begin\n stBeg = (r[1].exclude_begin? || r[0].exclude_begin?)\n else\n stBeg = r[1].exclude_begin?\n end\n\n # Set the candidate end value. (Rangeary.comparable_end() for Ruby-2.6 Endless Range)\n # Note: this comparison ignores @infinities even if set,\n # because @infinities may not be defined in the arguments!\n # Anyway, nothing should be larger than the upper limit\n # and so this should be fine.\n if comparable_beginend_core(r[0]).end == comparable_beginend_core(r[1]).end\n cEndOrig = r[1].end\n cEnd = comparable_beginend_core(r[1]).end\n stEnd = (r[0].exclude_end? || r[1].exclude_end?)\n else\n a = [[comparable_beginend_core(r[0]).end, 0, r[0].end], [comparable_beginend_core(r[1]).end, 1, r[1].end]].min\n cEnd = a[0]\n cEndIndex = a[1]\t# r[cEndIndex] == RangeExtd obj that gives the end of the resultant range.\n cEndOrig = a[2]\n stEnd = nil\n end\n\n case cBeg <=> cEnd\n when 1\t# cBeg > cEnd\n RangeExtd::NONE\n\n when 0\t# cBeg == cEnd\n stEnd = r[0].exclude_end?\n if (!stBeg) && (!stEnd)\n RangeExtd(cBeg..cBeg)\t# Point range\n else\n RangeExtd::NONE\n end\n\n when -1\t# cBeg < cEnd\n # Now, the range must be (cBeg, cEnd). May need adjustment of the exclude status.\n if stEnd.nil?\n stEnd = r[cEndIndex].exclude_end?\n # else\n # # Already defined.\n end\t# if stEnd.nil?\n\n RangeExtd(cBeg, cEndOrig, :exclude_begin => stBeg, :exclude_end => stEnd)\n else\n raise\n end\t\t# case cBeg <=> cEnd\n\n end", "def merge_two_intervals(l1, l2)\n return l2 if l1.empty?\n return l1 if l2.empty?\n i, j = 0, 0\n [].tap do |r|\n while i < l1.length || j < l2.length\n if j == l2.length || (i < l1.length && l1[i].start < l2[j].start)\n k = l1[i]\n i += 1\n elsif i == l1.length || (j < l2.length && l1[i].start >= l2[j].start)\n k = l2[j]\n j += 1\n end\n if r.empty? || r[-1].end < k.start\n r << k\n else\n r[-1].end = [r[-1].end, k.end].max\n end\n end\n end\nend", "def intersecting_rectanges(rect1, rect2)\n\n intersecting_rect_width = 0\n intersecting_rect_height = 0\n intersecting_rect_left_x = 0\n intersecting_rect_bottom_y = 0\n\n if rect1[:left_x] + rect1[:width] > rect2[:left_x] && rect2[:left_x] > rect1[:left_x]\n intersecting_rect_width = rect1[:left_x] + rect1[:width] - rect2[:left_x]\n intersecting_rect_left_x = rect2[:left_x]\n elsif rect2[:left_x] + rect2[:width] > rect1[:left_x] && rect1[:left_x] > rect2[:left_x]\n intersecting_rect_width = rect2[:left_x] + rect2[:width] - rect1[:left_x]\n intersecting_rect_left_x = rect1[:left_x]\n end\n\n if rect1[:bottom_y] + rect1[:height] > rect2[:bottom_y] && rect2[:bottom_y] > rect1[:bottom_y]\n intersecting_rect_height = rect1[:bottom_y] + rect1[:height] - rect2[:bottom_y]\n intersecting_rect_bottom_y = rect1[:bottom_y]\n elsif rect2[:bottom_y] + rect2[:height] > rect1[:bottom_y] && rect1[:bottom_y] > rect2[:height]\n intersecting_rect_height = rect2[:bottom_y] + rect2[:height] - rect1[:bottom_y]\n intersecting_rect_bottom_y = rect2[:bottom_y]\n end\n \n {\n :left_x => intersecting_rect_left_x,\n :bottom_y => intersecting_rect_bottom_y,\n\n :width => intersecting_rect_width,\n :height => intersecting_rect_height\n }\nend", "def test_overlaping\n x = IntegerRange.new(1, 5)\n y = IntegerRange.new(3, 10)\n\n assert_equal(x.mergeable?(y), true)\n assert_equal(y.mergeable?(x), true)\n end", "def intersect( v1, v2 )\n b1, b2 = bound( v1 ), bound( v2 )\n cr = []\n if b1 && b2 then\n\tres = 0\n elsif b1 then\n\tcr = cross( v1, v2 )\n\tres =1\n elsif b2 then \n\tcr = cross( v1, v2 )\n\tres =2\n else\n\tcr = cross( v1, v2 )\n\tif cr.size == 2 then\n\t res = 3\n\telse\n\t res = 4\n\tend\n end\n return res, cr\n end", "def region_by_boundaries(left, right)\n if left && right\n if left != right\n IntervalNotation::Syntax::Long.closed_closed(left, right)\n else\n IntervalNotation::Syntax::Long.point(left)\n end\n else\n if !left && !right\n IntervalNotation::Syntax::Long::Empty\n else\n raise 'Wrong parsing assumptions. My bug!'\n end\n end\nend", "def e123_include_intersect (n, min, max)\n end", "def overlaps(first, second)\n return first.start.between?(second.start, second.end) ||\n first.end.between?(second.start, second.end) ||\n second.start.between?(first.start, first.end) ||\n second.end.between?(first.start, first.end)\nend", "def segments_intersect?(line_one, line_two)\n x1 = line_one[:x]\n y1 = line_one[:y]\n x2 = line_one[:x2]\n y2 = line_one[:y2]\n\n x3 = line_two[:x]\n y3 = line_two[:y]\n x4 = line_two[:x2]\n y4 = line_two[:y2]\n\n uA = ((x4-x3)*(y1-y3) - (y4-y3)*(x1-x3)) / ((y4-y3)*(x2-x1) - (x4-x3)*(y2-y1))\n uB = ((x2-x1)*(y1-y3) - (y2-y1)*(x1-x3)) / ((y4-y3)*(x2-x1) - (x4-x3)*(y2-y1))\n\n uA >= 0 && uA <= 1 && uB >= 0 && uB <= 1\n end", "def intersect(nums1, nums2)\n nums1.sort!\n nums2.sort!\n\n pointer_1 = 0\n pointer_2 = 0\n\n intersection = []\n while pointer_1 < nums1.length && pointer_2 < nums2.length\n selected = nums1[pointer_1]\n while pointer_2 < nums2.length && nums2[pointer_2] < selected\n pointer_2 += 1\n end\n\n if pointer_2 >= nums2.length\n return intersection\n end\n\n count = 0\n while nums1[pointer_1] && nums2[pointer_2] && nums1[pointer_1] == nums2[pointer_2]\n count += 1\n pointer_1 += 1\n pointer_2 += 1\n end\n\n intersection += [selected] * count\n\n while nums1[pointer_1] && nums1[pointer_1] == selected\n pointer_1 += 1\n end\n end\n\n intersection\nend", "def overlap(a, b)\n o = a.to_a & b.to_a\n o.size < 2 ? nil : (o.first..o.last)\nend", "def intersection(range)\n # Return self if nil (the other range has no restrictions) or if it matches the other range (they are equivalent)\n return self.clone if range.nil?\n return self.clone if eql?(range)\n\n # Figure out which range starts later (the more restrictive one)\n if low <= range.low\n earlier_start = self\n later_start = range\n else\n earlier_start = range\n later_start = self\n end\n \n # Return nil if there is no common time (the two ranges are entirely disjoint)\n return nil unless later_start.contains?(earlier_start.high)\n \n # Figure out which ranges ends earlier (the more restrictive one)\n if high >= range.high\n earlier_end = self\n later_end = range\n else\n earlier_end = range\n later_end = self\n end\n\n Range.new(\"TS\", later_start.low.clone, earlier_end.high.clone, nil)\n end", "def merge(other)\n if include?(other.begin) || other.include?(self.begin)\n cmp = self.begin <=> other.begin\n if cmp < 0\n min = self.begin\n excl_begin = exclude_begin?\n elsif cmp > 0\n min = other.begin\n excl_begin = other.exclude_begin?\n else\n min = self.begin\n excl_begin = exclude_begin? && other.exclude_begin?\n end\n\n cmp = self.end <=> other.end\n if cmp > 0\n max = self.end\n excl_end = self.exclude_end?\n elsif cmp < 0\n max = other.end\n excl_end = other.exclude_end?\n else\n max = self.end\n excl_end = exclude_end && other.exclude_end?\n end\n\n MinMaxRange.create(excl_begin ? GtRange.new(min) : GtEqRange.new(min), excl_end ? LtRange.new(max) : LtEqRange.new(max))\n elsif exclude_end? && !other.exclude_begin? && self.end == other.begin\n # Adjacent, self before other\n from_to(self, other)\n elsif other.exclude_end? && !exclude_begin? && other.end == self.begin\n # Adjacent, other before self\n from_to(other, self)\n elsif !exclude_end? && !other.exclude_begin? && self.end.next(:patch) == other.begin\n # Adjacent, self before other\n from_to(self, other)\n elsif !other.exclude_end? && !exclude_begin? && other.end.next(:patch) == self.begin\n # Adjacent, other before self\n from_to(other, self)\n else\n # No overlap\n nil\n end\n end", "def range_intersect?(s1, s2)\n s1range = s1.to_a.min..s1.to_a.max\n s2range = s2.to_a.min..s2.to_a.max\n return s1range.include?(s2range.first) || s2range.include?(s1range.first)\nend", "def intersection(*args)\n other = coerce_range(*args)\n sorted = [self, other].sort\n\n return nil if self.class.compare(sorted[0].end, sorted[1].begin) < 0\n\n ARange[sorted[1].begin, self.class.min(sorted[1].end, sorted[0].end)]\n end", "def arel_tt_intersect(instant, range_end)\n arel_intersect(:ttstart_at, :ttend_at, instant, range_end)\n end", "def OverlappingRanges(arr)\n intersection = (arr[0]..arr[1]).to_a & (arr[2]..arr[3]).to_a\n intersection.size >= arr[4] ? 'true' : 'false'\nend", "def intersection(range)\n cmp = self.begin <=> range.end\n if cmp > 0\n nil\n elsif cmp == 0\n exclude_begin? || range.exclude_end? ? nil : EqRange.new(self.begin)\n else\n cmp = range.begin <=> self.end\n if cmp > 0\n nil\n elsif cmp == 0\n range.exclude_begin? || exclude_end? ? nil : EqRange.new(range.begin)\n else\n cmp = self.begin <=> range.begin\n min = if cmp < 0\n range\n elsif cmp > 0\n self\n else\n self.exclude_begin? ? self : range\n end\n\n cmp = self.end <=> range.end\n max = if cmp > 0\n range\n elsif cmp < 0\n self\n else\n self.exclude_end? ? self : range\n end\n\n if !max.upper_bound?\n min\n elsif !min.lower_bound?\n max\n else\n MinMaxRange.new(min, max)\n end\n end\n end\n end", "def test_merge_overlaping_2\n x = IntegerRange.new(1, 5)\n y = IntegerRange.new(3, 10)\n\n assert_equal(y.mergeable?(x), true)\n y.merge(x)\n\n assert_equal(y.bottom, 1)\n assert_equal(y.top, 10)\n assert_equal(y.to_a, (1..10).to_a)\n\n a = each_to_a(y)\n\n assert_equal(a, (1..10).to_a)\n end", "def find_min_from_range(segment_arr, qlow, qhi, low, hi, pos)\n if(qlow <= low && qhi >= hi) # total overlap\n return segment_arr[pos]\n elsif(qlow > hi || qhi < low) # No Overlap\n return Integer::INFINITY\n end\n\n mid = (low+hi)/2\n [find_min_from_range(segment_arr, qlow, qhi, low, mid, pos*2+1),\n find_min_from_range(segment_arr, qlow, qhi, mid+1, hi, pos*2+2)].min\nend", "def OverlappingRanges(arr)\n ((arr[0]..arr[1]).to_a & (arr[2]..arr[3]).to_a).size >= arr[4]\nend", "def test_range_overlap_for_intersecting_ranges\n segment = basic_segment\n segment.instance_variable_set(:@start_time, 1.0)\n segment.instance_variable_set(:@end_time, 3.0)\n\n assert_in_delta(1.0, segment.send(:range_overlap, 2.0..4.0))\n end", "def segment_intersection(seg1, seg2)\n x1, y1, x2, y2 = seg1\n x3, y3, x4, y4 = seg2\n line1 = segment_to_line(*seg1)\n line2 = segment_to_line(*seg2)\n\n xmin = [[x1, x2].min, [x3, x4].min].max\n xmax = [[x1, x2].max, [x3, x4].max].min\n ymin = [[y1, y2].min, [y3, y4].min].max\n ymax = [[y1, y2].max, [y3, y4].max].min\n\n x, y = line_intersection(line1, line2)\n return nil unless x && y\n\n if x >= xmin && x <= xmax && y >= ymin && y <= ymax\n return [x, y]\n end\n\n nil\n end", "def & other_range\n case other_range\n when Range\n intersection = []\n each do |i|\n intersection << i if other_range.include? i\n end\n result = intersection.to_ranges\n case result[0]\n when Integer\n return (result[0])..(result[0])\n when Range, nil\n return result[0]\n end\n else\n raise \"unsupported type\"\n end\n end", "def rect_intersection(r1, r2)\n return (r1.x + r1.width > r2.x && r1.x < r2.x + r2.width &&\n r1.y + r1.height > r2.y && r1.y < r2.y + r2.height)\n end", "def OverlappingRanges(arr)\n first_num = arr[0]\n second_num = arr[1]\n third_num = arr[2]\n forth_num = arr[3]\n first_arr = (first_num..second_num).to_a\n second_arr = (third_num..forth_num).to_a\n merged_array = first_arr.concat(second_arr)\n (merged_array.size - merged_array.uniq.size == arr[4]) ? true : false\nend", "def test_merge_overlaping_1\n x = IntegerRange.new(1, 5)\n y = IntegerRange.new(3, 10)\n\n assert_equal(x.mergeable?(y), true)\n x.merge(y)\n\n assert_equal(x.bottom, 1)\n assert_equal(x.top, 10)\n assert_equal(x.to_a, (1..10).to_a)\n\n a = each_to_a(x)\n\n assert_equal(a, (1..10).to_a)\n end", "def intersection(another_transmembrane_domain_defintion)\n res = (@start..@stop).to_a & (another_transmembrane_domain_defintion.start..another_transmembrane_domain_defintion.stop).to_a\n res.empty? ? nil : (res.first..res.last)\n end", "def overlap(first_rect, second_rect)\n a1 = first_rect[0]\n a2 = first_rect[1]\n b1 = second_rect[0]\n b2 = second_rect[1]\n\n if b1[0] < a2[0] && b1[1] < a2[1]\n return true\n else \n return false\n end\n\nend", "def bounding_range(r1, r2)\n check_pre((\n (prim_shape?(r1)) and\n (prim_shape?(r2))\n ))\n\n if r1.range1d? and r2.range1d?\n lower = (r1.first < r2.first) ? r1.first : r2.first\n upper = (r1.last < r2.last) ? r2.last : r1.last\n\n Range1d.new(lower, upper)\n elsif r1.range2d? and r2.range2d?\n x_range = bounding_range(r1.x_range, r2.x_range)\n y_range = bounding_range(r1.y_range, r2.y_range)\n\n Range2d.new(x_range, y_range)\n else\n check_pre(false)\n end\nend", "def rectangle_inclusion_lambda(x1, y1, x2, y2)\n # take top left point and bottom right one\n x1, x2 = x2, x1 if x1 > x2\n y1, y2 = y2, y1 if y1 > y2\n\n ->(x, y) { (x1..x2).cover?(x) && (y1..y2).cover?(y) }\n end", "def merge(intervals_a, intervals_b)\n\tmerged = []\n\n\ti, j, start_point, end_point = 0,0,0,1\n\n\twhile i < intervals_a.length and j < intervals_b.length\n\n\t\t# check if intervals overlap and intervals_a[i]'s start time lies within the other intervals_b[j]\n\t\ta_overlaps_b = intervals_a[i][start_point] >= intervals_b[j][start_point] && intervals_a[i][start_point] <= intervals_b[j][end_point]\n\n\t\t# check if intervals overlap and intervals_b[j]'s start time lies within the other intervals_a[i]\n\t\tb_overlaps_a = intervals_b[j][start_point] >= intervals_a[i][start_point] && intervals_b[j][start_point] <= intervals_a[i][end_point]\n\n\t\t# store the the intersection part\n\n\t\tif a_overlaps_b || b_overlaps_a\n\t\t\tnew_start = [intervals_a[i][start_point], intervals_b[j][start_point]].max\n\t\t\tnew_end = [intervals_a[i][end_point], intervals_b[j][end_point]].min\n\t\t\tmerged.append([new_start, new_end])\n\t\tend\n\n\t\t# move next from the interval which is finishing first\n\n\t\tif intervals_a[i][end_point] < intervals_b[j][end_point]\n\t\t\ti += 1\n\t\telse\n\t\t\tj += 1\n\t\tend\n\n\tend\n\n\treturn merged\n\nend", "def OverlappingRanges(arr)\n\n # code goes here\n return arr \n \nend", "def bounding_range(range1, range2)\n check_pre(primshape?(range1) && primshape?(range2) && equal_dimension?(range1, range2))\n if range1.range1d? then Range1d[(range1.first <= range2.first ? range1.first : range2.first), (range1.last >= range2.last ? range1.last : range2.last)]\n elsif range1.range2d? then Range2d[bounding_range(range1.x_range, range2.x_range), bounding_range(range1.y_range, range2.y_range)]\n end\nend", "def test_disjoint\n x = IntegerRange.new(1, 2)\n y = IntegerRange.new(4, 5)\n\n assert_equal(x.mergeable?(y), false)\n assert_equal(y.mergeable?(x), false)\n end", "def cross(v1, v2)\n dx, dy = v2[0] - v1[0], v2[1] - v1[1]\n cr = [] # array containing intersections\n\n if dx == 0 and dy ==0 then\n\tnc = 0\n elsif dx == 0 then\n\tt = ( 0.0 - v1[1] ) / dy # y = 0\n\tx , y = v1[0] + t * dx, v1[1] + t * dy\n cr.push( [x, y] ) if x >= 0 && x <= 1 && t >= 0 && t <= 1\n\tt = ( 1.0 - v1[1] ) / dy # y = 1\n\tx, y = v1[0] + t * dx, v1[1] + t * dy\n\tcr.push( [x, y] ) if x >= 0 && x <= 1 && t >= 0 && t <= 1\n elsif dy == 0 then\n\tt = ( 0.0 - v1[0] ) / dx # x = 0\n\tx, y = v1[0] + t * dx, v1[1] + t * dy\n\tcr.push( [x, y] ) if y >= 0 && y <= 1 && t >= 0 && t <= 1\n\tt = ( 1.0 - v1[0] ) / dx # x = 1\n\tx, y = v1[0] + t * dx, v1[1] + t * dy\n cr.push( [x, y] ) if y >= 0 && y <= 1 && t >= 0 && t <= 1\n else\n\tt = ( 0.0 - v1[1] ) / dy # y = 0\n\tx , y = v1[0] + t * dx, v1[1] + t * dy\n cr.push( [x, y] ) if x >= 0 && x <= 1 && t >= 0 && t <= 1\n\tt = ( 1.0 - v1[1] ) / dy # y = 1\n\tx, y = v1[0] + t * dx, v1[1] + t * dy\n\tcr.push( [x, y] ) if x >= 0 && x <= 1 && t >= 0 && t <= 1\n\tt = ( 0.0 - v1[0] ) / dx # x = 0\n\tx, y = v1[0] + t * dx, v1[1] + t * dy\n\tcr.push( [x, y] ) if y >= 0 && y <= 1 && t >= 0 && t <= 1\n\tt = ( 1.0 - v1[0] ) / dx # x = 1\n\tx, y = v1[0] + t * dx, v1[1] + t * dy \n cr.push( [x, y] ) if y >= 0 && y <= 1 && t >= 0 && t <= 1\n end\n return cr\n end", "def intersection_point(a1, a2, b1, b2)\n ip = nil\n bounds_x = bounds(a1.x, a2.x)\n bounds_y = bounds(a1.y, a2.y)\n # first line is horizontal\n if a1.y == a2.y\n # second line is vertical -> there can be an intersection\n if b2.x == b1.x\n ip = Coord2.new(b1.x, a1.y)\n # Then we check if the point actually intersects\n bounds_b = bounds(b1.y, b2.y)\n\n return nil if b1.x < bounds_x[0] || b1.x > bounds_x[1]\n return nil if bounds_b[0] > bounds_y[0] || bounds_b[1] < bounds_y[1]\n end\n # first line is vertical\n elsif a1.x == a2.x\n # second line is horizontal -> there can be an intersection\n if b2.y == b1.y\n ip = Coord2.new(a1.x, b1.y)\n # Then we check if the point actually intersects\n bounds_b = bounds(b1.x, b2.x)\n return nil if b1.y < bounds_y[0] || b1.y > bounds_y[1]\n return nil if bounds_b[0] > bounds_x[0] || bounds_b[1] < bounds_x[1]\n end\n end\n\n ip\n end", "def time_intersection(start_a, finish_a, start_b, finish_b)\r\n\t # If one interval finishes before the other starts, intersection is zero.\r\n\t if finish_a < start_b or finish_b < start_a\r\n\t return 0\r\n\t else\r\n\t # Otherwise, intersection goes from the maximum start time to minimum finish time.\r\n\t return ([finish_a, finish_b].min - [start_a, start_b].max) / 1.hours\r\n\t end\r\n\t end", "def get_combined_interval(interval_arr, left_edge, right_edge)\n p \"interval_arr: #{interval_arr}\"\n interval_arr.each do |interval| # get combined interval\n p \"interval: #{interval}\"\n p \"left_edge: #{left_edge} right_edge: #{right_edge}\"\n if interval[0] >= 0 && interval[0] < left_edge && interval[1] >= left_edge\n left_edge = interval[0]\n interval_arr.delete(interval)\n elsif interval[0] < 0 && interval[0] > left_edge && interval[1] <= left_edge\n left_edge = interval[0]\n interval_arr.delete(interval)\n elsif interval[1] >= 0 && interval[1] > right_edge && interval[0] <= right_edge\n right_edge = interval[1]\n interval_arr.delete(interval)\n elsif interval[1] < 0 && interval[1] < right_edge && interval[0] >= right_edge\n right_edge = interval[1]\n interval_arr.delete(interval)\n end\n end\n\n interval_arr.each do |interval| # get intervals not part of combined interval\n \n end\n puts\n [interval_arr, left_edge, right_edge]\nend", "def intersection(note_a, note_b)\n\n return (note_a[0] <= note_b[1] and note_a[1] >= note_b[0])\n\n end", "def test_range_overlap_for_non_intersecting_ranges\n segment = basic_segment\n segment.instance_variable_set(:@start_time, 1.0)\n segment.instance_variable_set(:@end_time, 3.0)\n\n assert_in_delta(0.0, segment.send(:range_overlap, 4.0..5.0))\n end", "def bisectors\n s = self.sides.map { |side| Line.new(side.p1, side.p2) }\n c = self.incenter\n\n inter1 = Line.new(self.vertices[0], c).intersection(s[1]).first\n inter2 = Line.new(self.vertices[1], c).intersection(s[2]).first\n inter3 = Line.new(self.vertices[2], c).intersection(s[0]).first\n\n {\n self.vertices[0] => Segment.new(self.vertices[0], inter1), \n self.vertices[1] => Segment.new(self.vertices[1], inter2),\n self.vertices[2] => Segment.new(self.vertices[2], inter3),\n }\n end", "def intersections(list_a, list_b)\n list_a & list_b\nend", "def checkSrepIntersection\n (0..$sreps.length-1).each do |j|\n (0..$sreps.length-1).each do |i|\n if i != j\n $sreps[j].checkIntersection($sreps[i])\n end\n end\n end\n end", "def compare_ranges(true_ranges, inferred_ranges, insertion_mode = false)\n matches = 0\n misaligned = 0\n # Sides can be one of \"none\", \"left\", \"right\", \"ambiguous\" or \"both\"\n sides = []\n true_ranges.each_with_index do |t1, i|\n next unless i.even?\n t2 = true_ranges[i+1]\n inferred_ranges.each_with_index do |i1, k|\n next unless k.even?\n old_matches = matches\n old_misaligned = misaligned\n i2 = inferred_ranges[k+1]\n if t1 <= i1 && t2 >= i2\n matches += (i2 - i1)\n side = \"none\"\n side = \"left\" if t1 == i1\n side = \"right\" if t2 == i2\n side = \"both\" if t2 == i2 && t1 == i1\n sides << side\n elsif !insertion_mode && t1 <= i1 && i1 < t2 && t2 <= i2\n matches += (t2 - i1)\n misaligned += i2 - t2\n if t1 == i1\n sides << \"left\"\n else\n sides << \"none\"\n end\n elsif insertion_mode && t1 <= i1 && i1 <= t2 && t2 <= i2\n #puts \"YOUNK\"\n matches += (t2 - i1)\n misaligned += i2 - t2\n #elsif t1 >= i1 && t2 <= i2\n # matches += (t2 - t1)\n # misaligned += (i2 - t2) + (t1 - i1)\n # $logger.debug \"BUBBLES\"\n elsif !insertion_mode && t1 >= i1 && t2 >= i2 && t1 < i2\n matches += (i2 - t1)\n misaligned += (t1 - i1)\n if t2 == i2\n sides << \"right\"\n else\n sides << \"none\"\n end\n elsif insertion_mode && t1 >= i1 && t2 >= i2 && t1 <= i2\n #puts \"YOUNS\"\n matches += (i2 - t1)\n misaligned += (t1 - i1)\n\n end\n $logger.debug \"Matches #{matches}\"\n $logger.debug \"Misaligned #{misaligned}\"\n if matches != old_matches || misaligned != old_misaligned\n inferred_ranges.delete_at(k)\n inferred_ranges.delete_at(k)\n break\n end\n #puts misaligned\n end\n end\n\n inferred_ranges.each_with_index do |i1, k|\n next unless k.even?\n i2 = inferred_ranges[k+1]\n misaligned += i2-i1\n sides << \"none\"\n end\n if matches < 0 || misaligned < 0\n puts matches\n puts misaligned\n exit\n end\n $logger.debug(\"SIDES #{sides}\")\n [matches, misaligned, sides]\nend", "def intersection\n\t\t\tarray = self.sort_elements\n\t\t\tarray.inject() do |common, element|\n\t\t\t\tvalue_first = comparison_value(common, :last)\n\t\t\t\tvalue_element = comparison_value(element, :first)\n\t\t\t\tcase value_first <=> value_element\n\t\t\t\twhen -1 then return nil\n\t\t\t\twhen 0 then value_first\n\t\t\t\telse\n\t\t\t\t\tif element.class == Range \n\t\t\t\t\t\tvalue_element..([value_first, comparison_value(element, :last)].min)\n\t\t\t\t\telse\n\t\t\t\t\t\tvalue_element\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend", "def intersection_with(other)\n r1,r2 = matched_range_types(self, other)\n max_begin = [r1.begin,r2.begin].max\n min_end = [r1.end, r2.end ].min\n excl = ( r1.end == min_end && \n r1.respond_to?(:exclude_end?) && r1.exclude_end?\n ) ||\n ( r2.end == min_end && \n r2.respond_to?(:exclude_end?) && r2.exclude_end?\n )\n unless max_begin > min_end\n Range.new(max_begin, min_end, excl).extend(DateTimeRange)\n end\n end", "def query_range(left, right)\n \n end", "def query_range(left, right)\n \n end", "def intersection2(arr1, arr2)\n arr1, arr2, idx1, idx2 = arr1.sort, arr2.sort, 0, 0\n\n intersection = []\n while idx1 < arr1.length && idx2 < arr2.length\n case arr1[idx1] <=> arr2[idx2]\n when -1\n idx1 += 1\n when 0\n intersection << arr1[idx1]\n idx1 += 1\n idx2 += 1\n when 1\n idx2 += 1\n end\n end\n intersection\nend", "def front_rear_and_internal_collisions\n colliding_with.where(ended: false).where('reservations.starts_at' => range) + colliding_with.where('reservations.ends_at' => range)\n end", "def set_intersection set1, set2 \n\tresult \t\t\t= [];\n\tsec_index = 0 \n\tfirst_index = 0\n\n\twhile sec_index < set2.size && first_index < set1.size do \n\t\tif set1[first_index].to_i > set2[sec_index].to_i\n\t\t\tsec_index += 1\n\t\telsif set1[first_index].to_i == set2[sec_index].to_i\n\t\t\tresult << set1[first_index]\n\t\t\tfirst_index += 1\n\t\telsif set1[first_index].to_i < set2[sec_index].to_i\n\t\t\tfirst_index += 1\n\t\tend\n\tend\n\treturn result\nend", "def get_intersection\n end", "def intersect(other)\n begin_at = self.begin >= other.begin ? self.begin : other.begin\n end_at = self.end <= other.end ? self.end : other.end\n\n begin_at <= end_at ? self.class.new(begin_at..end_at) : nil\n end", "def range_cover?(outer, inner)\n outer.cover?(inner.begin) && outer.cover?(inner.end)\nend", "def overlaps?(other)\n # overlap == start < finish' AND start' < finish\n self.first <= other.actual_last and other.first <= self.actual_last\n end", "def find_intersection(a1, a2)\n a1_hash = {}\n \n a1.each do |num|\n if a1_hash[num]\n a1_hash[num] +=1\n else\n a1_hash[num] = 1\n end\n end\n \n intersection = []\n \n a2.each do |num|\n if a1_hash[num] && a1_hash[num] > 0\n a1_hash[num] -= 1\n intersection << num\n end\n end\n \n return intersection\nend", "def intersect point1, point2, a1, b1, x1, x2\n a2 = (point2.latitude - point1.latitude)/(point2.longitude-point1.longitude)\n b2 = point1.latitude - a2*point1.longitude\n x = (b2-b1)/(a1-a2)\n x3 = point1.longitude < point2.longitude ? point1.longitude : point2.longitude\n x4 = point1.longitude > point2.longitude ? point1.longitude : point2.longitude\n x >= x1 && x <= x2 && x >= x3 && x <= x4\n end", "def included?(range, number)\n if range.exclude_end?\n number >= range.begin && number < range.end\n else\n number >= range.begin && number <= range.end\n end\nend", "def intersection(nums1, nums2)\n unique = {}\n res = []\n nums1.each do |num|\n if !(unique[num])\n unique[num] = true\n end\n end\n \n nums2.each do |num|\n if unique[num] && !(res.include?(num))\n res.push(num)\n end\n end\n \n res\n end", "def arel_intersect(start_column, end_column, start_or_instant_or_range=nil, range_end=nil)\n table = self.arel_table\n if range_end\n table[start_column].lt(range_end).and(table[end_column].gt(start_or_instant_or_range))\n elsif Range === start_or_instant_or_range\n table[start_column].lt(start_or_instant_or_range.db_end).and(table[end_column].gt(start_or_instant_or_range.db_begin))\n else\n start_or_instant_or_range ||= InfinityLiteral\n table[start_column].lteq(start_or_instant_or_range).and(table[end_column].gt(start_or_instant_or_range))\n end\n end", "def overlap(first_rectangle, second_rectangle)\n\tfirst_rectangle_x1 = first_rectangle[0][0]\n\tfirst_rectanlge_y1 = first_rectangle[0][1]\n\tfirst_rectangle_x2 = first_rectangle[1][0]\n\tfirst_rectanlge_y2 = first_rectangle[1][1]\n\n\tsecond_rectangle_x1 = second_rectangle[0][0]\n\tsecond_rectanlge_y1 = second_rectangle[0][1]\n\tsecond_rectangle_x2 = second_rectangle[1][0]\n\tsecond_rectanlge_y2 = second_rectangle[1][1]\n\n\tif first_rectangle_x1 < second_rectangle_x2 && first_rectangle_x2 > second_rectangle_x1 && first_rectanlge_y1 < second_rectanlge_y2 && first_rectanlge_y2 > second_rectanlge_y1\n\t\treturn true\n\telse\n\t\treturn false\n\tend\nend", "def range_array_union(a, b)\n # convert starting numbers to ranges\n a[a.size-1] = a[a.size-1]..Graphics.frame_count if a[a.size-1].is_a?(Numeric)\n b[b.size-1] = b[b.size-1]..Graphics.frame_count if b[b.size-1].is_a?(Numeric)\n # initialize indices\n i = j = 0\n # stop if either interval doesn't exist\n return if a[i] == nil || b[j] == nil\n # start iteration\n loop do\n # if both arrays' last element\n if a[i + 1] == nil && b[j + 1] == nil\n # if not intersecting intervals\n if a[i].first > b[j].last + 1 || b[j].first > a[i].last + 1\n # add both ranges sorted\n a[i].first < b[j].first ? a[i + 1] = b[j] : (a[i + 1], a[i] = a[i], b[j])\n else\n # get range borders\n min_pos = (a[i].first < b[j].first ? a[i].first : b[j].first)\n max_pos = (a[i].last > b[j].last ? a[i].last : b[j].last)\n # interval union is the last element\n a[i] = min_pos..max_pos\n end\n # abort iteration\n break\n # if no more elements in this array\n elsif a[i] == nil\n # add all elements from other array\n a += b[j, b.size - j]\n # abort iteration\n break\n # if no more elements in other array\n elsif b[j] == nil\n # abort iteration\n break\n # if other intervals is after this interval\n elsif b[j].first > a[i].last + 1\n # check next interval of this array\n i += 1\n # if array is after other array or other interval is within this one\n elsif a[i].first > b[j].last + 1\n # add other interval into this array\n a.insert(i, b[j])\n # check next interval of this array\n i += 1\n # check next interval of other array\n j += 1\n elsif a[i].first >= b[j].first && a[i].last <= b[j].last\n # check next interval of other array\n j += 1\n # if other interval starts before and ends before this interval\n elsif a[i].first < b[j].first && a[i].last > b[j].last\n # unite intervals\n a[i] = b[j].first..a[i].last\n # check next interval of other array\n j += 1\n # if other interval ends after this interval\n else\n # get range borders\n min_pos = (a[i].first < b[j].first ? a[i].first : b[j].first)\n # unite intervals\n a[i] = min_pos..b[j].last\n # as longs as intervals of this array intersect with this interval\n while a[i + 1] != nil && a[i].last + 1 >= a[i + 1].first\n # get range borders\n max_pos = (a[i].last > a[i + 1].last ? a[i].last : a[i + 1].last)\n # unite this interval and next interval of this array\n a[i] = a[i].first..max_pos\n # delete next interval of this array\n a.delete_at(i + 1)\n end\n # check next interval of other array\n j += 1\n end\n end\n # if last range is a converted start number\n if a.size > 0 && a[a.size - 1].last == Graphics.frame_count\n # convert back\n a[a.size - 1] = a[a.size - 1].first\n end\n end", "def intersects?(*args)\n other = coerce_range(*args)\n raise ArgumentError, \"#{self.begin.class} expected, received #{other.begin.class}\" unless other.begin.kind_of?(self.begin.class)\n\n if other.instant?\n self.begin <= other.begin and other.end < self.end\n else\n other.begin < self.end and self.begin < other.end\n end\n end", "def min_meeting_rooms(intervals)\n s, e = [], []\n intervals.each do |i|\n s << i.start\n e << i.end\n end\n s.sort!\n e.sort!\n i = j = 0\n x = ans = 0\n while i < intervals.size\n if s[i] < e[j]\n x += 1\n ans = [ans, x].max\n i += 1\n else\n x -= 1\n j += 1\n end\n end\n ans\nend", "def range_to_cidr a, b\n c = nil\n bitmask1 = 0x80000000\n bitmask0 = 0x7fffffff\n cidr = 1\n best = [nil, 32]\n\n c = a & bitmask1\n same_start = c == (b & bitmask1)\n same_end = (a & bitmask0) ^ (b & bitmask0) == bitmask0\n while cidr < 32 && same_start\n if same_end\n best = [c, cidr]\n #elsif best.first\n # return best\n end\n cidr += 1\n bitmask1 = (bitmask1 >> 1) | 0x80000000\n bitmask0 = (bitmask0 >> 1) & 0x7fffffff\n c = a & bitmask1\n same_start = c == (b & bitmask1)\n same_end = (a & bitmask0) ^ (b & bitmask0) == bitmask0\n end\n return best\nend", "def segments_intersection(a, b, c, d)\n denominator = (b.y - a.y)*(d.x - c.x) - (a.x - b.x)*(c.y - d.y) \n return false if denominator == 0\n x = ( (b.x - a.x) * (d.x - c.x) * (c.y - a.y) + (b.y - a.y) * (d.x - c.x) * a.x - (d.y - c.y) * (b.x - a.x) * c.x ) / denominator\n y = -( (b.y - a.y) * (d.y - c.y) * (c.x - a.x) + (b.x - a.x) * (d.y - c.y) * a.y - (d.x - c.x) * (b.y - a.y) * c.y ) / denominator\n if (x - a.x) * (x - b.x) <= 0 && (y - a.y) * (y - b.y) <= 0 && (x - c.x) * (x - d.x) <= 0 && (y - c.y) * (y - d.y) <= 0 \n return true\n else\n return false\n end\n end", "def overlap()\n\n # find max and min x coordinates in each rectangle\n max_rectangle_x = []\n min_rectangle_x = []\n (1..2).each do |i|\n max_rectangle_x[i] = 0\n min_rectangle_x[i] = 1000\n (1..4).each do |j|\n print \"Enter x_coordinate of corner #{j} of recatangle #{i}: \"\n x_coordinate = gets.chomp.to_i\n if max_rectangle_x[i] < x_coordinate\n max_rectangle_x[i] = x_coordinate\n end\n if min_rectangle_x[i] > x_coordinate\n min_rectangle_x[i] = x_coordinate \n end\n end\n end \n\n# find max and min y coordinates in each rectangle\n max_rectangle_y = []\n min_rectangle_y = []\n (1..2).each do |i|\n max_rectangle_y[i] = 0\n min_rectangle_y[i] = 1000\n (1..4).each do |j|\n print \"Enter y_coordinate of corner #{j} of recatangle #{i}: \"\n y_coordinate = gets.chomp.to_i\n if max_rectangle_y[i] < y_coordinate\n max_rectangle_y[i] = y_coordinate\n end\n if min_rectangle_y[i] > y_coordinate\n min_rectangle_y[i] = y_coordinate\n end\n end\n end \n\n# Do max/min tests for overlap [see top of program]\n\n puts \"max_rectangle_x[1] = #{max_rectangle_x[1]}\"\n puts \"min_rectangle_x[1] = #{min_rectangle_x[1]}\"\n puts \"max_rectangle_x[2] = #{max_rectangle_x[2]}\"\n puts \"min_rectangle_x[2] = #{min_rectangle_x[2]}\"\n puts \"max_rectangle_y[1] = #{max_rectangle_y[1]}\"\n puts \"min_rectangle_y[1] = #{min_rectangle_y[1]}\"\n puts \"max_rectangle_y[2] = #{max_rectangle_y[2]}\"\n puts \"min_rectangle_y[2] = #{min_rectangle_y[2]}\"\n\n if max_rectangle_x[1] < min_rectangle_x[2] || \\\n max_rectangle_x[2] < min_rectangle_x[1] || \\\n max_rectangle_y[1] < min_rectangle_y[2] || \\\n max_rectangle_y[2] < min_rectangle_y[1]\n puts \"Rectangles do not overlap\"\n else\n puts \"Rectangles overlap\" \n end\nend", "def bounded_line_numbers(line, min, max, surrounding_lines)\n lower = line - surrounding_lines > min ? line - surrounding_lines : min\n upper = line + surrounding_lines < max ? line + surrounding_lines : max\n (lower..upper).to_a\n end", "def intersection(arr1, arr2)\n arr1 = arr1.sort\n arr2 = arr2.sort\n idx1, idx2 = 0,0\n i = []\n while(idx1 < arr1.length && idx2 < arr2.length)\n case(arr1[idx1] <=> arr2[idx2])\n when 0\n i << arr1[idx1]\n idx1 += 1\n idx2 += 1\n when 1\n idx2 += 1\n when -1\n idx1 += 1\n end\n end\n i\nend", "def check_node_overlap!\n node_to_positions = {}\n each_node do |node|\n node.proper_range.each do |position|\n if node_to_positions[position]\n already = node_to_positions[position]\n puts \"There is a proper_range overlap between #{node} and #{already}\"\n puts \"Overlapping: #{already.proper_range & node.proper_range}\"\n binding.pry\n end\n node_to_positions[position] = node\n end\n end\n end", "def overlaps?(range)\n !(completely_left_of?(range) || completely_right_of?(range))\n end", "def intersection(nums1, nums2)\n present = Hash.new\n intersection_array = []\n\n nums1.each do |num|\n present[num] = 1\n end\n\n nums2.each do |num|\n if present[num]\n present.delete(num)\n intersection_array << num\n end\n end\n\n intersection_array\nend", "def cells_overlapping(x, y)\n cells_at_points(corner_points_of_entity(x, y)).collect {|cx, cy| at(cx, cy) }\n end", "def calc_rectangular_intersection(rectangle1, rectangle2)\n rectangle3 = {} \n return \"No intersection\" if rectangle2.\n\n #Calculating y and height\n if rectangle2.y + rectangle2.height > rectangle1.y +rectangle1.height\n if rectangle2.y < rectangle1.y\n rectangle3.y = rectangle1.y\n rectangle3.height = rectangle1.height\n else\n rectangle3.y = rectangle1.y + rectangle1.height - rectangle2.y\n rectangle3.height = rectangle1.y + rectangle1.height\n end\n else\n if rectangle2.y < rectangle1.y\n rectangle3.y = rectangle1.y\n rectangle3.height = rectangle2.y + rectangle2.height\n else\n rectangle3.y = rectangle2.height\n rectangle3.height = rectangle2.y + rectangle2.height\n end\n end", "def intersection(lat, lng, r)\n \n # Convert degrees to meters\n x1 = Segment.length([lat, lng], [lat, @a[1]]) # lng\n x1 *= -1 if lng > @a[1]\n\n y1 = Segment.length([lat, lng], [@a[0], lng]) # lat\n y1 *= -1 if lat > @a[0]\n \n x2 = Segment.length([lat, lng], [lat, @b[1]]) # lng\n x2 *= -1 if lng > @b[1]\n\n y2 = Segment.length([lat, lng], [@b[0], lng]) # lat\n y2 *= -1 if lat > @b[0]\n \n # Circle equation: lat**2 + lng**2 = r**2\n # Segment equation: lat = y1 + (lng-x1)/(x2-x1) * (y2-y1)\n # See also: http://mathworld.wolfram.com/Circle-LineIntersection.html\n \n dx = x2 - x1\n dy = y2 - y1\n dr = Math.sqrt(dx**2 + dy**2) # Caution: this is estimation\n d = x1*y2 - x2*y1 \n delta = r**2 * dr**2 - d**2 \n\n sgn = lambda{ |x| x < 0 ? -1 : 1 }\n coordinates = lambda do |sign|\n x = (d*dy + sign * sgn[dy] * dx * Math.sqrt(delta)) / dr**2\n y = (-d*dx + sign * dy.abs * Math.sqrt(delta)) / dr**2\n\n intersection_lat = 180*y / (Math::PI * R) + lat\n intersection_lng = x / ( Math.cos(intersection_lat*Rad)*R) * (180/Math::PI) + lng\n \n [intersection_lat, intersection_lng] if (@a[1]..@b[1]).include?(intersection_lng) || (@b[1]..@a[1]).include?(intersection_lng) and\n (@a[0]..@b[0]).include?(intersection_lat) || (@b[0]..@a[0]).include?(intersection_lat)\n end\n \n if delta > 0\n # Return closest point (to point @a) of two\n [-1, 1].map{ |sign| coordinates[sign] }.compact.sort_by{|x,y| y }.first\n elsif delta == 0\n # Tangent line: only one point\n coordinates[0]\n else\n # No intersecting points\n nil\n end\n end", "def clash_check(a, b)\n\tclashes = []\n a.each do |a_start, a_finish|\n range_a = a_start..a_finish\n\n # check against each of b's slots\n b.each do |b_start, b_finish|\n range_b = b_start..b_finish\n \n # detect overlap of ranges\n # if Rails: range_a.overlaps?(range_b)\n if range_a.cover?(range_b.first) || range_b.cover?(range_a.first) \n\t\t\t\tclashes << [range_a, range_b]\n end\n end\n end\n clashes.empty?\nend", "def intersection(nums1, nums2)\n nums1 & nums2\n end", "def findTheIntersections\n intersection = [] #Numeros que A y B comparten\n differenceB = [] #Numeros que B tiene y no A\n differenceA =[] #Numero que A tiene y no B\n puts \"Sus intersecciones son: \"\n #Aqui se saca la interseccion \n for i in 0...@B.size\n if @A.include?(@B[i]) == true\n intersection.push(@B[i])\n i +=1 \n end\n end\n #Aqui solo se buscan los numeros diferentes entre A y B\n for u in 0...@A.size\n if @B.include?(@A[u]) == false\n differenceA.push(@A[u])\n u +=1 \n end\n end\n #Aqui solo se buscan los numeros diferentes entre B y A\n for i in 0...@B.size\n if @A.include?(@B[i]) == false\n differenceB.push(@B[i])\n i +=1 \n end\n end\n #Aqui se hace la union\n union = intersection + differenceA +differenceB\n #Por ultimo se imprime\n puts \"A ⋂ B = #{intersection}\"\n puts \"A ⋃ B = #{union.sort}\"\n puts \"A — B = #{differenceA}\" \n puts \"B — A = #{differenceB}\" \n end", "def boundaries\n [intervals.first[0], intervals.last[1]]\n end", "def intersection(nums1, nums2)\n hsh = {}\n result = []\n\n nums1.each do |num|\n hsh[num] = true\n end\n\n nums2.each do |num|\n if hsh[num]\n result.push(num) \n hsh[num] = false\n end\n end\n\n result\nend", "def love_rectangle(rect_1, rect_2)\n ranges_1 = make_range(rect_1)\n ranges_2 = make_range(rect_2)\n\n match_x = matching_range(ranges_1[:x], ranges_2[:x])\n match_y = matching_range(ranges_1[:y], ranges_2[:y])\n\n if [match_x.empty?, match_y.empty?].any?\n \"No match!\"\n else\n make_output(match_x, match_y)\n end\nend", "def common_intervals(n)\n Enumerator.new do |y|\n common_ngrams(n).each_with_object(Set.new) do |(gram), intervals|\n indexes = indexes_of(gram)\n indexes[0..-2].each_with_index { |m, i| intervals.add(indexes[i + 1] - m) }\n\n y << intervals\n end\n fail StopIteration\n end\n end", "def intersect2(nums1, nums2)\n counts1 = num_counts(nums1)\n counts2 = num_counts(nums2)\n\n intersection = []\n counts1.each do |k, v|\n if counts2.key?(k)\n times = [v, counts2[k]].min\n intersection.concat([k] * times)\n end\n end\n intersection\nend", "def intersection(other)\n raise ArgumentError, \"value must be a #{self.class.name}\" unless other.is_a?(VersionRange)\n result = @ranges.map { |range| other.ranges.map { |o_range| range.intersection(o_range) } }.flatten\n result.compact!\n result.uniq!\n result.empty? ? EMPTY_RANGE : VersionRange.new(result, nil)\n end" ]
[ "0.7381147", "0.7220778", "0.71983415", "0.70048034", "0.6994546", "0.6978018", "0.6960054", "0.68424785", "0.68065727", "0.67823124", "0.67188334", "0.66775256", "0.66387403", "0.6632962", "0.6558203", "0.6479933", "0.64468604", "0.643191", "0.6414687", "0.6394847", "0.63589257", "0.6357114", "0.63544446", "0.6339782", "0.6306295", "0.6285223", "0.62712735", "0.6249639", "0.6234578", "0.62101704", "0.6184623", "0.61779785", "0.6162964", "0.615138", "0.6143029", "0.6098198", "0.6096082", "0.60840774", "0.60783887", "0.60700077", "0.60468507", "0.6040445", "0.60341805", "0.6029275", "0.6009118", "0.5988927", "0.59846646", "0.5969982", "0.59697485", "0.5957764", "0.5953884", "0.59435916", "0.5938484", "0.5917164", "0.59171313", "0.59153134", "0.5913358", "0.5903903", "0.58957106", "0.58882254", "0.5881177", "0.5880519", "0.5872793", "0.587004", "0.587004", "0.5842479", "0.5832201", "0.58232754", "0.5820031", "0.58199847", "0.58191746", "0.5812053", "0.5810543", "0.5809128", "0.5805584", "0.57998973", "0.5794742", "0.57931244", "0.57880783", "0.5773361", "0.5761849", "0.57480067", "0.57462376", "0.57457143", "0.57319283", "0.57295597", "0.57198334", "0.57086784", "0.5702586", "0.56962144", "0.5673743", "0.5668751", "0.56665015", "0.566198", "0.565994", "0.56587505", "0.5656636", "0.56559384", "0.56454754", "0.56417984", "0.56244224" ]
0.0
-1
Hill: find the minimum X such that given an array you can make it strictly ascending by adding or subtracting up to X to each element.
def hill(v) flat = [] v.each_with_index do |el, i| flat << el - i end value = 0 low = flat[0] high = flat[0] flat.each_with_index do |el| if el < low low = el elsif el > high high = el low = el end new_val = high - low value = new_val if new_val > value end (value + 1) / 2 end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def better_my_min(array)\n array.inject do |acc, ele|\n if acc <= ele\n acc\n else\n ele\n end\n end\n end", "def my_min_v2(array)\n minimum = array.first\n\n array[1..-1].each do |element|\n minimum = element if minimum > element\n end\n\n minimum\nend", "def better_my_min(array)\n smallest = array[0]\n array[1..-1].each do |el|\n smallest = el if el < smallest\n end\n smallest\nend", "def my_min_linear(array)\n min = array[0]\n\n array.each do |num|\n min = num if num < min\n end\n min\nend", "def my_min2(array)\n array.inject { |acc, ele| acc < ele ? acc : ele}\nend", "def my_min(arr) #linear\n arr.reduce do |smallest, num|\n if smallest < num\n smallest\n else\n smallest = num\n end\n end\nend", "def smallest(array)\nend", "def my_min_improved(arr)\n min = arr[0]\n\n arr.each do |el|\n min = el if el < min\n end\n\n return min\nend", "def better_min(array)\n min_val = array.first\n\n array.each do |el| #O(n)\n if el < min_val\n min_val = el\n end\n end\n min_val\n end", "def my_min_v2(arr) # O(n)\n num = arr[0]\n arr.each { |int| num = int if int < num }\n num\nend", "def my_min(arr)\n arr.inject{|acc, el| el < acc ? acc = el : acc }\nend", "def my_min(array)\n\t\n\tarray.min\n\t\nend", "def linear_my_min(arr)\n # arr.inject do |min, ele|\n # min > ele \n # end\n # arr.first \n\n min = arr.first \n\n arr.each do |ele|\n min = ele if ele < min \n end\n min \n\nend", "def my_min(arr)\n output = arr.first\n \n (1...arr.length).each do |i|\n (i+1...arr.length).each do |j|\n output = arr[j] if arr[j] < output\n end\n end\n \n output\nend", "def my_min(array) # O(n) - Linear\n counter = array[0]\n\n (1...array.length).each do |i|\n if counter > array[i]\n counter = array[i]\n end\n end\n counter\nend", "def my_min_2(array)\n array.sort!\n array.first\nend", "def my_min2(arr)\n answer = arr[0]\n arr.each_with_index do |ele, idx|\n if idx != arr.length - 1\n answer = arr[idx] if answer >= arr[idx]\n end\n end\n answer\nend", "def my_min(array)\n sorted = false\n until sorted\n sorted = true\n\n array.each_index do |idx|\n next if idx + 1 == array.length\n if array[idx] > array[idx + 1]\n array[idx], array[idx + 1] = array[idx + 1], array[idx]\n sorted = false\n end\n end\n end\n\n array.first\nend", "def get_min(arr)\n arr.inject do |memo,x|\n if memo < x\n memo\n else\n x\n end\n end\nend", "def my_min(arr) # Find\n min = arr[0]\n\n arr.each do |el| # Go through array once O(n)\n min = el if el < min # update min while going through if found min\n end\n min\nend", "def my_min2(array)\n min = array.first\n array.each do |el|\n min = [el, min].min\n end\n min\nend", "def minimum(arr)\n m = arr.min\n m\n end", "def my_min2(arr)\n minimum = arr[0]\n arr[1..-1].each do |el|\n minimum = el if el < minimum\n end\n minimum\nend", "def smallest array\n [array.min]\n end", "def my_min2(array)\n minimum = array.first\n array.each_index do |idx|\n if array[idx] < minimum\n minimum = array[idx]\n end\n end\n minimum\nend", "def my_min(array)\n min_val = array.first\n array.each_with_index do |el1, idx1| # O(n)\n array.each_with_index do |el2, idx2| # O(n)\n if idx1 < idx2 # O(1)\n if el1 < el2# O(1)\n if el1 < min_val# O(1)\n min_val = el1# O(1)\n end\n else\n if el2 < min_val# O(1)\n min_val = el2# O(1)\n end\n end\n end\n end\n end\n min_val\n end", "def my_min(arry)\n mini = arry.first\n arry.each do |ele|\n if ele < mini\n mini = ele\n end\n end\n mini\nend", "def my_min_2(arr) #O(N)\n min_num = arr.first\n \n arr.each { |num| min_num = num if num < min_num }\n \n min_num\n end", "def find_min_value(array)\n return array.min\nend", "def find_min_value(array)\n answer = array.sort!\n answer[0]\nend", "def solve(array)\n ##Set minimum to be the last element.\n minimum = array[-1]\n\n ## Iterate until we reach the change.\n array.each_with_index do |element, index|\n if array[index] < array[index - 1]\n minimum = array[index]\n break\n end\n end\nend", "def check_list_linear(array)\n min = array.first\n array.each do |num|\n min = num if num < min\n end\n min\n end", "def my_min(arr)\n l = arr.length - 1 # constant\n # min = 0 # is this more efficient than swapping? \n (0...l).each do |i| # n times1\n if arr[i] < arr[i+1] # 1\n arr[i], arr[i+1] = arr[i+1], arr[i] # 1\n end\n end\n\n arr.last # 1\nend", "def my_min(arr)\n min = arr[0]\n (1...arr.length).each do |i|\n if arr[i] < min\n min = arr[i]\n end\n end\n min\nend", "def my_min_lin(arr) \n arr.inject do |min, num| \n if num < min \n num \n else \n min \n end \n end \nend", "def find_min_value(array)\n min = 0\n array.length.times do |count|\n if count == 0\n min = array[count]\n else\n if array[count] < min\n min = array[count]\n end\n end\n end\n min\nend", "def my_min2(arr)\n smallest = arr[0]\n arr[1..-1].each do |el|\n smallest = el if el < smallest\n end\n smallest\nend", "def find_min(array)\n min_difference = nil\n for i in 0..array.length - 1 do\n for j in i + 1..array.length - 1 do\n difference = (array[i] - array[j]).abs\n if min_difference.nil? || difference < min_difference\n min_difference = difference\n end\n end\n end\n min_difference\n end", "def my_min2(arr)\n min = arr.first\n arr.each { |el| min = el if el < min }\n min\nend", "def my_min(array)\n\n smallest = array.first\n array.each_with_index do |el, i|\n smallest = el if el < smallest\n end\n smallest\n\nend", "def array_min(array, len)\n if len == 1\n array[0]\n else\n first = array.pop\n rest = array_min(array, len - 1)\n if first < rest\n first\n else\n rest\n end\n end\nend", "def my_min2(arr)\r\n min = arr[0]\r\n arr.each { |num| min = num if num < min }\r\n min\r\nend", "def phase_two(arr)\n min = arr[0]\n arr.each do |ele|\n if ele < min\n min = ele\n end\n end\n\n min\nend", "def smallest_integer(array)\n array.min\nend", "def my_min2(arr)\n min = arr.first \n arr.each {|ele| min = ele if ele < min }\n min\nend", "def my_min_2(array)#O(n)\n array.inject do |acc, ele|#O(n)\n if acc < ele\n acc\n else\n ele\n end\n end\nend", "def my_min2(array)\n lowest_val = Float::INFINITY\n array.each do |el|\n lowest_val = el if el < lowest_val\n end\n\n lowest_val\nend", "def my_min2(array)\n lowest_num = array.first\n array.each do |el1|\n next if lowest_num == el1\n if el1 < lowest_num\n lowest_num = el1\n end\n end\n lowest_num\nend", "def best_my_min(arr)\n smallest = arr.shift\n arr.each do |el|\n smallest = el unless el > smallest\n end\n smallest\nend", "def my_min(array)\n min = array.first\n array.each {|el| min = el if min > el}\n min\nend", "def find_min2(array)\n min = array[0]\n \n array.each do |num|\n if num < min\n min = num\n end\n end\n \n return min\nend", "def my_min2(arr)\n start = 0\n for i in (0...arr.length)\n start = arr[i] if start > arr[i]\n end\n start\nend", "def my_min2(array)\n min = array.first\n array.each {|item| min = item if item <= min}\n return min\nend", "def faster_my_min(arr) # O(n)\n min = arr[0]\n arr.each do |ele|\n min = ele if ele < min\n end\n min\nend", "def find_min_value(array)\n min_element = 10000000\n array.length.times { |index|\n if min_element > array[index]\n min_element = array[index]\n end\n }\n return min_element# Add your solution here\nend", "def find_min(nums)\n nums.rotate(rand(1..10)).min\nend", "def good_my_min(arr)\n smallest = arr.first\n arr.each do |el|\n smallest = el if el < smallest\n end\n smallest\nend", "def my_min_2(arr)\n min = arr.shift\n\n (0...arr.length).each do |i|\n min = arr[i] if min > arr[i]\n end\n \n min\nend", "def my_min2(arr)\n minimum = arr.first\n arr.each do |num|\n minimum = num if num < minimum\n end\n minimum\nend", "def my_min(arr)\n min = arr.first\n\n arr.each do |el|\n min = el if el < min\n end\n\n min\nend", "def find_min_value(array)\n min_value = array[0]\n array.length.times do |count|\n if array[count] < min_value\n min_value = array[count]\n end\n end\n min_value\nend", "def minimum_sum(array, x)\n sum = 0\n array.sort.reverse.each_with_index do |e, i|\n sum = sum + e\n puts \"Number #{e}\"\n return puts \"Answer is #{i+1} elements, Suma #{sum} >= #{x}\" if sum >= x\n end\n return puts \"There are no elements that was >= #{x}\"\nend", "def my_min_fast(arr)\n smallest = arr[0]\n arr.each do |ele|\n if ele < smallest\n smallest = ele\n end\n end\n return smallest\nend", "def get_min(array)\n return array.inject do |current_min, n|\n if (current_min > n)\n n\n else\n current_min\n end\n end\nend", "def solve_again(array)\n minimum = array[0]\n\n array.each do |element|\n element = minimum if element < minimum\n end\n minimum\nend", "def my_min(arr)\n min = arr[0]\n arr.each do |num|\n if num < min\n min = num\n end\n end\n min\n\nend", "def smallest_of_x(numbers)\n i = 0\n smallest = numbers[0]\n smallestpos = 0\n while i < numbers.length - 1\n if smallest > numbers[1+i]\n smallest = numbers[1+i]\n smallestpos = i + 1\n end\n i += 1\n end\n return smallestpos\nend", "def my_min_2(arr)\n least = arr[0]\n\n arr.each do |i|\n arr.each do |y|\n if i < y && i < least\n least = i\n end\n end\n end\n\n least\n\n\nend", "def smallest_difference_model(array)\n numbers = [array[0], array[1]]\n min_dif = (array[0] - array[1]).abs\n\n array.each_with_index do |n1, i|\n array[(i + 1)..-1].each do |n2|\n diff = (n1 - n2).abs\n\n if min_dif > diff\n numbers = [n1, n2]\n min_dif = diff\n end\n end\n end\n\n [numbers.min, numbers.max]\nend", "def my_min(arr) #O(n2)\n min = arr.first\n arr.each_with_index do |el_1 , i|\n (i+1...arr.length).each do |el_2|\n if arr[el_2] < el_1 && arr[el_1] < min \n min = arr[el_2]\n end \n end \n end \n min \n end", "def my_min2(arr)\n smallest = arr.first\n arr.each do |el|\n smallest = el if el < smallest\n end\n smallest\nend", "def local_min(arr)\n mid = arr.length/2\n min = arr[mid]\n upper = arr.length-1\n lower = 0\n\n while !(arr[mid+lower+1] > min && arr[mid+lower-1] > min)\n # byebug\n #Calculate a new mid point and upper and lower bound.\n if arr[mid+1] < min \n lower = mid\n else\n upper = mid\n end\n mid = ((upper - lower) / 2) \n min = arr[mid + lower] \n end\n min\nend", "def minSum(array, sum=0)\n array.sort!.each.with_index(1) { |n, i| sum += n * array[-i] }\n sum / 2\nend", "def my_min_iterative(array)\n minimum = nil\n\n array.each { |element| minimum = element if minimum.nil? || element < minimum }\n\n minimum\nend", "def local_mins(array)\n length = array.length\n return [0] if length == 1\n\n mins = []\n\n # For rest of elments\n (0..length - 1).each do |i|\n if i.zero? && array[i] <= array[i + 1]\n mins << i\n elsif i == length - 1 && array[i] < array[i - 1]\n mins << i\n elsif i + 1 < length && array[i] <= array[i - 1] && array[i] < array[i + 1]\n mins << i\n end\n end\n mins\nend", "def find_smallest(array, length)\n min = array[0]\n\n length.times do |index|\n if array[index] < min\n min = array[index]\n end\n end\n\n return min\nend", "def my_min(arr)\n min = arr[0]\n (0...arr.size).each do |i1|\n (i1 + 1...arr.size).each do |i2|\n min = arr[i2] if arr[i2] < min\n end\n end\n min\nend", "def find_min(array)\n n = array.size\n high = n-1\n low = 0\n while true do\n mid = (high + low)/2\n return array[high] if mid==high \n return array[mid] if array[mid+1] > array[mid] && array[mid-1] > array[mid]\n # check if low is greater than high\n if array[low] > array[high] \n # check mid is greater than high\n if array[mid] >= array[high]\n # low is in left side \n low = mid + 1\n else\n high = mid - 1\n end\n else\n return array[low]\n end\n end \nend", "def find_smallest_int(arr)\n return arr.min\nend", "def my_min(arr)\n sorted = false \n while !sorted \n sorted = true \n (0...arr.length-1).each do |i|\n if arr[i] < arr[i+1]\n arr[i], arr[i+1] = arr[i+1], arr[i]\n sorted = false \n end \n end \n end \n arr[-1]\nend", "def find_smallest_num(arr)\n\treturn arr.min()\nend", "def lowestnumber arr\n idx = 0 \n min = arr[0]\n while idx <= arr.length - 1\n if arr[idx] > min \n min = min\n else\n min = arr[idx]\n end\n \n idx = idx + 1\n end\n return min\nend", "def find_min(arr)\n min = arr.first\n (1...arr.length).each do |idx|\n min = arr[idx] if arr[idx] < min\n end\n min\nend", "def my_min(array)\n array.find do |ele|\n array.all? do |ele1|\n ele <= ele1\n end\n end\n end", "def my_min_phase_2(list)\n min = list[0]\n (1...list.length).each do |i|\n min = list[i] if list[i] < min\n end\n min\nend", "def phase_1_min(list)\n smallest = 0\n list.each_with_index do |num1, indx1|\n list.each_with_index do |num2, indx2|\n next if indx1 == indx2\n smallest = num1 if num1 < num2 && num1 < smallest\n end\n end\n smallest\nend", "def my_min(arr)\n min = arr.first\n (0...arr.length).each do |idx1|\n (idx1...arr.length).each do |idx2|\n if (idx2 != idx1) && (arr[idx1] < arr[idx2]) && (arr[idx1] < min)\n min = arr[idx1]\n end\n\n end\n end\n min\n\nend", "def my_min_once(arr)\n min = arr.first \n\n (0...arr.count).each do |i|\n min = arr[i] if arr[i] < min \n end\n\n min \nend", "def min_moves(nums)\n nums.sum - nums.size * nums.min\nend", "def find_min(*nums)\n nums.reduce do | acc, current_value |\n if acc > current_value\n current_value\n else\n acc\n end\n end\nend", "def find_min(arr)\n return arr[0] if arr.length == 1\n\n left = 0\n right = arr.length - 1\n\n loop do\n mid = (left + right) / 2\n\n prev_value = arr[mid - 1]\n curr_value = arr[mid]\n next_value = arr[mid + 1]\n\n return curr_value if prev_value && prev_value > curr_value\n return next_value if next_value && curr_value > next_value\n\n curr_value < arr[right] ? right = mid - 1 : left = mid + 1\n end\nend", "def _lower_bound(array,value,l,r)\r\n return l if r==l\r\n ind=(r+l)/2\r\n return value<=array[ind] ? _lower_bound(array,value,l,ind) : _lower_bound(array,value,ind+1,r)\r\nend", "def my_min(arr)\n\n smallest_value = arr[0]\n\n arr.each do |ele1| # [ 0, 3, 5, 4, -5, 10, 1, 90 ] O(n)\n # smallest_value = ele1 if ele1 < smallest_value\n if arr.all?{|ele2| ele1 <= ele2 } #O(n)\n smallest_value = ele1\n end\n end\n\n smallest_value\n\nend", "def smallest_missing(ints)\n ((1..ints.max + 1).to_a - ints).min\nend", "def find_smallest_int(arr)\n puts arr.min\nend", "def my_min(list)\r\n list.inject { |min,ele| min < ele ? min : ele }\r\n \r\n # Time : O(n)\r\n # Space : O(1)\r\nend", "def my_min_2(arr)\n\n smallest_value = arr[0] # O(1)\n\n arr.each do |ele1| # [ 0, 3, 5, 4, -5, 10, 1, 90 ] O(n)\n smallest_value = ele1 if ele1 <= smallest_value #O(1)\n end\n\n smallest_value #O(1)\n\nend", "def my_min_linear(list)\n smallest_number = list.first\n \n list.each do |num|\n smallest_number = num if num < smallest_number\n end\n\n smallest_number\nend", "def my_min_fast(list)\n smallest = list.first\n\n list[1..-1].each { |n| smallest = n if n < smallest }\n smallest\nend", "def get_minimum_number\n\t start = 0\n\t last = @src_array.length-1\n\n\t\twhile(@src_array[start] > @src_array[last])\n\t\t\tmid = start + (last-start)/2\n\t\t\tif (@src_array[mid] > @src_array[last])\n\t\t\t\tstart = mid+1\n\t\t\telse\n\t\t\t\tlast = mid\n\t\t\tend\n\t\tend\n\t\treturn @src_array[start]\n\tend", "def my_min_ii(list)\n min = list.first\n list.each do |el|\n min = el if el < min\n end\n min\nend" ]
[ "0.76129997", "0.74145097", "0.73758173", "0.7367551", "0.7359541", "0.7330479", "0.7317693", "0.7302399", "0.72603536", "0.72531956", "0.72435087", "0.7218045", "0.7207991", "0.71793324", "0.71555924", "0.71309173", "0.7127069", "0.7107026", "0.706305", "0.70531857", "0.70467776", "0.70386535", "0.7036944", "0.6990913", "0.69851506", "0.6977309", "0.6962711", "0.69527745", "0.6948749", "0.69361186", "0.6920732", "0.6916237", "0.6913373", "0.6911864", "0.6908297", "0.6907592", "0.68967944", "0.6882903", "0.6882307", "0.68775195", "0.685952", "0.685878", "0.6857509", "0.68566275", "0.68559253", "0.68528897", "0.6849434", "0.68423295", "0.6838729", "0.6837932", "0.6837762", "0.6834915", "0.6833704", "0.6815808", "0.68146193", "0.68101656", "0.68021315", "0.6787905", "0.678576", "0.6779513", "0.67693436", "0.67646205", "0.676362", "0.674168", "0.6717964", "0.67065966", "0.6698818", "0.6692056", "0.6681227", "0.66728526", "0.66626793", "0.6660957", "0.66595805", "0.6658374", "0.6649044", "0.664803", "0.6634294", "0.6626822", "0.6626553", "0.66224533", "0.66156673", "0.66130537", "0.6606053", "0.6594196", "0.6593312", "0.6573523", "0.6555389", "0.6553226", "0.65483624", "0.65474564", "0.65339035", "0.65301144", "0.6527071", "0.6519459", "0.65190697", "0.6510383", "0.64989007", "0.64856535", "0.6483671", "0.64803535", "0.64796406" ]
0.0
-1
Challenge 5: Maximum Difference Given an array of integer elements, a subsequence of this array is a set of consecutive elements from the array (i.e: given the array v: [7, 8, 3, 5, 1], a subsequence of v is 8, 3, 5) Your task is to write a function that finds a left and a right subsequence of the array that satisfy the following conditions the two subsequences are unique (they don't have shared elements) the difference between the sum of the elements in the right subsequence and the sum of the elements in the left subsequence is maximum print the difference to the standard output (stdout) Note that your function will receive the following arguments: v which is the array of integers Data constraints the array has at least 2 and at most 1,000,000 numbers all the elements in the array are integer numbers in the following range: [1000, 1000] given an array and a starting index, return whether or not you can get to a zero by jumping forwards or backwards in the array by the numbers you land on
def can_win(array, index) positions_to_try = [index] visited = [] until positions_to_try.empty? pos = positions_to_try.shift value = array[pos] next if value.nil? || visited[pos] return true if value == 0 visited[pos] = true positions_to_try << pos + value positions_to_try << pos - value end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def maximum_difference_2(v)\n\n integral_sum = [0]\n max = 0\n for index in (0..v.length-1) do\n integral_sum.push(integral_sum[index] + v[index])\n end\n\n for seq_len_left in (1..v.length-1) do\n for left_side in (0..(v.length-seq_len_left-1)) do\n sum_l = integral_sum[seq_len_left+left_side] - integral_sum[left_side]\n sum_l_abs = sum_l.abs\n for seq_len_right in (1..(v.length-seq_len_left)) do\n for right_side in (left_side+seq_len_left..(v.length-seq_len_right)) do\n sum_r = integral_sum[right_side + seq_len_right] - integral_sum[right_side]\n sum_r_abs = sum_r.abs\n dif = sum_l_abs + sum_r_abs\n if dif > max\n max = dif\n end\n end\n end\n end\n end\n puts \"#{max}\"\nend", "def maximum_difference(v)\n\n integral_sum = [0]\n max = 0\n for index in (0..v.length-1) do\n integral_sum.push(integral_sum[index] + v[index])\n end\n\n for seq_len in (1..v.length-1) do\n for left_side in (0..(v.length-seq_len-1)) do\n sum_l = integral_sum[seq_len+left_side] - integral_sum[left_side]\n sum_l_abs = sum_l.abs\n for right_side in (left_side+seq_len..(v.length-seq_len)) do\n sum_r = integral_sum[right_side + seq_len] - integral_sum[right_side]\n sum_r_abs = sum_r.abs\n dif = sum_l_abs + sum_r_abs\n if dif > max\n max = dif\n end\n end\n end\n end\n puts \"#{max}\"\nend", "def solution(a)\n # first and last positions are excluded for the double slice\n a[0] = 0\n a[-1] = 0\n\n #get the sum of maximum subarray, from the left to the right direction\n max_from_left = []\n max_ending = 0\n a.each do |v|\n max_ending = [0, max_ending + v].max\n max_from_left << max_ending\n end\n \n #get the sum of maximum subarray, from the right to the left direction\n max_from_right = []\n max_ending = 0\n a.reverse.each do |v|\n max_ending = [0, max_ending + v].max\n max_from_right << max_ending\n end\n max_from_right.reverse!\n\n # when comparing both directions excludes the i index and take the maximum double slice value.\n n = a.size\n max_double_slice = 0\n for i in 1..n-2\n max_double_slice = [max_double_slice, max_from_left[i - 1] + max_from_right[i + 1]].max\n end\n\n max_double_slice\n\nend", "def disjoint_attempt(arr)\n part = [0]\n maxPrev = [0]\n maxLeft = []\n minPrev = [0]\n minLeft = []\n max = 0\n\n # main idea: subsequence sum is partial sum at end minus partial\n # sum at start. Max score is thus either\n # maxLeft[i] + maxPrev[i] - 2 * part[i] or\n # - minLeft[i] - minPrev[i] + 2 * part[i]\n # for some i\n\n\n # calculate partial sums up to each index in the array\n # calculate max of these seen so far at each index\n arr.each_with_index do |el, i|\n k = i + 1\n part[k] = part[i] + el\n maxPrev[k] = [maxPrev[i], part[k]].max\n minPrev[k] = [minPrev[i], part[k]].min\n end\n\n maxLeft[arr.size] = part[arr.size]\n minLeft[arr.size] = part[arr.size]\n\n # calculate max partial sum remaining at each index\n # now that we have enough info, update max score\n arr.size.downto(1) do |i|\n k = i - 1\n maxLeft[k] = [maxLeft[i], part[k]].max\n minLeft[k] = [minLeft[i], part[k]].min\n max = [max, maxLeft[i] + maxPrev[i] - 2 * part[i],\n 0 - minLeft[i] - minPrev[i] + 2 * part[i]].max\n end\n\n # loop doesn't catch this\n max = [max, maxLeft[0] + maxPrev[0] - 2 * part[0],\n 0 - minLeft[0] - minPrev[0] + 2 * part[0]].max\n return max\nend", "def solution(a)\n min_index = nil\n max_index = nil\n\n a.each_with_index do |num, index|\n if index < a.length-1\n if num > a[index + 1]\n min_index = index\n break\n end\n end\n end\n\n reversed_array = a.reverse\n\n reversed_array.each_with_index do |num, index|\n if index < reversed_array.length-1\n if num < reversed_array[index + 1]\n max_index = a.length - index - 1\n break\n end\n end\n end\n\n if min_index.nil? && max_index.nil?\n return 0\n end\n\n until a.sort == a[0...min_index] + a[min_index..max_index].sort + a[max_index+1..-1]\n minimum_in_sub = a[min_index..max_index].sort.first\n maximum_in_sub = a[min_index..max_index].sort.last\n\n new_min_index = a[0...min_index].reverse.index(a[0...min_index].reverse.find{|n| n >= minimum_in_sub})\n\n if new_min_index\n min_index = min_index - new_min_index - 1\n end\n\n new_max_index = a[max_index+1..-1].index(a[max_index+1..-1].find{|n| n <= maximum_in_sub})\n\n if new_max_index\n max_index = max_index + new_max_index + 1\n end\n end\n\n max_index - min_index + 1\nend", "def solution(a)\n numbers = a.sort\n (0..numbers.length-3).each do |index|\n triplet = numbers[index..index + 2]\n max_value = triplet.max\n sum = triplet.min(2).inject(&:+)\n\n return 1 if sum > max_value\n end\n\n 0\nend", "def solution(a)\n n = a.size\n starting = Array.new(n, 0)\n ending = Array.new(n, 0)\n\n (1..n - 2).each {|i| starting[i] = [starting[i - 1] + a[i], 0].max}\n (1..n - 2).reverse_each {|i| ending[i] = [ending[i + 1] + a[i], 0].max}\n\n sum = 0\n (1..n - 2).each {|i| sum = [sum, starting[i - 1] + ending[i + 1]].max}\n sum\nend", "def max_sub_array_DYNAMIC(nums)\n puts \"\\nSTARTING WITH #{nums}\"\n return 0 if nums == nil\n \n # take inventory of the continuous patches\n continuousPositiveSegments = {}\n continuousNegativeAndZeroSegments = {}\n # key = startingIndex, value = sum\n \n # iterate thru to assemble the 2 inventories \n curr_index = 0\n startingPosIndex = nil\n runningPosTotal = 0\n startingNegIndex = nil\n runningNegTotal = 0\n \n while curr_index < nums.length \n \n if nums[curr_index] > 0\n # positive element\n if !startingPosIndex\n # start a new pos segment\n startingPosIndex = curr_index\n runningPosTotal += nums[curr_index]\n \n if startingNegIndex\n # end previous neg segment, add to inventory and reset counters\n continuousNegativeAndZeroSegments[startingNegIndex] = runningNegTotal\n startingNegIndex = nil\n runningNegTotal = 0\n end\n \n elsif startingPosIndex\n # already in the middle of a pos segment\n runningPosTotal += nums[curr_index]\n end\n \n else\n # negative or zero element\n if !startingNegIndex\n # start a new neg segment\n startingNegIndex = curr_index\n runningNegTotal += nums[curr_index]\n \n if startingPosIndex\n # end previous pos segment, add to inventory and reset counters\n continuousPositiveSegments[startingPosIndex] = runningPosTotal\n startingPosIndex = nil\n runningPosTotal = 0\n end\n elsif startingNegIndex\n # already in the middle of a neg segment\n runningNegTotal += nums[curr_index]\n end\n end\n \n curr_index += 1\n end\n \n # nums array ended, wrap up whatever the last segment happened to be\n if startingPosIndex\n continuousPositiveSegments[startingPosIndex] = runningPosTotal\n else\n continuousNegativeAndZeroSegments[startingNegIndex] = runningNegTotal\n end\n \n ###### FINISHED TAKING INVENTORY #####\n puts \"Continuous positive segments:\\t#{continuousPositiveSegments}\"\n puts \"Continuous neg/zero segments:\\t#{continuousNegativeAndZeroSegments}\\n\\n\"\n \n \n \n ###### EVALUATE FOR BEST SUM #####\n positiveSegStartingIndices = continuousPositiveSegments.keys\n \n if positiveSegStartingIndices.length == 0\n # return the least negative single element then\n return nums.max()\n \n elsif positiveSegStartingIndices.length == 1\n # only 1 single patch of continuousPositive Segments exist\n return continuousPositiveSegments.values[0]\n \n else\n # evaluate which patches add up for highest number\n # we want to start from each positive segment\n curr_winner = 0\n \n positiveSegStartingIndices.each do |i|\n puts \"starting at #{i}\"\n curr_contender = 0\n \n if continuousPositiveSegments[i]\n curr_contender += continuousPositiveSegments[i]\n elsif continuousNegativeAndZeroSegments[i]\n curr_contender += continuousNegativeAndZeroSegments[i]\n else\n # this index is in not the start of a pos or neg segment\n end\n \n if curr_contender > curr_winner\n curr_winner = curr_contender\n puts \"new winner! #{curr_contender}\"\n end\n \n j = i + 1\n while j < nums.length \n if continuousPositiveSegments[j]\n curr_contender += continuousPositiveSegments[j]\n elsif continuousNegativeAndZeroSegments[j]\n curr_contender += continuousNegativeAndZeroSegments[j]\n else\n # this index is in not the start of a pos or neg segment\n end\n \n if curr_contender > curr_winner\n curr_winner = curr_contender\n puts \"\\tnew winner of #{curr_contender}! From index #{i} to end of segment starting with index #{j}\"\n end\n j += 1\n end\n end\n \n puts \"WINNER!!! #{curr_winner}\"\n return curr_winner\n end\nend", "def kadanes_algorithm(array)\n maxEndingHere = array[0]\n maxSoFar = array[0]\n array.slice(1..-1).each do |num|\n maxEndingHere = [num, maxEndingHere + num].max\n maxSoFar = [maxSoFar, maxEndingHere].max\n end\n return maxSoFar\nend", "def solution(a)\n # write your code in Ruby 2.2\n return 0 if a.length == 3\n range = a[1...-1]\n min = Float::INFINITY\n max_ending = 0\n range.inject(0) do |max, y|\n if max_ending + y > 0\n max_ending += y\n if min == Float::INFINITY\n max = [max, max_ending].max\n min = y\n else\n min = y if y < min\n max = [max, max_ending - min].max\n end\n else\n max_ending = 0\n min = Float::INFINITY\n end\n max\n end\nend", "def solution(a)\n if a.count >= 3\n distances = []\n last = nil\n (1...a.count - 1).each { |i|\n if a[i] > a[i - 1] and a[i] > a[i + 1]\n distances << i - last if last\n last = i\n end\n }\n puts distances.inspect\n \n (distances.count + 1).downto(1) { |flags|\n return flags if distances.all? { |d| d >= flags }\n }\n end\n 0\nend", "def solution(a)\n # write your code in Ruby 2.2\n binding.pry\n trips = Hash.new {|h,k| h[k]=0}\n start = 0\n ending = 0\n min = nil\n a.each_with_index do |trip,i|\n ending = i\n\n if trips[trip] == 0\n min = ending - start\n end\n trips[trip] += 1\n\n while start < ending\n break if trips[a[start]] - 1 == 0\n trips[start] -= 1\n start += 1\n min = ending - start if ending-start < min\n end\n end\n min\nend", "def solve(array)\n largest_diff = array[1] - array[0]\n result = []\n\n array.each_with_index do |element, index|\n if array[index + 1] != nil\n if (array[index + 1] - array[index]) >= largest_diff\n result << array[index + 1]\n end\n end\n end\nend", "def contig_sum(array)\n greatest_diff = -Float::INFINITY\n subsets = []\n\n i = 0\n while i < array.length\n j = i + 1\n while j <= array.length\n subsets << array[i..j]\n j += 1\n end\n i += 1\n end\n\n subsets.each do |arr|\n sum = arr.inject(:+)\n if sum > greatest_diff\n greatest_diff = sum\n end\n end\n greatest_diff\n\nend", "def max_sequence(arr)\n sum = 0\n \n arr.each_with_index do |ele, i| \n l = arr.length\n\n while l >= i\n sub_arr = arr[i..l]\n sum = sub_arr.sum if sub_arr.sum > sum\n l -= 1\n end \n end\n \n sum\nend", "def max_sub_arr(arr)\n max_so_far = 0\n max_ending_here = 0\n start_i = nil\n end_i = nil\n arr.each_with_index do |el, i|\n if max_ending_here == 0 && max_ending_here + el > 0\n start_i = i\n end\n\n max_ending_here = max_ending_here + el\n if max_ending_here < 0\n max_ending_here = 0\n end\n\n if max_so_far < max_ending_here\n max_so_far = max_ending_here\n end_i = i\n end\n end\n\n return [start_i, end_i], max_so_far\nend", "def solution(a)\n left = 0\n right = a.sum\n a.each_with_index do |element, index|\n right -= element\n return index if left == right\n left += element\n end\n -1\nend", "def solution(a)\n sea_slices = find_slices(a.map(&:zero?))\n mountain_slices = find_slices(a.map(&:nonzero?), true)\n best = 0\n (a.length - 1).times do |i|\n if sea_slices[i] && mountain_slices[i + 1]\n best = [best, sea_slices[i] + mountain_slices[i + 1]].max\n end\n end\n best\nend", "def arrayMaximalAdjacentDifference(inputArray)\n max = 0\n \n for i in 1..(inputArray.count - 1)\n value = inputArray[i] - inputArray[i-1]\n if value < 0\n value = - value\n end\n if value > max\n max = value\n end\n end\n \n max\nend", "def max_sub_array(array)\n max_sum = current_val = array[0]\n array.each_with_index do |num, i|\n if (i > 0)\n sum = current_val + num\n if (sum > num)\n current_val = sum\n else\n current_val = num\n end\n if current_val > max_sum\n max_sum = current_val\n end\n end\n end\n max_sum\nend", "def max_sequence(arr)\n puts arr\n index = 0\n numIndexes = 0\n highestSum = arr.min\n \n length = arr.count\n \n highestNum = arr.max\n\n if arr != [] && highestNum < 0 \n return 0\n elsif arr == []\n return 0\n end\n \n arr.map.with_index do |n,i|\n\n for c in 0..i\n \n sum = arr.slice(c,length-i).inject(:+)\n\n if sum > highestSum\n highestSum = sum\n index = i\n numIndexes = length-i\n end\n \n end\n \n end\n \n highestSum\n \nend", "def findLongestSubarrayBySum(s, arr)\n history = {0 => -1} \n sum = 0 \n max_length = 0 \n result = [-1]\n\n for idx in 0...arr.length \n sum += arr[idx]\n history[sum] = idx if history[sum].nil? \n\n if history[sum - s]\n length = idx - history[sum - s]\n if length > max_length \n max_length = length \n result = [history[sum - s]+2, idx+1]\n end \n end \n end \n\n result\nend", "def smallest_diff_between_sub_arrays(arr)\n # write your code in Ruby 2.2\n first_part = 0\n second_part = 0\n result = 0\n arr.each_with_index do |num, i|\n next if i == arr.length - 1\n\n # you just need to sum the array once\n # indeed the 'second part' of the first split is the biggest one\n # no need to do this calculation again after\n if i.zero?\n first_part = arr[0]\n second_part = arr[1, arr.length - 1].inject(:+)\n result = (first_part - second_part).abs\n else\n # after that you just need to pass over one number from the second to the first part\n # and check if diff is smaller thant current result\n first_part += num\n second_part -= num\n diff = (first_part - second_part).abs\n result = diff if diff < result\n end\n end\n result\nend", "def max_sequence(arr)\r\n return 0 if arr.all? { |el| el < 0 }\r\n return arr.sum if arr.all? { |el| el > 0 }\r\n return 0 if arr.empty?\r\n \r\n sub_arrs = []\r\n (0...arr.size).each do |start_index|\r\n # p \"start #{start_index}\"\r\n (1..arr.size - start_index).each do |length|\r\n # p \"length #{length}\"\r\n sub_arrs << arr[start_index, length]\r\n end\r\n end\r\n sub_arrs.map do |sub_arr|\r\n sub_arr.sum\r\n end.max\r\nend", "def deviation(v,d)\n maxDeviation = 0\n for i in 0..v.length-d\n sequence = v.slice(i,d)\n if sequence.max >= maxDeviation\n deviation = sequence.max - sequence.min\n maxDeviation = deviation if maxDeviation < deviation\n end\n end\n puts maxDeviation\nend", "def solution(a)\n left_sum = a.first\n right_sum = a.drop(1).reduce(:+)\n min_diff = (left_sum - right_sum).abs\n\n a.take(a.length - 1).drop(1).each do |element|\n left_sum += element\n right_sum -= element\n\n current_diff = (left_sum - right_sum).abs\n\n if current_diff < min_diff\n min_diff = current_diff\n end\n end\n min_diff\nend", "def solution(a)\n first_sum = a[0]\n second_sum = a.inject(&:+) - a.first\n result = (first_sum - second_sum).abs\n\n a[1..-2].each do |elem|\n first_sum = first_sum + elem\n second_sum = second_sum - elem\n tmp_result = (first_sum - second_sum).abs\n result = tmp_result if tmp_result < result\n end\n\n result\nend", "def max_slice(a)\n n = a.length\n k1 = Array.new(n, 0)\n k2 = Array.new(n, 0)\n\n (1..(n-1)).each {|i| k1[i] = [k1[i-1] + a[i], 0].max }\n\n i = n - 2\n while i > 0 do\n k2[i] = [k2[i+1]+a[i], 0].max\n i -= 1\n end\n\n max_val = 0\n (1..(n-2)).each do |i|\n max_val = [max_val, k1[i-1] + k2[i + 1]].max\n end\n\n return max_val\nend", "def solution(a)\n # write your code in Ruby 2.2\n left = 0\n right = a.reduce(:+)\n difference = []\n\n for i in 1..(a.size-1) do\n left += a[i-1]\n right -= a[i-1]\n absolute = (left - right).abs\n difference.push(absolute)\n end\n #puts \"#{difference}\"\n return difference.min\nend", "def largest_cont_subsum_fast(list)\n # for constant size to be true, you cant create any variables\n # whose memory size depends on the size of the input\n curr_sum = list[0]\n largest_sum = list[0]\n\n # we know there are n^2 potential, so if we ever check all of them\n # it must be n^2\n\n # there must be a way to find the max without checking every subarray\n list[1..-1].each do |ele|\n # debugger\n if curr_sum > largest_sum\n largest_sum = curr_sum\n end\n\n if curr_sum < 0\n curr_sum = 0\n end\n\n curr_sum += ele\n\n end\n\n # debugger\n return [largest_sum, curr_sum].max\n\nend", "def LongestIncreasingSequence(arr)\n size = arr.size\n \n while size > 1\n sub_seq = arr.combination(size).to_a\n sub_seq.each do |seq|\n inc_seq = true\n seq.each_cons(2) { |num1, num2| break inc_seq = false unless num2 > num1 }\n return seq.size if inc_seq\n end \n size -= 1\n end\n 1\nend", "def largest_contiguous_subsum_good(arr) \n last_max = arr.first\n current_max = 0\n arr.each do |num|\n temp_sum = current_max + num\n if temp_sum < 0\n last_max = current_max if temp_sum > last_max\n else\n if temp_sum > last_max\n last_max = temp_sum\n end\n end\n if num > temp_sum\n current_max = num\n else\n current_max = temp_sum\n end\n end\n last_max\nend", "def max_sub_array(nums)\n current_sum = nil\n max_sum = nil\n \n nums.each do |n|\n if current_sum.nil?\n current_sum = n\n elsif current_sum + n < n\n current_sum = n\n else\n current_sum = current_sum + n\n end\n max_sum = current_sum if max_sum.nil? || current_sum > max_sum\n end\n max_sum\nend", "def solve(array)\n largest_sum = 0\n\n array.each_with_index do |element, index|\n current_largest_sum = 0\n if element > 0\n current_largest_sum += element\n\n array[index..(-1)].each do |el|\n current_largest_sum += el if el > element\n end\n current_largest_sum -= element\n largest_sum = current_largest_sum if current_largest_sum > largest_sum\n end\n end\n largest_sum\nend", "def largest_continguous_subsum(arr)\n largest_sum = arr.first\n current_sum = arr.first\n \n (1...arr.length).each do |i|\n current_sum += arr[i]\n if current_sum > largest_sum\n largest_sum = current_sum\n elsif current_sum < 0\n current_sum = 0\n end\n end\n largest_sum\nend", "def largest_difference_divide_and_conquer(array)\n # To lower space complexity, I'll call \"array[0..array.length / 2]\" etc.\n # manually each time, but I'd rather store the subarrays as their own variable\n # to make the code cleaner\n max_difference_first = largest_difference_nested_iteration(array[0..(array.length / 2)])\n max_difference_second = largest_difference_nested_iteration(array[(array.length / 2 + 1)..(array.length - 1)])\n\n max_difference = [max_difference_first, max_difference_second].max\n [max_difference, (array[(array.length / 2 + 1)..(array.length - 1)].max - array[0..(array.length / 2)].min)].max\nend", "def maxSubArraySum(a)\n maxint =(2**(0.size * 8 -2) -1)\n msf = -maxint - 1\n max_end = 0\n \n for i in (0..a.length-1)\n max_end = max_end + a[i] \n if (msf < max_end)\n msf = max_end\n end\n \n if (max_end < 0) \n max_end = 0 \n end\n end\n return msf\nend", "def max_sub_array(nums)\n return 0 if nums == nil\n return nil if nums.empty?\n \n max_by_here = nums[0]\n max_so_far = nums[0]\n \n nums.each_with_index do |num, index|\n unless index == 0\n if max_so_far < 0\n if num > max_so_far\n max_so_far = num\n end\n else\n max_by_here += num\n \n if max_by_here < 0\n max_by_here = 0\n elsif max_by_here > max_so_far\n max_so_far = max_by_here\n end\n end\n end\n end\n \n return max_so_far\nend", "def max_sub(a)\na[(0...(n=a.size)).inject([]){|r,i|(i...n).inject(r){|r,j|r<<(i..j)}}.sort_by{|r|a[r].inject{|i,j|i+j}}[-1]]\nend", "def largest_contiguous_subsum2(array)\n #all negative numbers\n if array.none? {|el| el > 0 }\n max = array.first\n array.each do |el1|\n next if max == el1\n if el1 > max\n max = el1\n end\n end\n max\n end\n\n current_sum = 0\n max_sum = 0\n\n array.each do |num|\n current_sum += num\n max_sum = current_sum if current_sum > max_sum\n if current_sum < 0\n current_sum = 0\n next\n current_sum += num\n max_sum = current_sum if current_sum > max_sum\n end\n\n end\n max_sum\n\nend", "def max_sub_array(numbers)\n max = numbers[0]\n\n (1...numbers.size).each do |idx|\n current_sum = numbers[idx] + numbers[idx - 1]\n numbers[idx] = current_sum if current_sum > numbers[idx]\n max = numbers[idx] if numbers[idx] > max\n end\n\n max\nend", "def longest_increasing_subsequence(nums) len = nums.length\n return len if len < 2\n\n# After calculating lis for each index, take a max by 1 value equal to max, go backwards on lis array, and every time we find an element equal to max, we add that element to result and decrement max by 1. Hereby we'll get the indexes array in reversed order.\n lis_array = find_lis_lengths(nums)\n\n result = []\n max = lis_array.max\n i = len - 1\n while i >= 0\n if lis_array[i] == max\n result.unshift(nums[i])\n max -= 1\n end\n i-= 1\n end\n result\n\nend", "def largest_continous_subsum\n largest = 0\n subsets = []\n\n i = 0\n while i < self.length\n j = i\n while j < self.length\n subsets << self[i..j]\n j += 1\n end\n i += 1\n end\n\n subsets.each do |pair|\n if largest < pair.reduce(:+)\n largest = pair.reduce(:+)\n end\n end\n largest\n\n end", "def sub_max(array)\n so_far = array[0]\n max_point = array[0] # [0] -2 and [1] 1 sum -1, number 1\n\n array.each do |number|\n # to find the max between the two values:\n max_point = max((number + max_point), number)\n so_far = max(max_point, so_far)\n end\n\n return so_far\nend", "def longest_equal_subarray(array)\n return 0 if array == 0\n\n current_length, max_length, number = 0, 0, array.first\n\n array[1..-1].each do |x|\n if x == number\n current_length += 1\n else\n number = x\n current_length = 0\n end\n\n max_length = [max_length, current_length].max\n end\n\n max_length\nend", "def solution(a)\n min_val = 10_000\n min_pos = 0\n \n sums = [0]\n for i in (0..a.count - 1) \n sums << sums.last + a[i] \n end\n for p in (0..a.count - 2)\n for q in (p + 1..[p + 2, a.count - 1].min)\n s = (sums[q + 1] - sums[p]).to_f / (q - p + 1)\n if s < min_val\n min_val = s\n min_pos = p\n end\n end\n end\n min_pos\nend", "def sub_sum_improved(array)\n max = array[0]\n current_sum = array[0]\n i = 0\n (1...array.length).each do |i|\n max = [array[i], array[i] + max].max\n current_sum = [current_sum, max].max\n end\n current_sum\n end", "def find_unsorted_subarray4(nums)\n min = Float::INFINITY\n max = -Float::INFINITY\n\n flag = false\n\n nums.each_cons(2) do |n1, n2|\n flag = true if n2 < n1\n min = [min, n2].min if flag\n end\n\n flag = false\n nums.reverse.each_cons(2) do |n1, n2|\n flag = true if n2 > n1\n max = [max, n2].max if flag\n end\n\n left = nums.length\n right = 0\n\n (0..nums.size - 1).each do |index|\n left = index\n break if nums[index] > min\n end\n\n (nums.size - 1).downto(0) do |index|\n right = index\n break if nums[index] < max\n end\n\n right > left ? right - left + 1 : 0\nend", "def solve(nums)\n sorted = nums.sort\n largest = 0\n (0...sorted.length - 1).each do |i|\n if (sorted[i+1] - sorted[i]) > largest\n largest = (sorted[i+1] - sorted[i])\n end\n end\n return largest\n\nend", "def solution(a)\n # write your code in Ruby 2.2\n left, right = 0, a.reduce(:+)\n min = 0\n (1...a.size).to_a.each do |i|\n left = left + a[i-1]\n right = right - a[i-1]\n diff = (left - right).abs\n if i == 1\n min = diff\n else\n min = diff < min ? diff : min\n end\n end\n min\nend", "def subarray(arr,num)\n\t#sort the array, use pointers\n\tj = 0\n\ti = 0\n\tsum = 0\n\twhile j < arr.length\n\t\tif sum < num\n\t\t\t#moving up the array if sum is less than number\n\t\t\tsum += arr[j]\n\t\t\tj += 1\n\t\telse\n\t\t\tminLen = [9000, j-i].min\n\t\t\tif i == (j-1)\n\t\t\t\treturn 1\n\t\t\tend\n\t\t\tsum -= arr[i]\n\t\t\ti += 1\n\t\tend\n\t\tputs sum, \"first\"\n\t\tputs minLen, \"minfirst\"\n\t\tputs i,\"i\", j, \"j\"\n\tend\n\t\n\twhile sum >= num\n\t\tminLen = [9000, j-i].min\n\t\ti += 1\n\t\tsum -= arr[i]\n\t\tputs sum, \"second\"\n\t\tputs minLen, \"minsecond\"\n\t\tputs i,\"i\", j, \"j\"\n\tend\n\tif minLen == 9000\n\t\tputs 0\n\telse\n\t\tputs minLen\n\tend\n\nend", "def maxSubArray(a)\n return nil if a.empty?\n curr_sum = a[0]\n max_sum = a[0]\n (1...a.length).each do |i| \n if curr_sum <= 0\n curr_sum = a[i]\n else\n curr_sum += a[i]\n end\n max_sum = curr_sum if max_sum < curr_sum\n end\n max_sum\nend", "def solution(a)\n return 0 if a.length < 3\n\n # Find minimum 2-slice and its index - min_2 = [a, b], idx\n min_2 = a.each_cons(2).each_with_index.reduce do |i, j|\n i[0].sum() <= j[0].sum() ? i : j\n end\n\n # Find minimum 3-slice and its index - min_3 = [a, b], idx\n min_3 = a.each_cons(3).each_with_index.reduce do |i, j|\n i[0].sum() <= j[0].sum() ? i : j\n end\n\n # Integer cross multiply instead of float divide for average\n min_2[0] = min_2[0].sum() * 3\n min_3[0] = min_3[0].sum() * 2\n \n # Return index of smaller slice\n min_2[0] <= min_3[0] ? min_2[1] : min_3[1]\nend", "def slow_solution(a)\n m = 0\n a.size.times do |i|\n a[i] = a[i].abs\n m = [a[i], m].max\n end\n maxsum = a.sum # sum of absolute val of all nums in array\n # maxsum = a.map(&:abs).sum <- Ruby shortcut\n\n # If dp = 1 at an index, it means some combo of elements in a add up to that index\n dp = [0] * (maxsum + 1)\n dp[0] = 1\n\n a.size.times do |j|\n maxsum.downto(0).each do |possible_sum|\n puts \"a[j]: #{a[j]}, possible sum: #{possible_sum}\"\n if (dp[possible_sum] == 1) and (possible_sum + a[j] <= maxsum)\n\n # if possible_sum + new element a[j] is possible sum, dp = 1!\n dp[possible_sum + a[j]] = 1\n puts \"Mark #{possible_sum + a[j]} as possible sum in dp\"\n end\n end\n puts \"row: #{j}, a[j]: #{a[j]}, dp: #{dp}\"\n puts\n end\n\n min_q_minus_p = maxsum\n\n # Divide array a into 2 parts, where P = sum of part 1 and Q = sum of part 2,\n # P + Q = maxsum, and P <= maxsum / 2 <= Q.\n # We want largest possible P to get smallest possible Q-P.\n\n # loop from 0 to maxsum / 2, covering every possible P, Q division\n (maxsum / 2 + 1).times do |possible_half_sum|\n # puts \"possible_half_sum: #{possible_half_sum}\"\n if dp[possible_half_sum] == 1 # means P or Q = possible_half_sum\n q_minus_p = maxsum - 2 * possible_half_sum\n # puts \"Q - P: #{q_minus_p}\"\n min_q_minus_p = [min_q_minus_p, q_minus_p].min\n # puts \"min Q - P: #{min_q_minus_p}\"\n end\n end\n\n min_q_minus_p\nend", "def max_sequence(arr)\n return arr.first if arr.size == 1\n return 0 if arr.all? { |num| num < 0 } || arr.empty?\n current_sum = arr.first\n maximum = arr.first\n\n arr[1..-1].each do |num|\n current_sum = 0 if current_sum < 0\n current_sum += num\n maximum = current_sum if current_sum > maximum\n end\n\n maximum\nend", "def linear_subsum(arr)\n largest = arr[0] # 5\n current = 0 # -4\n\n (0...arr.length).each do |idx| # 1\n current += arr[idx]\n largest = current if current >= largest\n current = 0 if current < 0\n end\n largest\nend", "def arrayChange(a)\n total = 0\n a.each_with_index do |v, i|\n next if i == 0 \n if(v <= a [i-1]) \n total += (a[i-1] + 1) - a[i]\n a[i] = a[i-1] + 1\n end\n end\n total\nend", "def max_sum_no_consecutive(array)\n return if array.size = 0\n\n global_max = array[0]\n current_max = array[0]\n\n for i in 1..array.size - 1\n \n end\nend", "def solution(a)\n ((1..a.size + 1).to_a - a).first\nend", "def solution(arr)\n dp = Array.new(arr.max+2, 0)\n arr.each { |a| dp[a] += 1 }\n\n for i in 2...dp.size do\n dp[i] = [dp[i-2] + i*dp[i], dp[i-1]].max\n end\n dp.last\nend", "def solution(a)\r\n # write your code in Ruby 2.2\r\n #trangular\r\n # a[0] = 10\r\n # a[2] = 5\r\n # a[4] = 8\r\n # 10 + 5 > 8\r\n # 5 + 8 > 10\r\n #8 + 10 > 5\r\n \r\n \r\n l=a.count\r\n \r\n i=0\r\n while(i<l) do\r\n j=i+1\r\n while(j<l) do\r\n k=j+1\r\n \r\n \r\n while(k<l) do\r\n if((a[i] + a[j] > a[k]) && (a[j] +a[k] > a[i]) && (a[k] + a[i] >a[j]))\r\n return 1\r\n end\r\n k+=1 \r\n end \r\n \r\n j+=1 \r\n end\r\n i+=1\r\n end\r\n \r\n return 0\r\n \r\nend", "def kadanes_algorithm(arr)\n unless arr.all? { |ele| ele < 0 }\n max_so_far = 0\n max_ending = 0\n arr.each do |ele|\n max_ending = max_ending + ele\n max_ending = 0 if max_ending < 0\n max_so_far = max_ending if max_ending > max_so_far\n end\n else\n max_so_far = arr.max\n end\n puts max_so_far\nend", "def solution(m, a)\n n = a.count\n result = 0\n front = 0\n numbers = Array.new(m + 1, false)\n n.times { |back|\n while front < n and not numbers[a[front] - 1]\n numbers[a[front] - 1] = true\n front += 1\n result += front - back\n return 1_000_000_000 if result >= 1_000_000_000\n end\n numbers[a[back] - 1] = false\n }\n result\nend", "def largest_contiguous_subsum2(list)\n\n largest = list.first\n current = list.first\n\n list[1..-1].each do |num|\n if current < num && current < 0 #dealing with a condition of negative nums and want to restart\n current = num\n elsif num < 0 && current > largest #about to begin negative nums, compare current and largest\n largest = current\n current += num\n else\n current += num\n end\n end\n\n return current if largest < current\n largest\nend", "def largest_contiguous_sub_sum2(arr)\n #one varable tracks largest sum\n #one variable tracks current sum\n #O(n) + O(1)\n # list = [2, 3, -6, 7, -6, 7]\n\n # largest_sum= arr.first\n\n # i = 0\n # arr_end = true\n\n # while arr_end\n # current_sum = arr[i]\n # if arr[i+1] == nil\n # arr_end = false\n # puts \"This is current sum: #{current_sum}\"\n # else\n # if current_sum > largest_sum\n # current_sum += arr[i+1]\n # largest_sum = current_sum\n # end\n # end\n # if i < arr.length\n # arr_end = true\n # i += 1\n # end\n # end\n # largest_sum\n \n\n\n # arr.each_with_index do |ele, idx|\n # if ele > largest_sum\n # largest_sum = ele\n # end\n\n # i = idx\n # sum = ele\n # while i < arr.length - 1\n # if sum <= sum + arr[i+1]\n # largest_sum = sum + arr[i+1]\n # end\n # sum = sum + arr[i+1]\n # i+=1\n # end\n # end\n # largest_sum\n\nend", "def solution(a)\n comp_array = (Array.new(a.length+1){ |index| index+1 })\n diff = comp_array - a\n p diff[0]\nend", "def maximum_sum_subarray(nums)\n highest_seen = nums[0]\n lowest_seen = nums[0]\n highest_curr = nums[0]\n lowest_curr = nums[0]\n\n nums[1..-1].each do |num|\n temp = highest_curr\n highest_curr = [num, highest_curr + num, lowest_curr + num].max\n lowest_curr = [num, temp + num, lowest_curr + num].min\n\n highest_seen = [highest_seen, highest_curr].max\n lowest_seen = [lowest_seen, lowest_curr].max\n end\n highest_seen\nend", "def largest_contiguous_subsum_2(arr)\n (1...arr.length).each do |i|\n if arr[i] + arr[i - 1] > 0\n arr[i] = arr[i] + arr[i - 1]\n elsif arr[i] < 0 && arr[i-1] < 0\n arr[i] = [arr[i-1], arr[i]].max\n else\n arr[i] = 0\n end\n end\n\n arr.max\nend", "def contiguous_sub_sum2(arr)\n max = arr.first\n curr_sum = 0\n arr.each do |num|\n curr_sum += num\n max = curr_sum if curr_sum > max\n curr_sum = 0 if curr_sum < 0\n end\n max\nend", "def opt_max_sum(arr)\n result = -1000\n (0...arr.length).each do |start|\n sum = 0\n (1..arr.length).each do |size|\n if start + size > arr.length\n break\n end\n sum += arr[start + size - 1]\n if sum > result\n result = sum\n end\n end\n end\n return result\nend", "def DP_solve(a)\n max, head, tail = 0, 0, 0\n cur_head = 0\n sum = [ [0, a[0]].max ] # base case\n (1...a.size).each do |j|\n sum[j] = [0, sum[j-1] + a[j]].max # bottom-up\n cur_head = j if sum[j-1] == 0 and sum[j] > 0\n if sum[j] > max\n head = cur_head\n tail = j\n max = sum[j]\n end\n end\n return max, head, tail\nend", "def find_max_crossing_subarray(arr, low, mid, high)\n sum = max_left = 0\n left_sum = -Float::INFINITY\n max_left = 0\n (low..mid).reverse_each do |i|\n sum += arr[i]\n if sum > left_sum\n left_sum = sum\n max_left = i\n end\n end\n\n sum = max_right = 0\n right_sum = -Float::INFINITY\n (mid+1..high).each do |j|\n sum += arr[j]\n if sum > right_sum\n right_sum = sum\n max_right = j\n end\n end\n\n [max_left, max_right, left_sum+right_sum]\nend", "def maximum_sub_array2(arr)\n current = []\n max_sum = cur_sum = 0\n max = (0...arr.size).inject([]) do |max, i|\n current << arr[i]\n cur_sum += arr[i]\n if cur_sum > max_sum\n max << i\n max_sum = cur_sum\n end\n max\n end\n arr[max[0]..max[-1]]\nend", "def better_largest_continous_subsum\n largest = first\n current = first\n switch = false\n each_with_index do |num, idx|\n # debugger\n next if idx == 0\n if switch\n current = num\n largest = current if current > largest\n switch = false\n elsif current + num < current\n if num.abs > current\n switch = true\n else\n current += num\n end\n else\n current += num\n end\n largest = current if current > largest\n end\n largest\n end", "def lis(array)\n helper = Array.new(array.length, 1)\n (1..array.length - 1).each do |array_index|\n (0..array_index).each do |inner_value|\n if array[inner_value] < array[array_index]\n helper[array_index] = [helper[inner_value] + 1, helper[array_index]].max\n end\n end\n end\n helper.max\nend", "def find_unsorted_subarray2(nums)\n sort_nums = nums.sort\n\n left = nums.length\n right = 0\n\n sort_nums.each_with_index do |num, index|\n if num != nums[index]\n left = [index, left].min\n right = [index, right].max\n end\n end\n\n right >= left ? right - left + 1 : 0\nend", "def max_sub_array(nums)\n dp = [nums.first]\n max = dp[0]\n\n (1...nums.length).each do |i|\n prev_max = dp[i - 1] > 0 ? dp[i - 1] : 0\n dp[i] = nums[i] + prev_max\n max = [max, dp[i]].max\n end\n\n max\nend", "def contig_sum2(array)\n greatest_sum = array[0]\n useful_sum = array[0]\n\n array.each_index do |idx|\n useful_sum = 0 if useful_sum < 0 && idx == 0\n next if idx == 0\n useful_sum += array[idx]\n\n if useful_sum > greatest_sum\n greatest_sum = useful_sum\n elsif useful_sum < 0\n useful_sum = 0\n end\n end\n\n greatest_sum\nend", "def solution(a)\n return 0 if a.length < 3\n a.sort.each_cons(3) { |e| return 1 if e[0] + e[1] > e[2] }\n return 0\nend", "def solution(a)\n # [1, -INFINITY, -INFINITY, -INFINITY, -INFINITY, -INFINITY]\n # [1,-1, 1, 10, 0, -1] row = 1. start_val = 1\n # [1,-1, 1, 10, 0, -1] row = 2. start_val = -1\n # [1,-1, 1, 10, 0, -1] row = 3. start_val = 1\n # [1,-1, 1, 10, 9, 8] row = 4. start_val = 10\n # [1,-1, 1, 10, 9, 8] row = 5. start_val = 9\n\n dp = [a[0]] + [MININT] * (a.size - 1)\n (1..a.size - 1).each do |row|\n start_index = row - 1\n start_val = dp[start_index]\n\n # we may only move forward up to 6 spots\n end_col = [a.size - 1, start_index + 6].min\n puts \"start_val: #{start_val}. Inner loop start_col: #{row} / end_col: #{end_col}\"\n\n (row..end_col).each do |col|\n puts \"row: #{row}, col: #{col}\"\n dp[col] = [dp[col], start_val + a[col]].max\n end\n p dp\n puts\n end\n\n \"Answer: #{dp.last}\"\nend", "def contiguous_sequence(array)\n max_sum = array.first\n array.each_with_index do |num, idx|\n current_sum = num\n array[(idx+1)..-1].each do |num|\n current_sum += num\n max_sum = current_sum if current_sum > max_sum\n end\n end\n\n max_sum\nend", "def find_max_crossing_subarray(array, low, mid, high)\n left_sum = -Float::INFINITY\n max_left = max_right = 0\n sum = 0\n mid.downto(low) do |index|\n sum += array[index]\n if sum > left_sum\n left_sum = sum\n max_left = index\n end\n end\n\n right_sum = -Float::INFINITY\n sum = 0\n (mid+1).upto(high) do |index|\n sum += array[index]\n if sum > right_sum\n right_sum = sum\n max_right = index\n end\n end\n\n [max_left, max_right, left_sum + right_sum]\nend", "def contig_subsum(array)\n sub_arrays = []\n i = 0\n j = 0\n while i < array.length do\n while j < array.length do\n sub_arrays << array[i..j]\n j += 1\n end\n i += 1\n j = i\n end\n\n max_sum = 0\n arr = []\n\n sub_arrays.each do |sub|\n arr << sub.inject(:+)\n end\n\n arr.uniq.sort.last\n\nend", "def max_sequence(arr)\n return 0 if arr.empty?\n\n max_ending_here = max_so_far = 0\n \n arr.each do |n|\n max_ending_here = [n, max_ending_here + n].max\n max_so_far = [max_so_far, max_ending_here].max\n end\n \n max_so_far\nend", "def max_sub_array(arr)\n current_sum = arr[0]\n max_sum = current_sum\n\n arr[1..-1].each do |num|\n current_sum = [num, current_sum + num].max\n max_sum = [max_sum, current_sum].max\n end\n\n return max_sum\nend", "def solution(a)\n return 1 if a.empty?\n a.sort!\n return 1 if a.first > 1\n return a.first + 1 if a.length <2\n (0..(a.length)).each do |index|\n return a[index] + 1 if a[index] + 1 != a[index + 1]\n end\n return a.last + 1\nend", "def max_sequence(arr)\n return 0 if arr.empty? || arr.all?(&:negative?)\n\n result = []\n 1.upto(arr.size) { |n| result << arr.each_cons(n).map(&:sum).max }\n result.max\nend", "def max_subsection_sum(arr)\n current_sum = 0\n greatest_sum = 0\n\n arr.each_with_index do |num, idx|\n if current_sum + num < 0\n current_sum = 0\n else\n current_sum += num\n greatest_sum = current_sum if current_sum > greatest_sum\n end\n end\n greatest_sum\nend", "def max_sub_array(nums)\n return if nums.empty?\n\n max_so_far = Array.new(nums.length)\n max_so_far[0] = nums[0]\n\n (1...nums.length).each do |i|\n max_so_far[i] = [nums[i], nums[i] + max_so_far[i-1]].max\n end\n\n return max_so_far.max\nend", "def largest_contiguous_subsum2(arr)\n max = arr[0]\n current = arr[0]\n arr.drop(1).each do |num|\n current += num\n max = current if current > max\n current = 0 if current < 0\n end\n max\nend", "def longest_decreasing_subsequence(sequence)\n len = sequence.length\n\n # construct a temp array to store lenght of LDS at each index(default len: 1)\n temp = [1] * len # or Array.new(len, 1)\n\n (len - 2).downto(0) do |i|\n (len - 1).downto(i - 1) do |j|\n if sequence[i] > sequence[j] && temp[i] < temp[j] + 1\n temp[i] = temp[j] + 1\n end\n end\n end\n\n return temp.max\nend", "def arrayManipulation(n, queries)\n diffArr =[]\n for i in 0..n\n diffArr.push(0)\n end\n for j in queries\n diffArr[j[0]-1] += j[2]\n diffArr[j[1]] -= j[2]\n end\n max = 0\n sum = 0\n for k in diffArr\n sum += k\n max = [sum, max].max\n end\n return max\n\nend", "def solution(a)\n n = a.size\n return 0 unless n > 2\n a.sort!\n\n (2..n - 1).each do |i|\n return 1 if a[i - 2] + a[i - 1] > a[i]\n end\n\n return 0\nend", "def solution(a)\n (0..a.size - 2).map { |i| ( a[0..i].inject(:+) - a[i+1..a.size].inject(:+) ).abs }.min\nend", "def largest_contiguous_subsum2(arr)\n answer = arr[0]\n current_sum = arr[0] \n arr.each_with_index do |ele,idx|\n if idx == 0 \n current_sum = arr[idx]\n answer = current_sum\n elsif current_sum > 0 \n current_sum += arr[idx] \n answer = current_sum unless answer > current_sum \n else\n current_sum = arr[idx]\n end\n end\n answer\nend", "def solution(a)\n s= a.sort\n 0.step(s.size - 1).inject(0) do |result, x|\n z= x+2\n (x+1).step(s.size - 1).inject(result) do |acc, y|\n z+=1 while z < s.size && s[x] + s[y] > s[z]\n acc += z-y-1\n end\n end\nend", "def largest_difference_nested_iteration(array)\n max_difference = 0\n\n array.each_with_index do |element, i|\n array[i..(array.length - 1)].each do |subsequent_element|\n max_difference = [subsequent_element - element, max_difference].max\n end\n end\n max_difference\nend", "def find_difference(a, m)\n a.sort!\n first = 0\n last = 0\n i = 0\n min_diff = 1000000\n while i+m-1 < a.length\n diff = a[i+m-1] - a[i]\n if diff < min_diff\n min_diff = diff\n first = i\n last = i+m-1\n end\n i += 1\n end\n result = a[last]-a[first]\n return result\nend", "def maximum_value_contiguous_subsequence_3(array)\n len = array.length\n max, current_sum = array[0], array[0]\n\n for i in (1...len)\n current_sum = maximum(array[i], array[i] + current_sum)\n max = maximum(max, current_sum)\n end\n max\nend", "def find_unsorted_subarray3(nums)\n left = nums.length\n right = 0\n\n stack = []\n\n nums.each_with_index do |num, index|\n left = [left, stack.pop].min while !stack.empty? && nums[stack.last] > num\n stack.push index\n end\n\n stack.clear\n\n (nums.size - 1).downto(0) do |index|\n right = [right, stack.pop].max while !stack.empty? && nums[stack.last] < nums[index]\n stack.push index\n end\n\n right > left ? right - left + 1 : 0\nend", "def solution(a)\n return 0 if a.length < 3\n a.sort!\n\n for i in 0..(a.length - 3)\n return 1 if a[i] + a[i + 1] > a[i + 2]\n end\n return 0\nend" ]
[ "0.7730241", "0.76064557", "0.74778116", "0.74468887", "0.73017704", "0.6956514", "0.6944656", "0.6921782", "0.68170035", "0.67708206", "0.67589134", "0.6756629", "0.6733883", "0.6725273", "0.67202836", "0.67056674", "0.6687934", "0.6671229", "0.66570085", "0.6646567", "0.6645459", "0.66412663", "0.66239935", "0.66203874", "0.6614637", "0.6597231", "0.6588487", "0.65778756", "0.6573806", "0.6573173", "0.6559595", "0.6558447", "0.6543621", "0.6543557", "0.6532924", "0.65299314", "0.6529812", "0.6519137", "0.65178084", "0.6512443", "0.6512123", "0.6491001", "0.6479966", "0.6475229", "0.6472217", "0.6470712", "0.646952", "0.6464686", "0.6456167", "0.64533114", "0.64419276", "0.6434995", "0.6434607", "0.6432098", "0.6427092", "0.64241886", "0.6423537", "0.6423156", "0.6421347", "0.64140683", "0.6413788", "0.64034146", "0.6402398", "0.6402389", "0.6397116", "0.6396919", "0.63964987", "0.63908976", "0.6390739", "0.6389424", "0.6386882", "0.63860893", "0.6372864", "0.6371696", "0.63671434", "0.6364247", "0.6362139", "0.6361023", "0.6354057", "0.6344803", "0.6344009", "0.6343755", "0.63378465", "0.6328547", "0.63144314", "0.6311671", "0.6311238", "0.6305746", "0.6305033", "0.6302199", "0.62942076", "0.629073", "0.6287966", "0.6282705", "0.62818265", "0.6281414", "0.62780327", "0.62757814", "0.6275734", "0.6274102", "0.62726754" ]
0.0
-1
TODO: Given an array of integers, find the two subsequences that are disjoint and contiguous such that the difference of their sums is maximized.
def disjoint_attempt(arr) part = [0] maxPrev = [0] maxLeft = [] minPrev = [0] minLeft = [] max = 0 # main idea: subsequence sum is partial sum at end minus partial # sum at start. Max score is thus either # maxLeft[i] + maxPrev[i] - 2 * part[i] or # - minLeft[i] - minPrev[i] + 2 * part[i] # for some i # calculate partial sums up to each index in the array # calculate max of these seen so far at each index arr.each_with_index do |el, i| k = i + 1 part[k] = part[i] + el maxPrev[k] = [maxPrev[i], part[k]].max minPrev[k] = [minPrev[i], part[k]].min end maxLeft[arr.size] = part[arr.size] minLeft[arr.size] = part[arr.size] # calculate max partial sum remaining at each index # now that we have enough info, update max score arr.size.downto(1) do |i| k = i - 1 maxLeft[k] = [maxLeft[i], part[k]].max minLeft[k] = [minLeft[i], part[k]].min max = [max, maxLeft[i] + maxPrev[i] - 2 * part[i], 0 - minLeft[i] - minPrev[i] + 2 * part[i]].max end # loop doesn't catch this max = [max, maxLeft[0] + maxPrev[0] - 2 * part[0], 0 - minLeft[0] - minPrev[0] + 2 * part[0]].max return max end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def largest_contiguous_subsum(arr)\n i = 0\n subs = []\n while i < arr.length\n j = i\n\n while j < arr.length\n subs << arr[i..j]\n\n j += 1\n end\n\n i += 1\n end\n\n\n return (subs.max {|a, b| a.sum <=> b.sum}).sum\n\nend", "def largest_contiguous_subsum(arr)\n subs = []\n l = arr.length\n (0...l).each do |i|\n (0...l).each do |j| \n subs << arr[i..j] if arr[i..j].length > 0 # n*n *( n) == n^3 + n\n end\n end\n subs.map(&:sum).max\nend", "def largest_contiguous_subsum(arr) # n^2\n subs = []\n (0...arr.length).each do |start_i|\n (start_i...arr.length).each do |end_i|\n subs << arr[start_i..end_i]\n end\n end\n\n subs.map { |sub| sub.inject(:+) }.max\nend", "def largest_contiguous_subsum1(array)\n sub_array = []\n\n array.each_index do |i|\n array.each_index do |j|\n next if i > j\n sub_array << array[i..j]\n end\n end\n sum = sub_array.first.inject(:+)\n sub_array.each do |el|\n sum = el.inject(:+) if el.inject(:+) > sum\n end\n sum\nend", "def largest_contiguous_subsum_1(arr)\n res = []\n i = 0\n while i < arr.length\n j = i\n while j < arr.length\n res << arr[i..j].reduce(:+)\n j += 1\n end\n i += 1\n end\n res.max\nend", "def largest_contiguous_subsum_n_2(arr)\n subs = []\n arr.each_with_index do |el1, i|\n arr.each_with_index do |el2, j|\n if j > i \n subs << arr[i..j]\n end\n end\n end\n subs\n x = subs.max_by {|arr| arr.sum}\n x.sum\nend", "def largest_contiguous_subsum(arr)\n subsets = [] \n\n (0...arr.length).each do |i| \n (i...arr.length).each do |j| \n subsets << arr[i..j]\n end \n end \n \n subsets.map {|sub| sub.sum}.max \nend", "def largest_contiguous_subsum(array)\n sub_arrays = []\n i = 1\n until i == array.length + 1\n array.each_cons(i) do |sub|\n sub_arrays << sub\n end\n i += 1\n end\n sub_arrays.map {|sub| sub.reduce(:+)}.max\nend", "def contig_sum(array)\n greatest_diff = -Float::INFINITY\n subsets = []\n\n i = 0\n while i < array.length\n j = i + 1\n while j <= array.length\n subsets << array[i..j]\n j += 1\n end\n i += 1\n end\n\n subsets.each do |arr|\n sum = arr.inject(:+)\n if sum > greatest_diff\n greatest_diff = sum\n end\n end\n greatest_diff\n\nend", "def largest_continous_subsum\n largest = 0\n subsets = []\n\n i = 0\n while i < self.length\n j = i\n while j < self.length\n subsets << self[i..j]\n j += 1\n end\n i += 1\n end\n\n subsets.each do |pair|\n if largest < pair.reduce(:+)\n largest = pair.reduce(:+)\n end\n end\n largest\n\n end", "def largest_contiguous_subsum(array)\n new_arr = []\n (0...array.length).each do |idx1|\n sum = [array[idx1]]\n new_arr << sum\n (idx1+1...array.length).each do |idx2|\n sum += [array[idx2]]\n new_arr << sum\n end\n end\n\n sums = []\n new_arr.each do |pair|\n sums << pair.sum\n end\n\n sums.max\nend", "def largest_contiguous_subsum(array)\n arr = []\n (0...array.length).each do |i|\n (i + 1...array.length).each do |j|\n arr << array[i] + array[j] \n end\n end\n arr.max\n \nend", "def largest_contiguous_subsum1(array)\r\n subset = []\r\n array.each_index do |i| # make subets, store into 'subset' array\r\n (i...array.length).each do |j| # o(n^2)\r\n subset << array[i..j] # o(n^3) cause slicing\r\n end\r\n end\r\n\r\n subset_sum = []\r\n subset.each do |ele|\r\n subset_sum << ele.sum\r\n end\r\n subset_sum.max\r\nend", "def largest_contiguous_sum(array)\n subsets = []\n subarr = []\n\n\n array.each_index do |i|\n array.each_index do |j|\n next if j < i\n subsets << array[i..j] unless subsets.include? array[i..j]\n end\n end\n sum = 0\n subsets.each do |sarr|\n next if sarr.empty?\n sum = [sarr.inject(:+), sum].max\n end\n sum\nend", "def contiguous_sum(arr)\n sums = []\n (0...arr.size).each do |i1|\n (i1...arr.size).each do |i2|\n sums << arr[i1..i2]\n end\n end\n max = 0\n sums.each {|el|max = el.sum if el.sum > max}\n max\nend", "def largest_contiguous_subsum_2(arr)\n (1...arr.length).each do |i|\n if arr[i] + arr[i - 1] > 0\n arr[i] = arr[i] + arr[i - 1]\n elsif arr[i] < 0 && arr[i-1] < 0\n arr[i] = [arr[i-1], arr[i]].max\n else\n arr[i] = 0\n end\n end\n\n arr.max\nend", "def contiguous_sequence(array)\n max_sum = array.first\n array.each_with_index do |num, idx|\n current_sum = num\n array[(idx+1)..-1].each do |num|\n current_sum += num\n max_sum = current_sum if current_sum > max_sum\n end\n end\n\n max_sum\nend", "def largest_sub_sum(array)\n subsets = []\n i = 0\n while i < array.length\n j = i\n while j < array.length\n subsets << array[i..j]\n j += 1\n end\n i += 1\n end\n result = nil\n subsets.map {|subset| subset.inject(:+)}.each do |sum|\n result = sum if result.nil? || result < sum\n end\n result\nend", "def largest_contiguous_subsum(arr)\n max = 0\n\n (0...arr.count).each do |i|\n sum = arr[i]\n (i + 1...arr.count).each do |j|\n sum += arr[j]\n max = sum if max < sum \n end \n end \n\n max\nend", "def largest_contiguous_subsum(arry)\n sums = 0\n size = arry.length\n\n (0..size - 1).each do | i|\n sub = []\n (i + 1..size).each do |j|\n sub = arry[i..j]\n if sub.sum > sums\n sums = sub.sum \n end\n end\n end\n sums\nend", "def largest_contiguous_subsum(arr)\n sums = []\n\n (0...arr.length).each do |idx1|\n (idx1+1...arr.length).each do |idx2|\n sums << arr[idx1..idx2].sum\n end\n end\n\n sums.max\nend", "def contiguous_sub_sum2(arr)\n max = arr.first\n curr_sum = 0\n arr.each do |num|\n curr_sum += num\n max = curr_sum if curr_sum > max\n curr_sum = 0 if curr_sum < 0\n end\n max\nend", "def largest_contiguous_subsum(arr)\n\n\nend", "def largest_contiguous_subsum(array)\n sub_arrs = []\n array.each_index do |ind1|\n array[ind1..-1].each_index do |ind2|\n sub_arrs.push(array[ind1..ind2+ind1])\n end\n end\n max_sum = sub_arrs.first.sum\n sub_arrs.each {|sub| max_sum = sub.sum if sub.sum >= max_sum }\n return max_sum\nend", "def largest_contiguous_subsum_v1(arr)\n subs = [] # ( +2 )\n\n (0...arr.length).each do |idx1| # ( n )\n (idx1..arr.length - 1).each do |idx2| # ( n )\n subs << arr[idx1..idx2].sum # ( n * ( 1 + ))\n end\n end\n\n subs.max # ( n )\nend", "def largest_contiguous_subsum(arr)\n sum = arr.first\n\n (0...(arr.length - 1)).each do |idx1|\n (idx1..(arr.length - 1)).each do |idx2|\n if idx1 == idx2\n ss = arr[idx1]\n else\n ss = arr[idx1..idx2].reduce(:+)\n end\n sum = ss if ss > sum\n end\n end\n sum\nend", "def solution(a)\n # first and last positions are excluded for the double slice\n a[0] = 0\n a[-1] = 0\n\n #get the sum of maximum subarray, from the left to the right direction\n max_from_left = []\n max_ending = 0\n a.each do |v|\n max_ending = [0, max_ending + v].max\n max_from_left << max_ending\n end\n \n #get the sum of maximum subarray, from the right to the left direction\n max_from_right = []\n max_ending = 0\n a.reverse.each do |v|\n max_ending = [0, max_ending + v].max\n max_from_right << max_ending\n end\n max_from_right.reverse!\n\n # when comparing both directions excludes the i index and take the maximum double slice value.\n n = a.size\n max_double_slice = 0\n for i in 1..n-2\n max_double_slice = [max_double_slice, max_from_left[i - 1] + max_from_right[i + 1]].max\n end\n\n max_double_slice\n\nend", "def largest_contiguous_subsum_1(arr)\n largest = []\n (0...arr.length).each do |i|\n (i...arr.length).each do |j|\n largest << arr[i..j]\n end\n end\n sums = largest.map do |sub_array|\n sub_array.sum\n end\n sums.max\nend", "def phase_2_largest_contiguous_sum(arr)\n\n return [[]] if arr.empty?\n subs = arr.take(arr.count-1).phase_2_largest_contiguous_sum\n subs.concat(subs.map {|sub| sub + [last]})\n\n largest_sum = subs.first.sum \n\n subs.each do |sub|\n current_sum = sub.sum \n if current_sum > largest_sum\n largest_sum = current_sum\n end\n end\n\n largest_sum\n\nend", "def largest_contiguous_subsum(array)\n sums_list = []\n sums = []\n\n idx1 = 0\n\n while idx1 < array.length #O(n)\n idx2 = idx1 #O(1)\n while idx2 < array.length #O(n)\n sums_list << array[idx1..idx2] #O(n)\n idx2 += 1\n end\n idx1 += 1\n end\n\n sums_list.each do |list| #O(n)\n sums << list.reduce {|sum, num| sum + num} #O(n)\n end\n sums.max\nend", "def bad_contig_subsum(arr)\n # n! || n^3 ?\n sub_arrays = []\n arr.each_index do |i|\n (i...arr.length).each do |j|\n sub_arrays << arr[i..j]\n end\n end\n\n # above * n^2 ? << bottleneck\n max = sub_arrays.first.inject(&:+)\n sub_arrays.each do |sub_arr|\n sub_sum = sub_arr.inject(&:+)\n max = sub_sum if sub_sum > max\n end\n max\nend", "def largest_contiguous_subsum_slow(arr)\n res = arr.first\n (0...arr.length - 1).each do |i|\n (i+1...arr.length).each do |j|\n tmp_sum = arr[i..j].reduce(:+)\n res = tmp_sum if tmp_sum > res\n end\n end\n return res\nend", "def largest_contiguous_sub_sum(arr)\n subarrs = [] #O(1)\n\n (0...arr.length).each do |idx| #O(n)\n (idx...arr.length).each do |jdx| #O(n/2)\n subarrs << arr[idx..jdx] #O(n)\n end\n end \n\n subarrs.map! do |array| #O(n)\n array.reduce(:+) #O(n)\n end \n\n subarrs.max #O(n)\nend", "def largest_contiguous_subsum1(list)\n greatest_sum = -1.0/0.0\n (0...list.length).each do |i|\n (i...list.length).each do |j|\n greatest_sum = list[i..j].sum if greatest_sum < list[i..j].sum\n end\n end\n greatest_sum\nend", "def better_contig_subsum(arr)\n max_sum = arr.inject(&:+) # O(n)\n temp_sum = max_sum\n\n loop do # O(n)\n left = temp_sum - arr.first\n right = temp_sum - arr.last\n\n if arr.length == 1\n if arr.first > max_sum\n return arr.first\n else\n return max_sum\n end\n end\n\n if right >= left\n max_sum = right if right >= max_sum\n temp_sum = right\n arr.pop\n else\n max_sum = left if left >= max_sum\n temp_sum = left\n arr.shift\n end\n end\n\n max_sum\nend", "def largest_contiguous_subsum(array)\n sub_arrays = []\n (0...array.length).each do |i|\n (0...array.length).each do |x|\n sub_arrays << array[i..x] unless array[i..x].empty?\n end\n end\n p sub_arrays.length\n max_array = sub_arrays.max_by { |sub| sub.sum }\n max_array.sum\n\nend", "def largest_contiguous_subsum(arr)\n max_sum = arr.first\n\n (0...arr.length).each do |start|\n (start...arr.length).each do |ending|\n sum = arr[start..ending].sum\n max_sum = sum if sum > max_sum\n end\n end\n\n max_sum\nend", "def largest_contiguous_subsum2(array)\n # return [list[0]] if list.count == 1\n #\n # start_num = list.shift\n # large_sum = start_num\n #\n # other_list = list.dup\n #\n # idx = 0\n # while idx < list.count\n # sum = list[0..idx].inject(:+)\n # if large_sum < start_num + sum\n # large_sum = start_num + sum\n # end\n # idx += 1\n # end\n #\n # [large_sum] + largest_contiguous_subsum2(other_list)\n\n largest = nil\n current = 0\n\n array.each do |el|\n current += el\n if largest.nil? || current > largest\n largest = current\n end\n current = 0 if current < 0\n end\n\n largest\n\nend", "def largest_contiguous_subsum(arr)\n subsets = []\n\n (0...arr.length).each do |idx1|\n (idx1...arr.length).each do |idx2|\n subsets << arr[idx1..idx2]\n end\n end \n\n largest_sum = subsets.first.sum\n\n subsets.each do |subset|\n if subset.sum > largest_sum\n largest_sum = subset.sum\n end\n end\n\n print subsets\nend", "def largest_contiguous_subsum(arr)\n max = arr.first\n arr.each_index do |idx1|\n (idx1+1..arr.length).each do |idx2|\n sub_arr = arr[idx1...idx2]\n sum = sub_arr.reduce(:+)\n max = sum if max < sum \n end\n\n end\n max\nend", "def largest_contiguous_sub_sum1(arr)\n subarrays = []\n arr.each_with_index do |num1, i|\n arr.each_with_index do |num2, j|\n subarrays << arr[i..j] if i <= j\n end\n end\n\n subarrays.map! do |subarray|\n subarray.sum\n end\n\n subarrays.sort[-1]\nend", "def largest_contiguous_subsum2(array)\n #all negative numbers\n if array.none? {|el| el > 0 }\n max = array.first\n array.each do |el1|\n next if max == el1\n if el1 > max\n max = el1\n end\n end\n max\n end\n\n current_sum = 0\n max_sum = 0\n\n array.each do |num|\n current_sum += num\n max_sum = current_sum if current_sum > max_sum\n if current_sum < 0\n current_sum = 0\n next\n current_sum += num\n max_sum = current_sum if current_sum > max_sum\n end\n\n end\n max_sum\n\nend", "def largest_sub_sum(array) #technically I believe this is a n^3 operation since you are first doing a n^2 with the nested loop and then multiplying by n at the end (the map/ another loop) -- hence the n^3\n answer_subs = []\n\n (0...array.length).each do |i|\n ((i + 1)...array.length).each do |j|\n answer_subs << [array[i]]\n answer_subs << [array[j]]\n answer_subs << array[i..j] #should have every combo in subs now\n end\n end\n answer_subs.sort.uniq.map{|sub| sub.reduce(:+)}.max\n # .map {|sub| sub.reduce(:+)}.max # should 1) reduce(:+)/ add up every element in each array. The map returns the array and then max returns the max number\nend", "def largest_contiguous_subsum_2(arr)\n sum = 0\n max = 0\n arr.each do |num|\n sum += num\n if sum > 0\n max = sum if sum > max\n else\n sum = 0\n end\n end\n max\nend", "def largest_contiguous_subsum(list)\n length = 1\n sub_arrays = []\n until length == list.length\n sub_arrays += list.each_cons(length).to_a\n length += 1\n end\n sub_arrays.map! { |el| el.reduce(:+) }.max\n\n # sub_arrays = []\n #\n # list.each_with_index do |ele, idx1|\n # list.each_with_index do |ele2, idx2|\n # sub_arrays << list[idx1..idx2] unless list[idx1..idx2].length < 1\n # end\n # end\n # sub_arrays.map! { |el| el.reduce(:+) }.max\n\nend", "def largest_contiguous_subsum_1(list)\n subs = []\n (0...list.length).each do |idx| #O(n)\n (idx...list.length).each do |idx_2| #O(n)\n subs << list[idx..idx_2] #O(n)\n end\n end\n max = list.first\n subs.each do |subarr|\n if subarr.sum > max\n max = subarr.sum\n end\n end\n max\nend", "def largest_contiguous_subsum(arr)\r\n all_sub_arrays = [] # space : O(n^2)\r\n\r\n (0...arr.length).each do |i|\r\n (i...arr.length).each do |i2|\r\n all_sub_arrays << arr[i..i2] # slice makes n^3\r\n end\r\n end\r\n\r\n all_sub_arrays.map { |sub_arr| sub_arr.sum }.max # O(n^2)\r\nend", "def largest_contiguous_subsum(nums)\n running_sum = 0\n max = nums.first || 0\n\n nums.each do |n|\n running_sum += n\n max = running_sum if max < running_sum\n running_sum = 0 if running_sum < 0\n end\n max\nend", "def largest_contiguous_subsum(array)\n previous_sum = 0\n current_sum = 0\n array.each_with_index do |el, i|\n\n current_sum = previous_sum + el\n if previous_sum < 0\n if el < previous_sum\n current_sum = previous_sum\n else\n current_sum = el\n end\n end\n\n previous_sum = current_sum\n end\n\n current_sum\nend", "def largest_contiguous_subsum(arr)\n current_sum = arr.first \n max_sum = arr.first \n (0...arr.length-1).each do |i|\n if current_sum < 0 \n current_sum = [current_sum, arr[i+1]].max\n max_sum = current_sum\n else \n current_sum += arr[i+1]\n max_sum = [current_sum, max_sum].max\n end \n end \n max_sum\nend", "def largest_contiguous_subsum1(list)\n subs = []\n (0...list.length).each do |i|\n (i...list.length).each do |j|\n subs << list[i..j]\n end\n end\n\n subs.map(&:sum).max\nend", "def maximum_value_contiguous_subsequence_dp(array)\n len = array.length\n result = [array[0]]\n\n for i in (1...len)\n result[i] = maximum(array[i], array[i] + result[-1])\n end\n\n result.max\nend", "def largest_contiguous_subsum(list) # O(n^2)\n subs_sums = []\n\n list.each_index do |i|\n list.each_index do |j|\n next if j < i\n subs_sums << list[i..j]\n end\n end\n\n highest_array_sum = nil\n subs_sums.each do |array|\n array_sum = array.reduce(:+)\n if highest_array_sum == nil || array_sum > highest_array_sum\n highest_array_sum = array_sum\n end\n end\n\n highest_array_sum\nend", "def largest_contiguous_subsum(list)\n new_arr = []\n\n (0...list.length).each do |idx1| #O(n)\n (0...list.length).each do |idx2| #O(n)\n if idx2 >= idx1 #O(1)\n new_arr << list[idx1..idx2].sum #O(1)\n end \n end \n \n end \n \n return new_arr.max #O(n)\nend", "def largest_contiguous_subsum(arr)\n result = []\n\n arr.each_with_index do |el1, idx1|\n i = idx1\n while i < arr.length\n result << arr[idx1..i]\n i += 1\n end\n end\n\n largest_sum = result.first.inject(:+)\n result.each do |sub_arr|\n curr_sum = sub_arr.inject(:+)\n largest_sum = curr_sum if curr_sum > largest_sum\n end\n largest_sum\nend", "def largest_contiguous_subsum(array)\r\n max = array.first \r\n current_sum = 0\r\n array.each do |ele|\r\n current_sum += ele\r\n max = current_sum if current_sum > max\r\n current_sum = 0 if current_sum < 0\r\n end\r\n max\r\nend", "def largest_contiguous_subsum(arr)\n answer = []\n arr.each_with_index do |ele1,idx1|\n arr.each_with_index do |ele2,idx2|\n answer << arr[idx1..idx2].sum \n end\n end\n answer.sort[-1]\nend", "def largest_contiguous_subsum2(arr)\n max = arr[0]\n current = arr[0]\n arr.drop(1).each do |num|\n current += num\n max = current if current > max\n current = 0 if current < 0\n end\n max\nend", "def largest_contiguous_sum(arr)\n largest_sum = nil\n p_tations = subsets(arr)\n\n p_tations.each do |tation|\n if largest_sum == nil\n largest_sum = tation.sum \n elsif tation.sum > largest_sum\n largest_sum = tation.sum \n end\n end \n\n largest_sum\nend", "def contig_subsum(array)\n sub_arrays = []\n i = 0\n j = 0\n while i < array.length do\n while j < array.length do\n sub_arrays << array[i..j]\n j += 1\n end\n i += 1\n j = i\n end\n\n max_sum = 0\n arr = []\n\n sub_arrays.each do |sub|\n arr << sub.inject(:+)\n end\n\n arr.uniq.sort.last\n\nend", "def better_largest_contiguous_subsum(arr)\n largest_sum = 0\n current_sum = 0\n i = 0\n while i < arr.length\n if arr[i] + current_sum >= 0\n current_sum += arr[i]\n else\n current_sum = 0\n end \n largest_sum = current_sum if current_sum > largest_sum \n i += 1\n end\n largest_sum\n end", "def largest_contiguous_subsum1(list)\n p Time.now\n sub_arrays = []\n list.each_index do |i|\n list.each_index do |j|\n next if j < i\n sub_arrays << list[i..j]\n end\n end\n sub_arrays.map{|numbers| numbers.inject(:+)}.max\n p Time.now\nend", "def largest_contiguous_subsum(array)\n current_sum = array.first\n largest_sum = array.first\n array.each do |num|\n current_sum += num\n if largest_sum < current_sum\n largest_sum = current_sum\n end\n end\n largest_sum\nend", "def largest_contiguous_subsum_v2(arr) # O(n)\n\n largest_sum = arr[0]\n current_sum = arr[0]\n \n (1...arr.length).each do |i|\n if current_sum < 0\n if current_sum < arr[i]\n current_sum = arr[i]\n end\n else\n current_sum += arr[i]\n end\n if current_sum > largest_sum\n largest_sum = current_sum\n end\n end\n largest_sum\nend", "def largest_contiguous_subsum2(array)\r\n largest = array[0]\r\n current_sum = array[0]\r\n\r\n (1...array.length).each do |i|\r\n current_sum = 0 if current_sum < 0\r\n num = array[i]\r\n current_sum += num\r\n if current_sum > largest\r\n largest = current_sum\r\n end\r\n end\r\n\r\n largest\r\nend", "def maximum_value_contiguous_subsequence_3(array)\n len = array.length\n max, current_sum = array[0], array[0]\n\n for i in (1...len)\n current_sum = maximum(array[i], array[i] + current_sum)\n max = maximum(max, current_sum)\n end\n max\nend", "def largest_contiguous_subsum1(list)\n sums = []\n\n list.each_with_index do |el1, i1|\n list.each_with_index do |el2, i2|\n if i1 == i2\n sums << el1\n else\n sums << el1 + el2\n end\n end\n end\n\n result = sums.first\n\n sums.each do |sum|\n result = sum if sum > result\n end\n\n result\nend", "def largest_contiguous_subsum_good(arr) \n last_max = arr.first\n current_max = 0\n arr.each do |num|\n temp_sum = current_max + num\n if temp_sum < 0\n last_max = current_max if temp_sum > last_max\n else\n if temp_sum > last_max\n last_max = temp_sum\n end\n end\n if num > temp_sum\n current_max = num\n else\n current_max = temp_sum\n end\n end\n last_max\nend", "def largest_contiguous_subsum(arr)\r\n # sub_arr = []\r\n # (0...arr.length).each do |idx|\r\n # (idx...arr.length).each do |idx_2| \r\n # sub_arr << arr[idx..idx_2]\r\n # end\r\n # end\r\n # p sub_arr.length \r\n # sub_arr.map {|sub| sub.sum }.max\r\n max = arr.first #8\r\n curr = arr.first #8\r\n arr.drop(1).each do |ele| \r\n curr = 0 if curr < 0\r\n curr += ele\r\n max = curr if curr > max\r\n end\r\n max\r\nend", "def solution(a)\n sea_slices = find_slices(a.map(&:zero?))\n mountain_slices = find_slices(a.map(&:nonzero?), true)\n best = 0\n (a.length - 1).times do |i|\n if sea_slices[i] && mountain_slices[i + 1]\n best = [best, sea_slices[i] + mountain_slices[i + 1]].max\n end\n end\n best\nend", "def largest_contiguous_subsum(arry)\n bigone = arry.first || 0\n actual_sum = 0\n\n arry.each do |number|\n actual_sum += number\n if actual_sum > bigone\n bigone = actual_sum \n end\n if actual_sum < 0\n actual_sum = 0 \n end\n end\n return bigone\nend", "def largest_contiguous_subsum(list)\r\n sub_arr = []\r\n list.each_with_index do |ele1,idx1|\r\n list.each_with_index do |ele2,idx2|\r\n sub_arr<< list[idx1..idx2] if idx2>=idx1\r\n end\r\n end\r\n p sub_arr.size\r\n sub_arr.map{ |sub| sub.sum}.max\r\n #(O(n^2 + m)\r\nend", "def maximum_value_contiguous_subsequence(array)\n len = array.length\n return array.max if all_negatives?(array)\n\n max = array[0]\n for i in (0...len)\n current_sum = 0\n for j in (i...len)\n current_sum += array[j]\n max = maximum(max, current_sum)\n end\n end\n max\nend", "def largest_contiguous_subsum_2(list)\n current_sum = 0\n largest_sum = 0\n (0...list.length).each do |idx|\n current_sum += list[idx]\n largest_sum = current_sum if current_sum > largest_sum\n current_sum = 0 if current_sum < 0\n end\n largest_sum\nend", "def largest_con_sum(arr)\n subsets = []\n\n arr.each_index do |i|\n j = i\n until j >= arr.length\n subsets << arr[i..j]\n j += 1\n end\n end\n subsets.map { |arr| arr.reduce(&:+) }.max\nend", "def largest_contiguous_sub_sum3(arr)\n\n largest_sum = arr.first\n current_sum = arr.first\n\n (1...arr.length).each do |index|\n current_num = arr[index]\n prev_num = arr[index-1]\n\n if largest_sum < current_num\n largest_sum = current_num\n end\n\n current_sum = current_sum + current_num\n prev_sum = prev_num + current_num\n\n if prev_sum > current_sum\n current_sum = prev_sum\n end\n\n if largest_sum < current_sum\n largest_sum = current_sum\n end\n end\n largest_sum\nend", "def largest_contiguous_subsum2(arr)\n answer = arr[0]\n current_sum = arr[0] \n arr.each_with_index do |ele,idx|\n if idx == 0 \n current_sum = arr[idx]\n answer = current_sum\n elsif current_sum > 0 \n current_sum += arr[idx] \n answer = current_sum unless answer > current_sum \n else\n current_sum = arr[idx]\n end\n end\n answer\nend", "def largest_contiguous_subsum(list)\n # O(N*M) ==> Time\n # O(N*M) ==> Space\n sub_arrs = sub_arrays_of(list) # O(N^3)\n sums = []\n sub_arrs.each do |sub_arr| ## O(N*M)\n sums << sub_arr.sum\n end\n # Get the max of the sums array\n sums.max # O(N)\nend", "def largest_contiguous_subsum(arr)\n max = arr[0]\n current = 0\n (0...arr.length).each do |i|\n current += arr[i]\n max = current if current > max\n current = 0 if current < 0\n end\n max\nend", "def largest_contiguous_subsum(list)\n helper_arr = [list.first]\n (1...list.length).each do |idx|\n if helper_arr[-1] + list[idx] > list[idx]\n helper_arr << helper_arr[-1] + list[idx]\n else\n helper_arr << list[idx]\n end\n end\n helper_arr.max\nend", "def largest_contiguous_subsum1(list)\n arr = []\n (0...list.length).each do |i|\n (i...list.length).each { |j| arr << list[i..j] }\n end\n largest_sum = arr.first.sum\n arr.each do |sub_arr|\n largest_sum = sub_arr.sum if sub_arr.sum > largest_sum\n end\n largest_sum\nend", "def largest_contiguous_subsum(arr) #BigO of O(n)\n max = 0 \n current_sum = 0\n arr.each_with_index do |el,idx|\n if current_sum + el >= el \n current_sum += el \n else \n current_sum = el \n end \n max = current_sum if current_sum > max \n end \n max\nend", "def largest_contiguous_subsum(arr)\n sum = 0\n arr_indices = []\n running_sums = []\n arr.each_with_index do |num,idx|\n sum += num \n arr_indices << idx \n running_sums << sum\n end \n running_sums.max\n\nend", "def largest_contiguous_subsum(arr)\n global_sum = arr.first\n # p \"global = #{global_sum}\"\n i = 0\n pot = 0\n while i < arr.length\n pot += arr[i]\n global_sum = pot if global_sum < pot\n pot = 0 if pot < 0\n i += 1\n end\n global_sum\nend", "def largest_contiguous_subsum_once(arr)\n largest_subsum = 0\n current = 0\n\n arr.each do |elm|\n current += elm\n if largest_subsum < current\n largest_subsum = current\n elsif current < 0\n current = 0 \n end \n end \n\n # (0...arr.count).each do |i|\n # current_subsum = (largest_subsum + arr[i])\n # if current_subsum > largest_subsum \n # largest_subsum = current_subsum \n # elsif current_subsum < 0 \n # largest_subsum = 0 \n # end\n # end \n\n largest_subsum \nend", "def solution(a)\n n = a.size\n starting = Array.new(n, 0)\n ending = Array.new(n, 0)\n\n (1..n - 2).each {|i| starting[i] = [starting[i - 1] + a[i], 0].max}\n (1..n - 2).reverse_each {|i| ending[i] = [ending[i + 1] + a[i], 0].max}\n\n sum = 0\n (1..n - 2).each {|i| sum = [sum, starting[i - 1] + ending[i + 1]].max}\n sum\nend", "def best_largest_contiguous_subsum(arr)\n return arr.max if arr.max < 0\n largest = 0\n current = 0\n\n\n (0..(arr.length-1)).each do |idx1|\n if current + arr[idx1] < 0\n current = arr[idx1]\n else\n current += arr[idx1]\n end\n\n largest = current if current > largest\n end\n largest\nend", "def largest_contiguous_subsum2(array)\n largest_sum = array.first\n current_sum = array.first\n\n (1..array.length-1).each do |i|\n current_sum = 0 if current_sum < 0\n current_sum += array[i]\n largest_sum = current_sum if current_sum > largest_sum\n end\n largest_sum\n \nend", "def largest_contiguous_subsum_one(list)\n sub_arr = []\n sum = 0\n list.each_with_index do |ele, i|\n (i...list.length).each do |i2|\n sub_arr << list[i..i2]\n end\n end\n sub_arr.each do |arr|\n if arr.sum > sum\n sum = arr.sum\n end\n end\n sum\nend", "def largest_contiguous_subsum(list)\n arr = []\n list.length.times do |id|\n arr << [list[id]]\n id2 = id + 1\n while id2 < list.length\n arr << list[id..id2]\n id2 += 1\n end\n end\n sum_arr = arr.map{ |el| el.reduce(:+)}\n arr[sum_arr.find_index{|el| el == sum_arr.max}]\nend", "def largest_contiguous_subsum_1(list) \n subs = [] #O(1)\n (0...list.length).each do |start_num| #O(n)\n (start_num...list.length).each do |end_num| #O(n)\n subs << list[start_num..end_num] #O(n)\n end\n end\n subs_sum = [] #O(1)\n subs.each do |sub| #O(n**2)\n sub_sum = 0 #O(1)\n sub.each {|s| sub_sum += s} #O(n)\n subs_sum << sub_sum #O(1)\n end\n subs_sum.inject do |acc,el| #O(n)\n if acc > el #O(1)\n acc #O(1)\n else\n el #O(1)\n end\n end\n end", "def largest_contiguous_subsum(list) # O(n^2)\n array = []\n list.each_with_index do |ele1, i1| # O(n^2)\n (i1...list.length).each do |i2|\n array << list[i1..i2]\n end\n end\n\n max_sum = array.first.sum\n array[1..-1].each do |subarr| # O(n^2)\n sum = subarr.sum\n if sum > max_sum\n max_sum = sum\n end\n end\n\n max_sum\n\nend", "def largest_contiguous_subsum(list)\n subs = [] \n (0...list.length).each do |i|\n (i...list.length).each do |j|\n subs << list[i..j]\n end\n end\n\n subs.map {|el| el.sum}.max\nend", "def large_contig_subsum2(arr)\n timestart = Time.now\n max_sum = 0\n curr_sum = 0\n i = 0\n while i < arr.length\n if arr[i] + curr_sum > 0\n curr_sum += arr[i]\n max_sum = curr_sum if curr_sum > max_sum\n else\n curr_sum = 0\n end\n i += 1\n end\n\n p (Time.now - timestart) * 1000\n max_sum\nend", "def largest_contiguous_subsum_fast(arr)\n global_max = arr.first\n prev_max = arr.first\n\n arr.drop(1).each do |el|\n curr_max = (prev_max + el > el) ? (prev_max + el) : el\n prev_max = curr_max\n global_max = curr_max if curr_max > global_max\n end\n global_max\nend", "def all_subarrays_largest_contiguous_subsum(integers)\n subarrays = []\n (0...integers.length).each do |start_i| # n start_i's ????\n (start_i...integers.length).each do |end_i| # average of n/2 end_i's ????\n subarrays << integers[start_i..end_i] # average number of elements in each subarray is n/2 ????\n end\n end\n p \"Number of subarrays: #{subarrays.length}\"\n p \"'Memory space': #{subarrays.flatten.length}\"\n subarrays.map(&:sum).max\nend", "def largest_contiguous_subsum_1(list)\r\n subarrays = [] #1\r\n list.each_with_index do |ele1, i| #n\r\n list[i...list.length].each_with_index do |ele2,i2| #(n-1)\r\n subarrays << list[i..i2+i] #k \r\n end\r\n end # n^2\r\n subarrays.map { |subarray| subarray.sum}.max # n^x\r\nend", "def largest_contiguous_subsum_two(list)\n largest_sum = list[0]\n current_sum = 0\n # list.inject {|acc, ele| acc + ele}\n list.each do |ele|\n current_sum = [ele, current_sum + ele].max\n largest_sum = [largest_sum, current_sum].max\n end\n largest_sum\nend", "def running_tally_largest_contiguous_subsum(integers)\n max_sum = integers.first\n local_sum = integers.first\n (1...integers.length).each do |idx|\n current_int = integers[idx]\n if current_int + local_sum > 0\n local_sum += current_int\n elsif max_sum.positive?\n local_sum = 0\n elsif current_int > local_sum\n local_sum = current_int\n end\n \n max_sum = local_sum if local_sum > max_sum\n end\n max_sum\nend", "def largest_contiguous_sub_sum1(list)\n max = list[0]\n (0...list.length).each do |i|\n (i...list.length).each do |j| \n sub_sum = list[i..j].sum \n max = sub if sub >= max \n end\n end\n max\nend" ]
[ "0.7588492", "0.7526391", "0.7478525", "0.7438863", "0.74315846", "0.7416461", "0.736408", "0.734911", "0.7346965", "0.730636", "0.7294165", "0.72899026", "0.7286098", "0.72835416", "0.72739893", "0.7273657", "0.7267079", "0.7222528", "0.7209317", "0.71969265", "0.7192207", "0.71918005", "0.7191093", "0.71875376", "0.7184034", "0.71832216", "0.7174885", "0.7160908", "0.71584857", "0.71536857", "0.7152656", "0.71447945", "0.7129771", "0.71163815", "0.7112735", "0.7110208", "0.7098463", "0.70901847", "0.7084628", "0.7076423", "0.70751864", "0.7072058", "0.7065796", "0.7060995", "0.70529985", "0.7052676", "0.705251", "0.7042073", "0.7037994", "0.7023808", "0.7022314", "0.70196897", "0.70189524", "0.7014025", "0.70079917", "0.6993956", "0.6993022", "0.698912", "0.69879264", "0.69840986", "0.6978218", "0.69762385", "0.69760376", "0.6975949", "0.69739085", "0.6966983", "0.69597554", "0.69594127", "0.6955115", "0.69535726", "0.69450456", "0.69425786", "0.69368196", "0.6931957", "0.6930998", "0.6914897", "0.69132537", "0.6905627", "0.69032377", "0.6900426", "0.68999726", "0.68948454", "0.68941444", "0.68935186", "0.6893293", "0.689044", "0.6887995", "0.6887206", "0.68730325", "0.6872524", "0.68659145", "0.68586457", "0.6831896", "0.68302804", "0.6829575", "0.6827573", "0.6824145", "0.6818366", "0.68165743", "0.6816295" ]
0.79555225
0
time: O(n^2), space: O(n)
def is_shuffle?(str1, str2, str3) return false unless str1.size + str2.size == str3.size seen = {} considering = [[0, 0]] str3.each_char do |chr| next_gen = [] considering.each do |pair| next if seen[pair] seen[pair] = true idx1, idx2 = pair next_gen << [idx1 + 1, idx2] if str1[idx1] == chr next_gen << [idx1, idx2 + 1] if str2[idx2] == chr end considering = next_gen end !considering.empty? end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def find_dublicate(array)\n sum = 1000000*(1000000+1)/2 # (n*(n+1))/2\n array.each do |el| \n sum -= el\n end\n return sum\nend", "def solution(a)\r\n n=a.size\r\n i=1\r\n for k in a.sort do\r\n\tif k!=i \r\n\t then \r\n\t return 0\r\n\t break;\r\n\tend\r\n i+=1;\r\n end\t\r\n return 1 if a.inject(:+) ==n*(n+1)/2;\r\nend", "def my_min_2(list)\r\n min = 0 # O(1)\r\n \r\n list.each do |ele| # O(n) \r\n if ele < min # O(1)\r\n min = ele # O(1)\r\n end\r\n end\r\n min # O(1) \r\nend", "def largest_subsum(list)\n max = list[0] # O(1)\n current_sum = list[0] # O(1)\n\n (1...list.length).each do |i| # O(n)\n # debugger\n if current_sum < 0 # O(1)\n current_sum = 0 # O(1)\n end \n current_sum += list[i] # O(1)\n if current_sum > max # O(1)\n max = current_sum # O(1)\n end\n end\n\n max # O(1)\n\nend", "def my_min_2(array)#O(n)\n array.inject do |acc, ele|#O(n)\n if acc < ele\n acc\n else\n ele\n end\n end\nend", "def my_min(list) \n\n list.each_with_index do |ele, i| #O(n)\n compare_arr = list[0...i] + list[i+1..-1] # O(2n) \n return ele if compare_arr.all? { |ele2| ele < ele2 } #O(n)\n end\n\n #time complexity = O(n^2) + O(2n)\n\nend", "def sub_sum(list)\n sub_arr = []\n (0...list.length).each do |i| #O(n)\n (i...list.length).each do |j| #O(n)\n sub_arr << list[i..j] if i <= j\n end\n end\n largest_continuous_sub_sum1(sub_arr)\nend", "def sorted_squares(nums)\n # This takes O(n)\n nums.map! { |num| num**2 }\n # This can take Ο(n logn)\n bubble_sort(nums)\nend", "def solution(a)\n # In production environment this will be my solution:\n # a.uniq.size\n #\n # But since this is a coding challenge, my assumption\n # is that you're looking for a by-hand O(N*logN) solution\n\n return 0 if a.empty?\n\n n = a.size\n ary = a.sort\n uniques = 1\n (1...n).each do |i|\n uniques += 1 if ary[i] != ary[i - 1]\n end\n uniques\nend", "def three_sum_fastest(arr)\n count = 0\n\n (0..arr.length - 2).each { |i|\n set = Set.new\n\n (i + 1..arr.length - 1).each { |j|\n if set.include?(-arr[i] - arr[j])\n count += 1\n end\n\n set.add(arr[j])\n }\n }\n count\nend", "def largest_contiguous_subsum_2(list)# [2, 3, -6, 7, -6, 7]\n largest_num = list[0]#2 O(1)\n running_sum = list[0]#2 - 5 after entering loop. O(1)\n\n (1...list.length).each do |i| #O(n) \n running_sum = 0 if running_sum < 0 #O(1)\n running_sum += list[i] #O(1)\n largest_num = running_sum if running_sum > largest_num #O(1)\n end\n return largest_num #O(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 solution(m, a)\n n = a.count\n result = 0\n front = 0\n numbers = Array.new(m + 1, false)\n n.times { |back|\n while front < n and not numbers[a[front] - 1]\n numbers[a[front] - 1] = true\n front += 1\n result += front - back\n return 1_000_000_000 if result >= 1_000_000_000\n end\n numbers[a[back] - 1] = false\n }\n result\nend", "def naive(array)\n max = -10000\n for i in (0..array.length - 1)\n for j in (i..array.length - 1)\n total = array[i..j].inject { |m,k| m + k }\n max = total if total > max\n end\n end\n max\nend", "def find_duplicate_space(nums)\n # sort nums first (lgn), then check for dups by iterate over (n)\n last_seen = 0\n nums.sort!.each do |num|\n return num if last_seen == num\n last_seen = num\n end\nend", "def solution(a)\n n = a.size\n a.sort!\n\n count = 0\n for i in 0...n-2 do\n k = i+2\n for j in i+1...n-1 do\n while k < n and a[i] + a[j] > a[k] do\n k += 1\n end\n count += k - j - 1\n end\n end\n count\nend", "def solution(a)\n n = a.size\n passing_cars = 0\n\n suffix_sums = Array.new(n + 1, 0)\n\n a.reverse.each_with_index do |elem, i|\n suffix_sums[i + 1] = suffix_sums[i] + elem\n end\n suffix_sums.reverse!\n\n a.each_with_index do |car, i|\n if car == 0\n passing_cars += suffix_sums[i]\n end\n end\n\n passing_cars > 1_000_000_000 ? -1 : passing_cars\nend", "def fds(n)\n\n # arr = []\n # (n + 1).times.each{|e| arr << e if e > 0}\n # arr.flat_map.reduce(:*)\n # arr.flat_map.reduce(:*).to_s.split(//).map(&:to_i).reduce(:+)\n (1..n).to_a.flat_map.reduce(:*).to_s.split(//).map(&:to_i).reduce(:+)\n\nend", "def seesaw?(arr)\n left_sum = 0\n arr.each_index do |i| #O(n)\n if i > 0\n left_sum = arr[0...i].reduce(:+) #O(n)\n end\n if i < arr.size-1\n right_sum = arr[i+1..-1].reduce(:+); #O(n)\n else\n right_sum = 0\n end\n if left_sum == right_sum\n return true\n end\n end\n return false\nend", "def largest_contiguous_subsum(arr) #BigO of O(n)\n max = 0 \n current_sum = 0\n arr.each_with_index do |el,idx|\n if current_sum + el >= el \n current_sum += el \n else \n current_sum = el \n end \n max = current_sum if current_sum > max \n end \n max\nend", "def my_min_2(arr)\n\n smallest_value = arr[0] # O(1)\n\n arr.each do |ele1| # [ 0, 3, 5, 4, -5, 10, 1, 90 ] O(n)\n smallest_value = ele1 if ele1 <= smallest_value #O(1)\n end\n\n smallest_value #O(1)\n\nend", "def solution(a)\n n = a.size\n return 0 unless n > 2\n a.sort!\n\n (2..n - 1).each do |i|\n return 1 if a[i - 2] + a[i - 1] > a[i]\n end\n\n return 0\nend", "def solution(a)\n len = a.size\n unique = {}\n i = 0\n while i < len\n item = a[i]\n if unique.has_key?(item)\n unique[item] += 1\n else\n unique[item] = 1\n end\n i += 1\n end\n pairs = 0\n unique.each do |key,count|\n (1...count).step {|n| pairs += n }\n end\n return pairs > 1_000_000_000 ? 1_000_000_000 : pairs\nend", "def find_duplicate(nums)\n if !nums or nums.size == 0\n return nil\n else\n fast = nums[ 0 ]\n slow = nums[ 0 ]\n while true\n fast = nums[ fast ]\n fast = nums[ fast ]\n slow = nums[ slow ]\n if fast == slow\n new_node = nums[ 0 ]\n while new_node != slow\n new_node = nums[ new_node ]\n slow = nums[ slow ]\n end\n return slow\n end\n end\n end\nend", "def fibonacci(n)\n return fib_helper([0, 1], 2, n)\n # if you'd like to test what i THINK is an O(1) space complexity solution.....\n # i did run this through the tests and it SHOULD work:\n # return faster_fib_helper([0, 1], 2, n)\nend", "def largest_contiguous_subsum2(list)\n # O(N) ==> Time\n # O(1) ==> Space\n largest = list.first\n curr = list.first\n\n len = list.length\n (1...len).each do |i|\n curr = 0 if curr < 0 \n curr += list[i]\n largest = curr if curr > largest\n end\n largest\nend", "def solution(a)\n # write your code in Ruby 2.2\n n = a.length\n \n counter = Array.new(n+1, 0)\n \n a.each do |x|\n counter[x-1] += 1\n end\n \n return counter.index { |x| x == 0 } + 1\nend", "def two_sum?(array, target)\n #O(n)\n hash = Hash.new(0)\n i = 1\n array.each do |ele|\n hash[ele] = i \n i += 1\n end\n hash.each_key do |k|\n return true if hash.has_key?(target - k) && hash[k] != hash[target - k]\n end\n false \nend", "def largest_contiguous_subsum1(list)\n p Time.now\n sub_arrays = []\n list.each_index do |i|\n list.each_index do |j|\n next if j < i\n sub_arrays << list[i..j]\n end\n end\n sub_arrays.map{|numbers| numbers.inject(:+)}.max\n p Time.now\nend", "def stones(n, a, b)\n ar=[0]\n (n-1).times do |val|\n tmp=[]\n ar.each do |v|\n tmp << v+a if !tmp.include?(v+a)\n tmp << v+b if !tmp.include?(v+b)\n end\n ar=tmp\n end\n ar.sort\nend", "def findDiffSquares(n)\n sum = 0\n (1..n).each { |i|\n (1..n).each { |j|\n sum += i*j unless i == j\n }\n }\n sum\nend", "def largest_contiguous_subsum_1(list) \n subs = [] #O(1)\n (0...list.length).each do |start_num| #O(n)\n (start_num...list.length).each do |end_num| #O(n)\n subs << list[start_num..end_num] #O(n)\n end\n end\n subs_sum = [] #O(1)\n subs.each do |sub| #O(n**2)\n sub_sum = 0 #O(1)\n sub.each {|s| sub_sum += s} #O(n)\n subs_sum << sub_sum #O(1)\n end\n subs_sum.inject do |acc,el| #O(n)\n if acc > el #O(1)\n acc #O(1)\n else\n el #O(1)\n end\n end\n end", "def move_zeros(array)\n zero_count = 0\n # O(n)\n array.each do |num|\n\n zero_count += 1 if num == 0\n end\n\n # O(n)\n array = array.select { |num| num != 0 }\n \n # O(1)\n zero_count.times do\n array += [0]\n end\n\n array\nend", "def hash_two_sum(arr,target_sum)\n #creates a new hash with each element that is satisfying the target_sum\n hash = Hash.new(0) #{|h,k| h[k] = []}\n (0...arr.length).each { |i| hash[i] = arr[i]} #O(n)\nend", "def three_sum_fast(arr)\n arr = merge_sort(arr)\n count = 0\n\n (0..arr.length - 1).each { |i|\n (i + 1..arr.length - 1).each { |j|\n if bin_search(arr, -arr[i] - arr[j]) > j\n count += 1\n end\n }\n }\n count\nend", "def find_missing(array, n)\n i = 0\n\n (1..n).each { |number| i = i ^ number }\n array.each { |number| i = i ^ number }\n\n i\nend", "def canBeSum(n, array, cache)\n\ti = 0\n\twhile array[i] <= n / 2\n\t\tif cache[n-array[i]] # array.include?(n-array[i]) is OK, but very slow\n\t\t\treturn true\n\t\tend\n\n\t\ti += 1\n\tend\n\n\treturn false\nend", "def find_amicables(n)\n pairs = []\n sum = 0\n for i in 0..n do \n next if pairs.include? i\n d = sum_proper_divisors(i)\n next if d == i\n p = sum_proper_divisors(d)\n if p == i \n pairs << d\n pairs << i\n sum += d + i\n end\n end\n return sum\nend", "def solution(a)\n # write your code in Ruby 2.2\n num_of_elements=a.length\n num_of_zeros=0\n tot_num_car_pairs=0\n a.each do |element|\n if element == 0\n num_of_zeros+=1\n else\n tot_num_car_pairs+=num_of_zeros\n end\n end\n return tot_num_car_pairs>1_000_000_000?-1:tot_num_car_pairs\nend", "def two_sum(arr) #o(ns)\n set = Set.new\n arr.each{|el| set << el}\n arr.select{|el| set.include?(-1 * el)}\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 largest_contiguous_subsum(list)\n new_arr = []\n\n (0...list.length).each do |idx1| #O(n)\n (0...list.length).each do |idx2| #O(n)\n if idx2 >= idx1 #O(1)\n new_arr << list[idx1..idx2].sum #O(1)\n end \n end \n \n end \n \n return new_arr.max #O(n)\nend", "def solution(a)\n # write your code in Ruby 2.2\n sum = a.inject(:+)\n acc = 0\n\n min = 99999999\n a[0..-2].each do |n|\n sum -= n\n acc += n\n\n min = [(acc - sum).abs, min].min\n end\n min\nend", "def amicable_numbers(n)\r\n numbers = Array.new\r\n 2.upto(n) do |x|\r\n y = d(x)\r\n if !numbers.include?(y)\r\n numbers.push(x,y) if d(y) == x && y != x\r\n end\r\n end\r\n return numbers\r\nend", "def efficient_contiguous_subsum(list)\n current_sum = list[0] #0\n largest_sum = list[0] #5\n # debugger\n (1...list.length).each do |i| \n if current_sum + list[i] > 0 \n current_sum += list[i] \n largest_sum = current_sum if current_sum > largest_sum\n else \n current_sum = 0\n end \n end \n largest_sum\nend", "def josephus_survivor(n,k)\n arr = (1..n).to_a\n\n while arr.length > 1\n idx = k % arr.length\n\n if arr.length > k\n arr = arr.drop(k) + arr.take(k - 1)\n elsif arr.length == k \n arr = arr[0...-1]\n else\n arr = arr.drop(idx) + arr.take(idx - 1)\n end\n end\n \n arr[0]\nend", "def running_time(array)\n cnt = 0\n (1...(array.length)).each do |x|\n y = x\n while y.positive?\n break unless array[y - 1] > array[y]\n\n temp_num = array[y]\n array[y] = array[y - 1]\n array[y - 1] = temp_num\n cnt += 1\n y -= 1\n end\n end\n cnt\nend", "def solve( n = 10_000 )\n (1..n).select {|i| i.amicable?}.reduce( :+ )\n end", "def largest_cont_subsum_fast(list)\n # for constant size to be true, you cant create any variables\n # whose memory size depends on the size of the input\n curr_sum = list[0]\n largest_sum = list[0]\n\n # we know there are n^2 potential, so if we ever check all of them\n # it must be n^2\n\n # there must be a way to find the max without checking every subarray\n list[1..-1].each do |ele|\n # debugger\n if curr_sum > largest_sum\n largest_sum = curr_sum\n end\n\n if curr_sum < 0\n curr_sum = 0\n end\n\n curr_sum += ele\n\n end\n\n # debugger\n return [largest_sum, curr_sum].max\n\nend", "def sum_upon_sums(array)\n # Step 0: initialize variables => O(1)\n max = -1\n sum = 0\n\n # Step 1: Get Max and Sum => O(n)\n array.each do |num|\n max = num if num >= max\n sum += num\n end\n\n # Step 2: Get summation => O(1)\n summation = max * (max + 1) / 2\n\n # Step 3: Return Missing value by subtracting summation and sum => O(1)\n summation - sum\nend", "def my_min_2(nums) # O(n)\n smallest = 0\n nums.each do |num|\n smallest = num if num < smallest\n end\n smallest\nend", "def largest_contiguous_subsum_fast(list)\n start = Time.now\n max_sum = list[0]\n cur_sum = list[0]\n list[1..-1].each do |el|\n if el >= cur_sum && cur_sum < 0\n cur_sum = el\n else\n cur_sum += el\n end\n max_sum = cur_sum if cur_sum > max_sum\n end\n finish = Time.now\n puts \"Runtime: #{finish - start}\"\n return max_sum\nend", "def solution_slow_2(n, p, q)\n sieve = sieve_of_erathosteneses(n)\n # puts \"sieve:#{sieve}\"\n semi = semiprimes(n, sieve)\n # puts \"sp:#{semi}\"\n prefix = [0,0,0,0,1]\n 5.upto(n) do |x|\n if semi.include? x \n prefix << prefix.last + 1\n else\n prefix << prefix.last\n end\n end\n # puts \"prefix:#{prefix}\"\n\n queries = [p,q].transpose\n\n\n res = queries.map do |query|\n prefix[query.last] - prefix[query.first - 1]\n end\n\n # puts \"res:#{res}\"\n\n res\n end", "def two_sum?(arr, target_sum) # O(N)\n hash = Hash.new(0)\n count = Hash.new(0)\n\n arr.each do |num|\n hash[num] = target_sum - num\n count[num] += 1\n end\n\n hash.each do |key, value|\n if hash.has_key?(value) \n if key == value \n if count[value] > 1\n return true\n end\n else\n return true\n end\n end\n end\n\n false\nend", "def solution(a)\n s= a.sort\n 0.step(s.size - 1).inject(0) do |result, x|\n z= x+2\n (x+1).step(s.size - 1).inject(result) do |acc, y|\n z+=1 while z < s.size && s[x] + s[y] > s[z]\n acc += z-y-1\n end\n end\nend", "def my_min(array) # O(n) - Linear\n counter = array[0]\n\n (1...array.length).each do |i|\n if counter > array[i]\n counter = array[i]\n end\n end\n counter\nend", "def largest_contiguous_subsum(list) # O(n^2)\n array = []\n list.each_with_index do |ele1, i1| # O(n^2)\n (i1...list.length).each do |i2|\n array << list[i1..i2]\n end\n end\n\n max_sum = array.first.sum\n array[1..-1].each do |subarr| # O(n^2)\n sum = subarr.sum\n if sum > max_sum\n max_sum = sum\n end\n end\n\n max_sum\n\nend", "def solution(a)\n result = 0\n tmp_count = 0\n a.each_with_index do |val, idx|\n if val.zero?\n tmp_count += 1\n else\n result += tmp_count\n end\n end\n return result > 1000000000 ? -1 : result\nend", "def my_min_v2(arr) # O(n)\n num = arr[0]\n arr.each { |int| num = int if int < num }\n num\nend", "def solution(a)\n # write your code in Ruby 2.2\n seen = {}\n\n a.each do |number|\n seen[number] = true\n end\n\n max = a.max\n\n for i in 1..(max + 1)\n return i unless seen[i]\n end\n\n 1\nend", "def seesaw2?(arr)\n left_sum = 0\n right_sum = arr.size > 1 ? arr[1..-1].reduce(:+) : 0\n\n arr.each_index do |i| #O(n)\n return true if left_sum == right_sum\n left_sum += arr[i]\n i < arr.size-1 ? right_sum -= arr[i+1] : right_sum = 0\n end\n return false\nend", "def fast_lcss(arr)\n i_arr = []\n biggest = 0\n max_sub_arr = []\n arr.length.times do |x|\n arr.map do |ele1|\n i_arr += [ele1]\n sum = i_arr.inject(0) do |a, b|\n a + b\n end\n max_sub_arr = i_arr if sum > biggest\n biggest = sum if sum > biggest \n end\n i_arr = []\n arr.shift\n end\n max_sub_arr\nend", "def solution(a)\n counter = Hash.new(0)\n a.each do |elem|\n counter[elem] += 1\n end\n\n (1..a.size).each do |number|\n return 0 if counter[number] != 1\n end\n\n 1\nend", "def solution(a)\n min_val = 10_000\n min_pos = 0\n \n sums = [0]\n for i in (0..a.count - 1) \n sums << sums.last + a[i] \n end\n for p in (0..a.count - 2)\n for q in (p + 1..[p + 2, a.count - 1].min)\n s = (sums[q + 1] - sums[p]).to_f / (q - p + 1)\n if s < min_val\n min_val = s\n min_pos = p\n end\n end\n end\n min_pos\nend", "def equal(arr)\n size = arr.size\n hash = Hash.new{|h,k| h[k] = []}\n (0...size).each do |i|\n (i + 1...size - 1).each do |j|\n sum = arr[i] + arr[j]\n if hash.has_key?(sum)\n values = hash[sum]\n values << i\n values << j\n return values\n else\n hash[sum] = [i, j]\n end\n end\n end\nend", "def sub_sum(list)\n array = []\n (0...list.length).each do |idx1|\n (idx1...list.length).each do |idx2|\n array << list[idx1..idx2] #O(n)\n end\n end \n array.map {|sub| sub.length > 1 ? sub.sum : sub.first}.max\nend", "def solution(a)\n return 1 if a.empty?\n a.sort!\n return 1 if a.first > 1\n return a.first + 1 if a.length <2\n (0..(a.length)).each do |index|\n return a[index] + 1 if a[index] + 1 != a[index + 1]\n end\n return a.last + 1\nend", "def solution(a)\n left = 0\n right = a.sum\n a.each_with_index do |element, index|\n right -= element\n return index if left == right\n left += element\n end\n -1\nend", "def find3(a, X)\n # scan through array\n # build hash storing complement in each key\n complements = {}\n a.each_with_index do |val, ind|\n if complements[X - val]\n complements[X - val].push(ind)\n else\n complements[X - val] = [ind]\n end\n end\n\n # scan through the array again\n # get complement\n # for each value scan the remainder of the arrray\n # for a value such taht a + b = the complement\n\n # for each character we have built a dictionary such that, we can find\n # x = a + complement\n\n # [1, 2, 3]\n # 1 + 2 = 3\n # 1 + 3 = 4 =>\n\n # for each value in the array (a) look at all following values (b) and see if a + b\n # is in the dictionary, if it is, check that their indices do not collide with the index\n # stored at dict(a+b)\n\n a.each_with_index do |va, i|\n a.each_with_index do |vb, j|\n break if i == j\n\n complement = va + vb\n indices = complements[complement]\n\n indices.each do |z|\n # every index is unique\n return [i, j, z] unless z == i || z == j\n end\n end\n end\n\n return nil\nend", "def naive_algorithm(arr)\n\tproduct = 0\n\tarr.each do |i|\n\t arr.each do |j|\n\t \tp = arr[i] * arr[j]\n\t \tproduct = p if product < p\n\t end\t\n\tend\t\t\n\tproduct\nend", "def dp_possible_trees(n)\n array = Array.new(n+2) { Array.new(n+1) { 0 } }\n (0...n+2).to_a.each do |i|\n array[i][0] = 1\n end\n\n sum = 0\n (1...n+1).to_a.each do |i|\n sum = 0\n (1..i).to_a.each do |j|\n array[j][i] = array[n+1][i-j] * array[n+1][j-1]\n sum += array[j][i]\n end\n array[n+1][i] = sum\n end\n array[n+1].last\nend", "def my_min1(arr)\n arr.each do |el1| #O(n)\n if arr.all? {|el2| el1 <= el2 } #O(n + 1)\n return el1\n end\n end \nend", "def bad_two_sum?(arr, target)\n arr.each_with_index do |num1, idx1| #O(n)\n arr.each_with_index do |num2, idx2| #O(n)\n return true if idx2 > idx1 && num1 + num2 == target #O(1)\n end\n end\n false\nend", "def largest_contiguous_subsum2(list)\n result = list.first\n sum = list.first\n\n list.each_with_index do |n, i|\n next if i == 0\n\n sum = 0 if sum < 0\n\n sum += n\n\n result = sum if sum > result\n end\n\n result\nend", "def removNb(n)\n results = []\n (2..n).each do |a|\n b = (n*(n+1)/2.0-a)/(a + 1)\n results << [a, b.to_i] if b % 1 == 0 && b < n && b > 2\n end\n results\nend", "def arrayManipulation(n, queries)\n arr = Array.new(n + 2, 0)\n\n queries.each do |a, b, k|\n arr[a] += k\n arr[b + 1] -= k\n end\n\n max_sum = 0\n sum = 0\n arr.filter { |diff| diff != 0 }.each do |diff|\n sum += diff\n max_sum = [max_sum, sum].max\n end\n\n max_sum\nend", "def answer(n, a)\n count = 0\n n.times do |nn|\n next if a[nn] != nn + 1\n a[nn], a[nn + 1] = a[nn + 1], a[nn]\n count += 1\n end\n count\nend", "def third_anagram?(str1, str2)\n beginning_time = Time.now\n str1.split(\"\").sort == str2.split(\"\").sort #O(nlogn)\n \"Time complexity of first_anagram: #{(Time.now - beginning_time)}\"\nend", "def two_sum_v3?(arr, target) \n hash = Hash.new\n arr.each { |ele| hash[ele] = ele } #o(n)\n arr.each do |ele| #o(n)\n search_value = target - ele\n return true if !hash[search_value].nil? && hash[search_value] != ele\n end\n false\nend", "def brute_force_two_sum(array, target)\n indexes = []\n array.each.with_index do |n1, index1|\n array.each.with_index do |n2, index2|\n indexes.push(index1) if target - n1 == n2 && index1 != index2\n end\n end\n indexes\nend", "def sum_to_n? arr, n\n if arr.length > 1\n for i in arr do\n ndx = arr.find_index(i)\n x = arr.delete_at(ndx)\n if arr.include?(n - x)\n return true\n end\n arr.insert(ndx, x)\n end\n end\n return false\nend", "def bad_contig_subsum(arr)\n # n! || n^3 ?\n sub_arrays = []\n arr.each_index do |i|\n (i...arr.length).each do |j|\n sub_arrays << arr[i..j]\n end\n end\n\n # above * n^2 ? << bottleneck\n max = sub_arrays.first.inject(&:+)\n sub_arrays.each do |sub_arr|\n sub_sum = sub_arr.inject(&:+)\n max = sub_sum if sub_sum > max\n end\n max\nend", "def arrayManipulation(n, queries)\n nums = Array.new(n+1, 0)\n queries.each do |query|\n nums[query[0]-1] += query[2]\n nums[query[1]] -= query[2]\n end\n\n max = nums.first\n (1..nums.length-1).each do |i|\n nums[i] += nums[i - 1]\n max = nums[i] if nums[i] > max && i < (nums.size - 1)\n end\n\n max\nend", "def solution(a)\n a.sort!\n a.each_with_index do |element, index|\n return 0 if element != index + 1\n end\n 1\nend", "def largest_contiguous_sub_sum2(arr)\n #one varable tracks largest sum\n #one variable tracks current sum\n #O(n) + O(1)\n # list = [2, 3, -6, 7, -6, 7]\n\n # largest_sum= arr.first\n\n # i = 0\n # arr_end = true\n\n # while arr_end\n # current_sum = arr[i]\n # if arr[i+1] == nil\n # arr_end = false\n # puts \"This is current sum: #{current_sum}\"\n # else\n # if current_sum > largest_sum\n # current_sum += arr[i+1]\n # largest_sum = current_sum\n # end\n # end\n # if i < arr.length\n # arr_end = true\n # i += 1\n # end\n # end\n # largest_sum\n \n\n\n # arr.each_with_index do |ele, idx|\n # if ele > largest_sum\n # largest_sum = ele\n # end\n\n # i = idx\n # sum = ele\n # while i < arr.length - 1\n # if sum <= sum + arr[i+1]\n # largest_sum = sum + arr[i+1]\n # end\n # sum = sum + arr[i+1]\n # i+=1\n # end\n # end\n # largest_sum\n\nend", "def solution(a)\n accessed = Array.new(a.size + 1, nil)\n caterpillar_back = 0\n count = 0\n\n a.each_with_index do |x, caterpillar_front|\n if accessed[x] == nil\n accessed[x] = caterpillar_front\n else\n new_caterpillar_back = accessed[x] + 1\n first_part_size = caterpillar_front - caterpillar_back\n second_part_size = caterpillar_front - new_caterpillar_back\n count += first_part_size * (first_part_size + 1) / 2\n count -= (second_part_size) * (second_part_size + 1) / 2\n caterpillar_back.upto(new_caterpillar_back - 1) { |n| accessed[a[n]] = nil}\n accessed[x] = caterpillar_front\n caterpillar_back = new_caterpillar_back\n end\n end\n\n remaining_size = a.size - caterpillar_back\n count += (remaining_size) * (remaining_size + 1) / 2\n end", "def second_anagram?(word_1, word_2) #O(n^2)\n matching_word = word_2.split(\"\")\n\n word_1.each_char do |ele|\n if matching_word.index(ele) #evaluating the conditional\n matching_word.delete_at(matching_word.index(ele)) #n many times, do this\n end\n end\n\n matching_word.empty? #constant O(1)\nend", "def largest_contiguous_subsum(list)\r\n sub_arr = []\r\n list.each_with_index do |ele1,idx1|\r\n list.each_with_index do |ele2,idx2|\r\n sub_arr<< list[idx1..idx2] if idx2>=idx1\r\n end\r\n end\r\n p sub_arr.size\r\n sub_arr.map{ |sub| sub.sum}.max\r\n #(O(n^2 + m)\r\nend", "def sorted_squared_array_n_nlogn(values)\n values.collect!{|val| val*val}\n merge_sort(values)\nend", "def solution(a)\n # we could do radix sort and then loop over all the items in order to find the missing element\n # in the ordered list or use the Gauss theorem: https://study.com/academy/lesson/finding-the-sum-of-consecutive-numbers.html\n #\n # if we use the Gauss theorem we can do:\n # sum = (1 + N+1) * ( N / 2 )\n #\n # if (1 + N+1) % 2 == 1 we need to sum also (n+1+1)/2 + 1\n #\n # then remove every item from the sum: the remainder is the missing number\n len = a.length\n sum = (1 + len + 1) * ((len + 1) / 2)\n sum += ((len + 1) / 2.0).ceil unless (len + 1) % 2 == 0\n\n a.reduce(sum) do |sum, i|\n sum - i\n end\nend", "def solution(a)\r\n # write your code in Ruby 2.2\r\n \r\n arr =[]\r\n a.each_with_index{|el,i|\r\n \r\n if !arr.index(el) \r\n arr << el\r\n end\r\n \r\n }\r\n arr.count\r\nend", "def unique_items(arr) #O(n)\n hash = Hash.new(0)\n results = []\n arr.each do |el|\n hash[el] += 1\n end\n hash.select { |k, v| k if v == 1 }.keys\nend", "def problem_57\n ret,n,d = 0,1,1\n 1000.times do |i|\n n,d = (n+2*d),(n+d)\n ret += 1 if n.to_s.length > d.to_s.length\n end\n ret\nend", "def solution(a)\n ((1..a.size + 1).to_a - a).first\nend", "def solution(a)\n # write your code in Ruby 2.2\n binding.pry\n trips = Hash.new {|h,k| h[k]=0}\n start = 0\n ending = 0\n min = nil\n a.each_with_index do |trip,i|\n ending = i\n\n if trips[trip] == 0\n min = ending - start\n end\n trips[trip] += 1\n\n while start < ending\n break if trips[a[start]] - 1 == 0\n trips[start] -= 1\n start += 1\n min = ending - start if ending-start < min\n end\n end\n min\nend", "def two_sum(integers, target)\n # O(n)\n integers_with_index = integers.each_with_index.to_a\n # O(n*log(n))\n integers_with_index = integers_with_index.sort_by { |(n, _)| n }\n\n front, back = 0, integers_with_index.count - 1\n\n until front == back\n sum = integers_with_index[front][0] + integers_with_index[back][0]\n if sum == target\n return [integers_with_index[front][1], integers_with_index[back][1]].sort\n elsif sum > target\n back -= 1\n else\n front += 1\n end\n end\nend", "def sum_to_n? arr, n\n hash = Hash.new\n arr.each do |val|\n if hash.key? val\n return true\n else\n hash[n-val] = val\n end\n end\n return false\nend", "def my_min2 # O(n) time complexity\n smallest = self.first\n self.each do |num|\n sleep(1)\n smallest = num if num < smallest \n end\n smallest\n end", "def my_min_2(arr) #O(N)\n min_num = arr.first\n \n arr.each { |num| min_num = num if num < min_num }\n \n min_num\n end", "def my_min(arr) # Find\n min = arr[0]\n\n arr.each do |el| # Go through array once O(n)\n min = el if el < min # update min while going through if found min\n end\n min\nend", "def remove_duplicates(nums)\n record_leng = 0\n uniq_arr = nums.uniq\n uniq_arr.each do |i|\n record_leng += 1 if count_great_two?(nums, i)\n end\n return (record_leng + uniq_arr.size)\nend" ]
[ "0.71603787", "0.6699279", "0.66349244", "0.6444679", "0.6424871", "0.63408345", "0.6330529", "0.6330144", "0.6315709", "0.6283777", "0.6225761", "0.6224092", "0.62086004", "0.6178786", "0.6167653", "0.6160198", "0.6156636", "0.6155491", "0.61404717", "0.61083657", "0.60904926", "0.60862887", "0.60785806", "0.60681343", "0.60630333", "0.60539407", "0.6038126", "0.60350806", "0.60156393", "0.6010616", "0.6003868", "0.6002666", "0.5981809", "0.59684247", "0.5966372", "0.5952208", "0.59444904", "0.59397554", "0.5920567", "0.59088695", "0.5905753", "0.59035414", "0.58952105", "0.58945066", "0.5894314", "0.58928543", "0.58843356", "0.58714163", "0.5870776", "0.58706754", "0.58679605", "0.5865807", "0.5847561", "0.5842648", "0.5840963", "0.58396214", "0.5829846", "0.582821", "0.58276236", "0.58256567", "0.5823745", "0.58237374", "0.58234066", "0.5823241", "0.5822746", "0.5818996", "0.58186364", "0.5817691", "0.58161205", "0.58087826", "0.58062655", "0.57976764", "0.5797152", "0.5791187", "0.5791182", "0.57893425", "0.5787667", "0.57836294", "0.5781745", "0.5779633", "0.5779072", "0.57740504", "0.5771272", "0.5762481", "0.57603776", "0.5757313", "0.57569706", "0.57548577", "0.5751816", "0.57493603", "0.5746672", "0.5744004", "0.5741357", "0.57405096", "0.57352054", "0.5734861", "0.5724055", "0.5721947", "0.5720284", "0.57191414", "0.5716139" ]
0.0
-1
time to parse some lisp input: string with newlines and tabs output: parens around function blocks iterate through characters in the string there are several states the parser can be in the token counting state, where line tokens are counted up and tabs are counted the tab counting state, where tabs are being read to determine the structure of the following line the ("[ state, where a stack is built up, newlines, tabs, and spaces are ignored, and only one token is being created the backslash state, where the following character is ignored
def parse_lisp(str) # TODO: handle the tab tree and resulting token structure depth_stack = [] # can have (, ", and [ current_token = nil state_stack = [] state = "token counting" tab_count = 0 str.each_char do |char| current_token << char if state == "tab counting" && char != "\t" # do stuff with tabs and structure tab_count = 0 end if char == "\\" state = "backslash" else case state when "token counting" when "tab counting" when "within paren, quote, or bracket" case char when ")" depth_stack.pop if depth_stack[-1] == '(' when "]" depth_stack.pop if depth_stack[-1] == '[' when '"' depth_stack.pop if depth_stack[-1] == '"' else if "([".include?(char) depth_stack << char else end end when "backslash" state = state_stack.pop end end end puts pre_parse end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parse str\n self.ss = scanner_class.new str\n self.lineno = 1\n self.start_of_current_line_pos = 0\n self.state ||= nil\n\n do_parse\n end", "def parse str\n self.ss = scanner_class.new str\n self.lineno = 1\n self.start_of_current_line_pos = 0\n self.state ||= nil\n\n do_parse\n end", "def parse str\n begin\n @str=str\n @tokens=Lexer.new.tokenize(str)\n @tokens=@tokens.reject!{|tok| tok.is_a? [:comment,:newline]}\n ast=parse_module()\n #pp ast\n rescue Exception => e\n puts \"PARSING ERROR : #{e}\"\n puts \"in C source at line/col #{showNext.pos}\"\n puts e.backtrace\n abort\n end\n end", "def lexer(input)\n\t# We're gonna run a nice Lexer now\n\t# Get ourselves some tokens\n\t\n\ttokens = [] # Startin' with the input code in a mighty nice array\n\tc_line = 0 # current line in program\n\tspecial_case = false\n\teof_reached = false\n\t\n\tc_string = \"\"\t# the current string of chars\n\tc_pos = 1\t\t# current position in file\n\ts_pos = nil \t# current position of string\n\t\n\t# get a line of input\n\tfor line in input\n\t\t\n\t\t# check characters in line of input\n\t\tfor i in 0...line.length\n\t\t\n\t\t\t# checks for special cases\n\t\t\tif special_case\n\t\t\t\t\n\t\t\t\tlast_token = tokens[tokens.length - 1].type\n\t\t\t\t\n\t\t\t\t# Boolop\n\t\t\t\tif last_token == \"T_BOOLOP\"\n\t\t\t\t\t\n\t\t\t\t\tspecial_case = false\n\t\t\t\t\tnext\n\t\t\t\t\n\t\t\t\t# String time!\n\t\t\t\telsif last_token == \"T_QUOTE\"\n\t\t\t\t\n\t\t\t\t\t# make sure that we're not going to be using nil for tokenize\n\t\t\t\t\tif s_pos == nil\n\t\t\t\t\t\ts_pos = i\n\t\t\t\t\tend\n\t\t\t\n\t\t\t\t\t# check the different options\n\t\t\t\t\tcase line[i]\n\t\t\t\t\n\t\t\t\t\t# found a closing quotation mark\n\t\t\t\t\twhen /\"/\n\t\t\t\t\t\ttokens.push(tokenize(c_string, \"string\", c_line, s_pos))\n\t\t\t\t\t\ttokens.push(tokenize(line[i], \"op\", c_line, i))\n\t\t\t\t\t\tc_string = \"\"\n\t\t\t\t\t\tspecial_case = false\n\t\t\t\t\t\n\t\t\t\t\t# space or letter\n\t\t\t\t\twhen /( )/, $character\n\t\t\t\t\t\tc_string = c_string + line[i]\n\t\t\t\t\t\n\t\t\t\t\t# invalid options\n\t\t\t\t\telse\n\t\t\t\t\t\n\t\t\t\t\t\t# checks for end of line, else it's a bad character\n\t\t\t\t\t\tif i == line.length - 1\n\t\t\t\t\t\t\traise StringDetectionError.new(\"unclosed\", line[i], c_line, i)\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\traise StringDetectionError.new(\"char\", line[i], c_line, i)\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\n\t\t\n\t\t\t# test here for EOF symbol\n\t\t\telsif $eof.match(line[i])\n\t\t\t\t\n\t\t\t\t# tokenize current string\n\t\t\t\tif c_string != \"\"\n\t\t\t\t\ttokens.push(tokenize(c_string, \"character\", c_line, s_pos))\n\t\t\t\t\t\n\t\t\t\t\tc_string = \"\"\n\t\t\t\t\ts_pos = nil\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\teof_reached = true\n\t\t\t\t\n\t\t\t\t# tokenize '$'\n\t\t\t\ttokens.push(tokenize(line[i], \"op\", c_line, i))\n\t\t\t\t\n\t\t\t# Testin' for whitespace\n\t\t\telsif $space.match(line[i])\n\t\t\t\n\t\t\t\tif c_string != \"\"\n\t\t\t\t\ttokens.push(tokenize(c_string, \"character\", c_line, s_pos))\n\t\t\t\t\t\n\t\t\t\t\tc_string = \"\"\n\t\t\t\t\ts_pos = nil\n\t\t\t\tend\n\t\t\t\n\t\t\t# Testin' for operators\n\t\t\t# note: the whitespace issue was handled with the previous elsif\n\t\t\telsif $operator.match(line[i])\n\t\t\t\n\t\t\t\t# tokenize c_string if applicable\n\t\t\t\tif c_string != \"\"\n\t\t\t\t\ttokens.push(tokenize(c_string, \"character\", c_line, s_pos))\n\t\t\t\t\t\n\t\t\t\t\tc_string = \"\"\n\t\t\t\t\ts_pos = nil\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\t# test for that elusive boolop...\n\t\t\t\t# make sure we don't access a non-existent item...\n\t\t\t\tif i != line.length - 1\n\t\t\t\t\tif /[!|=]/.match(line[i]) and /=/.match(line[i + 1])\n\t\t\t\t\t\t# attempt to tokenize the operator\n\t\t\t\t\t\ttokens.push(tokenize(line[i] + line[i + 1], \"op\", c_line, i))\n\t\t\t\t\t\tspecial_case = true\n\t\t\t\t\telse\n\t\t\t\t\t\ttokens.push(tokenize(line[i], \"op\", c_line, i))\n\t\t\t\t\tend\n\t\t\t\telse\n\t\t\t\t\ttokens.push(tokenize(line[i], \"op\", c_line, i))\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\t# if op is \", start the string gathering process\n\t\t\t\tif /\"/.match(line[i])\n\t\t\t\t\tspecial_case = true\n\t\t\t\tend\n\t\t\t\t\n\t\t\t# Testin' for alpha numeric characters\n\t\t\telsif $character.match(line[i])\n\t\t\t\n\t\t\t\t# set position of current string\n\t\t\t\tif c_string == \"\" and s_pos == nil\n\t\t\t\t\ts_pos = c_pos\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\t# add new character to current string\n\t\t\t\tc_string = c_string + String(line[i])\n\t\t\t\t\n\t\t\telsif $digit.match(line[i])\n\t\t\t\n\t\t\t\t# test for more than one digit\n\t\t\t\t# make sure we don't access a non-existent item...\n\t\t\t\tif i != line.length - 1\n\t\t\t\t\tif $digit.match(line[i + 1])\n\t\t\t\t\t\traise UnknownSymbolError.new(line[i + 1], c_line, c_pos + 1)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\ttokens.push(tokenize(line[i], \"digit\", c_line, i))\n\t\t\t\n\t\t\t# else raise error for unknown symbol\n\t\t\telse\n\t\t\t\tif s_pos != nil\n\t\t\t\t\traise UnknownSymbolError.new(line[i], c_line, s_pos)\n\t\t\t\telse\n\t\t\t\t\traise UnknownSymbolError.new(line[i], c_line, c_pos)\n\t\t\t\tend\n\t\t\tend\n\t\t\t\n\t\t\t# update current position\n\t\t\tc_pos = update_cpos(c_pos, line[i])\n\n\t\tend\n\t\t\n\t\t\n\t\t# check for loose ends\n\t\tif special_case\n\t\t\n\t\t\t# check to make sure that all strings on this line are finished\n\t\t\tif tokens[tokens.length - 1] == \"T_QUOTE\" or tokens[tokens.length - 1] == \"T_STRING\"\n\t\t\t\traise StringDetectionError.new(\"unclosed\", \"\", c_line, 0)\n\t\t\t\n\t\t\t# if boolop, reset special_case\n\t\t\telsif tokens[tokens.length - 1] == \"T_BOOLOP\"\n\t\t\t\tspecial_case = false\n\t\t\tend\n\t\t\n\t\tend\n\t\t\n\t\t# check to make sure no current strings are left\n\t\tif c_string != \"\"\n\t\t\ttokens.push(tokenize(c_string, \"character\", c_line, s_pos))\n\t\tend\n\t\t\n\t\t# reset for next line\n\t\tc_string = \"\"\n\t\tc_pos = 0\n\t\ts_pos = nil\n\t\t\n\t\t# increment the line number\n\t\tc_line = c_line + 1\n\tend\n\t\n\t# if no EOF symbol ($) detected\n\tif !eof_reached\n\t\tbegin\n\t\t\traise EOFDetectionError.new(\"dne\", 0, 0)\n\t\trescue EOFDetectionError\n\t\t\ttokens.push(tokenize(\"$\", \"op\", c_line, 0))\n\t\tend\n\tend\n\t\n\t# return token list\n\treturn tokens\n\t\nend", "def yylex # 826 lines\n c = ''\n self.space_seen = false\n command_state = false\n src = self.src\n\n self.token = nil\n self.yacc_value = nil\n\n return yylex_string if lex_strterm\n\n command_state = self.command_start\n self.command_start = false\n\n last_state = lex_state\n\n loop do # START OF CASE\n if src.scan(/[\\ \\t\\r\\f\\v]/) then # \\s - \\n + \\v\n self.space_seen = true\n next\n elsif src.check(/[^a-zA-Z]/) then\n if src.scan(/\\n|#/) then\n self.lineno = nil\n c = src.matched\n if c == '#' then\n src.pos -= 1\n\n while src.scan(/\\s*#.*(\\n+|\\z)/) do\n @comments << src.matched.gsub(/^ +#/, '#').gsub(/^ +$/, '')\n end\n\n return RubyLexer::EOF if src.eos?\n end\n\n # Replace a string of newlines with a single one\n src.scan(/\\n+/)\n\n next if in_lex_state?(:expr_beg, :expr_value, :expr_class,\n :expr_fname, :expr_dot)\n\n if src.scan(/([\\ \\t\\r\\f\\v]*)\\./) then\n self.space_seen = true unless src[1].empty?\n\n src.pos -= 1\n next unless src.check(/\\.\\./)\n end\n\n self.command_start = true\n self.lex_state = :expr_beg\n return :tNL\n elsif src.scan(/[\\]\\)\\}]/) then\n if src.matched == \"}\" then\n self.brace_nest -= 1\n else\n self.paren_nest -= 1\n end\n\n cond.lexpop\n cmdarg.lexpop\n tern.lexpop\n\n self.lex_state = if src.matched == \")\" then\n :expr_endfn\n else\n :expr_endarg\n end\n\n self.yacc_value = src.matched\n result = {\n \")\" => :tRPAREN,\n \"]\" => :tRBRACK,\n \"}\" => :tRCURLY\n }[src.matched]\n return result\n elsif src.scan(/\\!/) then\n if in_lex_state?(:expr_fname, :expr_dot) then\n self.lex_state = :expr_arg\n\n if src.scan(/@/) then\n self.yacc_value = \"!@\"\n return :tUBANG\n end\n else\n self.lex_state = :expr_beg\n end\n\n if src.scan(/[=~]/) then\n self.yacc_value = \"!#{src.matched}\"\n else\n self.yacc_value = \"!\"\n end\n\n return TOKENS[self.yacc_value]\n elsif src.scan(/\\.\\.\\.?|,|![=~]?/) then\n self.lex_state = :expr_beg\n tok = self.yacc_value = src.matched\n return TOKENS[tok]\n elsif src.check(/\\./) then\n if src.scan(/\\.\\d/) then\n rb_compile_error \"no .<digit> floating literal anymore put 0 before dot\"\n elsif src.scan(/\\./) then\n self.lex_state = :expr_dot\n self.yacc_value = \".\"\n return :tDOT\n end\n elsif src.scan(/\\(/) then\n result = if ruby18 then\n yylex_paren18\n else\n yylex_paren19\n end\n\n self.paren_nest += 1\n\n self.expr_beg_push \"(\"\n\n return result\n elsif src.check(/\\=/) then\n if src.scan(/\\=\\=\\=|\\=\\=|\\=~|\\=>|\\=(?!begin\\b)/) then\n self.fix_arg_lex_state\n tok = self.yacc_value = src.matched\n return TOKENS[tok]\n elsif src.scan(/\\=begin(?=\\s)/) then\n @comments << src.matched\n\n unless src.scan(/.*?\\n=end( |\\t|\\f)*[^\\n]*(\\n|\\z)/m) then\n @comments.clear\n rb_compile_error(\"embedded document meets end of file\")\n end\n\n @comments << src.matched\n\n next\n else\n raise \"you shouldn't be able to get here\"\n end\n elsif src.scan(/\\\"(#{ESC_RE}|#(#{ESC_RE}|[^\\{\\#\\@\\$\\\"\\\\])|[^\\\"\\\\\\#])*\\\"/o) then\n self.yacc_value = src.matched[1..-2].gsub(ESC_RE) { unescape $1 }\n self.lex_state = :expr_end\n return :tSTRING\n elsif src.scan(/\\\"/) then # FALLBACK\n self.lex_strterm = [:strterm, STR_DQUOTE, '\"', \"\\0\"] # TODO: question this\n self.yacc_value = \"\\\"\"\n return :tSTRING_BEG\n elsif src.scan(/\\@\\@?#{IDENT_CHAR_RE}+/o) then\n self.token = src.matched\n\n rb_compile_error \"`#{token}` is not allowed as a variable name\" if\n token =~ /\\@\\d/\n\n return process_token(command_state)\n elsif src.scan(/\\:\\:/) then\n if is_beg? || in_lex_state?(:expr_class) || is_space_arg? then\n self.lex_state = :expr_beg\n self.yacc_value = \"::\"\n return :tCOLON3\n end\n\n self.lex_state = :expr_dot\n self.yacc_value = \"::\"\n return :tCOLON2\n elsif ! is_end? && src.scan(/:([a-zA-Z_]#{IDENT_CHAR_RE}*(?:[?!]|=(?==>)|=(?![=>]))?)/) then\n # scanning shortcut to symbols\n self.yacc_value = src[1]\n self.lex_state = :expr_end\n return :tSYMBOL\n elsif src.scan(/\\:/) then\n # ?: / then / when\n if is_end? || src.check(/\\s/) then\n self.lex_state = :expr_beg\n # TODO warn_balanced(\":\", \"symbol literal\");\n self.yacc_value = \":\"\n return :tCOLON\n end\n\n case\n when src.scan(/\\'/) then\n self.lex_strterm = [:strterm, STR_SSYM, src.matched, \"\\0\"]\n when src.scan(/\\\"/) then\n self.lex_strterm = [:strterm, STR_DSYM, src.matched, \"\\0\"]\n end\n\n self.lex_state = :expr_fname\n self.yacc_value = \":\"\n return :tSYMBEG\n elsif src.check(/[0-9]/) then\n return parse_number\n elsif src.scan(/\\[/) then\n self.paren_nest += 1\n\n result = src.matched\n\n if in_lex_state? :expr_fname, :expr_dot then\n self.lex_state = :expr_arg\n case\n when src.scan(/\\]\\=/) then\n self.paren_nest -= 1 # HACK? I dunno, or bug in MRI\n self.yacc_value = \"[]=\"\n return :tASET\n when src.scan(/\\]/) then\n self.paren_nest -= 1 # HACK? I dunno, or bug in MRI\n self.yacc_value = \"[]\"\n return :tAREF\n else\n rb_compile_error \"unexpected '['\"\n end\n elsif is_beg? then\n self.tern.push false\n result = :tLBRACK\n elsif is_arg? && space_seen then\n self.tern.push false\n result = :tLBRACK\n else\n result = :tLBRACK2\n end\n\n self.expr_beg_push \"[\"\n\n return result\n elsif src.scan(/\\'(\\\\.|[^\\'])*\\'/) then\n self.yacc_value = src.matched[1..-2].gsub(/\\\\\\\\/, \"\\\\\").gsub(/\\\\'/, \"'\") # \"\n self.lex_state = :expr_end\n return :tSTRING\n elsif src.check(/\\|/) then\n if src.scan(/\\|\\|\\=/) then\n self.lex_state = :expr_beg\n self.yacc_value = \"||\"\n return :tOP_ASGN\n elsif src.scan(/\\|\\|/) then\n self.lex_state = :expr_beg\n self.yacc_value = \"||\"\n return :tOROP\n elsif src.scan(/\\|\\=/) then\n self.lex_state = :expr_beg\n self.yacc_value = \"|\"\n return :tOP_ASGN\n elsif src.scan(/\\|/) then\n self.fix_arg_lex_state\n self.yacc_value = \"|\"\n return :tPIPE\n end\n elsif src.scan(/\\{/) then\n self.brace_nest += 1\n if lpar_beg && lpar_beg == paren_nest then\n self.lpar_beg = nil\n self.paren_nest -= 1\n\n expr_beg_push \"{\"\n\n return :tLAMBEG\n end\n\n result = if is_arg? || in_lex_state?(:expr_end, :expr_endfn) then\n :tLCURLY # block (primary)\n elsif in_lex_state?(:expr_endarg) then\n :tLBRACE_ARG # block (expr)\n else\n self.tern.push false\n :tLBRACE # hash\n end\n\n self.expr_beg_push \"{\"\n self.command_start = true unless result == :tLBRACE\n\n return result\n elsif src.scan(/->/) then\n self.lex_state = :expr_endfn\n return :tLAMBDA\n elsif src.scan(/[+-]/) then\n sign = src.matched\n utype, type = if sign == \"+\" then\n [:tUPLUS, :tPLUS]\n else\n [:tUMINUS, :tMINUS]\n end\n\n if in_lex_state? :expr_fname, :expr_dot then\n self.lex_state = :expr_arg\n if src.scan(/@/) then\n self.yacc_value = \"#{sign}@\"\n return utype\n else\n self.yacc_value = sign\n return type\n end\n end\n\n if src.scan(/\\=/) then\n self.lex_state = :expr_beg\n self.yacc_value = sign\n return :tOP_ASGN\n end\n\n if (is_beg? || (is_arg? && space_seen && !src.check(/\\s/))) then\n if is_arg? then\n arg_ambiguous\n end\n\n self.lex_state = :expr_beg\n self.yacc_value = sign\n\n if src.check(/\\d/) then\n if utype == :tUPLUS then\n return self.parse_number\n else\n return :tUMINUS_NUM\n end\n end\n\n return utype\n end\n\n self.lex_state = :expr_beg\n self.yacc_value = sign\n return type\n elsif src.check(/\\*/) then\n if src.scan(/\\*\\*=/) then\n self.lex_state = :expr_beg\n self.yacc_value = \"**\"\n return :tOP_ASGN\n elsif src.scan(/\\*\\*/) then\n result = if is_space_arg? src.check(/./m) then\n warning \"`**' interpreted as argument prefix\"\n :tDSTAR\n elsif is_beg? then\n :tDSTAR\n else\n # TODO: warn_balanced(\"**\", \"argument prefix\");\n :tPOW\n end\n self.yacc_value = \"**\"\n self.fix_arg_lex_state\n return result\n elsif src.scan(/\\*\\=/) then\n self.lex_state = :expr_beg\n self.yacc_value = \"*\"\n return :tOP_ASGN\n elsif src.scan(/\\*/) then\n result = if is_space_arg? src.check(/./m) then\n warning(\"`*' interpreted as argument prefix\")\n :tSTAR\n elsif is_beg? then\n :tSTAR\n else\n # TODO: warn_balanced(\"*\", \"argument prefix\");\n :tSTAR2 # TODO: rename\n end\n\n self.yacc_value = \"*\"\n self.fix_arg_lex_state\n return result\n end\n elsif src.check(/\\</) then\n if src.scan(/\\<\\=\\>/) then\n self.fix_arg_lex_state\n self.yacc_value = \"<=>\"\n return :tCMP\n elsif src.scan(/\\<\\=/) then\n self.fix_arg_lex_state\n self.yacc_value = \"<=\"\n return :tLEQ\n elsif src.scan(/\\<\\<\\=/) then\n self.fix_arg_lex_state\n self.lex_state = :expr_beg\n self.yacc_value = \"\\<\\<\"\n return :tOP_ASGN\n elsif src.scan(/\\<\\</) then\n if (!in_lex_state?(:expr_dot, :expr_class) &&\n !is_end? &&\n (!is_arg? || space_seen)) then\n tok = self.heredoc_identifier\n return tok if tok\n end\n\n self.fix_arg_lex_state\n self.yacc_value = \"\\<\\<\"\n return :tLSHFT\n elsif src.scan(/\\</) then\n self.fix_arg_lex_state\n self.yacc_value = \"<\"\n return :tLT\n end\n elsif src.check(/\\>/) then\n if src.scan(/\\>\\=/) then\n self.fix_arg_lex_state\n self.yacc_value = \">=\"\n return :tGEQ\n elsif src.scan(/\\>\\>=/) then\n self.fix_arg_lex_state\n self.lex_state = :expr_beg\n self.yacc_value = \">>\"\n return :tOP_ASGN\n elsif src.scan(/\\>\\>/) then\n self.fix_arg_lex_state\n self.yacc_value = \">>\"\n return :tRSHFT\n elsif src.scan(/\\>/) then\n self.fix_arg_lex_state\n self.yacc_value = \">\"\n return :tGT\n end\n elsif src.scan(/\\`/) then\n self.yacc_value = \"`\"\n case lex_state\n when :expr_fname then\n self.lex_state = :expr_end\n return :tBACK_REF2\n when :expr_dot then\n self.lex_state = if command_state then\n :expr_cmdarg\n else\n :expr_arg\n end\n return :tBACK_REF2\n end\n self.lex_strterm = [:strterm, STR_XQUOTE, '`', \"\\0\"]\n return :tXSTRING_BEG\n elsif src.scan(/\\?/) then\n\n if is_end? then\n self.lex_state = ruby18 ? :expr_beg : :expr_value # HACK?\n self.tern.push true\n self.yacc_value = \"?\"\n return :tEH\n end\n\n if src.eos? then\n rb_compile_error \"incomplete character syntax\"\n end\n\n if src.check(/\\s|\\v/) then\n unless is_arg? then\n c2 = { \" \" => 's',\n \"\\n\" => 'n',\n \"\\t\" => 't',\n \"\\v\" => 'v',\n \"\\r\" => 'r',\n \"\\f\" => 'f' }[src.matched]\n\n if c2 then\n warning(\"invalid character syntax; use ?\\\\\" + c2)\n end\n end\n\n # ternary\n self.lex_state = ruby18 ? :expr_beg : :expr_value # HACK?\n self.tern.push true\n self.yacc_value = \"?\"\n return :tEH\n elsif src.check(/\\w(?=\\w)/) then # ternary, also\n self.lex_state = :expr_beg\n self.tern.push true\n self.yacc_value = \"?\"\n return :tEH\n end\n\n c = if src.scan(/\\\\/) then\n self.read_escape\n else\n src.getch\n end\n self.lex_state = :expr_end\n\n if version == 18 then\n self.yacc_value = c[0].ord & 0xff\n return :tINTEGER\n else\n self.yacc_value = c\n return :tSTRING\n end\n elsif src.check(/\\&/) then\n if src.scan(/\\&\\&\\=/) then\n self.yacc_value = \"&&\"\n self.lex_state = :expr_beg\n return :tOP_ASGN\n elsif src.scan(/\\&\\&/) then\n self.lex_state = :expr_beg\n self.yacc_value = \"&&\"\n return :tANDOP\n elsif src.scan(/\\&\\=/) then\n self.yacc_value = \"&\"\n self.lex_state = :expr_beg\n return :tOP_ASGN\n elsif src.scan(/&/) then\n result = if is_arg? && space_seen &&\n !src.check(/\\s/) then\n warning(\"`&' interpreted as argument prefix\")\n :tAMPER\n elsif in_lex_state? :expr_beg, :expr_mid then\n :tAMPER\n else\n :tAMPER2\n end\n\n self.fix_arg_lex_state\n self.yacc_value = \"&\"\n return result\n end\n elsif src.scan(/\\//) then\n if is_beg? then\n self.lex_strterm = [:strterm, STR_REGEXP, '/', \"\\0\"]\n self.yacc_value = \"/\"\n return :tREGEXP_BEG\n end\n\n if src.scan(/\\=/) then\n self.yacc_value = \"/\"\n self.lex_state = :expr_beg\n return :tOP_ASGN\n end\n\n if is_arg? && space_seen then\n unless src.scan(/\\s/) then\n arg_ambiguous\n self.lex_strterm = [:strterm, STR_REGEXP, '/', \"\\0\"]\n self.yacc_value = \"/\"\n return :tREGEXP_BEG\n end\n end\n\n self.fix_arg_lex_state\n self.yacc_value = \"/\"\n\n return :tDIVIDE\n elsif src.scan(/\\^=/) then\n self.lex_state = :expr_beg\n self.yacc_value = \"^\"\n return :tOP_ASGN\n elsif src.scan(/\\^/) then\n self.fix_arg_lex_state\n self.yacc_value = \"^\"\n return :tCARET\n elsif src.scan(/\\;/) then\n self.command_start = true\n self.lex_state = :expr_beg\n self.yacc_value = \";\"\n return :tSEMI\n elsif src.scan(/\\~/) then\n if in_lex_state? :expr_fname, :expr_dot then\n src.scan(/@/)\n end\n\n self.fix_arg_lex_state\n self.yacc_value = \"~\"\n\n return :tTILDE\n elsif src.scan(/\\\\/) then\n if src.scan(/\\r?\\n/) then\n self.lineno = nil\n self.space_seen = true\n next\n end\n rb_compile_error \"bare backslash only allowed before newline\"\n elsif src.scan(/\\%/) then\n if is_beg? then\n return parse_quote\n end\n\n if src.scan(/\\=/) then\n self.lex_state = :expr_beg\n self.yacc_value = \"%\"\n return :tOP_ASGN\n end\n\n return parse_quote if is_arg? && space_seen && ! src.check(/\\s/)\n\n self.fix_arg_lex_state\n self.yacc_value = \"%\"\n\n return :tPERCENT\n elsif src.check(/\\$/) then\n if src.scan(/(\\$_)(\\w+)/) then\n self.lex_state = :expr_end\n self.token = src.matched\n return process_token(command_state)\n elsif src.scan(/\\$_/) then\n self.lex_state = :expr_end\n self.token = src.matched\n self.yacc_value = src.matched\n return :tGVAR\n elsif src.scan(/\\$[~*$?!@\\/\\\\;,.=:<>\\\"]|\\$-\\w?/) then\n self.lex_state = :expr_end\n self.yacc_value = src.matched\n return :tGVAR\n elsif src.scan(/\\$([\\&\\`\\'\\+])/) then\n self.lex_state = :expr_end\n # Explicit reference to these vars as symbols...\n if last_state == :expr_fname then\n self.yacc_value = src.matched\n return :tGVAR\n else\n self.yacc_value = src[1].to_sym\n return :tBACK_REF\n end\n elsif src.scan(/\\$([1-9]\\d*)/) then\n self.lex_state = :expr_end\n if last_state == :expr_fname then\n self.yacc_value = src.matched\n return :tGVAR\n else\n self.yacc_value = src[1].to_i\n return :tNTH_REF\n end\n elsif src.scan(/\\$0/) then\n self.lex_state = :expr_end\n self.token = src.matched\n return process_token(command_state)\n elsif src.scan(/\\$\\W|\\$\\z/) then # TODO: remove?\n self.lex_state = :expr_end\n self.yacc_value = \"$\"\n return \"$\"\n elsif src.scan(/\\$\\w+/)\n self.lex_state = :expr_end\n self.token = src.matched\n return process_token(command_state)\n end\n elsif src.check(/\\_/) then\n if src.beginning_of_line? && src.scan(/\\__END__(\\r?\\n|\\Z)/) then\n self.lineno = nil\n return RubyLexer::EOF\n elsif src.scan(/\\_\\w*/) then\n self.token = src.matched\n return process_token(command_state)\n end\n end\n end # END OF CASE\n\n if src.scan(/\\004|\\032|\\000/) || src.eos? then # ^D, ^Z, EOF\n return RubyLexer::EOF\n else # alpha check\n rb_compile_error \"Invalid char #{src.rest[0].chr} in expression\" unless\n src.check IDENT_RE\n end\n\n self.token = src.matched if self.src.scan IDENT_RE\n\n return process_token(command_state)\n end\n end", "def parse str\n self.ss = scanner_class.new str\n self.state ||= nil\n\n do_parse\n end", "def parse str\n self.ss = scanner_class.new str\n self.state ||= nil\n\n do_parse\n end", "def parse str\n self.ss = scanner_class.new str\n self.state ||= nil\n\n do_parse\n end", "def parse str\n self.ss = scanner_class.new str\n self.state ||= nil\n\n do_parse\n end", "def parse (input)\n\t\treturn parse_tail(input.gsub('(', ' ( ').gsub(')', ' ) ').split)\n\tend", "def speed_benchmark(string, n)\n initialize()\n bm(15) do |test|\n test.report(\"reverse markdown:\") { n.times do; parse_string(string); initialize(); end; }\n end\n end", "def parse(input, with_fps = DEFAULT_FPS)\n # Drop frame goodbye\n raise TimecodeLibError, \"We do not support drop frame\" if (input =~ /\\;/)\n \n hrs, mins, secs, frames = 0,0,0,0\n atoms = []\n \n # 10h 20m 10s 1f\n if input =~ /\\s/\n # TODO - this is ActiveSupport\n return input.split.map{|part| parse(part, with_fps) }.sum\n # 10s\n elsif input =~ /^(\\d+)s$/\n return new(input.to_i * with_fps, with_fps)\n # 10h\n elsif input =~ /^(\\d+)h$/i\n return new(input.to_i * 60 * 60 * with_fps, with_fps)\n # 20m\n elsif input =~ /^(\\d+)m$/i\n return new(input.to_i * 60 * with_fps, with_fps)\n # 60f - 60 frames, or 2 seconds and 10 frames\n elsif input =~ /^(\\d+)f$/i\n return new(input.to_i, with_fps)\n # A bunch of integers\n elsif (input =~ /^(\\d+)$/)\n ints = input.split(//)\n atoms.unshift [ints.pop, ints.pop].reverse.join.to_i\n atoms.unshift [ints.pop, ints.pop].reverse.join.to_i\n atoms.unshift [ints.pop, ints.pop].reverse.join.to_i\n atoms.unshift [ints.pop, ints.pop].reverse.join.to_i\n elsif (input =~ COMPLETE_TC_RE)\n atoms = input.scan(COMPLETE_TC_RE).to_a.flatten\n else\n raise CannotParse, \"Cannot parse #{input} into timecode, no match\"\n end\n \n if atoms.any?\n hrs, mins, secs, frames = atoms.map{|e| e.to_i}\n else\n raise CannotParse, \"Cannot parse #{input} into timecode, atoms were empty\"\n end\n \n at(hrs, mins, secs, frames, with_fps)\n end", "def chunk_char!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 14 )\n\n \n # - - - - main rule block - - - -\n # at line 68:3: (~ ( '>' | '<' | '#' | '`' | '\\\"' | '\\\\'' | '|' | '(' | ')' | '$' | ';' | ' ' | '?' | '*' | '~' | '\\\\\\\\' | '\\\\t' | '{' | '}' | '\\\\n' | '\\\\r' ) | '\\\\\\\\' . )\n alt_23 = 2\n look_23_0 = @input.peek( 1 )\n\n if ( look_23_0.between?( 0x0, 0x8 ) || look_23_0.between?( 0xb, 0xc ) || look_23_0.between?( 0xe, 0x1f ) || look_23_0 == 0x21 || look_23_0.between?( 0x25, 0x26 ) || look_23_0.between?( 0x2b, 0x3a ) || look_23_0 == 0x3d || look_23_0.between?( 0x40, 0x5b ) || look_23_0.between?( 0x5d, 0x5f ) || look_23_0.between?( 0x61, 0x7a ) || look_23_0.between?( 0x7f, 0xffff ) )\n alt_23 = 1\n elsif ( look_23_0 == 0x5c )\n alt_23 = 2\n else\n raise NoViableAlternative( \"\", 23, 0 )\n end\n case alt_23\n when 1\n # at line 68:5: ~ ( '>' | '<' | '#' | '`' | '\\\"' | '\\\\'' | '|' | '(' | ')' | '$' | ';' | ' ' | '?' | '*' | '~' | '\\\\\\\\' | '\\\\t' | '{' | '}' | '\\\\n' | '\\\\r' )\n if @input.peek( 1 ).between?( 0x0, 0x8 ) || @input.peek( 1 ).between?( 0xb, 0xc ) || @input.peek( 1 ).between?( 0xe, 0x1f ) || @input.peek(1) == 0x21 || @input.peek( 1 ).between?( 0x25, 0x26 ) || @input.peek( 1 ).between?( 0x2b, 0x3a ) || @input.peek(1) == 0x3d || @input.peek( 1 ).between?( 0x40, 0x5b ) || @input.peek( 1 ).between?( 0x5d, 0x5f ) || @input.peek( 1 ).between?( 0x61, 0x7a ) || @input.peek( 1 ).between?( 0x7f, 0xff )\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n end\n\n\n\n when 2\n # at line 70:5: '\\\\\\\\' .\n match( 0x5c )\n match_any\n\n end\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 14 )\n\n end", "def parse_line(line)\n # If the previous line didn't and a logical line, we're not going to start one. If it did,\n # we're indeed going to start a new logical line\n @state[:ll_start] = @state[:ll_end]\n\n # We will start with the assumption that we're going to end the current logical line. We may layer\n # find out that we did not, in fact, do so.\n @state[:ll_end] = true\n\n # Reset the line continuator flag the the last line may have set to true\n @state[:line_continuator] = false\n\n # Find the first non-(space/tab) character\n index = 0\n while index < line.length && [\" \", \"\\t\"].include?(line[index])\n index += 1\n end\n @state[:indent_string] = line[0...index]\n\n # Iterate over the line's characters as long as there are any. We use different iteration\n # methods depending on whether we're inside a string or not\n index = 0\n while index < line.length\n if @state[:in_string].nil?\n index = parse_characters_normal(line, index)\n else\n index = parse_characters_in_string(line, index)\n end\n end\n\n # We have reached the end of the line. Decide whether or not the logical line ends here.\n @state[:ll_end] = @state[:in_string].nil? && @state[:open_braces] == 0 && !@state[:line_continuator]\n end", "def next_token\n\n token = nil\n\n until ss.eos? or token do\n token =\n case state\n when nil then\n case\n when ss.skip(/\\s+/) then\n # do nothing\n when ss.skip(/:(#{SYMBOL_NAME})/o) then\n action { emit :tSYMBOL, &:to_sym }\n when ss.skip(/\"(.+?)\"/) then\n action { emit :tSTRING }\n when ss.skip(/[-+]?\\d+\\.\\d+/) then\n action { emit :tNUMBER, &:to_f }\n when ss.skip(/[-+]?\\d+/) then\n action { emit :tNUMBER, &:to_i }\n when ss.skip(/#{Regexp.union(\n %w\"( ) { | } [ ] < > $ ! ^ ` ... + * ? ,\"\n )}/o) then\n action { emit ss.matched, &:to_sym }\n when ss.skip(/#{REGEXP}/o) then\n action { emit_regexp }\n when ss.skip(/%?(#{CONST_NAME})/o) then\n action { emit :tPARAM_CONST }\n when ss.skip(/%([a-z_]+)/) then\n action { emit :tPARAM_NAMED }\n when ss.skip(/%(\\d*)/) then\n action { emit(:tPARAM_NUMBER) { |s| s.empty? ? 1 : s.to_i } } # Map `%` to `%1`\n when ss.skip(/_(#{IDENTIFIER})/o) then\n action { emit :tUNIFY }\n when ss.skip(/_/o) then\n action { emit :tWILDCARD }\n when ss.skip(/\\#(#{CALL})/o) then\n action { @state = :ARG; emit :tFUNCTION_CALL, &:to_sym }\n when ss.skip(/#{IDENTIFIER}\\?/o) then\n action { @state = :ARG; emit :tPREDICATE, &:to_sym }\n when ss.skip(/#{NODE_TYPE}/o) then\n action { emit :tNODE_TYPE, &:to_sym }\n when ss.skip(/\\#.*/) then\n action { emit_comment }\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n when :ARG then\n case\n when ss.skip(/\\(/) then\n action { @state = nil; emit :tARG_LIST }\n when ss.skip(//) then\n action { @state = nil }\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n else\n raise ScanError, \"undefined state at #{location}: '#{state}'\"\n end # token = case state\n\n next unless token # allow functions to trigger redo w/ nil\n end # while\n\n raise LexerError, \"bad lexical result at #{location}: #{token.inspect}\" unless\n token.nil? || (Array === token && token.size >= 2)\n\n # auto-switch state\n self.state = token.last if token && token.first == :state\n\n token\n end", "def parse(source)\n raise \"Attempt to continue parsing using finalized parser\" if @finished\n\n source.each_char() { |char|\n if @mode == :read_comment\n if char == \"\\n\"\n @mode = :find_name\n end\n elsif @in_escape == true\n buffer(case char\n when 'n' then \"\\n\"\n when 'r' then \"\\r\"\n when 'a' then \"\\a\"\n when 'b' then \"\\b\"\n when 'f' then \"\\f\"\n when 't' then \"\\t\"\n when '0' then \"\\0\"\n else char\n end, true)\n @in_escape = false\n else\n case char\n when ' ', \"\\t\"\n if @mode == :read_name\n parsedName(grab_and_reset_buffer())\n @mode = :find_value\n elsif ! ((@consume_whitespace && @last_char == char) || @mode == :find_name || @mode == :find_value)\n buffer char\n end\n\n when '{'\n case @mode\n when :read_name, :find_value\n parsedName(grab_and_reset_buffer()) if @mode == :read_name\n parsedNodeOpening()\n @depth += 1\n\n when :read_value, :find_name\n parsedValue(grab_and_reset_buffer()) if @mode == :read_value\n if @depth == 0 && @nameless_roots\n @depth += 1\n parsedName('')\n parsedNodeOpening()\n else\n raise error_string('Invalid character { - expected name.')\n end\n\n else\n raise error_string('Invalid character { - expected name.')\n end\n\n @mode = :find_name\n\n when '}'\n case @mode\n when :read_name, :find_value\n parsedName(grab_and_reset_buffer()) if @mode == :read_name\n parsedValue('')\n\n when :read_value\n parsedValue(grab_and_reset_buffer())\n end\n\n if @depth == 0\n raise error_string(\"Unexpected } - no matching {.\")\n end\n\n @depth -= 1\n @mode = :find_name\n\n parsedNodeClosing()\n\n when \"\\n\", '#', ';'\n case @mode\n when :read_name, :find_value\n parsedName(grab_and_reset_buffer()) if @mode == :read_name\n parsedValue('')\n when :read_value\n parsedValue(grab_and_reset_buffer())\n end\n\n @mode = char == '#' ? :read_comment : :find_name\n\n when \"\\\\\"\n @in_escape = true\n\n else\n if @mode == :find_name\n @mode = :read_name\n elsif @mode == :find_value\n @mode = :read_value\n end\n\n buffer(char)\n\n end\n end\n\n @last_char = char\n\n if char == \"\\n\"\n @line += 1\n @column = 1\n else\n @column += 1\n end\n }\n end", "def next_token\n return process_string if lex_strterm\n self.cmd_state = self.command_start\n self.command_start = false\n self.space_seen = false # TODO: rename token_seen?\n self.last_state = lex_state\n\n token = nil\n\n until ss.eos? or token do\n token =\n case state\n when nil then\n case\n when ss.skip(/[\\ \\t\\r\\f\\v]/) then\n action { self.space_seen = true; next }\n when text = ss.scan(/\\n|\\#/) then\n process_newline_or_comment text\n when text = ss.scan(/[\\]\\)\\}]/) then\n process_brace_close text\n when ss.match?(/\\!/) then\n case\n when is_after_operator? && (ss.skip(/\\!\\@/)) then\n action { result EXPR_ARG, :tUBANG, \"!@\" }\n when text = ss.scan(/\\![=~]?/) then\n action { result :arg_state, TOKENS[text], text }\n end # group /\\!/\n when ss.match?(/\\./) then\n case\n when text = ss.scan(/\\.\\.\\.?/) then\n action { result EXPR_BEG, TOKENS[text], text }\n when ss.skip(/\\.\\d/) then\n action { rb_compile_error \"no .<digit> floating literal anymore put 0 before dot\" }\n when ss.skip(/\\./) then\n action { self.lex_state = EXPR_BEG; result EXPR_DOT, :tDOT, \".\" }\n end # group /\\./\n when text = ss.scan(/\\(/) then\n process_paren text\n when text = ss.scan(/\\,/) then\n action { result EXPR_PAR, TOKENS[text], text }\n when ss.match?(/=/) then\n case\n when text = ss.scan(/\\=\\=\\=|\\=\\=|\\=~|\\=>|\\=(?!begin\\b)/) then\n action { result arg_state, TOKENS[text], text }\n when bol? && (text = ss.scan(/\\=begin(?=\\s)/)) then\n process_begin text\n when text = ss.scan(/\\=(?=begin\\b)/) then\n action { result arg_state, TOKENS[text], text }\n end # group /=/\n when ruby22_label? && (text = ss.scan(/\\\"#{SIMPLE_STRING}\\\":/o)) then\n process_label text\n when text = ss.scan(/\\\"(#{SIMPLE_STRING})\\\"/o) then\n action { result EXPR_END, :tSTRING, text[1..-2].gsub(ESC) { unescape $1 } }\n when text = ss.scan(/\\\"/) then\n action { string STR_DQUOTE; result nil, :tSTRING_BEG, text }\n when text = ss.scan(/\\@\\@?\\d/) then\n action { rb_compile_error \"`#{text}` is not allowed as a variable name\" }\n when text = ss.scan(/\\@\\@?#{IDENT_CHAR}+/o) then\n process_ivar text\n when ss.match?(/:/) then\n case\n when not_end? && (text = ss.scan(/:([a-zA-Z_]#{IDENT_CHAR}*(?:[?]|[!](?!=)|=(?==>)|=(?![=>]))?)/o)) then\n process_symbol text\n when not_end? && (text = ss.scan(/\\:\\\"(#{SIMPLE_STRING})\\\"/o)) then\n process_symbol text\n when not_end? && (text = ss.scan(/\\:\\'(#{SSTRING})\\'/o)) then\n process_symbol text\n when text = ss.scan(/\\:\\:/) then\n process_colon2 text\n when text = ss.scan(/\\:/) then\n process_colon1 text\n end # group /:/\n when ss.skip(/->/) then\n action { result EXPR_ENDFN, :tLAMBDA, nil }\n when text = ss.scan(/[+-]/) then\n process_plus_minus text\n when ss.match?(/[+\\d]/) then\n case\n when ss.skip(/#{NUM_BAD}/o) then\n action { rb_compile_error \"Invalid numeric format\" }\n when ss.skip(/#{INT_DEC}/o) then\n action { int_with_base 10 }\n when ss.skip(/#{INT_HEX}/o) then\n action { int_with_base 16 }\n when ss.skip(/#{INT_BIN}/o) then\n action { int_with_base 2 }\n when ss.skip(/#{INT_OCT_BAD}/o) then\n action { rb_compile_error \"Illegal octal digit.\" }\n when ss.skip(/#{INT_OCT}/o) then\n action { int_with_base 8 }\n when ss.skip(/#{FLOAT_BAD}/o) then\n action { rb_compile_error \"Trailing '_' in number.\" }\n when text = ss.scan(/#{FLOAT}/o) then\n process_float text\n when ss.skip(/#{INT_DEC2}/o) then\n action { int_with_base 10 }\n when ss.skip(/[0-9]/) then\n action { rb_compile_error \"Bad number format\" }\n end # group /[+\\d]/\n when text = ss.scan(/\\[/) then\n process_square_bracket text\n when was_label? && (text = ss.scan(/\\'#{SSTRING}\\':?/o)) then\n process_label_or_string text\n when ss.match?(/\\|/) then\n case\n when ss.skip(/\\|\\|\\=/) then\n action { result EXPR_BEG, :tOP_ASGN, \"||\" }\n when ss.skip(/\\|\\|/) then\n action { result EXPR_BEG, :tOROP, \"||\" }\n when ss.skip(/\\|\\=/) then\n action { result EXPR_BEG, :tOP_ASGN, \"|\" }\n when ss.skip(/\\|/) then\n action { state = is_after_operator? ? EXPR_ARG : EXPR_PAR; result state, :tPIPE, \"|\" }\n end # group /\\|/\n when text = ss.scan(/\\{/) then\n process_brace_open text\n when ss.match?(/\\*/) then\n case\n when ss.skip(/\\*\\*=/) then\n action { result EXPR_BEG, :tOP_ASGN, \"**\" }\n when ss.skip(/\\*\\*/) then\n action { result(:arg_state, space_vs_beginning(:tDSTAR, :tDSTAR, :tPOW), \"**\") }\n when ss.skip(/\\*\\=/) then\n action { result(EXPR_BEG, :tOP_ASGN, \"*\") }\n when ss.skip(/\\*/) then\n action { result(:arg_state, space_vs_beginning(:tSTAR, :tSTAR, :tSTAR2), \"*\") }\n end # group /\\*/\n when ss.match?(/</) then\n case\n when ss.skip(/\\<\\=\\>/) then\n action { result :arg_state, :tCMP, \"<=>\" }\n when ss.skip(/\\<\\=/) then\n action { result :arg_state, :tLEQ, \"<=\" }\n when ss.skip(/\\<\\<\\=/) then\n action { result EXPR_BEG, :tOP_ASGN, \"<<\" }\n when text = ss.scan(/\\<\\</) then\n process_lchevron text\n when ss.skip(/\\</) then\n action { result :arg_state, :tLT, \"<\" }\n end # group /</\n when ss.match?(/>/) then\n case\n when ss.skip(/\\>\\=/) then\n action { result :arg_state, :tGEQ, \">=\" }\n when ss.skip(/\\>\\>=/) then\n action { result EXPR_BEG, :tOP_ASGN, \">>\" }\n when ss.skip(/\\>\\>/) then\n action { result :arg_state, :tRSHFT, \">>\" }\n when ss.skip(/\\>/) then\n action { result :arg_state, :tGT, \">\" }\n end # group />/\n when ss.match?(/\\`/) then\n case\n when expr_fname? && (ss.skip(/\\`/)) then\n action { result(EXPR_END, :tBACK_REF2, \"`\") }\n when expr_dot? && (ss.skip(/\\`/)) then\n action { result((cmd_state ? EXPR_CMDARG : EXPR_ARG), :tBACK_REF2, \"`\") }\n when ss.skip(/\\`/) then\n action { string STR_XQUOTE, '`'; result(nil, :tXSTRING_BEG, \"`\") }\n end # group /\\`/\n when text = ss.scan(/\\?/) then\n process_questionmark text\n when ss.match?(/&/) then\n case\n when ss.skip(/\\&\\&\\=/) then\n action { result(EXPR_BEG, :tOP_ASGN, \"&&\") }\n when ss.skip(/\\&\\&/) then\n action { result(EXPR_BEG, :tANDOP, \"&&\") }\n when ss.skip(/\\&\\=/) then\n action { result(EXPR_BEG, :tOP_ASGN, \"&\" ) }\n when ss.skip(/\\&\\./) then\n action { result(EXPR_DOT, :tLONELY, \"&.\") }\n when text = ss.scan(/\\&/) then\n process_amper text\n end # group /&/\n when text = ss.scan(/\\//) then\n process_slash text\n when ss.match?(/\\^/) then\n case\n when ss.skip(/\\^=/) then\n action { result(EXPR_BEG, :tOP_ASGN, \"^\") }\n when ss.skip(/\\^/) then\n action { result(:arg_state, :tCARET, \"^\") }\n end # group /\\^/\n when ss.skip(/\\;/) then\n action { self.command_start = true; result(EXPR_BEG, :tSEMI, \";\") }\n when ss.match?(/~/) then\n case\n when is_after_operator? && (ss.skip(/\\~@/)) then\n action { result(:arg_state, :tTILDE, \"~\") }\n when ss.skip(/\\~/) then\n action { result(:arg_state, :tTILDE, \"~\") }\n end # group /~/\n when ss.match?(/\\\\/) then\n case\n when ss.skip(/\\\\\\r?\\n/) then\n action { self.lineno += 1; self.space_seen = true; next }\n when ss.skip(/\\\\/) then\n action { rb_compile_error \"bare backslash only allowed before newline\" }\n end # group /\\\\/\n when text = ss.scan(/\\%/) then\n process_percent text\n when ss.match?(/\\$/) then\n case\n when text = ss.scan(/\\$_\\w+/) then\n process_gvar text\n when text = ss.scan(/\\$_/) then\n process_gvar text\n when text = ss.scan(/\\$[~*$?!@\\/\\\\;,.=:<>\\\"]|\\$-\\w?/) then\n process_gvar text\n when in_fname? && (text = ss.scan(/\\$([\\&\\`\\'\\+])/)) then\n process_gvar text\n when text = ss.scan(/\\$([\\&\\`\\'\\+])/) then\n process_backref text\n when in_fname? && (text = ss.scan(/\\$([1-9]\\d*)/)) then\n process_gvar text\n when text = ss.scan(/\\$([1-9]\\d*)/) then\n process_nthref text\n when text = ss.scan(/\\$0/) then\n process_gvar text\n when text = ss.scan(/\\$[^[:ascii:]]+/) then\n process_gvar text\n when text = ss.scan(/\\$\\W|\\$\\z/) then\n process_gvar_oddity text\n when text = ss.scan(/\\$\\w+/) then\n process_gvar text\n end # group /\\$/\n when text = ss.scan(/\\_/) then\n process_underscore text\n when text = ss.scan(/#{IDENT}/o) then\n process_token text\n when ss.skip(/\\004|\\032|\\000|\\Z/) then\n action { [RubyLexer::EOF, RubyLexer::EOF] }\n when text = ss.scan(/./) then\n action { rb_compile_error \"Invalid char #{text.inspect} in expression\" }\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n else\n raise ScanError, \"undefined state at #{location}: '#{state}'\"\n end # token = case state\n\n next unless token # allow functions to trigger redo w/ nil\n end # while\n\n raise LexerError, \"bad lexical result at #{location}: #{token.inspect}\" unless\n token.nil? || (Array === token && token.size >= 2)\n\n # auto-switch state\n self.state = token.last if token && token.first == :state\n\n token\n end", "def parse_input (input_string)\n lines = input_string.split(/\\n/)\n\n state = :reading_map\n\n rover_x_start = 0\n rover_y_start = 0\n rover_facing_start = 0\n\n lines.each do |line|\n # drop empty lines\n next unless /(\\w)+/ =~ line\n\n case state\n when :reading_map\n match = /^\\s*(\\d+)\\s+(\\d+)\\s*$/.match(line)\n raise ArgumentError.new(\"Invalid map data >>#{line}<<\") unless match\n\n x_size = $1.to_i\n y_size = $2.to_i\n\n # the format is not the size, it's the greatest valid index\n init_map(x_size,y_size)\n\n state = :reading_rover_init\n\n when :reading_rover_init\n match = /^\\s*(\\d+)\\s+(\\d+)\\s+([NSWE])\\s*$/.match(line)\n # match = line.match /^\\s*(\\d+)\\s+(\\d+)\\s+([NSWE])\\s*$/\n raise ArgumentError.new(\"Invalid rover init >>#{line}<<\") unless match\n\n rover_x_start = $1.to_i\n rover_y_start = $2.to_i\n rover_facing_start = $3\n\n state = :reading_rover_instructions\n when :reading_rover_instructions\n match = /^\\s*([LRM]+)\\s*$/.match(line)\n raise ArgumentError.new(\"Invalid rover init >>#{line}<<\") unless match\n\n rover_instructions = $1\n\n add_rover(rover_x_start,rover_y_start,rover_facing_start,rover_instructions)\n\n state = :reading_rover_init\n end\n end\n\n end", "def tokenize input\n s = StringScanner.new input\n\n @line = 0\n @line_pos = 0\n\n until s.eos? do\n pos = s.pos\n\n @tokens << case\n when s.scan(/\\r?\\n/) then\n token = [:NEWLINE, s.matched, *token_pos(pos)]\n @line_pos = s.pos\n @line += 1\n token\n when s.scan(/ +/) then\n [:INDENT, s.matched_size, *token_pos(pos)]\n when s.scan(/(=+)\\s*/) then\n level = s[1].length\n level = 6 if level > 6\n @tokens << [:HEADER, level, *token_pos(pos)]\n\n pos = s.pos\n s.scan(/.*/)\n [:TEXT, s.matched, *token_pos(pos)]\n when s.scan(/^(-{3,}) *$/) then\n [:RULE, s[1].length - 2, *token_pos(pos)]\n when s.scan(/([*-])\\s+/) then\n @tokens << [:BULLET, :BULLET, *token_pos(pos)]\n [:SPACE, s.matched_size, *token_pos(pos)]\n when s.scan(/([a-z]|\\d+)\\.[ \\t]+\\S/i) then\n list_label = s[1]\n width = s.matched_size - 1\n\n s.pos -= 1 # unget \\S\n\n list_type = case list_label\n when /[a-z]/ then :LALPHA\n when /[A-Z]/ then :UALPHA\n when /\\d/ then :NUMBER\n else\n raise ParseError, \"BUG token #{list_label}\"\n end\n\n @tokens << [list_type, list_label, *token_pos(pos)]\n [:SPACE, width, *token_pos(pos)]\n when s.scan(/\\[(.*?)\\]( +|$)/) then\n @tokens << [:LABEL, s[1], *token_pos(pos)]\n [:SPACE, s.matched_size, *token_pos(pos)]\n when s.scan(/(.*?)::( +|$)/) then\n @tokens << [:NOTE, s[1], *token_pos(pos)]\n [:SPACE, s.matched_size, *token_pos(pos)]\n else s.scan(/.*/)\n [:TEXT, s.matched, *token_pos(pos)]\n end\n end\n\n self\n end", "def lex(expr)\n tokens = []\n i = -1\n while i < expr.size - 1\n tok ||= \"\"\n i += 1\n\n case expr[i].chr\n when '[', ']', '{', '}', ':', ','\n tokens << tok if tok.size > 0\n tokens << expr[i].chr\n tok = \"\"\n # String processing\n when '\"'\n raise \"Unexpected quote\" if tok.size > 0\n len = 1\n escaped = false\n while (len + i) < expr.size\n break if expr[len + i].chr == '\"' and not escaped\n if escaped\n case expr[len + i].chr\n when '\"', '/', '\\\\', 'b', 'f', 'n', 'r', 't', 'u'\n else\n raise \"Unable to escape #{expr[len + i].chr}\"\n end\n end\n escaped = expr[len + i].chr == \"\\\\\"\n len += 1\n end\n raise \"No matching endquote for string\" if (len + i) > expr.size\n tokens << convert_unicode(expr.slice(i, len+1))\n i += len\n # Number processing\n when '-', /[0-9]/\n len = 0\n while (len + i) < expr.size and /[0-9eE+-.]/.match(expr[len + i].chr)!= nil\n len += 1\n end\n num = expr.slice(i, len)\n\n # Verify syntax of the number using the JSON state machine\n raise \"Invalid number #{num}\" if /[-]?([1-9]|(0\\.))[0-9]*[eE]?[+-]?[0-9]*/.match(num) == nil\n\n tokens << num\n i += len - 1\n # Skip whitespace\n when ' ', '\\t'\n else\n tok << expr[i].chr\n end\n end\n tokens << tok if tok.size > 0\n tokens\n end", "def parse(input, with_fps = DEFAULT_FPS)\n # Drop frame goodbye\n if (input =~ DF_TC_RE)\n raise Error, \"We do not support drop-frame TC\"\n # 00:00:00:00\n elsif (input =~ COMPLETE_TC_RE)\n atoms_and_fps = input.scan(COMPLETE_TC_RE).to_a.flatten.map{|e| e.to_i} + [with_fps]\n return at(*atoms_and_fps)\n # 00:00:00+00\n elsif (input =~ COMPLETE_TC_RE_24)\n atoms_and_fps = input.scan(COMPLETE_TC_RE_24).to_a.flatten.map{|e| e.to_i} + [24]\n return at(*atoms_and_fps)\n # 00:00:00.0\n elsif input =~ FRACTIONAL_TC_RE\n parse_with_fractional_seconds(input, with_fps)\n # 00:00:00:000\n elsif input =~ TICKS_TC_RE\n parse_with_ticks(input, with_fps)\n # 10h 20m 10s 1f 00:00:00:01 - space separated is a sum of parts\n elsif input =~ /\\s/\n parts = input.gsub(/\\s/, ' ').split.reject{|e| e.strip.empty? }\n raise CannotParse, \"No atoms\" if parts.empty?\n parts.map{|part| parse(part, with_fps) }.inject{|sum, p| sum + p.total }\n # 10s\n elsif input =~ /^(\\d+)s$/\n return new(input.to_i * with_fps, with_fps)\n # 10h\n elsif input =~ /^(\\d+)h$/i\n return new(input.to_i * 60 * 60 * with_fps, with_fps)\n # 20m\n elsif input =~ /^(\\d+)m$/i\n return new(input.to_i * 60 * with_fps, with_fps)\n # 60f - 60 frames, or 2 seconds and 10 frames\n elsif input =~ /^(\\d+)f$/i\n return new(input.to_i, with_fps)\n # Only a bunch of digits, treat 12345 as 00:01:23:45\n elsif (input =~ /^(\\d+)$/)\n atoms_len = 2 * 4\n # left-pad input AND truncate if needed\n padded = input[0..atoms_len].rjust(8, \"0\")\n atoms = padded.scan(/(\\d{2})/).flatten.map{|e| e.to_i } + [with_fps]\n return at(*atoms)\n else\n raise CannotParse, \"Cannot parse #{input} into timecode, unknown format\"\n end\n end", "def parse(input, with_fps = DEFAULT_FPS)\n # Drop frame goodbye\n if (input =~ DF_TC_RE)\n raise Error, \"We do not support drop-frame TC\"\n # 00:00:00:00\n elsif (input =~ COMPLETE_TC_RE)\n atoms_and_fps = input.scan(COMPLETE_TC_RE).to_a.flatten.map{|e| e.to_i} + [with_fps]\n return at(*atoms_and_fps)\n # 00:00:00+00\n elsif (input =~ COMPLETE_TC_RE_24)\n atoms_and_fps = input.scan(COMPLETE_TC_RE_24).to_a.flatten.map{|e| e.to_i} + [24]\n return at(*atoms_and_fps)\n # 00:00:00.0\n elsif input =~ FRACTIONAL_TC_RE\n parse_with_fractional_seconds(input, with_fps)\n # 00:00:00:000\n elsif input =~ TICKS_TC_RE\n parse_with_ticks(input, with_fps)\n # 10h 20m 10s 1f 00:00:00:01 - space separated is a sum of parts\n elsif input =~ /\\s/\n parts = input.gsub(/\\s/, ' ').split.reject{|e| e.strip.empty? }\n raise CannotParse, \"No atoms\" if parts.empty?\n parts.map{|part| parse(part, with_fps) }.inject{|sum, p| sum + p.total }\n # 10s\n elsif input =~ /^(\\d+)s$/\n return new(input.to_i * with_fps, with_fps)\n # 10h\n elsif input =~ /^(\\d+)h$/i\n return new(input.to_i * 60 * 60 * with_fps, with_fps)\n # 20m\n elsif input =~ /^(\\d+)m$/i\n return new(input.to_i * 60 * with_fps, with_fps)\n # 60f - 60 frames, or 2 seconds and 10 frames\n elsif input =~ /^(\\d+)f$/i\n return new(input.to_i, with_fps)\n # Only a bunch of digits, treat 12345 as 00:01:23:45\n elsif (input =~ /^(\\d+)$/)\n atoms_len = 2 * 4\n # left-pad input AND truncate if needed\n padded = input[0..atoms_len].rjust(8, \"0\")\n atoms = padded.scan(/(\\d{2})/).flatten.map{|e| e.to_i } + [with_fps]\n return at(*atoms)\n else\n raise CannotParse, \"Cannot parse #{input} into timecode, unknown format\"\n end\n end", "def parse_time\n s0 = @scanner.pos\n if match_str('(') == :failed\n @scanner.pos = s0\n s0 = :failed\n else\n match_spaces\n s3 = parse_ms\n if s3 == :failed\n @scanner.pos = s0\n s0 = :failed\n else\n match_spaces\n if match_str('/') == :failed\n @scanner.pos = s0\n s0 = :failed\n else\n match_spaces\n s5 = parse_hms\n s5 = parse_ms(with_hour: true) if s5 == :failed\n if s5 == :failed\n @scanner.pos = s0\n s0 = :failed\n else\n match_spaces\n if match_str(')') == :failed\n @scanner.pos = s0\n s0 = :failed\n else\n @reported_pos = s0\n s0 = { 'now' => s3, 'total' => s5 }\n end\n end\n end\n end\n end\n s0\n end", "def parse_characters_normal(line, start_index)\n index = start_index\n\n while index < line.length\n if [ \"(\", \"{\", \"[\" ].include?(line[index])\n # Opening brace\n @state[:open_braces] += 1\n index += 1\n\n elsif [ \")\", \"}\", \"]\" ].include?(line[index])\n # Closing brace\n @state[:open_braces] -= 1\n index += 1\n\n elsif line[index] == \"#\"\n # We have found the start of a comment, so ignore the rest of the line\n index = line.length\n\n elsif line[index] == \"\\\\\" && index == line.length - 1\n # We have found a backslash as the last character -> line continuation\n @state[:line_continuator] = true\n index += 1\n\n elsif line[index] == '\"\"\"'\n # We have found a triple-quoted string. Advance index and leave\n @state[:in_string] = '\"\"\"'\n index += 3\n break\n\n elsif line[index] == \"'''\"\n # We have found a triple-quoted string. Advance index and leave\n @state[:in_string] = \"'''\"\n index += 3\n break\n\n elsif line[index] == '\"'\n # We have found a single-quoted string. Advance index and leave\n @state[:in_string] = '\"'\n index += 1\n break\n\n elsif line[index] == \"'\"\n # We have found a single-quoted string. Advance index and leave\n @state[:in_string] = \"'\"\n index += 1\n break\n\n else\n # Advance a character\n index += 1\n end\n end\n\n return index\n end", "def parse(script)\n next_token_id = 0\n\n token_records = []\n\n # Maps token name to token entry\n @tokenNameMap = {}\n\n script_lines = script.split(\"\\n\")\n @original_line_numbers = []\n\n # Join lines that have been ended with '\\' to their following lines;\n # only do this if there's an odd number of '\\' at the end\n\n @lines = []\n accum = nil\n accum_start_line = nil\n\n script_lines.each_with_index do |line, original_line_number|\n\n trailing_backslash_count = 0\n while line.length > trailing_backslash_count && line[-1-trailing_backslash_count] == '\\\\'\n trailing_backslash_count += 1\n end\n\n if accum.nil?\n accum = \"\"\n accum_start_line = original_line_number\n end\n\n if (trailing_backslash_count % 2 == 1)\n accum << line[0...-1]\n else\n accum << line\n @lines << accum\n @original_line_numbers << accum_start_line\n accum = nil\n end\n end\n\n if !accum.nil?\n raise ParseException, \"Incomplete final line: #{script}\"\n end\n\n # Now that we've stitched together lines where there were trailing \\ characters,\n # process each line as a complete token definition\n\n @lines.each_with_index do |line, line_index|\n line_number = 1 + @original_line_numbers[line_index]\n\n # Strip whitespace only from the left side (which will strip all of\n # it, if the entire line is whitespace). We want to preserve any\n # special escaped whitespace on the right side.\n line.lstrip!\n\n # If line is empty, or starts with '#', it's a comment\n if line.length == 0 || line[0] == '#'\n next\n end\n\n if !(line =~ TOKENNAME_EXPR)\n raise ParseException.build(\"Syntax error\", line_number, line)\n end\n\n pos = line.index(\":\")\n\n tokenName = line[0,pos].strip()\n\n expr = line[pos+1..-1]\n\n rex = RegParse.new(expr, @tokenNameMap, line_number)\n\n # Give it the next available token id, if it's not an anonymous token; else -1\n\n token_id = -1\n if tokenName[0] != '_'\n token_id = next_token_id\n next_token_id += 1\n end\n\n entry = TokenEntry.new(tokenName, rex, token_id)\n\n if @tokenNameMap.has_key?(tokenName)\n raise ParseException.build(\"Duplicate token name\",line_number,line)\n end\n @tokenNameMap[entry.name] = entry\n\n next if entry.id < 0\n\n if accepts_zero_characters(rex.start_state, rex.endState)\n raise ParseException.build(\"Zero-length tokens accepted\",line_number,line)\n end\n\n token_records << entry\n end\n\n combined = combine_token_nfas(token_records)\n\n builder = NFAToDFA.new(combined)\n builder.generate_pdf = @generate_pdf\n dfa = builder.nfa_to_dfa\n\n apply_redundant_token_filter(token_records, dfa)\n\n Tokn::DFA.new(token_records.map{|x| x.name}, dfa)\n end", "def tokenize input\n setup_scanner input\n\n until @s.eos? do\n pos = @s.pos\n\n # leading spaces will be reflected by the column of the next token\n # the only thing we loose are trailing spaces at the end of the file\n next if @s.scan(/ +/)\n\n # note: after BULLET, LABEL, etc.,\n # indent will be the column of the next non-newline token\n\n @tokens << case\n # [CR]LF => :NEWLINE\n when @s.scan(/\\r?\\n/) then\n token = [:NEWLINE, @s.matched, *pos]\n @s.newline!\n token\n # === text => :HEADER then :TEXT\n when @s.scan(/(=+)(\\s*)/) then\n level = @s[1].length\n header = [:HEADER, level, *pos]\n\n if @s[2] =~ /^\\r?\\n/ then\n @s.unscan(@s[2])\n header\n else\n pos = @s.pos\n @s.scan(/.*/)\n @tokens << header\n [:TEXT, @s.matched.sub(/\\r$/, ''), *pos]\n end\n # --- (at least 3) and nothing else on the line => :RULE\n when @s.scan(/(-{3,}) *\\r?$/) then\n [:RULE, @s[1].length - 2, *pos]\n # * or - followed by white space and text => :BULLET\n when @s.scan(/([*-]) +(\\S)/) then\n @s.unscan(@s[2])\n [:BULLET, @s[1], *pos]\n # A. text, a. text, 12. text => :UALPHA, :LALPHA, :NUMBER\n when @s.scan(/([a-z]|\\d+)\\. +(\\S)/i) then\n # FIXME if tab(s), the column will be wrong\n # either support tabs everywhere by first expanding them to\n # spaces, or assume that they will have been replaced\n # before (and provide a check for that at least in debug\n # mode)\n list_label = @s[1]\n @s.unscan(@s[2])\n list_type =\n case list_label\n when /[a-z]/ then :LALPHA\n when /[A-Z]/ then :UALPHA\n when /\\d/ then :NUMBER\n else\n raise ParseError, \"BUG token #{list_label}\"\n end\n [list_type, list_label, *pos]\n # [text] followed by spaces or end of line => :LABEL\n when @s.scan(/\\[(.*?)\\]( +|\\r?$)/) then\n [:LABEL, @s[1], *pos]\n # text:: followed by spaces or end of line => :NOTE\n when @s.scan(/(.*?)::( +|\\r?$)/) then\n [:NOTE, @s[1], *pos]\n # >>> followed by end of line => :BLOCKQUOTE\n when @s.scan(/>>> *(\\w+)?$/) then\n [:BLOCKQUOTE, @s[1], *pos]\n # anything else: :TEXT\n else\n @s.scan(/(.*?)( )?\\r?$/)\n token = [:TEXT, @s[1], *pos]\n\n if @s[2] then\n @tokens << token\n [:BREAK, @s[2], pos[0] + @s[1].length, pos[1]]\n else\n token\n end\n end\n end\n\n self\n end", "def next_token\n\n token = nil\n\n until ss.eos? or token do\n if ss.peek(1) == \"\\n\"\n self.lineno += 1\n # line starts 1 position after the newline\n self.start_of_current_line_pos = ss.pos + 1\n end\n self.old_pos = ss.pos\n token =\n case state\n when nil then\n case\n when ss.skip(/[ \\t]+/) then\n # do nothing\n when ss.skip(/\\/\\/[^\\r\\n]*/) then\n # do nothing\n when text = ss.scan(/\\r|\\n/) then\n newline text\n when text = ss.scan(/[!=<>]=?/) then\n action { [:SPECIAL, text] }\n when text = ss.scan(/[(){},;.\\-+\\/*]/) then\n action { [:SPECIAL, text] }\n when text = ss.scan(/#{DIGIT}+(\\.#{DIGIT}+)?/) then\n action { [:NUMBER, text] }\n when text = ss.scan(/nil/) then\n action { [:NIL, text] }\n when text = ss.scan(/false/) then\n action { [:FALSE, text] }\n when text = ss.scan(/true/) then\n action { [:TRUE, text] }\n when text = ss.scan(/#{ALPHA}(#{ALPHA}|#{DIGIT})*/) then\n action { [:IDENTIFIER, text] }\n when ss.skip(/\"\"/) then\n action { [:STRING, '\"\"'] }\n when ss.skip(/\"/) then\n [:state, :IN_STRING]\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n when :IN_STRING then\n case\n when text = ss.scan(/[^\"]+/) then\n action { [:STRING, \"\\\"#{text}\\\"\"] }\n when ss.skip(/\"/) then\n [:state, nil]\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n else\n raise ScanError, \"undefined state at #{location}: '#{state}'\"\n end # token = case state\n\n next unless token # allow functions to trigger redo w/ nil\n end # while\n\n raise LexerError, \"bad lexical result at #{location}: #{token.inspect}\" unless\n token.nil? || (Array === token && token.size >= 2)\n\n # auto-switch state\n self.state = token.last if token && token.first == :state\n\n token\n end", "def scan_for_t(token); end", "def minutes\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 25 )\n minutes_start_index = @input.index\n\n success = false # flag used for memoization\n\n begin\n # rule memoization\n if @state.backtracking > 0 and already_parsed_rule?( __method__ )\n success = true\n return \n end\n # at line 304:10: ( 'M' | 'm' ) ( 'I' | 'i' ) ( 'N' | 'n' ) ( 'U' | 'u' ) ( 'T' | 't' ) ( 'E' | 'e' ) ( 'S' | 's' )\n if @input.peek( 1 ).between?( T__40, T__41 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__24, T__25 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__34, T__35 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__14, T__15 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__16, T__17 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__28, T__29 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__38, T__39 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n\n success = true\n\n rescue ANTLR3::Error::RecognitionError => re\n report_error(re)\n recover(re)\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 25 )\n memoize( __method__, minutes_start_index, success ) if @state.backtracking > 0\n\n end\n \n return \n end", "def token!\n # at line 1:8: ( T__30 | T__31 | T__32 | T__33 | T__34 | T__35 | T__36 | T__37 | T__38 | T__39 | T__40 | T__41 | T__42 | T__43 | T__44 | T__45 | T__46 | T__47 | T__48 | T__49 | T__50 | T__51 | T__52 | T__53 | T__54 | INTEGER | FLOAT | BOOLEAN | STRING | CHAR | INIT | OPEN | CLOSE | TYPE_INT | TYPE_FLOAT | TYPE_STRING | TYPE_BOOL | TYPE_VOID | ENTITY | COMPONENT | SYSTEM | ENUM | IF | ELSE | RETURN | WHILE | IDENT | WS | COMMENT | MULTILINE_COMMENT | NL )\n alt_9 = 51\n alt_9 = @dfa9.predict( @input )\n case alt_9\n when 1\n # at line 1:10: T__30\n t__30!\n\n\n when 2\n # at line 1:16: T__31\n t__31!\n\n\n when 3\n # at line 1:22: T__32\n t__32!\n\n\n when 4\n # at line 1:28: T__33\n t__33!\n\n\n when 5\n # at line 1:34: T__34\n t__34!\n\n\n when 6\n # at line 1:40: T__35\n t__35!\n\n\n when 7\n # at line 1:46: T__36\n t__36!\n\n\n when 8\n # at line 1:52: T__37\n t__37!\n\n\n when 9\n # at line 1:58: T__38\n t__38!\n\n\n when 10\n # at line 1:64: T__39\n t__39!\n\n\n when 11\n # at line 1:70: T__40\n t__40!\n\n\n when 12\n # at line 1:76: T__41\n t__41!\n\n\n when 13\n # at line 1:82: T__42\n t__42!\n\n\n when 14\n # at line 1:88: T__43\n t__43!\n\n\n when 15\n # at line 1:94: T__44\n t__44!\n\n\n when 16\n # at line 1:100: T__45\n t__45!\n\n\n when 17\n # at line 1:106: T__46\n t__46!\n\n\n when 18\n # at line 1:112: T__47\n t__47!\n\n\n when 19\n # at line 1:118: T__48\n t__48!\n\n\n when 20\n # at line 1:124: T__49\n t__49!\n\n\n when 21\n # at line 1:130: T__50\n t__50!\n\n\n when 22\n # at line 1:136: T__51\n t__51!\n\n\n when 23\n # at line 1:142: T__52\n t__52!\n\n\n when 24\n # at line 1:148: T__53\n t__53!\n\n\n when 25\n # at line 1:154: T__54\n t__54!\n\n\n when 26\n # at line 1:160: INTEGER\n integer!\n\n\n when 27\n # at line 1:168: FLOAT\n float!\n\n\n when 28\n # at line 1:174: BOOLEAN\n boolean!\n\n\n when 29\n # at line 1:182: STRING\n string!\n\n\n when 30\n # at line 1:189: CHAR\n char!\n\n\n when 31\n # at line 1:194: INIT\n init!\n\n\n when 32\n # at line 1:199: OPEN\n open!\n\n\n when 33\n # at line 1:204: CLOSE\n close!\n\n\n when 34\n # at line 1:210: TYPE_INT\n type_int!\n\n\n when 35\n # at line 1:219: TYPE_FLOAT\n type_float!\n\n\n when 36\n # at line 1:230: TYPE_STRING\n type_string!\n\n\n when 37\n # at line 1:242: TYPE_BOOL\n type_bool!\n\n\n when 38\n # at line 1:252: TYPE_VOID\n type_void!\n\n\n when 39\n # at line 1:262: ENTITY\n entity!\n\n\n when 40\n # at line 1:269: COMPONENT\n component!\n\n\n when 41\n # at line 1:279: SYSTEM\n system!\n\n\n when 42\n # at line 1:286: ENUM\n enum!\n\n\n when 43\n # at line 1:291: IF\n if!\n\n\n when 44\n # at line 1:294: ELSE\n else!\n\n\n when 45\n # at line 1:299: RETURN\n return!\n\n\n when 46\n # at line 1:306: WHILE\n while!\n\n\n when 47\n # at line 1:312: IDENT\n ident!\n\n\n when 48\n # at line 1:318: WS\n ws!\n\n\n when 49\n # at line 1:321: COMMENT\n comment!\n\n\n when 50\n # at line 1:329: MULTILINE_COMMENT\n multiline_comment!\n\n\n when 51\n # at line 1:347: NL\n nl!\n\n\n end\n end", "def parse_line\n s0 = @scanner.pos\n match_spaces\n s2 = parse_te\n if s2 == :failed\n @scanner.pos = s0\n s0 = :failed\n else\n match_spaces\n s4 = @scanner.pos\n s5 = parse_fugou\n if s5 == :failed\n @scanner.pos = s4\n s4 = :failed\n else\n s6 = parse_from\n if s6 == :failed\n @scanner.pos = s4\n s4 = :failed\n else\n @reported_pos = s4\n s4 = transform_teban_fugou_from(s2, s5, s6)\n end\n end\n if s4 == :failed\n s4 = @scanner.pos\n s5 = []\n s6 = match_regexp(/[^\\r\\n ]/)\n while s6 != :failed\n s5 << s6\n s6 = match_regexp(/[^\\r\\n ]/)\n end\n @reported_pos = s4\n s4 = s5.join\n end\n if s4 == :failed\n @scanner.pos = s0\n s0 = :failed\n else\n match_spaces\n s6 = parse_time\n s6 = nil if s6 == :failed\n match_str('+')\n if parse_nl == :failed\n @scanner.pos = s0\n s0 = :failed\n else\n @reported_pos = s0\n s0 = { 'move' => s4, 'time' => s6 }\n end\n end\n end\n s0\n end", "def run str\n\t\t@input ||= ''\n\t\t@level += str.scan(LEVEL_UP).length\n\t\t@level -= str.scan(/(^|\\s)end($|\\s)/).length # Will probably fail with a character chain\n\t\t@input += str + \"\\n\"\n\t\tif @level <= 0\t\n\t\t\ttmp = input\n\t\t\treset\n\t\t\teval tmp, context \n\t\tend\n\tend", "def parse(source_buffer); end", "def parse(source_buffer); end", "def parse(source_buffer); end", "def get_token\n column, line = @column, @line\n while true\n get_chars if @buf.empty? and not @eof\n return [:eof, nil, line, column] if @eof and @buf.empty?\n case @buf\n when /\\A\\(/\n eat(1)\n return [:open, nil, line, column]\n when /\\A\\)/\n eat(1)\n return [:close, nil, line, column]\n when /\\A\\[\\]=/\n eat(3)\n return [:expr, :\"[]=\", line, column]\n when /\\A\\[\\](.*)/m\n # Can be partial []=\n if ($1 == \"\") and not @eof\n get_chars\n redo\n end\n eat(2)\n return [:expr, :\"[]\", line, column]\n when /\\A\\[(.*)/m\n # Can be partial [] or []=\n if ($1 == \"\") and not @eof\n get_chars\n redo\n end\n eat(1)\n return [:sqopen, nil, line, column]\n when /\\A\\]/\n eat(1)\n return [:sqclose, nil, line, column]\n when /\\A\\'/\n eat(1)\n return [:quote, nil, line, column]\n when /\\A\\`/ # `\n eat(1)\n return [:quasiquote, nil, line, column]\n when /\\A\\,@/\n eat(2)\n return [:\"unquote-splicing\", nil, line, column]\n when /\\A\\,(.?)/m\n # Possible begin of ,@\n if $1 == \"\" and not @eof\n get_chars\n redo\n else\n eat(1)\n return [:unquote, nil, line, column]\n end\n when /\\A([ \\t\\r\\n]+)/\n eat($1.size)\n column, line = @column, @line\n redo\n when /\\A(#!.*\\n)/\n eat($1.size)\n column, line = @column, @line\n redo\n when /\\A(;.*\\n)/\n eat($1.size)\n column, line = @column, @line\n redo\n when /\\A;/m\n # Partial COMMENT\n if @eof\n return\n else\n get_chars\n redo\n end\n when /\\A#!/m\n # Partial SHEBANG\n if @eof\n return\n else\n get_chars\n redo\n end\n when /\\A#t/\n eat(2)\n return [:expr, :true, line, column]\n when /\\A#f/\n eat(2)\n return [:expr, :false, line, column]\n when /\\A#\\Z/m\n # Partial SHEBANG or #T or #F\n unless @eof\n get_chars\n redo\n end\n when /\\A([+\\-]?[0-9]+(?:(?:\\.[0-9]+)?[eE][+\\-]?[0-9]+|\\.[0-9]+))(.?)/m\n # Possible FLOAT\n # Partial FLOAT also matches, so continue if possible\n s, c = $1, $2\n if (c == \"\" or c =~ /\\A[eE]/) and not @eof\n get_chars\n redo\n else\n eat(s.size)\n return [:expr, eval(s), line, column]\n end\n when /\\A([+\\-]?(?:[1-9][0-9]*|0x[0-9a-fA-F]+|0b[01]+|0o[0-7]+|0[0-7]+|0))(.?)/m\n # Possible INT\n # Partial INT also matches, so continue if possible\n # Partial FLOAT also matches, so handle it\n s, c = $1, $2\n if (c == \"\" or c =~ /\\A[.eExbo]/) and not @eof\n get_chars\n redo\n else\n eat(s.size)\n return [:expr, eval(s), line, column]\n end\n when /\\A([a-zA-Z!$%&*+\\-.:<=>?@^_~][0-9a-zA-Z!$%&*+\\-.:<=>?@^_~]*)(.?)/m\n # Possible ID\n # Partial ID also matches, so continue if possible\n if $2 == \"\" and not @eof\n get_chars\n redo\n else\n eat($1.size)\n s = $1.to_sym\n stt = Hash.new{|ht,k| k}.merge({ :\"..\" => :dotdot, :\"...\" => :dotdotdot })\n return [:expr, stt[s], line, column]\n end\n when /\\A(\"(?:[^\"#\\\\]|#*\\\\.|#+[^{\\\\#\"])*#*\")/\n eat($1.size)\n return [:expr, eval($1), line, column]\n when /\\A((\"(?:[^\"#\\\\]|#*\\\\.|#+[^{\\\\#\"])*#*)#\\{)/\n eat($1.size)\n return [:istr_beg, eval($2+'\"'), line, column]\n when /\\A(\\}((?:[^\"#\\\\]|#*\\\\.|#+[^{\\\\#\"])*#*\"))/\n eat($1.size)\n return [:istr_end, eval('\"'+$2), line, column]\n when /\\A(\\}((?:[^\"#\\\\]|#*\\\\.|#+[^{\\\\#\"])*#*)#\\{)/\n eat($1.size)\n return [:istr_mid, eval('\"'+$2+'\"'), line, column]\n when /\\A\"/ # \"\n # Possible partial string/istr_beg\n if @eof\n raise \"EOF inside string: #{@buf}\"\n else\n get_chars\n redo\n end\n when /\\A\\}/ # \"\n # Possible partial istr_mid/istr_end\n if @eof\n raise \"EOF inside interpolated string: #{@buf}\"\n else\n get_chars\n redo\n end\n when /\\A(\\/(?:[^\\/\\\\]|\\\\.)*\\/[mix]*)(.?)/\n if $2 == \"\" and not @eof\n get_chars\n redo\n else\n eat($1.size)\n return [:expr, eval($1), line, column]\n end\n when /\\A\\//\n # Possible partial regexp\n if @eof\n raise \"EOF inside interpolated string: #{@buf}\"\n else\n get_chars\n redo\n end\n else\n raise \"Not sure what to do with: #{@buf}\"\n end\n end \n end", "def parse(str)\n fields = []\n nest = 0\n field = ''\n str.each_char do |ch|\n got = false\n if nest == 0\n if ch == '('\n nest += 1\n end\n else\n if ch == '('\n nest += 1\n field << ch\n elsif ch == ')'\n nest -= 1\n if nest == 0\n got = true\n else\n field << ch\n end\n else\n field << ch\n end\n end\n\n if got\n fields << field\n field = ''\n end\n end\n\n fields\n end", "def next_token\n\n token = nil\n\n until ss.eos? or token do\n if ss.check(/\\n/) then\n self.lineno += 1\n # line starts 1 position after the newline\n self.start_of_current_line_pos = ss.pos + 1\n end\n self.old_pos = ss.pos\n token =\n case state\n when nil, :option, :inner, :start, :macro, :rule, :group then\n case\n when ss.skip(/options?.*/) then\n [:state, :option]\n when ss.skip(/inner.*/) then\n [:state, :inner]\n when ss.skip(/macros?.*/) then\n [:state, :macro]\n when ss.skip(/rules?.*/) then\n [:state, :rule]\n when ss.skip(/start.*/) then\n [:state, :start]\n when ss.skip(/end/) then\n [:state, :END]\n when ss.skip(/\\A((?:.|\\n)*)class ([\\w:]+.*)/) then\n action { [:class, *matches] }\n when ss.skip(/\\n+/) then\n # do nothing\n when text = ss.scan(/\\s*(\\#.*)/) then\n action { [:comment, text] }\n when (state == :option) && (ss.skip(/\\s+/)) then\n # do nothing\n when (state == :option) && (text = ss.scan(/stub/i)) then\n action { [:option, text] }\n when (state == :option) && (text = ss.scan(/debug/i)) then\n action { [:option, text] }\n when (state == :option) && (text = ss.scan(/do_parse/i)) then\n action { [:option, text] }\n when (state == :option) && (text = ss.scan(/lineno/i)) then\n action { [:option, text] }\n when (state == :option) && (text = ss.scan(/column/i)) then\n action { [:option, text] }\n when (state == :inner) && (text = ss.scan(/.*/)) then\n action { [:inner, text] }\n when (state == :start) && (text = ss.scan(/.*/)) then\n action { [:start, text] }\n when (state == :macro) && (ss.skip(/\\s+(\\w+)\\s+#{RE}/o)) then\n action { [:macro, *matches] }\n when (state == :rule) && (ss.skip(/\\s*#{ST}?[\\ \\t]*#{RE}[\\ \\t]*#{ACT}?/o)) then\n action { [:rule, *matches] }\n when (state == :rule) && (ss.skip(/\\s*:[\\ \\t]*#{RE}/o)) then\n action { [:grouphead, *matches] }\n when (state == :group) && (ss.skip(/\\s*:[\\ \\t]*#{RE}/o)) then\n action { [:grouphead, *matches] }\n when (state == :group) && (ss.skip(/\\s*\\|\\s*#{ST}?[\\ \\t]*#{RE}[\\ \\t]*#{ACT}?/o)) then\n action { [:group, *matches] }\n when (state == :group) && (ss.skip(/\\s*#{ST}?[\\ \\t]*#{RE}[\\ \\t]*#{ACT}?/o)) then\n action { [:groupend, *matches] }\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n when :END then\n case\n when ss.skip(/\\n+/) then\n # do nothing\n when text = ss.scan(/.*/) then\n action { [:end, text] }\n else\n text = ss.string[ss.pos .. -1]\n raise ScanError, \"can not match (#{state.inspect}) at #{location}: '#{text}'\"\n end\n else\n raise ScanError, \"undefined state at #{location}: '#{state}'\"\n end # token = case state\n\n next unless token # allow functions to trigger redo w/ nil\n end # while\n\n raise LexerError, \"bad lexical result at #{location}: #{token.inspect}\" unless\n token.nil? || (Array === token && token.size >= 2)\n\n # auto-switch state\n self.state = token.last if token && token.first == :state\n\n token\n end", "def parse(source); end", "def get_parse(s);end", "def run(source, until_token = :invalid, token_count = nil)\n @at_end = false\n @source = source\n @reader = source.each_char\n\n read_next()\n\n while token_count == nil || token_count > 0\n skip_whitespace()\n current = @marker.character\n break unless current\n\n token = Token.new\n token.kind = :invalid\n token.from = @marker.source_index\n token.position = @marker.position.dup\n\n case current\n when ?\", ?'\n read_string(token)\n\n when ?0\n case peek_next()\n when ?x, ?X, ?b, ?B then read_base_number(token)\n else read_number(token)\n end\n\n when ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9\n read_number(token)\n\n # dot, double dot, triple dot, and floats beginning with a dot\n when ?.\n token.kind = :dot\n case peek_next()\n when ?0, ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9 then read_number(token)\n when ?.\n read_next()\n token.kind = :double_dot\n\n if peek_next() == ?.\n read_next()\n token.kind = :triple_dot\n end\n\n token.value = Token::DESCRIPTORS[token.kind]\n else\n token.value = Token::DESCRIPTORS[token.kind]\n end\n\n when ?_, ?a, ?b, ?c, ?d, ?e, ?f, ?g, ?h, ?i, ?j, ?k, ?l, ?m, ?n, ?o, ?p,\n ?q, ?r, ?s, ?t, ?u, ?v, ?w, ?x, ?y, ?z, ?A, ?B, ?C, ?D, ?E, ?F, ?G, ?H,\n ?I, ?J, ?K, ?L, ?M, ?N, ?O, ?P, ?Q, ?R, ?S, ?T, ?U, ?V, ?W, ?X, ?Y, ?Z\n read_word(token)\n\n when ?\\n\n token.value = current\n token.kind = :newline\n\n when ??, ?#, ?@, ?$, ?%, ?(, ?), ?[, ?], ?{, ?}, ?^, ?~, ?`, ?\\\\, ?,, ?;\n token.value = current\n token.kind = PUNCTUATION_STRINGS[current]\n\n when ?=, ?|, ?&, ?:, ?+, ?*\n current << read_next() if peek_next() == current\n token.value = current\n token.kind = PUNCTUATION_STRINGS[current]\n\n when ?!\n current << read_next() if peek_next() == ?=\n token.value = current\n token.kind = PUNCTUATION_STRINGS[current]\n\n when ?>, ?<\n case peek_next()\n when ?=, current then current << read_next()\n end\n token.value = current\n token.kind = PUNCTUATION_STRINGS[current]\n\n when ?-\n case peek_next()\n when ?>, current then current << read_next()\n end\n token.value = current\n token.kind = PUNCTUATION_STRINGS[current]\n\n when ?/\n case peek_next()\n when ?/ then read_line_comment(token)\n when ?* then read_block_comment(token)\n else\n token.value = Token::DESCRIPTORS[token.kind = :slash]\n read_next()\n end\n\n end # case current\n\n token.to = @marker.source_index\n last_kind = token.kind\n if !(@skip_comments && token.comment?) && !(@skip_newlines && token.newline?)\n if last_kind != :invalid\n @tokens << token\n yield token if block_given?\n else\n raise RuntimeError, \"#{token.position} Invalid token: #{token.inspect}\"\n end\n end\n\n break if until_token == last_kind\n\n read_next()\n token_count -= 1 unless token_count.nil?\n end # while current && token_count > 0\n\n @source = nil\n @reader = nil\n\n self\n end", "def parse(str); end", "def _ast_sp\n while true # kleene\n\n begin # choice\n _tmp = match_string(\" \")\n break if _tmp\n _tmp = match_string(\"\\t\")\n end while false # end choice\n\n break unless _tmp\n end\n _tmp = true # end kleene\n set_failed_rule :_ast_sp unless _tmp\n return _tmp\n end", "def parse (file)\n File.open(file.path, \"r\") do |file|\n # read each char and use state\n tokens = Array.new\n state = TokenStates::TEXT_STATE\n input = \"\"\n last_newline = 0\n while file.eof? == false\n case state\n when TokenStates::TEXT_STATE\n #puts \"TEXT_STATE\"\n input = file.getc\n if input == \"<\"\n state = TokenStates::COMMAND_OPEN_STATE\n elsif input == \"\\n\"\n last_newline = file.pos\n else\n if tokens.length == 0 || tokens.last.class != Whip::TextToken\n tokens.push(Whip::TextToken.new(file.pos))\n end\n end\n when TokenStates::COMMAND_OPEN_STATE\n #puts \"COMMAND_OPEN_STATE\"\n pos = file.pos\n input += file.getc\n input += file.getc\n input += file.getc\n input += file.getc\n if input == \"<!--$\"\n state = TokenStates::COMMAND_NAME_STATE\n if tokens.last.class != Whip::CommandToken\n tokens.last.ends = pos\n end\n tokens.push(Whip::CommandToken.new(pos))\n tokens.last.indent = pos - last_newline - 1\n input = \"\"\n else\n state = TokenStates::TEXT_STATE\n if tokens.length == 0\n tokens.push(Whip::TextToken.new(pos))\n end\n end\n when TokenStates::COMMAND_NAME_STATE\n #puts \"COMMAND_NAME_STATE\"\n input += file.getc\n if input[-1] == \" \"\n state = TokenStates::COMMAND_ARGUMENT_START_STATE\n tokens.last.name = input[0...-1]\n input = \"\"\n end\n when TokenStates::COMMAND_ARGUMENT_START_STATE\n #puts \"COMMAND_ARGUMENT_START_STATE\"\n input = file.getc\n if input == '\"'\n state = TokenStates::COMMAND_ARGUMENT_STATE\n input = \"\"\n end\n when TokenStates::COMMAND_ARGUMENT_STATE\n #puts \"COMMAND_ARGUMENT_STATE\"\n input += file.getc\n if input[-1] == '\"'\n state = TokenStates::COMMAND_CLOSE_STATE\n tokens.last.argument = input[0...-1]\n input = \"\"\n end\n when TokenStates::COMMAND_CLOSE_STATE\n #puts \"COMMAND_CLOSE_STATE\"\n input += file.getc\n if input.strip == \"-->\"\n state = TokenStates::TEXT_STATE\n tokens.last.ends = file.pos\n input = \"\"\n end\n else\n end\n end\n tokens.last.ends = file.pos + 1\n return tokens\n end\n end", "def parse_all\n #check for skipping the block using add on module...\n parse_spc\n if @skiper.select{|f|send(f)}.length>0\n p \"skip > #{@row}\" if @dbg[:parse]\n else\n @plt_opt= '' \n #rtn= true if @selector.select{|f|send(f)}.length>0\n rtn = true if shortcut_exec( /(^[\\t ]*)\\-([\\w\\-&\\/:#.%]*\\{.*\\}=*) *([^\\n]*)\\n/) \n rtn = true if shortcut_exec( /(^[\\t ]*)\\-([\\w\\-&\\/:#.%=]*) *([^\\n]*)\\n/) \n rtn = true if shortcut_equal( /(^[\\t ]*)=([\\w\\-&\\/:#.%=]*) *([^\\n]*)\\n/) \n \n rtn = true if get_hot_simple(/^[\\t ]*(%)([\\$\\w\\-&\\/:#.\\[\\]]+\\{.*?\\}[= ]*)([^\\n]*)\\n/)\n rtn = true if get_hot_simple(/^[\\t ]*(%)([\\$\\w\\-&\\/:#.\\[\\]]+\\{.*?\\}[= ]*)()\\n/)\n rtn = true if get_hot_simple(/^[\\t ]*(%)([\\$\\w\\-&\\/:#.\\[\\]%=]+ )([^\\n]*)\\n/) \n rtn = true if get_hot_simple(/^[\\t ]*(%)([\\$\\w\\-&\\/:#.\\[\\]%=]+)()\\n/) \n \n rtn = true if get_div(/^[\\t ]*([#.])([\\w\\-&\\/.]*\\{.*\\}[= ]*)([^\\n]*)\\n/)\n rtn = true if get_div(/^[\\t ]*([#.])([\\w\\-&\\/.]*\\{.*\\}[= ]*)()\\n/)\n rtn = true if get_div(/^[\\t ]*([#.])([\\w\\-&\\/.=]* )([^\\n]*)\\n/) \n rtn = true if get_div(/^[\\t ]*([#.])([\\w\\-&\\/.=]*)()\\n/) \n rtn = true if get_input( /^[\\t ]*(:)([\\w\\-&\\/#.]*\\{.*\\}[= ]*)([^\\n]*)\\n/)\n rtn = true if get_input( /^[\\t ]*(:)([\\w\\-&\\/#.]*\\{.*\\}[= ]*)()\\n/)\n rtn = true if get_input( /^[\\t ]*(:)([\\w\\-&\\/#.=]* )([^\\n]*)\\n/) \n rtn = true if get_input( /^[\\t ]*(:)([\\w\\-&\\/#.=]*)()\\n/) \n rtn = true if parse_hot\n rtn = true if merge_hot\n rtn = true if merge_w2x\n rtn = true if parse_set_var\n rtn = true if parse_set_mem\n rtn = true if parse_get_mem\n rtn = true if inline_tag\n rtn = true if parse_end\n if parse_tags\n rtn = nil\n elsif !rtn\n auto_close \n end\n end\n rtn\n end", "def tokenize ; end", "def tokenize ; end", "def fn(s)\n\t# Not only that, but since I heard you liked functions, I put a\n\t# function IN YOUR FUNCTION.\n\t#\n\t# And not only that, THAT function is a recursive function\n\t# We'll call it sub, cause we're original.\n\t#\n\t# It takes more parameters:\n\t# s : the string we're parsing\n\t# i : an index to remember how many steps we did already\n\t# floor : the floor we're in at the moment\n\tdef sub(s, i, floor)\n\t\treturn i if floor < 0\n\n\t\t# A recursive function is a function which calls itself\n\t\t# here, we call ourself with different parameters:\n\t\t# s[1, s.length-1] : We remove the first character from the string\n\t\t# i+1 : We increase the number of steps we did already\n\t\t# floor + (s[0] == '(' ? 1 : -1 ) : We add 1 or subtract 1 depending on\n\t\t# wether the first character from the string is '(' or ')'\n\t\tsub(s[1, s.length-1], i+1, floor + (s[0] == '(' ? 1 : -1 ))\n\tend\n\n\t# Here is the first call to the recursive sub function:\n\t# We start with the full string, on the 0th step, on floor 0\n\tsub(s, 0, 0)\nend", "def string\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 31 )\n return_value = StringReturnValue.new\n\n # $rule.start = the first token seen before matching\n return_value.start = @input.look\n\n begin\n # at line 153:12: ( '\\\"' ( ESC | ~ ( '\\\\\\\\' | '\\\"' | '\\\\'' ) | '\\\\'' )* '\\\"' )\n # at line 153:12: ( '\\\"' ( ESC | ~ ( '\\\\\\\\' | '\\\"' | '\\\\'' ) | '\\\\'' )* '\\\"' )\n # at line 153:14: '\\\"' ( ESC | ~ ( '\\\\\\\\' | '\\\"' | '\\\\'' ) | '\\\\'' )* '\\\"'\n match(T__14, TOKENS_FOLLOWING_T__14_IN_string_1163)\n # at line 153:18: ( ESC | ~ ( '\\\\\\\\' | '\\\"' | '\\\\'' ) | '\\\\'' )*\n while true # decision 39\n alt_39 = 2\n look_39_0 = @input.peek(1)\n\n if (look_39_0.between?(WS, T__13) || look_39_0.between?(T__15, T__30) || look_39_0.between?(T__32, T__43))\n alt_39 = 1\n\n end\n case alt_39\n when 1\n # at line\n if @input.peek(1).between?(WS, T__13) || @input.peek(1).between?(T__15, T__30) || @input.peek(1).between?(T__32, T__43)\n @input.consume\n @state.error_recovery = false\n else\n mse = MismatchedSet(nil)\n raise mse\n end\n\n\n else\n break # out of loop for decision 39\n end\n end # loop for decision 39\n match(T__14, TOKENS_FOLLOWING_T__14_IN_string_1193)\n\n # - - - - - - - rule clean up - - - - - - - -\n return_value.stop = @input.look(-1)\n\n rescue ANTLR3::Error::RecognitionError => re\n report_error(re)\n recover(re)\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 31 )\n\n end\n\n return return_value\n end", "def extractFunctionMeta(line)\n res = \"\"\n numret = 0\n if line.include? '('\n mindex = line.index('(')\n sindex = line.index(')')\n res = line[3..(mindex - 1)]\n numret = line[(mindex - 1)..(sindex - 1)].length\n else\n spindex = (line.strip[3..line.length]).strip.index(' ')\n if spindex != nil\n res = line[3..spindex]\n numret = 2\n else\n res = line[3..line.length]\n numret = 0\n end\n end\n return res.strip, numret\nend", "def token!\n # at line 1:8: ( PROGRAM | PRINT | VAR | CTE | IF | ELSE | AND | OR | GT | GTE | LT | LTE | INTEGER | FLOAT | STRING | BOOLEAN | VOID | FUNCTION | FIN | RETURN | INPUT | WHILE | CLASS | WORD | NUM_I | NUM_F | BOOL | ID | LPAREN | RPAREN | LKEY | RKEY | EQUAL | DIF | SIMILAR | COMMA | DDOT | SEMI | PLUS | SUB | DIV | MUL | INHERITS | DOT | WHITESPACE )\n alt_10 = 45\n alt_10 = @dfa10.predict( @input )\n case alt_10\n when 1\n # at line 1:10: PROGRAM\n program!\n\n\n when 2\n # at line 1:18: PRINT\n print!\n\n\n when 3\n # at line 1:24: VAR\n var!\n\n\n when 4\n # at line 1:28: CTE\n cte!\n\n\n when 5\n # at line 1:32: IF\n if!\n\n\n when 6\n # at line 1:35: ELSE\n else!\n\n\n when 7\n # at line 1:40: AND\n and!\n\n\n when 8\n # at line 1:44: OR\n or!\n\n\n when 9\n # at line 1:47: GT\n gt!\n\n\n when 10\n # at line 1:50: GTE\n gte!\n\n\n when 11\n # at line 1:54: LT\n lt!\n\n\n when 12\n # at line 1:57: LTE\n lte!\n\n\n when 13\n # at line 1:61: INTEGER\n integer!\n\n\n when 14\n # at line 1:69: FLOAT\n float!\n\n\n when 15\n # at line 1:75: STRING\n string!\n\n\n when 16\n # at line 1:82: BOOLEAN\n boolean!\n\n\n when 17\n # at line 1:90: VOID\n void!\n\n\n when 18\n # at line 1:95: FUNCTION\n function!\n\n\n when 19\n # at line 1:104: FIN\n fin!\n\n\n when 20\n # at line 1:108: RETURN\n return!\n\n\n when 21\n # at line 1:115: INPUT\n input!\n\n\n when 22\n # at line 1:121: WHILE\n while!\n\n\n when 23\n # at line 1:127: CLASS\n class!\n\n\n when 24\n # at line 1:133: WORD\n word!\n\n\n when 25\n # at line 1:138: NUM_I\n num_i!\n\n\n when 26\n # at line 1:144: NUM_F\n num_f!\n\n\n when 27\n # at line 1:150: BOOL\n bool!\n\n\n when 28\n # at line 1:155: ID\n id!\n\n\n when 29\n # at line 1:158: LPAREN\n lparen!\n\n\n when 30\n # at line 1:165: RPAREN\n rparen!\n\n\n when 31\n # at line 1:172: LKEY\n lkey!\n\n\n when 32\n # at line 1:177: RKEY\n rkey!\n\n\n when 33\n # at line 1:182: EQUAL\n equal!\n\n\n when 34\n # at line 1:188: DIF\n dif!\n\n\n when 35\n # at line 1:192: SIMILAR\n similar!\n\n\n when 36\n # at line 1:200: COMMA\n comma!\n\n\n when 37\n # at line 1:206: DDOT\n ddot!\n\n\n when 38\n # at line 1:211: SEMI\n semi!\n\n\n when 39\n # at line 1:216: PLUS\n plus!\n\n\n when 40\n # at line 1:221: SUB\n sub!\n\n\n when 41\n # at line 1:225: DIV\n div!\n\n\n when 42\n # at line 1:229: MUL\n mul!\n\n\n when 43\n # at line 1:233: INHERITS\n inherits!\n\n\n when 44\n # at line 1:242: DOT\n dot!\n\n\n when 45\n # at line 1:246: WHITESPACE\n whitespace!\n\n\n end\n end", "def interactive_parser ( )\n puts 'Press <Enter> to exit...'\n #\n # Цикл обработки ввода.\n loop {\n\tstr = interactive_input( )\n\tbreak if str == \"\"\n\t#\n\t# Цикл посимвольной классификаци.\n\tstr.bytes.each do |c|\n\t parse( c.chr )\n\t puts 'parser: ' + @parserstate\n\t puts 'symbol: ' + interactive_output( c.chr ).to_s\n\t puts 'buffer: ' + @buffer.to_s\n\t puts 'state: ' + @chain.last.statename\n\t puts\n\tend\n }\n end", "def parse(str)\n mini = MiniP.new\n transf = MiniT.new\n\n transf.apply(\n mini.parse(str)\n )\nrescue Parslet::ParseFailed => failure\n puts failure.parse_failure_cause.ascii_tree\nend", "def read( start_position )\n pos = start_position.adjusted_stream_position\n line_number = column_number = 0\n\n if @source.at_eof?(stream_position) then\n line_number = @source.eof_line_number\n column_number = @source.eof_column_number\n else\n line_number = @source.line_number(stream_position)\n column_number = @source.column_number(stream_position)\n end\n \n characters = []\n states = [ start_position.state ]\n\n forever do\n c = readc(pos)\n action = states[-1].action_for( c )\n \n case action\n \n #\n # Read a single character and prepare to move on.\n \n when Plan::Actions::Read\n characters << c\n states << action.to_state\n pos += 1\n \n \n #\n # Group several characters for further processing. Unlike in the Parser, we\n # perform the Shift here directly. We don't move the pos, because nothing was\n # used.\n \n when Plan::Actions::Group\n length = action.by_production.length\n group = characters.slice!(-length..-1)\n states.slice!(-length..-1)\n states << states[-1].action_for(action.by_production.name).to_state\n characters << group\n\n\n #\n # Tokenize ends the read() operation. We set our answer into the start_position\n # and return.\n \n when Plan::Actions::Tokenize\n length = action.by_production.length\n if characters.length == length then\n start_position.determinant = Nodes::Token.new( characters.flatten, action.by_production.name, start_position.adjusted_stream_position, line_number, column_number, @source )\n break\n else\n nyi( \"error handling for too short Tokenize\" )\n end\n \n \n #\n # For lexical stuff, all Attempt actions will be of the same type. For Group\n # actions, we want the longest match (always), so we need to try all branches\n # and find the longest Token produced. For Tokenize, we need to interact with\n # the Parser's BranchInfo system.\n \n when Plan::Actions::Attempt\n case action.actions[0]\n when Plan::Actions::Group\n nyi()\n when Plan::Actions::Tokenize\n nyi()\n else\n nyi( \"attempt support for #{action.actions[0].class.name}\" )\n end\n \n \n #\n # If there is no action, we've got an error.\n \n when NilClass\n nyi( \"error\" )\n \n else\n nyi( \"not supported\", action )\n end\n end\n end", "def run(code, verbose = false)\n\n # loop over the code until end is reached\n #\n while(@str_p < code.size)\n puts code[@str_p,code.size-@str_p] if verbose\n\n # decide what shall be done now\n #\n case code[@str_p,1]\n\n # ignore this characters\n when \" \",\"\\r\",\"\\t\",\"\\n\"\n\n # perform addition on stack\n when \"+\"\n @stack.+\n\n # perform substraction on stack\n when \"-\"\n @stack.-\n\n # perform multiplication on stack\n when \"*\"\n @stack.*\n\n # perform division on stack\n when \"/\"\n @stack./\n\n # perform negation on stack\n when \"_\"\n @stack._\n\n # perform equality check on stack\n when \"=\"\n @stack.eq\n\n # perform greater than check on stack\n when \">\"\n @stack.>\n\n # perform NOT on stack\n when \"~\"\n @stack.~\n\n # perform AND on stack\n when \"&\"\n @stack.&\n\n # perform OR on stack\n when \"|\"\n @stack.|\n\n # Duplicate top element on stack\n when \"$\"\n @stack.dup\n\n # Remove top element on stack\n when \"%\"\n @stack.%\n\n # Perform swapping on 2 top elements\n when \"\\\\\"\n @stack.swap\n\n # Perform rotation on 3 top elements\n when \"@\"\n @stack.rot\n\n # Copy nth element to the top of stack\n when \"ø\"\n @stack.pick\n\n # handle comments\n when \"{\"\n @str_p = code.index('}', @str_p + 1)\n\n # Push the integer on stack\n when '0','1','2','3','4','5','6','7','8','9'\n num = code[@str_p..code.size].match /\\A\\d+/ \n @stack.push num[0].to_i\n @str_p += (num[0].size - 1)\n\n # read lambda function and push on stack\n when \"[\"\n f = 1\n c = 1\n while f > 0 do\n f += 1 if code.at(@str_p + c) == '['\n f -= 1 if code.at(@str_p + c) == ']'\n c += 1\n end\n @stack.push l = code[@str_p + 1 .. @str_p + c - 2]\n @str_p += l.size + 1\n\n # Print text between the \"\n when '\"'\n c = code[@str_p + 1 .. code.index('\"', @str_p + 1) - 1]\n @str_p += c.size+1\n puts c\n\n # Perform accessing on global variables a-z, : is value assignment, ; pushes value on stack\n when 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' #assing or push global variables\n if code.at(@str_p + 1) == ':'\n @global_variables[code.at(@str_p)] = @stack.pop\n @str_p += 1\n elsif code[@str_p + 1, 1] == ';'\n @stack.push @global_variables[code.at(@str_p)] or raise StandardError, \"Undefined global variable\"\n @str_p += 1\n else\n raise StandardError, \"Syntax error with global variables\"\n end\n\n # Execute the lambda function on stack (means copying it to after the !)\n when '!'\n code.insert(@str_p + 1, @stack.pop)\n\n # Print top element as integer\n when '.'\n puts @stack.pop.to_i\n\n # Print top element as character\n when ','\n puts @stack.pop.chr\n\n # Read one single character from stdin and push to stack\n when '^'\n c = nil\n while (c = ask('') { |q| q.character = true; q.echo = false }) != \"\\e\" do\n break\n end\n @stack.push c.to_i.to_s == c ? c.to_i : c\n\n # Push the Character after \\ as integer on stack\n when '\\''\n c = code.at(@str_p + 1)\n @stack.push c.to_i.to_s == c ? c.to_i : c\n @str_p += 1\n\n # Flush input and output\n when 'ß'\n STDOUT.flush\n\n # Perform an IF\n when '?'\n f = @stack.pop\n b = @stack.pop\n code = code.insert(@str_p + 1, f) if b == -1\n\n # Perform a WHILE\n when \"#\"\n a = @stack.pop\n b = @stack.pop\n @while_stack.push b\n @while_stack.push a\n code = code.insert(@str_p + 1, \"[#{b}]!W\")\n\n # Helper for WHILE\n when \"W\"\n r = @stack.pop\n a = @while_stack.pop\n b = @while_stack.pop\n if r == -1\n @while_stack.push b\n @while_stack.push a\n code = code.insert(@str_p + 1, \"[#{a}]![#{b}]!W\")\n end\n\n else\n raise StandardError, \"syntax error\"\n end\n\n @stack.show if verbose\n\n # in next step go for the next character\n @str_p += 1\n end\n end", "def tokenize ln, line\r\n pure_line = line.gsub(/^#{regex_line_comment}/, '') # trim line comment marker\r\n\r\n indent_level = 0\r\n processor_name = '_raw'\r\n line_code = ''\r\n block_open = false\r\n if matches = /#{regex_proc_line}/.match(pure_line) \r\n processor_name = matches[\"processor_name_\"]\r\n indent_level = matches[\"leading_spaces_\"].size\r\n line_code = matches[\"line_code_\"]\r\n block_open = true if /#{regex_block_start}\\s*$/ =~ line_code\r\n line_code.gsub!(/\\s*(#{regex_block_start})?\\s*$/, '') \r\n elsif matches = /^#{regex_proc_head}[^\\s]/.match(pure_line) \r\n indent_level = matches[\"leading_spaces_\"].size\r\n end\r\n\r\n Token.new ln, line, indent_level, processor_name, line_code, block_open \r\n end", "def string_parser(string_input)\n string_input.lines.each.with_index(1) do | line, index |\n puts \"Line #{index}: #{line}\"\n end\nend", "def parse(text)\n text = pre_proccess(text)\n text = pre_normalize(text)\n puts text.inspect if Chronic.debug\n\n tokens = Tokenizer::tokenize(' ' + text + ' ')\n tag(tokens, options)\n\n puts \"+#{'-' * 51}\\n| #{tokens}\\n+#{'-' * 51}\" if Chronic.debug\n\n token_group = TokenGroup.new(tokens, definitions(options), @now, options)\n span = token_group.to_span\n\n guess(span, options[:guess]) if span\n end", "def token!\n # at line 1:8: ( T__80 | T__81 | T__82 | EOL | LPAR | RPAR | LLAIZQ | LLADER | COMA | PUNTO | CORDER | CORIZQ | DELIM | ASIGNACION | DOUBLEDOT | COMILLA | OP_REL | OP_ARI | OP_LOG | K_ACCIONARCHIVO | K_ACCIONARREGLO | K_PACKAGE | K_CLASS | K_END | K_DEF | K_VAR | K_REQUIRE | K_IMPLEMENTS | K_EXTENDS | K_IMPRIMIR | K_CONVERSION | K_ASIGNACION | K_RETORNO | K_ACCIONSYS | K_INTERFACE | K_IF | K_TIMES | K_DO | K_EACH | K_ELSE | K_INVOKE | K_NEW | TIPO | K_REFERENCIA | K_INSPECCIONAR | K_MATEMATICA | K_NUM | K_RESIZE | K_ORDENAR | ModoOrd | K_BUSQUEDA | K_TIPOBUSQUEDA | K_WHERE | K_SPLIT | K_BEGIN | K_DIR | K_UNION | K_VISIBILIDAD | K_MODIFICADOR | K_ARRAY | K_PROPIEDAD | K_GET | K_SET | K_VALUE | K_INITIALIZE | K_FUNC | K_VOID | HexLiteral | DecimalLiteral | OctalLiteral | WS | LINE_COMMENT | Identificador )\n alt_28 = 73\n alt_28 = @dfa28.predict( @input )\n case alt_28\n when 1\n # at line 1:10: T__80\n t__80!\n\n\n when 2\n # at line 1:16: T__81\n t__81!\n\n\n when 3\n # at line 1:22: T__82\n t__82!\n\n\n when 4\n # at line 1:28: EOL\n eol!\n\n\n when 5\n # at line 1:32: LPAR\n lpar!\n\n\n when 6\n # at line 1:37: RPAR\n rpar!\n\n\n when 7\n # at line 1:42: LLAIZQ\n llaizq!\n\n\n when 8\n # at line 1:49: LLADER\n llader!\n\n\n when 9\n # at line 1:56: COMA\n coma!\n\n\n when 10\n # at line 1:61: PUNTO\n punto!\n\n\n when 11\n # at line 1:67: CORDER\n corder!\n\n\n when 12\n # at line 1:74: CORIZQ\n corizq!\n\n\n when 13\n # at line 1:81: DELIM\n delim!\n\n\n when 14\n # at line 1:87: ASIGNACION\n asignacion!\n\n\n when 15\n # at line 1:98: DOUBLEDOT\n doubledot!\n\n\n when 16\n # at line 1:108: COMILLA\n comilla!\n\n\n when 17\n # at line 1:116: OP_REL\n op_rel!\n\n\n when 18\n # at line 1:123: OP_ARI\n op_ari!\n\n\n when 19\n # at line 1:130: OP_LOG\n op_log!\n\n\n when 20\n # at line 1:137: K_ACCIONARCHIVO\n k_accionarchivo!\n\n\n when 21\n # at line 1:153: K_ACCIONARREGLO\n k_accionarreglo!\n\n\n when 22\n # at line 1:169: K_PACKAGE\n k_package!\n\n\n when 23\n # at line 1:179: K_CLASS\n k_class!\n\n\n when 24\n # at line 1:187: K_END\n k_end!\n\n\n when 25\n # at line 1:193: K_DEF\n k_def!\n\n\n when 26\n # at line 1:199: K_VAR\n k_var!\n\n\n when 27\n # at line 1:205: K_REQUIRE\n k_require!\n\n\n when 28\n # at line 1:215: K_IMPLEMENTS\n k_implements!\n\n\n when 29\n # at line 1:228: K_EXTENDS\n k_extends!\n\n\n when 30\n # at line 1:238: K_IMPRIMIR\n k_imprimir!\n\n\n when 31\n # at line 1:249: K_CONVERSION\n k_conversion!\n\n\n when 32\n # at line 1:262: K_ASIGNACION\n k_asignacion!\n\n\n when 33\n # at line 1:275: K_RETORNO\n k_retorno!\n\n\n when 34\n # at line 1:285: K_ACCIONSYS\n k_accionsys!\n\n\n when 35\n # at line 1:297: K_INTERFACE\n k_interface!\n\n\n when 36\n # at line 1:309: K_IF\n k_if!\n\n\n when 37\n # at line 1:314: K_TIMES\n k_times!\n\n\n when 38\n # at line 1:322: K_DO\n k_do!\n\n\n when 39\n # at line 1:327: K_EACH\n k_each!\n\n\n when 40\n # at line 1:334: K_ELSE\n k_else!\n\n\n when 41\n # at line 1:341: K_INVOKE\n k_invoke!\n\n\n when 42\n # at line 1:350: K_NEW\n k_new!\n\n\n when 43\n # at line 1:356: TIPO\n tipo!\n\n\n when 44\n # at line 1:361: K_REFERENCIA\n k_referencia!\n\n\n when 45\n # at line 1:374: K_INSPECCIONAR\n k_inspeccionar!\n\n\n when 46\n # at line 1:389: K_MATEMATICA\n k_matematica!\n\n\n when 47\n # at line 1:402: K_NUM\n k_num!\n\n\n when 48\n # at line 1:408: K_RESIZE\n k_resize!\n\n\n when 49\n # at line 1:417: K_ORDENAR\n k_ordenar!\n\n\n when 50\n # at line 1:427: ModoOrd\n modo_ord!\n\n\n when 51\n # at line 1:435: K_BUSQUEDA\n k_busqueda!\n\n\n when 52\n # at line 1:446: K_TIPOBUSQUEDA\n k_tipobusqueda!\n\n\n when 53\n # at line 1:461: K_WHERE\n k_where!\n\n\n when 54\n # at line 1:469: K_SPLIT\n k_split!\n\n\n when 55\n # at line 1:477: K_BEGIN\n k_begin!\n\n\n when 56\n # at line 1:485: K_DIR\n k_dir!\n\n\n when 57\n # at line 1:491: K_UNION\n k_union!\n\n\n when 58\n # at line 1:499: K_VISIBILIDAD\n k_visibilidad!\n\n\n when 59\n # at line 1:513: K_MODIFICADOR\n k_modificador!\n\n\n when 60\n # at line 1:527: K_ARRAY\n k_array!\n\n\n when 61\n # at line 1:535: K_PROPIEDAD\n k_propiedad!\n\n\n when 62\n # at line 1:547: K_GET\n k_get!\n\n\n when 63\n # at line 1:553: K_SET\n k_set!\n\n\n when 64\n # at line 1:559: K_VALUE\n k_value!\n\n\n when 65\n # at line 1:567: K_INITIALIZE\n k_initialize!\n\n\n when 66\n # at line 1:580: K_FUNC\n k_func!\n\n\n when 67\n # at line 1:587: K_VOID\n k_void!\n\n\n when 68\n # at line 1:594: HexLiteral\n hex_literal!\n\n\n when 69\n # at line 1:605: DecimalLiteral\n decimal_literal!\n\n\n when 70\n # at line 1:620: OctalLiteral\n octal_literal!\n\n\n when 71\n # at line 1:633: WS\n ws!\n\n\n when 72\n # at line 1:636: LINE_COMMENT\n line_comment!\n\n\n when 73\n # at line 1:649: Identificador\n identificador!\n\n\n end\n end", "def token!\n # at line 1:8: ( T__8 | T__9 | T__10 | T__11 | T__12 | T__13 | T__14 | T__15 | T__16 | T__17 | T__18 | T__19 | T__20 | T__21 | T__22 | T__23 | T__24 | T__25 | T__26 | T__27 | T__28 | T__29 | T__30 | T__31 | T__32 | T__33 | T__34 | T__35 | T__36 | T__37 | T__38 | T__39 | T__40 | T__41 | T__42 | T__43 | DIGIT | WS | EOL | LETTER )\n alt_3 = 40\n alt_3 = @dfa3.predict( @input )\n case alt_3\n when 1\n # at line 1:10: T__8\n t__8!\n\n when 2\n # at line 1:15: T__9\n t__9!\n\n when 3\n # at line 1:20: T__10\n t__10!\n\n when 4\n # at line 1:26: T__11\n t__11!\n\n when 5\n # at line 1:32: T__12\n t__12!\n\n when 6\n # at line 1:38: T__13\n t__13!\n\n when 7\n # at line 1:44: T__14\n t__14!\n\n when 8\n # at line 1:50: T__15\n t__15!\n\n when 9\n # at line 1:56: T__16\n t__16!\n\n when 10\n # at line 1:62: T__17\n t__17!\n\n when 11\n # at line 1:68: T__18\n t__18!\n\n when 12\n # at line 1:74: T__19\n t__19!\n\n when 13\n # at line 1:80: T__20\n t__20!\n\n when 14\n # at line 1:86: T__21\n t__21!\n\n when 15\n # at line 1:92: T__22\n t__22!\n\n when 16\n # at line 1:98: T__23\n t__23!\n\n when 17\n # at line 1:104: T__24\n t__24!\n\n when 18\n # at line 1:110: T__25\n t__25!\n\n when 19\n # at line 1:116: T__26\n t__26!\n\n when 20\n # at line 1:122: T__27\n t__27!\n\n when 21\n # at line 1:128: T__28\n t__28!\n\n when 22\n # at line 1:134: T__29\n t__29!\n\n when 23\n # at line 1:140: T__30\n t__30!\n\n when 24\n # at line 1:146: T__31\n t__31!\n\n when 25\n # at line 1:152: T__32\n t__32!\n\n when 26\n # at line 1:158: T__33\n t__33!\n\n when 27\n # at line 1:164: T__34\n t__34!\n\n when 28\n # at line 1:170: T__35\n t__35!\n\n when 29\n # at line 1:176: T__36\n t__36!\n\n when 30\n # at line 1:182: T__37\n t__37!\n\n when 31\n # at line 1:188: T__38\n t__38!\n\n when 32\n # at line 1:194: T__39\n t__39!\n\n when 33\n # at line 1:200: T__40\n t__40!\n\n when 34\n # at line 1:206: T__41\n t__41!\n\n when 35\n # at line 1:212: T__42\n t__42!\n\n when 36\n # at line 1:218: T__43\n t__43!\n\n when 37\n # at line 1:224: DIGIT\n digit!\n\n when 38\n # at line 1:230: WS\n ws!\n\n when 39\n # at line 1:233: EOL\n eol!\n\n when 40\n # at line 1:237: LETTER\n letter!\n\n end\n end", "def walk(_str, _index, _new_stack)\n\t#$ID += 1\n\tsmiley = false\n\tillegal = false\n\t_stack = Array.new(_new_stack)\n\t# puts \"[#{$ID}] \" + _str + \" + \" + _stack.join\n\tprev = ''\n\tlen = _str.length\n\n\t_str.each_char do |chr|\n\t\t# found illegal char\n\t\tif !$valid_chars.include? chr\n\t\t\t# balanced = NO\n\t\t\tillegal = true\n\t\t\tbreak\n\t\tend\n\n\t\t# watch for smiley at next interation\n\t\tif chr == ':'\n\t\t\tsmiley = true\n\t\t\tprev = chr\n\t\t\t_index += 1\n\t\t\tnext\n\t\tend\n\n\t\t# found possible smiley\n\t\tif (chr == '(' or chr == ')') and smiley == true\n\t\t\tif _index <= len\n\t\t\t\t#puts \"index: #{_index}\"\n\t\t\t\t_new_index = 0\n\t\t\t\t# puts \"[#{$ID}] \" + \"pass _stack: #{_stack.join}\"\n\t\t\t\twalk(_str[_index, len], _new_index, _stack)\n\t\t\tend\n\t\t\t# continue on this side with treating it as smiley\n\t\t\tsmiley = false\n\t\t\t_index += 1\n\t\t\tnext\n\t\t\t# end\n\t\tend\n\n\t\t# found regular ( paranthesis\n\t\tif chr == '('\n\t\t\t_stack.push(chr)\n\t\t\t# puts \"[#{$ID}] \" + \"push(#{_index})_stack: #{_stack.join}\"\n\t\t\t_index += 1\n\t\t\tnext\n\t\tend\n\n\t\t# found regular ) paranthesis\n\t\tif chr == ')'\n\t\t\t# if there is an ( paranthesis\n\t\t\tif _stack.size > 0\n\t\t\t\t_stack.pop\n\t\t\t\t# puts \"[#{$ID}] \" + \"pop(#{_index})_stack: #{_stack.join}\"\n\t\t\t\t_index += 1\n\t\t\t\tnext\n\t\t\telse\n\t\t\t\t# unbalanced paranthesis\n\t\t\t\tillegal = true\n\t\t\t\tbreak\n\t\t\tend\n\t\tend\n\n\t\t# other char after : -> reset smiley flag\n\t\tif smiley == true\n\t\t\tsmiley = false\n\t\t\t_index += 1\n\t\t\tnext\n\t\tend\n\n\t\t# any other char\n\t\t_index += 1\n\t\tnext\n\tend\n\n\t# check to see how we finished traversing the string\n\tif (_stack.size > 0 or illegal == true) and $balanced != YES\n\t\t$balanced = NO\n\telsif illegal == false\n\t\t$balanced = YES\n\tend\nend", "def interpreter\n dfaStack = [ ] \n loop do\n line = gets\n words = line.scan(/\\S+/)\n words.each{ |word|\n case word\n when /DONE/\n return\n when /DOT/\n f = dfaStack.last\n f.dotfile\n when /SIZE/\n f = dfaStack.last\n puts f.num_states\n when /PRINT/\n f = dfaStack.last\n f.prettyPrint\n when /DFA/\n f = dfaStack.pop\n f2 = f.toDFA\n dfaStack.push f2\n when /MINIMIZE/\n f = dfaStack.pop\n f2 = f.minimize\n dfaStack.push f2\n when /GENSTR([0-9]+)/\n f = dfaStack.last\n puts f.genStr($1)\n when /\"([a-z]*)\"/\n f = dfaStack.last\n str = $1\n if f.accept?(str)\n puts \"Accept #{str}\"\n else\n puts \"Reject #{str}\"\n end\n when /([a-zE])/\n puts \"Illegal syntax for: #{word}\" if word.length != 1\n f = NFA.new #changed from FA because it always gonna create a new NFA object\n sym = $1\n sym=\"\" if $1==\"E\"\n f.symbol!(sym)\n dfaStack.push f\n when /\\*/\n puts \"Illegal syntax for: #{word}\" if word.length != 1\n f = dfaStack.pop\n f.closure!\n dfaStack.push f\n when /\\|/\n puts \"Illegal syntax for: #{word}\" if word.length != 1\n f1 = dfaStack.pop\n f2 = dfaStack.pop\n f2.union!(f1)\n dfaStack.push f2\n when /\\./\n puts \"Illegal syntax for: #{word}\" if word.length != 1\n f1 = dfaStack.pop\n f2 = dfaStack.pop\n f2.concat!(f1)\n dfaStack.push f2\n else\n puts \"Ignoring #{word}\"\n end\n }\n end\nend", "def parse ( c )\n @parserstate = 'wait'\n retval = true\n #\n # * Фиксированное состояние (определенное): -1.\n # * Не фиксированное состояние (неопределенное): -2.\n # * Переход (смена состояний): >0.\n # \n @buffer << c\n \n #\n # Проверка переходов в другие состояния.\n #\n r = classify( @chain.last )\n\n #\n # Переход (прыжок) в другое состояние.\n # <branch>:\n #\n if r >= 0 then\n\t@chain << @states[r]\n\t@chain.last.run_init( @buffer )\n\treset( )\n\t@parserstate = 'branch'\n #\n # Возврат из текущего состояния.\n # <back>:\n #\n elsif r == -1 then\n\t@chain.last.run_fini( @buffer )\n\t#\n\t# если это состояние не первое в цепочке\n\t# тогда откатываемся назад.\n\t#\n\tif @chain.size > 1 then\n\t @chain.delete_at( @chain.size - 1 )\n\tend\n\treset( )\n\t@parserstate = 'back'\n #\n # Нет совпадений.\n # <miss>:\n #\n elsif r == -3 then\n\t#\n\t# если в процессе состояния <wait>\n\t# мы попали в <miss>, то накопленный\n\t# буфер надо обработать.\n\t#\n\t@buffer.each do |ch|\n\t @parserstate = 'miss'\n\t tag = true\n\t if @chain.last.ignore.size > 0 then\n\t tag = false if @chain.last.ignore.include?(ch)\n\t end\n\t if tag == true then\n\t r = @chain.last.run_handler( ch )\n\t #\n\t # Анализ результата обработки состояния.\n\t #\n\t case r.class.to_s\n\t #\n\t # Fixnum - переход на любое состояние (индекс).\n\t when 'Fixnum'\n\t if( (r >= 0) && (r < @states.size) ) then\n\t\t@chain << @states[r]\n\t\treset( )\n\t\t@parserstate = 'hardset'\n\t else\n\t\traise TypeError, \"Method <#{@chain.last.statename}> return incorrectly index.\"\n\t end\n\t #\n\t # nil - ничего не возвращает.\n\t when 'NilClass'\n\t #\n\t # else - расценивается как ошибка обработки.\n\t # обработка ложится на плечи разработчика.\n\t #\n\t else\n\t @parserstate = 'error'\n\t retval = false\n\t break\n\t end\n\t end\n\tend\n\t@buffer = []\n end\n return retval\n end", "def tokenize; end", "def tokenize; end", "def lex_state; end", "def next_token\n\n if @ss.bol?\n @line+=1\n @old_pos=@ss.pos\n end\n\n position=[@line,@ss.pos-@old_pos+1]\n\n return :eos if @ss.eos?\n\n case\n when text = @ss.scan(NEWLINE)\n next_token()\n when text = @ss.scan(SPACE)\n next_token()\n when text = @ss.scan(COMMENT)\n next_token()\n when text = @ss.scan(ARROW)\n return Token.new [:arrow,text,position]\n when text = @ss.scan(LT)\n return Token.new [:lt,text,position]\n when text = @ss.scan(LBRACK)\n return Token.new [:lbrack,text,position]\n when text = @ss.scan(RBRACK)\n return Token.new [:rbrack,text,position]\n when text = @ss.scan(IDENTIFIER)\n case\n when value = text.match(IDENT)\n return Token.new [:IDENT,text,position]\n when value = text.match(FLOAT)\n return Token.new [:FLOAT,text,position]\n when value = text.match(INT)\n return Token.new [:INT,text,position]\n when value = text.match(STRING)\n return Token.new [:STRING,text,position]\n when value = text.match(MODULE)\n return Token.new [:module,text,position]\n when value = text.match(CLASS)\n return Token.new [:class,text,position]\n when value = text.match(END_)\n return Token.new [:end,text,position]\n when value = text.match(ATTR)\n return Token.new [:attr,text,position]\n when value = text.match(LPAREN)\n return Token.new [:lparen,text,position]\n when value = text.match(RPAREN)\n return Token.new [:rparen,text,position]\n else\n return Token.new [:identifier,text,position]\n end\n else\n x = @ss.getch\n return Token.new [x, x,position]\n end\n end", "def token!\n # at line 1:8: ( T__12 | T__13 | T__14 | T__15 | T__16 | T__17 | T__18 | T__19 | T__20 | T__21 | T__22 | T__23 | T__24 | T__25 | T__26 | T__27 | T__28 | T__29 | T__30 | T__31 | T__32 | T__33 | T__34 | T__35 | T__36 | T__37 | T__38 | T__39 | T__40 | T__41 | T__42 | T__43 | T__44 | T__45 | T__46 | T__47 | T__48 | T__49 | T__50 | T__51 | T__52 | T__53 | T__54 | T__55 | T__56 | T__57 | T__58 | T__59 | ST | ND | RD | TH | DIGIT | WS | EOL | LETTER )\n alt_7 = 56\n alt_7 = @dfa7.predict( @input )\n case alt_7\n when 1\n # at line 1:10: T__12\n t__12!\n\n when 2\n # at line 1:16: T__13\n t__13!\n\n when 3\n # at line 1:22: T__14\n t__14!\n\n when 4\n # at line 1:28: T__15\n t__15!\n\n when 5\n # at line 1:34: T__16\n t__16!\n\n when 6\n # at line 1:40: T__17\n t__17!\n\n when 7\n # at line 1:46: T__18\n t__18!\n\n when 8\n # at line 1:52: T__19\n t__19!\n\n when 9\n # at line 1:58: T__20\n t__20!\n\n when 10\n # at line 1:64: T__21\n t__21!\n\n when 11\n # at line 1:70: T__22\n t__22!\n\n when 12\n # at line 1:76: T__23\n t__23!\n\n when 13\n # at line 1:82: T__24\n t__24!\n\n when 14\n # at line 1:88: T__25\n t__25!\n\n when 15\n # at line 1:94: T__26\n t__26!\n\n when 16\n # at line 1:100: T__27\n t__27!\n\n when 17\n # at line 1:106: T__28\n t__28!\n\n when 18\n # at line 1:112: T__29\n t__29!\n\n when 19\n # at line 1:118: T__30\n t__30!\n\n when 20\n # at line 1:124: T__31\n t__31!\n\n when 21\n # at line 1:130: T__32\n t__32!\n\n when 22\n # at line 1:136: T__33\n t__33!\n\n when 23\n # at line 1:142: T__34\n t__34!\n\n when 24\n # at line 1:148: T__35\n t__35!\n\n when 25\n # at line 1:154: T__36\n t__36!\n\n when 26\n # at line 1:160: T__37\n t__37!\n\n when 27\n # at line 1:166: T__38\n t__38!\n\n when 28\n # at line 1:172: T__39\n t__39!\n\n when 29\n # at line 1:178: T__40\n t__40!\n\n when 30\n # at line 1:184: T__41\n t__41!\n\n when 31\n # at line 1:190: T__42\n t__42!\n\n when 32\n # at line 1:196: T__43\n t__43!\n\n when 33\n # at line 1:202: T__44\n t__44!\n\n when 34\n # at line 1:208: T__45\n t__45!\n\n when 35\n # at line 1:214: T__46\n t__46!\n\n when 36\n # at line 1:220: T__47\n t__47!\n\n when 37\n # at line 1:226: T__48\n t__48!\n\n when 38\n # at line 1:232: T__49\n t__49!\n\n when 39\n # at line 1:238: T__50\n t__50!\n\n when 40\n # at line 1:244: T__51\n t__51!\n\n when 41\n # at line 1:250: T__52\n t__52!\n\n when 42\n # at line 1:256: T__53\n t__53!\n\n when 43\n # at line 1:262: T__54\n t__54!\n\n when 44\n # at line 1:268: T__55\n t__55!\n\n when 45\n # at line 1:274: T__56\n t__56!\n\n when 46\n # at line 1:280: T__57\n t__57!\n\n when 47\n # at line 1:286: T__58\n t__58!\n\n when 48\n # at line 1:292: T__59\n t__59!\n\n when 49\n # at line 1:298: ST\n st!\n\n when 50\n # at line 1:301: ND\n nd!\n\n when 51\n # at line 1:304: RD\n rd!\n\n when 52\n # at line 1:307: TH\n th!\n\n when 53\n # at line 1:310: DIGIT\n digit!\n\n when 54\n # at line 1:316: WS\n ws!\n\n when 55\n # at line 1:319: EOL\n eol!\n\n when 56\n # at line 1:323: LETTER\n letter!\n\n end\n end", "def token!\n # at line 1:8: ( RET | SCOPE | FRAGMENT | TREE_BEGIN | ROOT | BANG | RANGE | REWRITE | AT | LABEL_ASSIGN | LIST_LABEL_ASSIGN | T__67 | T__68 | T__69 | T__70 | T__71 | T__72 | T__73 | T__74 | T__75 | T__76 | T__77 | T__78 | T__79 | T__80 | T__81 | T__82 | T__83 | T__84 | T__85 | T__86 | T__87 | T__88 | T__89 | T__90 | T__91 | T__92 | T__93 | SL_COMMENT | ML_COMMENT | CHAR_LITERAL | STRING_LITERAL | DOUBLE_QUOTE_STRING_LITERAL | DOUBLE_ANGLE_STRING_LITERAL | INT | ARG_ACTION | ACTION | TOKEN_REF | RULE_REF | OPTIONS | TOKENS | WS )\n alt_21 = 52\n alt_21 = @dfa21.predict(@input)\n case alt_21\n when 1\n # at line 1:10: RET\n ret!\n\n when 2\n # at line 1:14: SCOPE\n scope!\n\n when 3\n # at line 1:20: FRAGMENT\n fragment!\n\n when 4\n # at line 1:29: TREE_BEGIN\n tree_begin!\n\n when 5\n # at line 1:40: ROOT\n root!\n\n when 6\n # at line 1:45: BANG\n bang!\n\n when 7\n # at line 1:50: RANGE\n range!\n\n when 8\n # at line 1:56: REWRITE\n rewrite!\n\n when 9\n # at line 1:64: AT\n at!\n\n when 10\n # at line 1:67: LABEL_ASSIGN\n label_assign!\n\n when 11\n # at line 1:80: LIST_LABEL_ASSIGN\n list_label_assign!\n\n when 12\n # at line 1:98: T__67\n t__67!\n\n when 13\n # at line 1:104: T__68\n t__68!\n\n when 14\n # at line 1:110: T__69\n t__69!\n\n when 15\n # at line 1:116: T__70\n t__70!\n\n when 16\n # at line 1:122: T__71\n t__71!\n\n when 17\n # at line 1:128: T__72\n t__72!\n\n when 18\n # at line 1:134: T__73\n t__73!\n\n when 19\n # at line 1:140: T__74\n t__74!\n\n when 20\n # at line 1:146: T__75\n t__75!\n\n when 21\n # at line 1:152: T__76\n t__76!\n\n when 22\n # at line 1:158: T__77\n t__77!\n\n when 23\n # at line 1:164: T__78\n t__78!\n\n when 24\n # at line 1:170: T__79\n t__79!\n\n when 25\n # at line 1:176: T__80\n t__80!\n\n when 26\n # at line 1:182: T__81\n t__81!\n\n when 27\n # at line 1:188: T__82\n t__82!\n\n when 28\n # at line 1:194: T__83\n t__83!\n\n when 29\n # at line 1:200: T__84\n t__84!\n\n when 30\n # at line 1:206: T__85\n t__85!\n\n when 31\n # at line 1:212: T__86\n t__86!\n\n when 32\n # at line 1:218: T__87\n t__87!\n\n when 33\n # at line 1:224: T__88\n t__88!\n\n when 34\n # at line 1:230: T__89\n t__89!\n\n when 35\n # at line 1:236: T__90\n t__90!\n\n when 36\n # at line 1:242: T__91\n t__91!\n\n when 37\n # at line 1:248: T__92\n t__92!\n\n when 38\n # at line 1:254: T__93\n t__93!\n\n when 39\n # at line 1:260: SL_COMMENT\n sl_comment!\n\n when 40\n # at line 1:271: ML_COMMENT\n ml_comment!\n\n when 41\n # at line 1:282: CHAR_LITERAL\n char_literal!\n\n when 42\n # at line 1:295: STRING_LITERAL\n string_literal!\n\n when 43\n # at line 1:310: DOUBLE_QUOTE_STRING_LITERAL\n double_quote_string_literal!\n\n when 44\n # at line 1:338: DOUBLE_ANGLE_STRING_LITERAL\n double_angle_string_literal!\n\n when 45\n # at line 1:366: INT\n int!\n\n when 46\n # at line 1:370: ARG_ACTION\n arg_action!\n\n when 47\n # at line 1:381: ACTION\n action!\n\n when 48\n # at line 1:388: TOKEN_REF\n token_ref!\n\n when 49\n # at line 1:398: RULE_REF\n rule_ref!\n\n when 50\n # at line 1:407: OPTIONS\n options!\n\n when 51\n # at line 1:415: TOKENS\n tokens!\n\n when 52\n # at line 1:422: WS\n ws!\n\n end\n end", "def parse(input_file, label_count)\n output = []\n\n input_file.each_line do |line|\n next if line.match(/\\/\\/.*/) \n\n if match = line.match(/push (?<segment>.+) (?<index>.+)/)\n push_constant_asm = %{\n @%s\n D=A\n @SP\n A=M\n M=D\n @SP\n M=M+1\n }\n push_relative_asm = %{\n @%s\n D=A\n @%s\n A=D+M\n D=M\n @SP\n A=M\n M=D\n @SP\n M=M+1\n }\n push_pointer_asm = %{\n @%s\n D=A\n @L#{label_count}\n D;JEQ\n @THAT\n D=M\n @L#{label_count + 1}\n 0;JMP\n (L#{label_count})\n @THIS\n D=M\n (L#{label_count + 1})\n @SP\n A=M\n M=D\n @SP\n M=M+1\n }\n push_indirect_asm = %{\n @%s\n D=A\n @%s\n A=D+A\n D=M\n @SP\n A=M\n M=D\n @SP\n M=M+1\n }\n case match[:segment] \n when \"constant\"\n output << (push_constant_asm % match[:index].strip).split\n when \"local\"\n output << (push_relative_asm % [match[:index].strip, \"LCL\"]).split\n when \"argument\"\n output << (push_relative_asm % [match[:index].strip, \"ARG\"]).split\n when \"this\"\n output << (push_relative_asm % [match[:index].strip, \"THIS\"]).split\n when \"that\"\n output << (push_relative_asm % [match[:index].strip, \"THAT\"]).split\n when \"pointer\"\n output << (push_pointer_asm % match[:index].strip).split\n label_count = label_count + 2\n when \"temp\"\n output << (push_indirect_asm % [match[:index].strip, \"R5\"]).split\n when \"static\"\n output << (push_indirect_asm % [match[:index].strip, \"16\"]).split\n end\n end\n\n pop_relative_asm = %{\n @%s\n D=M\n @%s\n D=D+A\n @R13\n M=D\n @SP\n AM=M-1\n D=M\n @R13\n A=M\n M=D\n }\n pop_pointer_asm = %{\n @%s\n D=A\n @L#{label_count}\n D;JEQ\n @THAT\n D=A\n @L#{label_count + 1}\n 0;JMP\n (L#{label_count})\n @THIS\n D=A\n (L#{label_count + 1})\n @R13\n M=D\n @SP\n AM=M-1\n D=M\n @R13\n A=M\n M=D\n }\n pop_indirect_asm = %{\n @%s\n D=A\n @%s\n D=D+A\n @R13\n M=D\n @SP\n AM=M-1\n D=M\n @R13\n A=M\n M=D\n }\n if match = line.match(/pop (?<segment>.+) (?<index>.+)/)\n case match[:segment] \n when \"local\"\n output << (pop_relative_asm % [\"LCL\", match[:index].strip]).split\n when \"argument\"\n output << (pop_relative_asm % [\"ARG\", match[:index].strip]).split\n when \"this\"\n output << (pop_relative_asm % [\"THIS\", match[:index].strip]).split\n when \"that\"\n output << (pop_relative_asm % [\"THAT\", match[:index].strip]).split\n when \"pointer\"\n output << (pop_pointer_asm % match[:index].strip).split\n label_count = label_count + 2\n when \"temp\"\n output << (pop_indirect_asm % [match[:index].strip, \"R5\"]).split\n when \"static\"\n output << (pop_indirect_asm % [match[:index].strip, \"16\"]).split\n end\n end\n\n math_asm = %{\n @SP\n D=M\n AM=D-1\n D=M\n A=A-1\n M=M%sD\n }\n output << (math_asm % \"+\").split if line.match(/add/)\n output << (math_asm % \"-\").split if line.match(/sub/)\n\n binary_logic_asm = %{\n @SP\n D=M\n AM=D-1\n D=M\n A=A-1\n M=D%sM\n }\n output << (binary_logic_asm % \"|\").split if line.match(/or/)\n output << (binary_logic_asm % \"&\").split if line.match(/and/)\n\n unary_logic_asm = %{\n @SP\n A=M-1\n D=M\n M=%sD\n }\n output << (unary_logic_asm % \"-\").split if line.match(/neg/)\n output << (unary_logic_asm % \"!\").split if line.match(/not/)\n\n comp_asm = %{\n @SP\n AM=M-1\n D=M\n A=A-1\n D=M-D\n @L#{label_count}\n D;%s\n D=0\n @L#{label_count + 1}\n 0;JMP\n (L#{label_count})\n D=-1\n (L#{label_count + 1})\n @SP\n A=M-1\n M=D\n }\n if line.match(/eq/)\n output << (comp_asm % \"JEQ\").split\n label_count = label_count + 2\n end\n if line.match(/gt/)\n output << (comp_asm % \"JGT\").split\n label_count = label_count + 2\n end\n if line.match(/lt/)\n output << (comp_asm % \"JLT\").split\n label_count = label_count + 2\n end\n end\n return [output, label_count]\nend", "def parse_factor\n case current\n when :L_PARANTH then\n expect(:L_PARANTH)\n exp = parse_expression\n expect(:R_PARANTH)\n\n exp\n when :ID then\n parse_variable_exp\n when :KW_NEW then\n parse_class_init\n else\n parse_constant\n end\n end", "def interpreter file\n dfaStack = [ ] \n loop do\n line = file.gets\n if line == nil then break end\n words = line.scan(/\\S+/)\n words.each{ |word|\n case word\n when /DONE/\n return\n when /SIZE/\n f = dfaStack.last\n puts f.num_states\n when /PRINT/\n f = dfaStack.last\n f.pretty_print\n when /STAT/\n f = dfaStack.last\n f.print_stats\n when /DFA/\n f = dfaStack.pop\n f2 = f.to_dfa\n dfaStack.push f2\n when /COMPLEMENT/\n f = dfaStack.pop\n f2 = f.complement!\n dfaStack.push f2\n when /GENSTR([0-9]+)/\n f = dfaStack.last\n puts f.gen_str($1)\n when /\"([a-z]*)\"/\n f = dfaStack.last\n str = $1\n if f.accept?(str)\n puts \"Accept #{str}\"\n else\n puts \"Reject #{str}\"\n end\n when /([a-zE])/\n puts \"Illegal syntax for: #{word}\" if word.length != 1\n f = FiniteAutomaton.new\n sym = $1\n sym=\"\" if $1==\"E\"\n f.symbol!(sym)\n dfaStack.push f\n when /\\*/\n puts \"Illegal syntax for: #{word}\" if word.length != 1\n f = dfaStack.pop\n f.closure!\n dfaStack.push f\n when /\\|/\n puts \"Illegal syntax for: #{word}\" if word.length != 1\n f1 = dfaStack.pop\n f2 = dfaStack.pop\n f2.union!(f1)\n dfaStack.push f2\n when /\\./\n puts \"Illegal syntax for: #{word}\" if word.length != 1\n f1 = dfaStack.pop\n f2 = dfaStack.pop\n f2.concat!(f1)\n dfaStack.push f2\n else\n puts \"Ignoring #{word}\"\n end\n }\n end\nend", "def parse\n line = @io.gets until md = /\\ATime before run:\\s+(?<time>.*)\\Z/.match(line)\n return unless md\n @db.date_time ||= DateTime.parse(md[:time])\n super\n @db[\"lparstat_out\"] = @db[\"lparstat_sum\"]\n end", "def parse(str)\n if str.nil? || str == \"\"\n raise ParserError.new(\"Empty input\",0,\"\")\n end\n\n s = StringScanner.new str\n @tokens = []\n\n until s.eos?\n s.skip(/\\s+/) ? nil :\n s.scan(/\\A[-+]?[0-9]*\\.[0-9]+(e[-+]?[0-9]+)?/i) ? (@tokens << [:FLOAT, s.matched]) :\n s.scan(/\\A[-+]?(0|[1-9]\\d*)/) ? (@tokens << [:INTEGER, s.matched]) :\n s.scan(/\\A\\.(?=\\s)/) ? (@tokens << ['.', '.']) :\n s.scan(/\\A[a-z\\-.\\/_:*<>+=$#][a-z\\-.\\/_:$*<>+=0-9]*/i) ? (@tokens << [:SYMBOL, s.matched]) :\n s.scan(/\\A\"(([^\\\\\"]|\\\\.)*)\"/) ? (@tokens << [:STRING, _unescape_string(s.matched.slice(1...-1))]) :\n s.scan(/\\A./) ? (a = s.matched; @tokens << [a, a]) :\n (raise ParserError.new(\"Scanner error\",s.pos,s.peek(5)))\n end\n @tokens.push [false, 'END']\n\n return do_parse.map do |i|\n normalize(i)\n end\n end", "def process\n return if @processed\n\n in_count = 0\n mark = -1\n start_of_chunk = -1\n last_of_chunk = -1\n chunk_name = ''\n chunk_loc = -1\n chunk_level = @define_hash[:register_level][:val]\n chunk_unused = @define_hash[:register_unused][:val]\n chunk_width = @define_hash[:register_width][:val]\n stack = [true]\n def_name = def_arg = def_rest = def_val = def_ref = def_kind = nil\n # true accepting input\n # false rejecting input\n # nil rejecting input due to nested #ifdef/#ifndef\n while in_count < @input.length\n l = input[in_count].chomp\n l_in_count = in_count\n while (in_count < @input.length) && (match = /\\\\[ \\t]*/.match(l))\n l[match.begin(0), match.end(0)] = @input[in_count].chomp # question: should we add a space before the next line?\n in_count += 1\n end\n skip = false\n #print \"in=#{in_count} out=#{@lines.length} mark=#{mark} start=#{start_of_chunk} '#{l}'\\n\"\n\n if /^#+[ \\t]/.match(l)\n mark = @lines.length\n elsif /^=+[ \\t]/.match(l)\n mark = @lines.length\n elsif (m = /^#define[ \\t]+(\\w+)[ \\t]*(\\([\\w, ]*\\))?[ \\t]+(.*)$/.match(l))\n def_name = m[1]\n def_arg = m[2]\n def_rest = m[3]\n if stack[-1]\n value = {}\n value[:arg] = def_arg.gsub(/[\\(\\)]/, '') if def_arg\n if def_rest && def_rest != '' # value and possibly ref\n if (m2 = /^(.*)[ \\t]+\\/\\*[ \\t]*([-A-Z0-9][- A-Z0-9]*)([-A-Z0-9])[ \\t]*\\*\\/[ \\t]*$/.match(def_rest)) # value and ref both present\n def_val = m2[1]\n def_ref = m2[2]\n def_kind = m2[3]\n value[:val] = def_val\n value[:ref] = def_ref + def_kind\n value[:kind] = def_kind\n @device_hash[def_name] = value if value[:kind] == 'D'\n @register_hash[def_name] = value if (value[:kind] == 'R' || value[:kind] == 'A')\n if /^[DRA]$/.match(value[:kind])\n if start_of_chunk >= 0 && last_of_chunk >= 0\n @chunks << {:start => start_of_chunk,\n :end => last_of_chunk,\n :key => chunk_loc,\n :name => chunk_name,\n :unused => chunk_unused,\n :level => chunk_level,\n :width => chunk_width}\n print \"chunk=#{@chunks[-1]}\\n\"\n end\n start_of_chunk = mark + 1\n chunk_name = def_name\n chunk_loc = @lines.length\n chunk_unused = @define_hash[:register_unused][:val]\n chunk_level = @define_hash[:register_level][:val]\n chunk_width = @define_hash[:register_width][:val]\n end\n last_of_chunk = @lines.length\n else\n value[:val] = def_rest # no ref present\n end\n end\n @define_hash[def_name] = value\n mark = @lines.length\n end\n\n elsif (m = /^#undef[ \\t]+(\\w+)[ \\t]*$/.match(l))\n def_name = m[1]\n @define_hash.delete(def_name) if stack[-1]\n\n elsif (m = /^#ifdef[ \\t]+(\\w+)[ \\t]*$/.match(l))\n def_name = m[1]\n if stack[-1].nil?\n stack.push(nil)\n else\n stack.push(@define_hash.has_key?(def_name))\n end\n skip = true\n\n elsif (m = /^#ifndef[ \\t]+(\\w+)[ \\t]*$/.match(l))\n def_name = m[1]\n if stack[-1].nil?\n stack.push(nil)\n else\n stack.push(!@define_hash.has_key?(def_name))\n end\n skip = true\n\n elsif /^#else[ \\t]*$/.match(l)\n if stack[-1] != nil\n stack[-1] = !stack[-1]\n end\n skip = true\n\n elsif /^#endif[ \\t]*$/.match(l)\n stack.pop if stack.length > 1\n skip = true\n end\n\n if stack[-1] && !skip\n @src_map[@lines.length] = l_in_count\n @lines << l\n end\n in_count += 1\n end\n\n if start_of_chunk > 0\n @chunks << {:start => start_of_chunk,\n :end => last_of_chunk,\n :key => chunk_loc,\n :name => chunk_name,\n :unused => chunk_unused,\n :level => chunk_level,\n :width => chunk_width}\n end\n @processed = true\n\n end", "def string!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 29 )\n\n\n\n type = STRING\n channel = ANTLR3::DEFAULT_CHANNEL\n # - - - - label initialization - - - -\n\n\n # - - - - main rule block - - - -\n # at line 195:5: '\\\"' ( '\\\\\\\\' '\\\"' |~ ( '\\\"' | '\\\\r' | '\\\\n' ) )* '\\\"'\n match( 0x22 )\n # at line 196:5: ( '\\\\\\\\' '\\\"' |~ ( '\\\"' | '\\\\r' | '\\\\n' ) )*\n while true # decision 3\n alt_3 = 3\n look_3_0 = @input.peek( 1 )\n\n if ( look_3_0 == 0x5c )\n look_3_2 = @input.peek( 2 )\n\n if ( look_3_2 == 0x22 )\n look_3_4 = @input.peek( 3 )\n\n if ( look_3_4.between?( 0x0, 0x9 ) || look_3_4.between?( 0xb, 0xc ) || look_3_4.between?( 0xe, 0xffff ) )\n alt_3 = 1\n\n else\n alt_3 = 2\n\n end\n elsif ( look_3_2.between?( 0x0, 0x9 ) || look_3_2.between?( 0xb, 0xc ) || look_3_2.between?( 0xe, 0x21 ) || look_3_2.between?( 0x23, 0xffff ) )\n alt_3 = 2\n\n end\n elsif ( look_3_0.between?( 0x0, 0x9 ) || look_3_0.between?( 0xb, 0xc ) || look_3_0.between?( 0xe, 0x21 ) || look_3_0.between?( 0x23, 0x5b ) || look_3_0.between?( 0x5d, 0xffff ) )\n alt_3 = 2\n\n end\n case alt_3\n when 1\n # at line 196:7: '\\\\\\\\' '\\\"'\n match( 0x5c )\n match( 0x22 )\n\n when 2\n # at line 197:7: ~ ( '\\\"' | '\\\\r' | '\\\\n' )\n if @input.peek( 1 ).between?( 0x0, 0x9 ) || @input.peek( 1 ).between?( 0xb, 0xc ) || @input.peek( 1 ).between?( 0xe, 0x21 ) || @input.peek( 1 ).between?( 0x23, 0xff )\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n\n end\n\n\n\n else\n break # out of loop for decision 3\n end\n end # loop for decision 3\n\n match( 0x22 )\n\n\n @state.type = type\n @state.channel = channel\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 29 )\n\n\n end", "def parse input\r\n split_index = input.index(/[{},]/)\r\n stack = []\r\n if split_index ==nil then\r\n\r\n end\r\n pre_string = input[0..split_index-1].strip\r\n post_string = input[split_index+1..input.length].strip\r\n case input[/[{},]/]\r\n when \"{\"\r\n \tstack << parse(post_string) if pre_string==\"\"\r\n \tif pre_string!=\"\" then\r\n \t\tstack = {}\r\n \t\tstack[pre_string] = parse(post_string)\r\n \tend\r\n when \"}\"\r\n \tstack << pre_string\r\n \treturn stack\r\n when \",\"\r\n end\r\n stack\r\n\r\nend", "def parse(s)\n parser = Stupidedi::Builder::StateMachine.build(@config)\n machine, result = parser.read(Stupidedi::Reader.build(s))\n\n # Report fatal tokenizer failures\n if result.fatal?\n result.explain{ |reason| raise reason + \" at #{result.position.inspect}\" }\n end\n machine\n end", "def token!\n # at line 1:8: ( T__62 | T__63 | T__64 | T__65 | STRING | TO_INT | TO_FLOAT | READ | PRINT | PRINTL | PRINTLN | TRUE | FALSE | FOR | IF | ELSE | ELIF | ELSEIF | WHILE | DO | RETURN | EXIT | BREAK | CONTINUE | CLASS | SUPERCLASS | NEW | ID | INT | COMMENT | WS | LB | RB | LCB | RCB | QUOTE | COMMA | DOT | COLON | SEMICOLON | ASSIGN | PLUS | MINUS | MUL | DIV | MOD | EQ | NE | LT | GT | LE | GE | AND | OR | NOT | QM )\n alt_16 = 56\n alt_16 = @dfa16.predict( @input )\n case alt_16\n when 1\n # at line 1:10: T__62\n t__62!\n\n when 2\n # at line 1:16: T__63\n t__63!\n\n when 3\n # at line 1:22: T__64\n t__64!\n\n when 4\n # at line 1:28: T__65\n t__65!\n\n when 5\n # at line 1:34: STRING\n string!\n\n when 6\n # at line 1:41: TO_INT\n to_int!\n\n when 7\n # at line 1:48: TO_FLOAT\n to_float!\n\n when 8\n # at line 1:57: READ\n read!\n\n when 9\n # at line 1:62: PRINT\n print!\n\n when 10\n # at line 1:68: PRINTL\n printl!\n\n when 11\n # at line 1:75: PRINTLN\n println!\n\n when 12\n # at line 1:83: TRUE\n true!\n\n when 13\n # at line 1:88: FALSE\n false!\n\n when 14\n # at line 1:94: FOR\n for!\n\n when 15\n # at line 1:98: IF\n if!\n\n when 16\n # at line 1:101: ELSE\n else!\n\n when 17\n # at line 1:106: ELIF\n elif!\n\n when 18\n # at line 1:111: ELSEIF\n elseif!\n\n when 19\n # at line 1:118: WHILE\n while!\n\n when 20\n # at line 1:124: DO\n do!\n\n when 21\n # at line 1:127: RETURN\n return!\n\n when 22\n # at line 1:134: EXIT\n exit!\n\n when 23\n # at line 1:139: BREAK\n break!\n\n when 24\n # at line 1:145: CONTINUE\n continue!\n\n when 25\n # at line 1:154: CLASS\n class!\n\n when 26\n # at line 1:160: SUPERCLASS\n superclass!\n\n when 27\n # at line 1:171: NEW\n new!\n\n when 28\n # at line 1:175: ID\n id!\n\n when 29\n # at line 1:178: INT\n int!\n\n when 30\n # at line 1:182: COMMENT\n comment!\n\n when 31\n # at line 1:190: WS\n ws!\n\n when 32\n # at line 1:193: LB\n lb!\n\n when 33\n # at line 1:196: RB\n rb!\n\n when 34\n # at line 1:199: LCB\n lcb!\n\n when 35\n # at line 1:203: RCB\n rcb!\n\n when 36\n # at line 1:207: QUOTE\n quote!\n\n when 37\n # at line 1:213: COMMA\n comma!\n\n when 38\n # at line 1:219: DOT\n dot!\n\n when 39\n # at line 1:223: COLON\n colon!\n\n when 40\n # at line 1:229: SEMICOLON\n semicolon!\n\n when 41\n # at line 1:239: ASSIGN\n assign!\n\n when 42\n # at line 1:246: PLUS\n plus!\n\n when 43\n # at line 1:251: MINUS\n minus!\n\n when 44\n # at line 1:257: MUL\n mul!\n\n when 45\n # at line 1:261: DIV\n div!\n\n when 46\n # at line 1:265: MOD\n mod!\n\n when 47\n # at line 1:269: EQ\n eq!\n\n when 48\n # at line 1:272: NE\n ne!\n\n when 49\n # at line 1:275: LT\n lt!\n\n when 50\n # at line 1:278: GT\n gt!\n\n when 51\n # at line 1:281: LE\n le!\n\n when 52\n # at line 1:284: GE\n ge!\n\n when 53\n # at line 1:287: AND\n and!\n\n when 54\n # at line 1:291: OR\n or!\n\n when 55\n # at line 1:294: NOT\n not!\n\n when 56\n # at line 1:298: QM\n qm!\n\n end\n end", "def solution(s)\n size = 0\n s.each_char do |c|\n if c == \"(\"\n size += 1\n elsif c == \")\"\n size -= 1\n return 0 if size < 0\n end\n end\n return 0 if size > 0\n return 1\nend", "def next_token\n return if @scanner.eos?\n\n if @scanner.scan(SKIP_PATTERN)\n @column += @scanner[:before].length\n\n new_lines = @scanner[:new_line].delete(\"\\r\")\n unless new_lines.empty?\n @lineno += new_lines.length\n @column = 0\n end\n\n @column += @scanner[:after].length\n end\n\n token =\n case\n when try_match(REFERENCE_PATTERN)\n Token.new :REFERENCE, @scanner[:identifier], @lineno, @column\n when try_match(PATH_PATTERN)\n Token.new :PATH, @scanner[:identifier], @lineno, @column\n when try_match(FILTER_PATTERN) && @scanner.check(OPEN_PAREN_PATTERN)\n Token.new :FILTER, \"?\", @lineno, @column\n when try_match(OPEN_BRACKET_PATTERN)\n @state_stack.push Token.new :OPEN_BRACKET, \"[\", @lineno, @column\n @state_stack.last\n when try_match(OPEN_PAREN_PATTERN)\n @state_stack.push Token.new :OPEN_PAREN, \"(\", @lineno, @column\n @state_stack.last\n when try_match(CLOSE_BRACKET_PATTERN)\n last = @state_stack.pop\n unless last\n raise TokenizeError.unexpected(\"]\", @lineno, @column)\n end\n unless last.type == :OPEN_BRACKET\n raise TokenizeError.unbalanced(\"[\", last.lineno, last.column)\n end\n Token.new :CLOSE_BRACKET, \"]\", @lineno, @column\n when try_match(CLOSE_PAREN_PATTERN)\n last = @state_stack.pop\n unless last\n raise TokenizeError.unexpected(\")\", @lineno, @column)\n end\n unless last.type == :OPEN_PAREN\n raise TokenizeError.unbalanced(\"(\", last.lineno, last.column)\n end\n Token.new :CLOSE_PAREN, \")\", @lineno, @column\n when try_match(SELF_PATTERN)\n Token.new :SELF, \"@\", @lineno, @column\n when try_match(NUMBER_PATTERN)\n Token.new :NUMBER, BigDecimal.new(@last_captured), @lineno, @column\n when try_match(STRING_PATTERN)\n Token.new :STRING, @scanner[:str], @lineno, @column\n when try_match(TRUE_PATTERN)\n Token.new :BOOLEAN, true, @lineno, @column\n when try_match(FALSE_PATTERN)\n Token.new :BOOLEAN, false, @lineno, @column\n when try_match(COLON_PATTERN)\n Token.new :COLON, \":\", @lineno, @column\n when try_match(COMMA_PATTERN)\n Token.new :COMMA, \",\", @lineno, @column\n when try_match(ADD_PATTERN)\n Token.new :ADD, \"+\", @lineno, @column\n when try_match(SUBTRACT_PATTERN)\n case @tokens.last&.type\n when nil, :OPEN_PAREN, :OPEN_BRACKET, :COMMA, :COLON, :POW, :MOD, :ADD, :SUBTRACT, :MULTIPLY, :DIVIDE\n if @scanner.check(NUMBER_PATTERN) ||\n @scanner.check(REFERENCE_PATTERN) ||\n @scanner.check(SUBTRACT_PATTERN) ||\n @scanner.check(OPEN_PAREN_PATTERN)\n Token.new :UMINUS, \"-\", @lineno, @column\n else\n raise TokenizeError.unexpected(\"-\", @lineno, @column)\n end\n else\n Token.new :SUBTRACT, \"-\", @lineno, @column\n end\n when try_match(MULTIPLY_PATTERN)\n Token.new :MULTIPLY, \"*\", @lineno, @column\n when try_match(DIVIDE_PATTERN)\n Token.new :DIVIDE, \"/\", @lineno, @column\n when try_match(POW_PATTERN)\n Token.new :POW, \"^\", @lineno, @column\n when try_match(MOD_PATTERN)\n Token.new :MOD, \"%\", @lineno, @column\n when try_match(EQUAL_TO_PATTERN)\n Token.new :EQUAL_TO, \"==\", @lineno, @column\n when try_match(NOT_EQUAL_TO_PATTERN)\n Token.new :NOT_EQUAL_TO, \"!=\", @lineno, @column\n when try_match(GREATER_THAN_OR_EQUAL_TO_PATTERN)\n Token.new :GREATER_THAN_OR_EQUAL_TO, \">=\", @lineno, @column\n when try_match(GREATER_THAN_PATTERN)\n Token.new :GREATER_THAN, \">\", @lineno, @column\n when try_match(LESS_THAN_OR_EQUAL_TO_PATTERN)\n Token.new :LESS_THAN_OR_EQUAL_TO, \"<=\", @lineno, @column\n when try_match(LESS_THAN_PATTERN)\n Token.new :LESS_THAN, \"<\", @lineno, @column\n when try_match(AND_PATTERN)\n Token.new :AND, \"&&\", @lineno, @column\n when try_match(OR_PATTERN)\n Token.new :OR, \"||\", @lineno, @column\n when try_match(NOT_PATTERN)\n Token.new :NOT, \"!\", @lineno, @column\n when try_match(INTERSECT_PATTERN)\n Token.new :INTERSECT, \"&\", @lineno, @column\n when try_match(UNION_PATTERN)\n Token.new :UNION, \"|\", @lineno, @column\n when try_match(IDENTIFIER_PATTERN) && @scanner.check(OPEN_PAREN_PATTERN)\n unless @scanner.check(OPEN_PAREN_PATTERN)\n raise TokenizeError.unexpected(@scanner.peek(7), @lineno, @column)\n end\n Token.new :FUNCTION, @last_captured, @lineno, @column\n else\n raise TokenizeError.unexpected(@scanner.peek(7), @lineno, @column)\n end\n\n @column += @last_captured.length\n @tokens << token\n\n token\n end", "def parse_string\n # Local array ( multidimensional ) to hold code structures\n parse_string_holder = []\n # Loop through each of the regular expressions in the @structures instance variable array\n @structures.each do | structure |\n # Check to see if the structure can be found in the @raw_command_string created in the previous method call\n if structure.match( @raw_command_string )\n # If any were found, loop through the found objects\n @raw_command_string.scan( structure ).each do | caught |\n # Pull out the longest array element corresponding to the whole found string\n # this is necessary due to the way Ruby handles results from a regex search; creating a MatchData\n # object which can be read and treated as an array\n found = caught.to_a.compact.max_by( &:length )\n # Find the starting point in the @raw_command_string instance variabl array using the found string as the\n # basis for a new regex.\n start = /#{ Regexp.quote( found ) }/.match( @raw_command_string ).begin( 0 )\n # Holder for substitution string\n substitute = \"\"\n # Create substitution string using least common character I could think of, if it proves necessary, this can\n # be swapped out for any other single character in the event \"~\" is needed down the road\n found.length.times { substitute << \"~\" }\n # Replace the structure in the original string ( ! = dustructive, meaning it changes the orignal object ) \n # with the substitute string to prevent duplication\n @raw_command_string.sub!( structure, substitute )\n # Add subarray to holder array consisting of the starting point ( for sorting ) and the found string\n parse_string_holder << [ start, found ]\n end\n end\n end\n # Check for non-valid structures, throw error\n if @raw_command_string.gsub( /~/, \"\" ).gsub( / /, \"\" ).length > 0\n # If there are any uncaught ( invalid ) block structures, set to false for error handling\n @parsed_command_string = false\n else\n # Assign to new instance variable a sorted multidimensional array consisting of all found command structures in \n # order of execution\n @parsed_command_string = parse_string_holder.sort\n end\n end", "def tokenize(string)\n parts = string.split(/\\s*[\\(\\)]\\s*/).map do |token|\n token.split(/\\s*,\\s*/).map do |exp|\n # avoid :to_sym on random input, symbols are never gc'ed\n if @functions.has_key? exp\n @functions[exp]\n elsif exp =~ /\\A[\\-\\+]?\\d+\\Z/\n exp.to_i\n elsif exp =~ /\\A[\\-\\+]?\\d*\\.\\d+\\Z/\n exp.to_f\n elsif \"true\" === exp\n true\n elsif \"false\" === exp\n false\n elsif \"null\" === exp or \"nil\" === exp\n nil\n # bare strings, but restricted to the following pattern\n elsif exp =~ /\\A[-\\.\\w]+\\Z/\n exp\n else\n raise InvalidAggSyntaxError.new \"syntax error in expression: #{exp.inspect}\"\n end\n end\n end\n parts.flatten\n end", "def tokenize\n # Array to contain all tokens.\n tokenArray = []\n # While getChar returns anything other than \"\"\n while getChar\n # Loop to next character until not a space.\n while charIsWhitespace\n nextChar\n end\n # Breaks if it hits the dreaded empty string.\n if getChar.nil?\n break\n end\n # If character is a letter.\n if(charIsAlpha) \n # Initialize local variables for scope.\n m = \"\"\n line = @line\n column = @column \n # While character is letter or number or underscore,\n # add to string \"m\" current character.\n while(charIsAlpha or charIsDigit or getChar == '_')\n m += getChar\n nextChar\n end\n # If the keywords include \"m\" string in hash array,\n # add to tokenArray a new token with the keywords having \"m\" as an index key,\n # its column and line as well for future use and debugging.\n if(Tokens::KEYWORDS.include?(m))\n tokenArray.push Token.new(Tokens::KEYWORDS[m], m, column, line)\n # Must be identifier, add to array as identifier.\n else\n tokenArray.push Token.new(Tokens::IDENT, m, column, line)\n end\n # If the current character is a number.\n elsif(charIsDigit)\n # Initialize local variables for scope.\n m = \"\"\n line = @line\n column = @column\n # Bool is for exception checking on periods. Most likely will be removed,\n # have yet to decide on ranges.\n dot = false\n # While char is number or period,\n while(charIsDigit or getChar == '.')\n # if period\n if(getChar == '.')\n # if dot is true\n if(dot)\n # Create exception class message.\n TokenizerException.new(column, line, \"Number literal contains too many dots.\")\n end\n # Sets flag for second dot if it happens before leaving scope.\n dot = true\n end\n # String adds new character and increments\n m += getChar\n nextChar\n end\n # Token complete, push token as number into tokenArray\n tokenArray.push Token.new(Tokens::NUMBER, m, column, line)\n # Current character doesn't fit into letter or number parameters.\n else\n # More instance variables\n column = @column\n line = @line\n # Starts off by saying this is a character, then moving to the next to check.\n m = getChar\n nextChar\n # While the string is in the operators add and increment character.\n while(Tokens::OPERATORS.include?(m))\n m += getChar if !getChar.nil?\n m += \" \" if getChar.nil?\n nextChar\n end\n # Jump back to the last character\n prevChar()\n # Take of the last character.\n m = m.slice(0, m.size - 1)\n # Pushes another token into the array.\n tokenArray.push Token.new(Tokens::OPERATORS[m], m, column, line)\n end\n end\n return tokenArray\n end", "def prepare_to_parse(input)\n @input = input\n @input_length = input.length\n reset_index\n @node_cache = Hash.new {|hash, key| hash[key] = Hash.new}\n @terminal_failures = []\n @regexps = {}\n @max_terminal_failure_index = 0\n end", "def bad_valid_syntax(str_sample)\n index = 0\n openers = [\"[\",\"{\", \"[\"]\n opener_stack = {\n \"{\":[],\n \"(\":[],\n \"[\":[]\n }\n while index < str_sample.size\n curr_char = str_sample[index]\n if openers.include?(curr_char)\n opener_stack[curr_char].push(index)\n elsif curr_char == \"}\"\n start = opener_stack[\"{\"].pop\n return false if (start..index).includes?(opener_stack[\"[\"].last)\n return false if (start..index).includes?(opener_stack[\"(\"].last)\n elsif curr_char == \")\"\n start = opener_stack[\"(\"].pop\n return false if (start..index).includes?(opener_stack[\"{\"].last)\n return false if (start..index).includes?(opener_stack[\"[\"].last)\n elsif curr_char ==\"]\"\n start = opener_stack[\"[\"].pop\n return false if (start..index).includes?(opener_stack[\"{\"].last)\n return false if (start..index).includes?(opener_stack[\"(\"].last)\n end\n index += 1\n end\n opener_stack.all?{|opener|opener.empty?}\nend", "def my_first_interpreter code\n # Implement your interpreter here\n text = ''\n count = 0\n x = 0\n while x < code.length do \n if code[x] == '+'\n count += 1\n elsif code[x] == '.'\n text << count.chr\n end\n if count >= 256\n count = 0\n end\n x += 1\n end\n text\nend", "def parse\n length = @chars.length\n @index = 0\n while @index < length\n @tokens << if custom?\n parse_custom\n else\n parse_char\n end\n @index += 1\n end\n @tokens\n end", "def st!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 49 )\n\n type = ST\n channel = ANTLR3::DEFAULT_CHANNEL\n # - - - - label initialization - - - -\n d = nil\n\n\n \n # - - - - main rule block - - - -\n # at line 348:5: d= ( ( DIGIT )* ) '1' ( 'S' | 's' ) ( 'T' | 't' )\n # at line 348:7: ( ( DIGIT )* )\n # at line 348:8: ( DIGIT )*\n # at line 348:8: ( DIGIT )*\n while true # decision 1\n alt_1 = 2\n look_1_0 = @input.peek( 1 )\n\n if ( look_1_0 == 0x31 )\n look_1_1 = @input.peek( 2 )\n\n if ( look_1_1.between?( 0x30, 0x39 ) )\n alt_1 = 1\n\n end\n elsif ( look_1_0 == 0x30 || look_1_0.between?( 0x32, 0x39 ) )\n alt_1 = 1\n\n end\n case alt_1\n when 1\n # at line 348:8: DIGIT\n digit!\n\n else\n break # out of loop for decision 1\n end\n end # loop for decision 1\n\n match( 0x31 )\n if @input.peek(1) == 0x53 || @input.peek(1) == 0x73\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n end\n\n\n if @input.peek(1) == 0x54 || @input.peek(1) == 0x74\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n end\n\n\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 49 )\n\n end", "def scan_statement\n # eat any whitespace at the start of the string\n whitespace = @scanner.scan_until(/\\S/)\n\n if whitespace\n @scanner.pos -= 1\n update_counter(whitespace[0..-2])\n end\n\n # look for matches\n case\n when text = @scanner.scan(/\\}\\}/)\n @context = :body\n token(:VAR_CLOSE, text)\n \n when text = @scanner.scan(/%\\}/)\n @context = :body\n token(:STMT_CLOSE, text)\n\n when text = @scanner.scan(/[=]=/) # i've added the square brackets because syntax highlighters dont like /=\n token(:OP_EQ, text)\n\n when text = @scanner.scan(/>=/)\n token(:OP_GEQ, text)\n\n when text = @scanner.scan(/<=/)\n token(:OP_LEQ, text)\n\n when text = @scanner.scan(/[=]>/) # i've added the square brackets because syntax highlighters dont like /=\n token(:OP_MAP, text)\n\n when text = @scanner.scan(/(if|else|endif|for|in|endfor|block|endblock|extends|render)[\\W]/)\n keyword = text[0..-2]\n @scanner.pos -= 1\n\n token(keyword.upcase.to_sym, keyword)\n\n when text = @scanner.scan(/[+\\-]?[0-9]+\\.[0-9]+/)\n token(:REAL, text)\n\n when text = @scanner.scan(/[+\\-]?[1-9][0-9]*|0/)\n token(:INTEGER, text)\n \n when text = @scanner.scan(/['][^']*[']|[\"][^\"]*[\"]/)\n token(:STRING, text)\n\n when text = @scanner.scan(/[A-Za-z_][A-Za-z0-9_\\.]*/)\n token(:IDENTIFIER, text)\n\n else\n next_character = @scanner.getch\n token(next_character, next_character)\n end\n end", "def execute!\n line_n = 0\n level = 0\n classes = []\n @source.each_line do |line|\n line_n += 1\n line.chomp!\n # indentify scopes\n level = line_level line\n\n # ignore comments!\n next if @comment_lines.include? line_n\n\n [\n [@class_regex, 'c'],\n [@proto_meths, 'p'],\n [@func_regex, 'f'],\n [@var_regex, 'v'],\n [@block, 'b']\n ].each do |regex, kind|\n mt = item_for_regex line, regex, level, :source => line, :line => line_n, :kind => kind\n unless mt.nil?\n # TODO: one token should not fit for multiple regex\n classes.push mt if kind == 'c'\n next if kind == 'f' # wait for later to determine whether it is a class method\n @tree << mt\n end\n end\n\n # instance variable or iterator (for/in)?\n token = line.match(@token_regex )\n token ||= line.match(@iterator_regex)\n\n # we have found something!\n if not token.nil?\n # should find token through the tree first\n token_name = token[1]\n existing_token = @tree.find {|o| o[:name] == token_name}\n if existing_token\n o = existing_token\n else\n o = {\n :name => token_name,\n :level => level,\n :parent => '',\n :source => line,\n :line => line_n\n }\n end\n\n # Remove edge cases for now\n\n # - if a line containes a line like: element.getElement('type=[checkbox]').lol()\n token_match_in_line = false\n token_match_in_line = line.match token_name\n unless token_match_in_line.nil?\n offset = token_match_in_line.offset 0\n str_before = line.slice 0, offset[0]\n str_after = line.slice offset[1], line.size\n [str_before, str_after].map do |str|\n # if there are unmatch quotes, our token is in a string\n token_match_in_line = ['\"', '\\''].any? { |q| str.scan(q).size % 2 == 1 }\n end\n end\n\n if token_match_in_line\n @tree = @tree.reject {|c| c[:name] == o[:name]}\n next\n end\n\n # - scope access and comparison in if x == 'lol'\n is_in_comparison = line =~ /::|==/\n\n # - objects with blank parent (parser bug?)\n has_blank_parent = o[:parent] =~ /\\.$/\n\n # - multiple consecutive assignments\n is_previous_not_the_same = !(@tree.last and @tree.last[:name] == o[:name] and @tree.last[:level] == o[:level])\n\n if !token_match_in_line and is_in_comparison.nil? and (has_blank_parent.nil? or is_previous_not_the_same)\n unless o[:kind]\n o[:kind] = line =~ /[:=]{1}.*[-=]\\s?\\>/ ? 'f' : 'v'\n end\n o[:parent] = scope_path o\n o[:parent] = @fake_parent if o[:parent].empty?\n\n # treat variable and function with a class as parent as property\n if ['f', 'v', 'o'].include? o[:kind]\n # TODO: process func params\n maybe_parent_class = classes.find {|c| c[:name] == o[:parent] }\n if maybe_parent_class\n o[:kind] = 'p'\n end\n end\n\n @tree << o unless @tree.include? o\n end\n end\n end\n\n @tree = comb_kinds @tree\n\n @tree = trim_tree @tree\n\n # P.S when found a token, first lookup in the tree, thus the duplicate won't appear\n # so there is no need of uniq_tree\n self # chain!\n end", "def tokenize str, terminates=false, &block\n if block_given?\n offset = 0\n while str.length > 0 do\n ostr = str\n str = ostr.sub /(^[ \\t\\r\\f\\v\\u00a0]*)([^\\]\\[)(}{,.?\\s\\u00a0]+|[()\\[\\]{},.?\\n])/i, '' # Pluck the next token\n spaces, token = $1, $2\n if token && ((str.length > 0) || terminates || token.match(/^[()\\[\\]{},.?\\n]/)) # This string really ends here (no continuation of non-delimiter)\n offset += spaces&.length || 0\n block.call token, offset unless token.empty?\n offset += token&.length || 0\n else\n return ostr # Return the unprocessed remainder of the string (which may be blank)\n end\n end\n ''\n else\n tokens = []\n while str.length > 0\n str = str.sub /(^[ \\t\\r\\f\\v\\u00a0]*)([^\\]\\[)(}{,.?\\s\\u00a0]+|[()\\[\\]{},.?\\n])/i, ''\n if $2\n tokens << $2\n else\n break\n end\n end\n tokens\n end\nend", "def fromStateString(line, s)\n\ti = s\n\tuntil line[i] == '\t' || i == line.length\n\t\ti = i+1\n\t\tif i>7\n\t\t\tputs 'ERROR: cannot read line in fromStateString'\n\t\t\treturn -1\n\t\tend\n\tend\n\treturn line[s..i-1]\nend", "def parse inline\n @inline = inline\n @src = StringScanner.new inline\n @pre = \"\".dup\n @yydebug = true\n do_parse.to_s\nend", "def process_code_state(ios, src, state)\n src.strip!\n src.gsub!(/^[ \\t]+/, '')\n case state\n when /code_(?:line_)?span/ then\n ios << \"\\n#{src}\"\n when /code_(?:line_)?print/ then\n ios << \"\\n_.((#{src}),ctx)\"\n when /code_(?:line_)?template/ then\n if src =~ /\\A(.*)(do|{)\\s*(\\|[^\\|]+\\|\\s*)?\\Z/\n ios << \"\\n(#{$~[1]}{#{$~[3]}\"\n @curly_end = $~[2] == '{'\n elsif !@curly_end && (src =~ /\\A\\s*end\\s*\\Z/)\n ios << '}).(_,ctx)'\n elsif @curly_end && (src =~ /\\A\\s*\\}\\s*\\Z/)\n ios << '}).(_,ctx)'\n else\n ios << \"\\n(#{src}).(_,ctx)\"\n end\n when /code_(?:line_)?visitor/\n m = src.match(/^([^ \\(]+)?(\\([^\\)]*\\))?\\s*(.*)$/)\n ios << \"\\n#{m[1]}_result=(#{m[3]}).(#{m[1]}_visitor#{m[2]},ctx)\"\n when :l10n then\n localize(ios, src)\n end\n end", "def scan\n @top_level.comment ||= \"\"\n state=:code_blank\n line_number = 0\n line = nil\n\n # This started out as a really long nested case statement,\n # which also led to repetitive code. I'd like to avoid that\n # so I'm using a \"table\" instead.\n\n # Firstly we need some procs to do the transition and processing\n # work. Because these are procs they are closures, and they can\n # use variables in the local scope.\n #\n # First, the \"nothing to see here\" stuff.\n code_noop = lambda do\n if line =~ /^\\s+$/\n state = :code_blank\n end\n end\n\n pod_noop = lambda do\n if line =~ /^\\s+$/\n state = :pod_blank\n end\n @top_level.comment += filter(line)\n end\n\n begin_noop = lambda do\n if line =~ /^\\s+$/\n state = :begin_blank\n end\n @top_level.comment += filter(line)\n end\n\n # Now for the blocks that process code and comments...\n\n transit_to_pod = lambda do\n case line\n when /^=(?:pod|head\\d+)/\n state = :pod_no_blank\n @top_level.comment += filter(line)\n when /^=over/\n state = :over_no_blank\n @top_level.comment += filter(line)\n when /^=(?:begin|for)/\n state = :begin_no_blank\n end\n end\n\n process_pod = lambda do\n case line\n when /^\\s*$/ then\n state = :pod_blank\n @top_level.comment += filter(line)\n when /^=cut/ then\n state = :code_no_blank\n when /^=end/ then\n $stderr.puts \"'=end' unexpected at #{line_number} in #{@file_name}\"\n else\n @top_level.comment += filter(line)\n end\n end\n\n process_begin = lambda do\n case line\n when /^\\s*$/ then\n state = :begin_blank\n @top_level.comment += filter(line)\n when /^=end/ then\n state = :code_no_blank\n when /^=cut/\n $stderr.puts \"'=cut' unexpected at #{line_number} in #{@file_name}\"\n else\n @top_level.comment += filter(line)\n end\n end\n\n transitions = { :code_no_blank => code_noop,\n :code_blank => transit_to_pod,\n :pod_no_blank => pod_noop,\n :pod_blank => process_pod,\n :begin_no_blank => begin_noop,\n :begin_blank => process_begin,\n }\n\n @content.each_line do |l|\n line = l\n line_number += 1\n transitions[state].call\n end\n\n @top_level\n end", "def ciclo_times\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 20 )\n\n\n return_value = CicloTimesReturnValue.new\n\n # $rule.start = the first token seen before matching\n return_value.start = @input.look\n\n\n root_0 = nil\n\n __DecimalLiteral94__ = nil\n __K_TIMES95__ = nil\n __K_DO96__ = nil\n __LLAIZQ97__ = nil\n __LLADER99__ = nil\n bodyexp98 = nil\n\n\n tree_for_DecimalLiteral94 = nil\n tree_for_K_TIMES95 = nil\n tree_for_K_DO96 = nil\n tree_for_LLAIZQ97 = nil\n tree_for_LLADER99 = nil\n\n begin\n root_0 = @adaptor.create_flat_list\n\n\n # at line 111:4: DecimalLiteral K_TIMES K_DO LLAIZQ bodyexp LLADER\n __DecimalLiteral94__ = match( DecimalLiteral, TOKENS_FOLLOWING_DecimalLiteral_IN_ciclo_times_475 )\n if @state.backtracking == 0\n tree_for_DecimalLiteral94 = @adaptor.create_with_payload( __DecimalLiteral94__ )\n @adaptor.add_child( root_0, tree_for_DecimalLiteral94 )\n\n end\n\n __K_TIMES95__ = match( K_TIMES, TOKENS_FOLLOWING_K_TIMES_IN_ciclo_times_477 )\n if @state.backtracking == 0\n tree_for_K_TIMES95 = @adaptor.create_with_payload( __K_TIMES95__ )\n @adaptor.add_child( root_0, tree_for_K_TIMES95 )\n\n end\n\n __K_DO96__ = match( K_DO, TOKENS_FOLLOWING_K_DO_IN_ciclo_times_479 )\n if @state.backtracking == 0\n tree_for_K_DO96 = @adaptor.create_with_payload( __K_DO96__ )\n @adaptor.add_child( root_0, tree_for_K_DO96 )\n\n end\n\n __LLAIZQ97__ = match( LLAIZQ, TOKENS_FOLLOWING_LLAIZQ_IN_ciclo_times_481 )\n if @state.backtracking == 0\n tree_for_LLAIZQ97 = @adaptor.create_with_payload( __LLAIZQ97__ )\n @adaptor.add_child( root_0, tree_for_LLAIZQ97 )\n\n end\n\n @state.following.push( TOKENS_FOLLOWING_bodyexp_IN_ciclo_times_483 )\n bodyexp98 = bodyexp\n @state.following.pop\n if @state.backtracking == 0\n @adaptor.add_child( root_0, bodyexp98.tree )\n end\n\n __LLADER99__ = match( LLADER, TOKENS_FOLLOWING_LLADER_IN_ciclo_times_485 )\n if @state.backtracking == 0\n tree_for_LLADER99 = @adaptor.create_with_payload( __LLADER99__ )\n @adaptor.add_child( root_0, tree_for_LLADER99 )\n\n end\n\n\n # - - - - - - - rule clean up - - - - - - - -\n return_value.stop = @input.look( -1 )\n\n\n if @state.backtracking == 0\n return_value.tree = @adaptor.rule_post_processing( root_0 )\n @adaptor.set_token_boundaries( return_value.tree, return_value.start, return_value.stop )\n\n end\n\n rescue ANTLR3::Error::RecognitionError => re\n report_error(re)\n recover(re)\n return_value.tree = @adaptor.create_error_node( @input, return_value.start, @input.look(-1), re )\n\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 20 )\n\n\n end\n\n return return_value\n end", "def string\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 60 )\n\n\n return_value = StringReturnValue.new\n\n # $rule.start = the first token seen before matching\n return_value.start = @input.look\n\n\n root_0 = nil\n\n __COMILLA324__ = nil\n set325 = nil\n __COMILLA326__ = nil\n\n\n tree_for_COMILLA324 = nil\n tree_for_set325 = nil\n tree_for_COMILLA326 = nil\n\n begin\n root_0 = @adaptor.create_flat_list\n\n\n # at line 573:9: COMILLA ( EscapeSequence |~ ( '\\\\'' | '\\\\\\\\' ) )* COMILLA\n __COMILLA324__ = match( COMILLA, TOKENS_FOLLOWING_COMILLA_IN_string_2819 )\n if @state.backtracking == 0\n tree_for_COMILLA324 = @adaptor.create_with_payload( __COMILLA324__ )\n @adaptor.add_child( root_0, tree_for_COMILLA324 )\n\n end\n\n # at line 573:17: ( EscapeSequence |~ ( '\\\\'' | '\\\\\\\\' ) )*\n while true # decision 44\n alt_44 = 2\n look_44_0 = @input.peek( 1 )\n\n if ( look_44_0.between?( ASIGNACION, COMA ) || look_44_0.between?( CORDER, WS ) || look_44_0.between?( T__81, T__82 ) )\n alt_44 = 1\n\n end\n case alt_44\n when 1\n # at line \n set325 = @input.look\n\n if @input.peek( 1 ).between?( ASIGNACION, COMA ) || @input.peek( 1 ).between?( CORDER, WS ) || @input.peek( 1 ).between?( T__81, T__82 )\n @input.consume\n if @state.backtracking == 0\n @adaptor.add_child( root_0, @adaptor.create_with_payload( set325 ) )\n end\n\n @state.error_recovery = false\n\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n\n mse = MismatchedSet( nil )\n raise mse\n\n end\n\n\n\n else\n break # out of loop for decision 44\n end\n end # loop for decision 44\n\n __COMILLA326__ = match( COMILLA, TOKENS_FOLLOWING_COMILLA_IN_string_2837 )\n if @state.backtracking == 0\n tree_for_COMILLA326 = @adaptor.create_with_payload( __COMILLA326__ )\n @adaptor.add_child( root_0, tree_for_COMILLA326 )\n\n end\n\n\n # - - - - - - - rule clean up - - - - - - - -\n return_value.stop = @input.look( -1 )\n\n\n if @state.backtracking == 0\n return_value.tree = @adaptor.rule_post_processing( root_0 )\n @adaptor.set_token_boundaries( return_value.tree, return_value.start, return_value.stop )\n\n end\n\n rescue ANTLR3::Error::RecognitionError => re\n report_error(re)\n recover(re)\n return_value.tree = @adaptor.create_error_node( @input, return_value.start, @input.look(-1), re )\n\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 60 )\n\n\n end\n\n return return_value\n end", "def parse_text(source, rs = nil)\n rs ||= RenderState.new\n \n # check\n case rs.header_id_type\n\t\t\twhen HeaderIDType::MD5, HeaderIDType::ESCAPE\n\t\t\telse\n rs.warnings << \"illegal header id type - #{rs.header_id_type}\"\n\t\t\tend\n \n # Create a StringScanner we can reuse for various lexing tasks\n @scanner = StringScanner::new( '' )\n \n # Make a copy of the string with normalized line endings, tabs turned to\n # spaces, and a couple of guaranteed newlines at the end\n \n text = detab(source.gsub( /\\r\\n?/, \"\\n\" ))\n text += \"\\n\\n\"\n @log.debug \"Normalized line-endings: %p\" % text\n \n #text = Utilities::prePaling(text) #Insert by set.minami 2013-04-27\n #Insert by set.minami 2013-04-03\n text = transform_block_quotes(text, rs)\n nrange = []\n departure = 1\n preproc = Marshal.load(Marshal.dump(text))\n text.clear\n stack = []\n html_text_number = 0\n# Utilities::initNumberStack\n\n preproc.lines { |line|\n html_text_number += 1\n begin\n line.gsub!(/^\\{nrange:(.*?)(;\\d+)??\\}/){ |match|\n #depNum = $2.delete(';').to_i\n #departure = if depNum > 0 then depNum else 1 end\n if /h(\\d)\\-h(\\d)/i =~ $1\n nrange.push($1)\n nrange.push($2)\n if nrange.size > 2 then\n nrange.pop\n nrange.pop\n raise \"Syntax Error!\" \n end\n end\n next\n }\n @log.debug line \n #calculate numbering\n range = nrange[1].to_i - nrange[0].to_i\n if range == 0 then range = 1 end\n if range < 0 then \n p \"AoBane Syntax Error:Header range is WRONG!\" +\n \"@ l.#{html_text_number}\";exit(-1)\n raise FatalError,\"AoBane Syntax Error:Header range is WRONG!\"\n end\n if line =~ /^(%{1,#{range}})(.*?)\\n/ then\n text << Utilities.\n calcSectionNo(nrange.min,range,$1.size,departure,$2,stack) +\n \"\\n\"\n else\n text << line\n end\n @log.debug nrange.minmax\n rescue => e\n @log.warn \"AoBane Syntax WARNING l.#{html_text_number}:#{line.chomp} haven't adopted\" \n @log.warn e \n end\n }\n\n text.gsub!(/\\*\\[(.*?)\\]\\((.*?)(\\|.*?)*(\\/.*?)*\\)/){|match|\n '<font color=\"' +\n if $2.nil? then '' else $2 end\t+'\" ' +\n 'face=\"' +\n if $3.nil? then '' else $3.delete('|') end + '\" ' +\n 'size=\"' +\n if $4.nil? then '' else $4.delete('/') end + '\">' +\n $1 + '</font>'\n }\n #Insert by set.minami 2013-04-21\n text = Utilities::abbrPreProcess(text)\n #Insert by set.minami 2013-04-01\n text.gsub!(/\\\\TeX\\{(.+?)\\\\TeX\\}/){\n begin\n $1.to_mathml\n rescue => e\n puts 'math_ml Error: ' + $1\n puts e\n end\n }\n\n text = Utilities::preProcFence(text,0).join(\"\\n\") #Insert by set.minami 2013-04-27\n #Insert by set.minami 2013-03-30 \n #Insert by set.minami\n\n\t\t\t# Filter HTML if we're asked to do so\n\t\t\tif self.filter_html\n\t\t\t\t#text.gsub!( \"<\", \"&lt;\" )\n\t\t\t\t#text.gsub!( \">\", \"&gt;\" )\n\t\t\t\t@log.debug \"Filtered HTML: %p\" % text\n\t\t\tend\n\n\t\t\t# Simplify blank lines\n\t\t\ttext.gsub!( /^ +$/, '' )\n\t\t\t@log.debug \"Tabs -> spaces/blank lines stripped: %p\" % text\n\n\n\t\t\t# Replace HTML blocks with placeholders\n\t\t\ttext = hide_html_blocks( text, rs )\n\t\t\t@log.debug \"Hid HTML blocks: %p\" % text\n\t\t\t@log.debug \"Render state: %p\" % rs\n\n\n\t\t\t# Strip footnote definitions, store in render state\n\t\t\ttext = strip_footnote_definitions( text, rs )\n\t\t\t@log.debug \"Stripped footnote definitions: %p\" % text\n\t\t\t@log.debug \"Render state: %p\" % rs\n\n\n\t\t\t# Strip link definitions, store in render state\n\t\t\ttext = strip_link_definitions( text, rs )\n\t\t\t@log.debug \"Stripped link definitions: %p\" % text\n\t\t\t@log.debug \"Render state: %p\" % rs\n\n\t\t\t# Escape meta-characters\n\t\t\ttext = escape_special_chars( text )\n\t\t\t@log.debug \"Escaped special characters: %p\" % text\n\n\t\t\t# Transform block-level constructs\n\t\t\ttext = apply_block_transforms( text, rs )\n\t\t\t@log.debug \"After block-level transforms: %p\" % text\n\n\t\t\t# Now swap back in all the escaped characters\n\t\t\ttext = unescape_special_chars( text )\n\t\t\t@log.debug \"After unescaping special characters: %p\" % text\n\n\t\t\t# Extend footnotes\n\t\t\tunless rs.footnotes.empty? then\n\t\t\t\ttext << %Q|<div class=\"footnotes\"><hr#{EmptyElementSuffix}\\n<ol>\\n|\n\t\t\t\trs.found_footnote_ids.each do |id|\n\t\t\t\t\tcontent = rs.footnotes[id]\n\t\t\t\t\thtml = apply_block_transforms(content.sub(/\\n+\\Z/, '') + %Q| <a href=\"#footnote-ref:#{id}\" rev=\"footnote\">&#8617;</a>|, rs)\n\t\t\t\t\ttext << %Q|<li id=\"footnote:#{id}\">\\n#{html}\\n</li>|\n\t\t\t\tend\n\t\t\t\ttext << %Q|</ol>\\n</div>\\n|\n\t\t\tend\n\n\t\t\t# Display warnings\n\t\t\tif @display_warnings then\n\t\t\t\tunless rs.warnings.empty? then\n\t\t\t\t\thtml = %Q|<pre><strong>[WARNINGS]\\n|\n\t\t\t\t\thtml << rs.warnings.map{|x| Util.escape_html(x)}.join(\"\\n\")\n\t\t\t\t\thtml << %Q|</strong></pre>|\n\n\t\t\t\t\ttext = html + text\n\t\t\t\tend\n\t\t\tend\n\n #Insert by set.minami 2013-04-21\n text = Utilities::abbrPostProcess(text)\n #Insert by set.minami 2013-03-30\n text = Utilities::insertTimeStamp(text)\n text = Utilities::postProcFence(text) #Insert by set.minami 2013-04-27\n\n text = Utilities::transformSpecialChar(text) #Insert by set.minami 2013-04-27\n\n return text\n end", "def lex_start; end" ]
[ "0.62273145", "0.62273145", "0.61859584", "0.60420746", "0.5964846", "0.5865738", "0.5865738", "0.5865738", "0.5865738", "0.58180296", "0.5816488", "0.57989705", "0.57957935", "0.5783337", "0.5772337", "0.5763411", "0.5749674", "0.57179713", "0.57089925", "0.57087326", "0.57041097", "0.57041097", "0.56900775", "0.56849223", "0.5680191", "0.55884624", "0.5569141", "0.55633456", "0.55558103", "0.5545987", "0.552234", "0.5519248", "0.5517172", "0.5517172", "0.5517172", "0.5490477", "0.5472887", "0.54702", "0.5468222", "0.54668605", "0.54441404", "0.5413195", "0.5400341", "0.53959996", "0.53955144", "0.5390633", "0.5390633", "0.5385487", "0.5374052", "0.53688633", "0.53544027", "0.53468", "0.5342491", "0.5313413", "0.5311002", "0.53076065", "0.53075486", "0.5302007", "0.52904594", "0.5288087", "0.52852255", "0.5282197", "0.5274117", "0.5267999", "0.5267999", "0.52673864", "0.52468175", "0.52444464", "0.52385956", "0.5238231", "0.52290136", "0.52233446", "0.5222461", "0.5221485", "0.5221196", "0.5209411", "0.5196737", "0.51938003", "0.51887894", "0.5180517", "0.5176848", "0.517413", "0.51719975", "0.51696813", "0.5162285", "0.5151861", "0.51494473", "0.51469433", "0.51343", "0.51318854", "0.51301384", "0.51257575", "0.512472", "0.5122307", "0.51215214", "0.51180226", "0.5113812", "0.51125723", "0.5110138", "0.5097981" ]
0.6894451
0
garante que sera usando um 'Range' ou 'Array' para meses e anos na importacao. Se vier um unico valor sera criado um range com apenas ele.
def validate_range(value) classname = value.class.to_s case classname when "Range" then value when "Array" then value else return (value..value) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def m_range\r\n end", "def to_range\n Range.new(self.start, self.end)\n end", "def range\n unless value.is_a? Range\n errors.add(:value, :range)\n end\n end", "def range; end", "def range; end", "def range; end", "def range\n @range ||= set_range\n end", "def range(arr)\n\nend", "def range( range )\n ::Vector.elements( range.to_a )\n end", "def create_range_data( rng, minrng=0, type=0, direction=2 )\n return Handlers::Range.createRange( rng, minrng, type, direction )\n end", "def parse_range_value(value)\r\n value << nil if value.kind_of?(Array) && value.length == 1\r\n value = [value, nil] if (value.kind_of?(String) || !value.respond_to?(:first))\r\n value\r\n end", "def parse_range\n val = super || return\n val.begin == val.end ? val.begin : val\n end", "def r(range)\n range.to_a\nend", "def breakable_range=(_arg0); end", "def range \n Range.new(@first, @last)\n end", "def range\n [@from, @to]\n end", "def to_range\n case\n when open?, unknown?\n nil\n else\n Range.new(unknown_start? ? Date.new : @from, max)\n end\n end", "def range(range)\n opts[:min] = range.begin\n opts[:max] = range.end\n end", "def values(range = nil)\n result_unflatten = if !::RANGES_JRUBY_BUG\n map { |x| x.v }\n else\n self.v\n end\n result = result_unflatten.flatten\n if range\n relevant_result = []\n result.each_with_index { |row_or_column, i| relevant_result << row_or_column if range.include?(i) }\n relevant_result\n else\n result\n end\n end", "def create_range(num)\n (1..num).to_a\nend", "def to_a\n get_range('-inf', '+inf', include_boundaries: true)\n end", "def range(range)\n assert_range range\n schema do |s|\n s.type range.begin.is_a?(Integer) ? 'integer' : 'number'\n s.minimum range.begin\n s.maximum range.end, exclusive: range.exclude_end? unless range.end.nil?\n end\n end", "def range=(range)\n @range = range\n end", "def +(object)\n raise \"Expecting RubyRanges::Array or Range, but was #{object.class} : #{object.inspect}\" unless object.is_a?(Range) || object.is_a?(Array)\n array_of_ranges = Array.new((object.is_a?(Range) ? (self.old_plus([object])) : super(object)))\n array_of_ranges.flatten_ranges\n end", "def range\n DEFAULT_RANGE\n end", "def range\n DEFAULT_RANGE\n end", "def range\n DEFAULT_RANGE\n end", "def test_range\n series = Dataset::Series.new\n ary = (1950..2007).map {|n| [ n, rand(100) ]}\n series.add(*ary)\n assert_equal(58, series.data.size)\n assert_raise(RuntimeError) { series.range() }\n assert_raise(TypeError) { series.range(Dataset::Chron::YYYYMM.new(\"01/1980\")) }\n assert_raise(TypeError) { series.range(nil, Dataset::Chron::YYYYMM.new(\"01/1980\")) }\n s2 = series.range(Dataset::Chron::YYYY.new(1980))\n assert_equal(28, s2.data.size)\n assert_equal(Dataset::Chron::YYYY.new(1980), s2.chrons.min)\n assert_equal(Dataset::Chron::YYYY.new(2007), s2.chrons.max)\n end", "def test_arrays_and_ranges\n assert_equal Range, (1..5).class\n assert_not_equal [1,2,3,4,5], (1..5)\n assert_equal [1,2,3,4,5], (1..5).to_a\n assert_equal [1,2,3,4], (1...5).to_a\n end", "def range\n @from..@to\n end", "def range=(range)\n @range = range\n end", "def breakable_range; end", "def range\n min, max = span\n min..max\n end", "def range_value\n string_value\n end", "def to_range\n min .. max\n end", "def value_to_range(value)\n case value.to_s\n when /\\A(\\-?\\d+)\\z/\n Range.new($1.to_i, $1.to_i)\n when /\\A(-?\\d+?)(\\.\\.\\.?|-|,)(-?\\d+)\\z/\n Range.new($1.to_i, $3.to_i, $2 == '...')\n else\n if @slop.strict?\n raise InvalidArgumentError, \"#{value} could not be coerced into Range\"\n else\n value\n end\n end\n end", "def within(range: T.unsafe(nil)); end", "def range(min, max)\n \tarr = []\n\tfor i in min..max\n arr << i\n end\n return arr\nend", "def range_start; range.first; end", "def range=(range)\n @range = Range.new(range)\n end", "def add_range!(range, ranges)\n # Make sure the arguments are correct\n return nil if range.nil? || ranges.nil?\n\n # Ignore the range if there is an existing one which is bigger\n return nil unless ranges[range.startLine].nil? || ranges[range.startLine].endLine < range.endLine\n ranges[range.startLine] = range\n nil\n end", "def range\n (@from..@to)\n end", "def test_single_value\n x = IntegerRange.new(42)\n\n assert_equal(x.bottom, 42)\n assert_equal(x.top, 42)\n assert_equal(x.to_a, (42..42).to_a)\n\n a = each_to_a(x)\n\n assert_equal(a, (42..42).to_a)\n end", "def range\n\t\t\t#(@end > @start) ? (@start .. @end) : (@end .. @start)\n\t\t\t(start .. self.end)\n\t\tend", "def declare_beg_range\n\t\t@beg_range = @beg_range.to_date \n\t\t@end_range = @end_range.to_date \n\tend", "def tt_range\n ARange.new(ttstart_at, ttend_at)\n end", "def source_range=(_arg0); end", "def check_range(rng)\n new(rng).results\n end", "def range(from, to)\n from_query(raw_range(from, to))\n end", "def range(start, ending)\n return [] if start >= ending - 1\n retu_arr = range(start, ending - 1)\n retu_arr << ending - 1\nend", "def data_range(record)\n #carico la campagna attiva\n camp = Campagne.find(:first,:conditions => [\"active = true\"])\n #a meno che la data non rientri nel range della campagna\n unless record.data >= camp.inizio && record.data <= camp.fine\n #salvo l'errore simple range\n simple_range_error(record,\"Data range\")\n end\n end", "def to_range\n (@start_date..@end_date)\n end", "def range\n @range ||= 0.upto(@limit)\n end", "def set_range(iRange)\n super\n end", "def unbounded\n ::Unbounded::Range.new(self.min, self.max, exclude_end?)\n end", "def auto_range(direction); end", "def __evolve_range__(serializer: nil)\n __evolve_range_naive__.transform_values! do |value|\n if serializer\n serializer.evolve(value)\n else\n case value\n when Time, DateTime then value.__evolve_time__\n when Date then value.__evolve_date__\n else value\n end\n end\n end\n end", "def SetRange(range)\n @range=range\n end", "def range\n @cached_range ||= get_range\n end", "def range(start_num, end_num)\n # one line version\n # (start_num...end_num).to_a\n\n # version 2\n exclusive_range = []\n (start_num...end_num).each do |num|\n exclusive_range << num\n end\n exclusive_range\nend", "def size_range(range)\n return [1,1] if range.nil?\n from = range.from\n to = range.to\n x = from.nil? ? 1 : from\n y = to.nil? ? TheInfinity : to\n [x, y]\n end", "def value_in_range(range)\n case range.first\n when Integer then number_in_range(range)\n when Time then time_in_range(range)\n when Date then date_in_range(range)\n else range.to_a.rand\n end\n end", "def restrict(value, range)\n [[value, range.first].max, range.last].min\n end", "def normalize_range_values(params, field_name, values)\n normalized = Array(values).map(&:presence).compact\n params[field_name] = (normalized.present? && values.length == 2) && (values.first...values.last) || nil\n end", "def _reduce_518(val, _values, result)\n result = @builder.range_inclusive(val[0], val[1], val[2])\n \n result\nend", "def normalize_range(range)\n ar = range.to_a\n if ar.min > 2 # normalizacja zadanego zakresu aby zawsze zakres zaczynał się od 2\n ar += (2..ar.min-1).to_a\n ar = ar.sort\n else\n ar.delete_if { |e| e < 2 }\n end\n ar\nend", "def value=(value)\n if !::RANGES_JRUBY_BUG\n ole_range.Value = value\n else\n rows.each_with_index do |r,i|\n columns.each_with_index do |c,j|\n ole_range.Cells(i+1,j+1).Value = (value.respond_to?(:pop) ? value[i][j] : value)\n end\n end\n end\n value\n rescue WIN32OLERuntimeError, Java::OrgRacobCom::ComFailException => msg \n raise RangeNotEvaluatable, \"cannot assign value to range #{self.inspect}\\n#{$!.message}\"\n end", "def range(start_num, end_num)\n range_array = []\n range_array << start_num\n\n if(start_num < end_num)\n range_array += range(start_num + 1, end_num)\n end\n\n range_array\nend", "def range(range, options={})\n range = (range..range) if range.is_a? Date\n data = range.map do |date|\n case type\n when :counter\n value = Prisma.redis.get(Prisma.redis_key(name, date)).to_i\n when :bitmap\n bitstring = Prisma.redis.get(Prisma.redis_key(name, date)) || ''\n string = bitstring.unpack('b*').first\n value = options[:skip_bitmap_count] ? string : string.count('1')\n end\n\n [date, value]\n end\n\n Hash[data]\n end", "def range(data)\n return (minimum(data)..maximum(data))\n end", "def add_range(left, right)\n \n end", "def add_range(left, right)\n \n end", "def include_with_range?(value)\n if value.is_a?(::Range)\n operator = exclude_end? ? :< : :<=\n end_value = value.exclude_end? ? last.succ : last\n include?(value.first) && (value.last <=> end_value).send(operator, 0)\n else\n include_without_range?(value)\n end\n end", "def _reduce_199(val, _values, result)\n result = new_irange(val[0], val[1], val[2])\n \n result\nend", "def vt_range\n ARange.new(vtstart_at, vtend_at)\n end", "def range(column)\n min(column)..max(column)\n end", "def range(input); end", "def effective_range\n @opts[:effective_range] ||= [nil, nil]\n @opts[:effective_range][0] ||= x.min\n @opts[:effective_range][1] ||= x.max\n @opts[:effective_range]\n end", "def one_index_range(range)\n Range.new(one_index_number(range.begin), one_index_number(range.end))\n end", "def one_index_range(range)\n Range.new(one_index_number(range.begin), one_index_number(range.end))\n end", "def range\n attributes.fetch(:range)\n end", "def range\n attributes.fetch(:range)\n end", "def range\n attributes.fetch(:range)\n end", "def range\n attributes.fetch(:range)\n end", "def normalized\n @normalized ||= valid_range? ? range : normalized_range(range)\n rescue Exception => e \n # puts e.message\n value\n end", "def include_range? other_range\n case other_range\n when Range\n if other_range.first >= self.first && other_range.last <= self.last\n return true\n else\n return false\n end\n else\n raise \"unsupported type\"\n end\n end", "def collect\n [@range_low, @range_high]\n end", "def to_range\n start_date..end_date\n end", "def slice( range)\n ::Vector.elements( self.to_a.slice(range) )\n end", "def _reduce_535(val, _values, result)\n result = @builder.range_inclusive(nil, val[0], val[1])\n\n result\nend", "def test_ranges\r\n assert_equal(@range.begin.to_f, @p2.to_f)\r\n assert(@range.cover?(@p5))\r\n assert(@range.end == @p8)\r\n assert(@range2.exclude_end?)\r\n assert_false(@range.exclude_end?)\r\n assert(@range.include?(@p3))\r\n assert(@range.max == @p8)\r\n assert(@range2.max == @p7)\r\n assert(@range.last(3) == [@p6, @p7, @p8])\r\n assert(@range.size == nil)\r\n end", "def _reduce_516(val, _values, result)\n result = @builder.range_inclusive(val[0], val[1], val[2])\n \n result\nend", "def range(start, ending)\n return [] if start >= ending - 1\n # retu_arr = []\n # retu_arr << start + 1\n # retu_arr.concat(range(start+1, ending))\n array = range(start+1, ending)\n array.unshift(start+1)\nend", "def range(*args)\n value = \"[\"\n args.each_slice(2) do |from, to|\n from = sanitize(from)\n to = sanitize(to)\n value += \"#{from}-#{to}\"\n end\n value += \"]\"\n append value\n end", "def source_range(*arguments); end", "def -(object)\n raise \"Expecting RubyRanges::Array or Range, but was #{object.class} : #{object.inspect}\" unless object.is_a?(Range) || object.is_a?(Array)\n if object.is_a?(Range)\n array_of_ranges = inject([]) do |new, range|\n new.old_plus([range - object])\n end\n else\n other = self\n object.each do |other_range|\n other = Array.new(other - other_range).flatten\n end\n other\n end\n end", "def check_range(name, range, value, unit = '')\n grace = (-0.00001..0.00001)\n str = value.to_s\n value = value.value if value.is_a?(Sass::Script::Value::Number)\n return value if range.include?(value)\n return range.first if grace.include?(value - range.first)\n return range.last if grace.include?(value - range.last)\n raise ArgumentError.new(\n \"#{name} #{str} must be between #{range.first}#{unit} and #{range.last}#{unit}\")\n end", "def range_summary(array)\r\n\r\nend", "def query_range(left, right)\n \n end", "def query_range(left, right)\n \n end" ]
[ "0.6830491", "0.6825375", "0.67711097", "0.67022", "0.67022", "0.67022", "0.6673403", "0.66349554", "0.66348237", "0.6590816", "0.6523634", "0.65096164", "0.642427", "0.6422655", "0.63773715", "0.63382196", "0.6328013", "0.6308158", "0.6302805", "0.6293935", "0.6293847", "0.6258703", "0.6249967", "0.6208183", "0.6190551", "0.6190551", "0.6190551", "0.61799407", "0.61787647", "0.6174829", "0.61512566", "0.6150749", "0.61408544", "0.61395913", "0.61352926", "0.6133832", "0.61307657", "0.6126311", "0.6126181", "0.61174905", "0.61079746", "0.60759795", "0.6038451", "0.6033008", "0.6026664", "0.602156", "0.60191184", "0.60156584", "0.6004918", "0.6000291", "0.59885913", "0.59785086", "0.59661216", "0.59597665", "0.5955099", "0.5954731", "0.5953244", "0.5950969", "0.59484494", "0.5948362", "0.5946106", "0.5932888", "0.5929947", "0.5924428", "0.59229773", "0.5919271", "0.59111935", "0.59099525", "0.5908932", "0.5904216", "0.5898322", "0.5898322", "0.58971137", "0.5888219", "0.5868108", "0.5861604", "0.5853916", "0.5851067", "0.5844204", "0.5842617", "0.58403677", "0.58403677", "0.58403677", "0.58403677", "0.5823352", "0.5819957", "0.5819605", "0.5813308", "0.5813021", "0.5812726", "0.581095", "0.5810844", "0.5810656", "0.58082116", "0.58035433", "0.5803046", "0.5801827", "0.5801782", "0.58006316", "0.58006316" ]
0.6750199
3
Common base command for Local/Push/Pull
def rsync_command utility(:rsync).dup << archive_option << mirror_option << exclude_option << " #{Array(additional_rsync_options).join(" ")}".rstrip end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def push(cmd); end", "def pull; end", "def remotes_action(command, id, host, action, remote_dir, std_in=nil)\n super(command,id,host,ACTION[action],remote_dir,std_in)\n end", "def push\n hg 'push'\n end", "def push(arg='')\n `git push #{arg} 2>&1`\n end", "def sync\n pull && push\n end", "def cmd\n c = [\"git push --set-upstream origin #{current_branch}\"]\n c << argument_string(unknown_options) unless unknown_options.empty?\n c.join(\" \")\n end", "def add_standard_git_tasks\n command(:remove_cache, :in_app_dir => false) do |app|\n directory = dir_for_app(app)\n if File.exists?(directory)\n puts \"Removing cached app #{app} at #{directory}\"\n FileUtils.rm_rf directory\n end\n end\n\n command(:clone, :in_app_dir => false) do |app|\n url = Zim.current_suite.application_by_name(app).git_url\n\n app_directory = dir_for_app(app)\n container_directory = File.dirname(app_directory)\n FileUtils.mkdir_p container_directory unless File.exists?(container_directory)\n directory_exists = File.directory?(app_directory)\n\n if directory_exists\n found = false\n in_app_dir(app) do\n `git remote -v`.split(\"\\n\").each do |line|\n elements = line.split(/[ \\t]+/)\n if elements[0] == 'origin' && elements[1] == url && elements[2] == '(fetch)'\n found = true\n break\n end\n end\n end\n unless found\n mysystem(\"rm -rf #{app_directory}\")\n directory_exists = false\n end\n end\n\n mysystem(\"git clone #{url}\") unless directory_exists\n end\n\n command(:gitk) do\n mysystem('gitk --all &') if Zim.cwd_has_unpushed_changes?\n end\n\n command(:fetch) do\n git_fetch\n end\n\n command(:reset) do\n git_reset_branch\n end\n\n command(:reset_origin) do\n git_reset_branch(\"origin/#{current_default_branch}\")\n end\n\n command(:git_reset_if_unchanged) do\n git_reset_if_unchanged\n end\n\n command(:diff_origin) do\n git_diff\n end\n\n command(:hub_pull_request) do\n hub_pull_request(Zim::Config.parameter_by_name('PR_MESSAGE'))\n end\n\n command(:goto_default_branch) do\n git_checkout\n end\n\n command(:pull) do\n git_pull\n end\n\n command(:git_prune) do\n git_prune\n end\n\n command(:git_gc) do\n git_gc\n end\n\n command(:push) do |app|\n run(:git_reset_if_unchanged, app)\n git_push if Zim.cwd_has_unpushed_changes?\n end\n\n command(:remove_local_branches) do |app|\n git_local_branch_list.select {|b| b != current_default_branch}.each do |branch|\n mysystem(\"git branch -D #{branch}\")\n end\n end\n\n command(:clean, :in_app_dir => false) do |app|\n run(:clone, app)\n run(:git_gc, app)\n run(:fetch, app)\n run(:reset, app)\n run(:goto_default_branch, app)\n run(:remove_local_branches, app)\n run(:pull, app)\n end\n\n command(:branch) do |app|\n git_checkout(Zim::Config.parameter_by_name('BRANCH'), true)\n end\n\n command(:real_clean, :in_app_dir => false) do |app|\n run(:clean, app)\n run(:reset_origin, app)\n end\n\n command(:ultra_clean, :in_app_dir => false) do |app|\n run(:real_clean, app)\n run(:git_prune, app)\n run(:git_gc, app)\n end\n\n desc 'Run following commands for each branch in the tag zim:branches (comma separated)'\n command(:each_zim_branch, :block_command => true) do |app_key|\n app = Zim.current_suite.application_by_name(app_key)\n branches = (app.tag_value('zim:branches') || current_default_branch).split(',')\n branches.each do |branch|\n git_checkout(branch)\n Zim::Driver.run_commands(app, Zim.current_commands)\n end\n\n # Return false so subsequent tasks not run\n false\n end\n\n desc 'Run ultra_clean and then each_zim_branch. Typically the first task.'\n command(:zimup, :in_app_dir => false, :block_command => true) do |app|\n run(:ultra_clean, app)\n run(:each_zim_branch, app)\n false\n end\n end", "def initial_push_command\n \"git remote add origin git@github.com:#{owner.login}/#{name}.git &&\\n\" +\n \"git push origin master &&\\n\" +\n \"git config --add branch.master.remote origin &&\\n\" +\n \"git config --add branch.master.merge refs/heads/master\" \n end", "def git_checkout_and_push_u(name, opts={})\n cmd = \"git checkout -b #{name}\"\n puts cmd\n out = `#{cmd}`\n if $? == 0\n cmd = \"git push -u origin #{name}\"\n puts cmd\n out = `#{cmd}`\n if $? == 0\n # nothing\n else\n $stderr.puts \"ERROR: failed to push '#{name}' to origin\"\n end\n else\n $stderr.puts \"ERROR: failed to checkout '#{name}'\"\n end\nend", "def cmd\n branch = self.known_options.first || default_branch\n c = [\"git checkout #{branch}\"]\n c << \"git pull\"\n c << \"git checkout #{current_branch}\"\n c.join(\"\\n\")\n end", "def test_pull\n \tassert_equal(UI.parseCommand('pull', PullCmd1*\" \"),UI.main(PullCmd1))\n \tassert_equal(UI.parseCommand('pull', PullCmdInv*\" \"),UI.main(PullCmdInv))\n end", "def push(remote)\n namehost, folder, _barefolder = split_url(remote.name)\n puts 'simple_push'\n simple_push(remote('origin'))\n puts 'bare_repo.push'\n bare_repo.push(remote)\n try_system %[ssh #{namehost} \"cd #{folder} && git pull origin\"]\n end", "def test_command_should_default_to_default_command\n assert_equal \"git\", @source.command\n @source.local { assert_equal \"git\", @source.command }\n end", "def shell_commands(cmd, args); end", "def push_repo_changes_aux(repo, opts={})\n diffs = DiffSummary.new()\n\n # adding untracked files (newly added files)\n repo.stage_changes()\n\n # commit if there has been changes\n if repo.changed?\n repo.commit(opts[:commit_msg]||\"Pushing changes from client\") #TODO: make more descriptive\n end\n\n if opts[:remote_repo] and opts[:remote_repo_url]\n repo.add_remote(opts[:remote_repo],opts[:remote_repo_url])\n end\n\n unless opts[:no_fetch]\n repo.fetch(remote(opts[:remote_repo]))\n end\n\n local_branch = repo.local_branch_name\n\n remote_branch_ref = remote_branch_ref(local_branch, opts)\n\n #check if merge needed\n commit_shas = Hash.new\n merge_rel = repo.merge_relationship(:remote_branch,remote_branch_ref, :ret_commit_shas => commit_shas)\n commit_sha = nil\n diffs = DiffSummary.new_version(repo)\n\n if merge_rel == :equal\n commit_sha = commit_shas[:other_sha]\n elsif [:branchpoint,:local_behind].include?(merge_rel)\n if opts[:force]\n diffs = DiffSummary.diff(repo,local_branch, remote_branch_ref)\n if diffs.any_diffs?()\n repo.push(remote_branch_ref, {:force => opts[:force]})\n end\n commit_sha = repo.find_remote_sha(remote_branch_ref)\n else\n where = opts[:where] || 'server'\n msg = \"Merge needed before module (#{pp_module(repo)}) can be pushed to #{where}. \"\n if where.to_sym == :catalog\n msg << \" Either a merge into the local module can be done with pull-dtkn command, followed by push-dtkn or force\"\n else\n msg << \"Force\"\n end\n msg << \" push can be used with the '--force' option, but this will overwrite remote contents\"\n raise ErrorUsage.new(msg)\n end\n elsif merge_rel == :no_remote_ref\n repo.push(remote_branch_ref)\n commit_sha = commit_shas[:local_sha]\n elsif merge_rel == :local_ahead\n # see if any diffs between fetched remote and local branch\n # this has be done after commit\n diffs = DiffSummary.diff(repo,local_branch, remote_branch_ref)\n\n if diffs.any_diffs?()\n repo.push(remote_branch_ref, {:force => opts[:force]})\n end\n\n commit_sha = repo.find_remote_sha(remote_branch_ref)\n else\n raise Error.new(\"Unexpected merge_rel (#{merge_rel})\")\n end\n\n {\"diffs\" => diffs, \"commit_sha\" => commit_sha, \"repo_obj\" => repo}\n end", "def git_push(host, branch, git_repo_path)\n git_on(host, \"push origin #{branch}\", git_repo_path)\nend", "def alert_if_needs_pushing(dir = Dir.pwd)\n Dir.chdir(dir) {puts \"WARNING: #{dir} needs to be pushed to remote origin\" if needs_pushing? }\nend", "def shell_commands(cmd, *args); end", "def github_pull\n Extension.github_sync\n end", "def push\n ensure_git_and_cucumber_available\n ensure_repository\n\n puts \"Not implemented yet... pull request for push please!\"\n end", "def git\n\tend", "def test_push\n \tassert_equal(UI.parseCommand('push', PushCmd1*\" \"),UI.main(PushCmd1))\n \tassert_equal(UI.parseCommand('push', PushCmdInv*\" \"),UI.main(PushCmdInv))\n end", "def pull from, to, dryrun=true, push=false\n build from, to, dryrun, push\n end", "def git command, *args\n run 'git', command.to_s, *args\nend", "def pull_latest_changes\n system \"cd #{Dots.home} && #{git_pull}\"\n end", "def execute\n raise NotImplementedError, 'Generic command has no actions'\n end", "def fetch\n git :fetch\n end", "def push(downstream, upstream, remote_branch='svn_git_port')\n name=get_dir_name(downstream, upstream)\n upstream_dir=File.join(name, 'upstream')\n Dir.chdir(upstream_dir) do\n puts `git checkout -b push`\n puts `git push upstream HEAD:#{remote_branch}`\n end\nend", "def command\n fail 'Not implemented.'\n end", "def command_raw(args)\n\n end", "def git_add_commit_push(host, branch, message, git_repo_path)\n git_add_everything(host, git_repo_path)\n git_commit_push(host, branch, message, git_repo_path)\nend", "def command; end", "def command; end", "def command; end", "def command; end", "def command; end", "def command; end", "def pull_execute(branch, dir)\n vConfig(CONFIG['configWebsite'])\n read_json(CONFIG['configWebsite'])\n pull = @parse_json_config['deploy']['github']['config']['pull']\n if pull == \"yes\"\n system_commands(\"cd #{dir}; git pull origin #{branch}\")\n end\n end", "def test_gitgo_different_from_remote_gitgo\n assert !sh(a, 'git branch -a').include?('gitgo')\n assert !sh(b, 'git branch -a').include?('gitgo')\n assert !sh(c, 'git branch -a').include?('gitgo')\n \n sh(b, 'git branch gitgo')\n sh(b, 'git checkout gitgo')\n method_root.prepare(b, \"bshasum\") {|io| io << \"b content\" }\n sh(b, 'git add bshasum')\n sh(b, 'git commit -m \"added document\"')\n \n # setup remote from c\n sh(c, 'git branch gitgo')\n sh(c, 'git checkout gitgo')\n method_root.prepare(c, \"cshasum\") {|io| io << \"c content\" }\n sh(c, 'git add cshasum')\n sh(c, 'git commit -m \"added document\"')\n sh(c, 'git push origin gitgo')\n \n # now try to push back, fails\n assert sh(b, 'git push origin gitgo').include?(\"! [rejected] gitgo -> gitgo (non-fast forward)\")\n \n sh(a, 'git checkout -f gitgo')\n assert_equal false, File.exists?(method_root.path(a, \"bshasum\"))\n assert_equal \"c content\", File.read(method_root.path(a, \"cshasum\"))\n \n # merge\n sh(b, 'git fetch')\n assert sh(b, 'git branch').include?('gitgo')\n assert sh(b, 'git branch -a').include?('origin/gitgo')\n sh(b, 'git merge origin/gitgo')\n \n # now push works\n sh(b, 'git push origin gitgo')\n sh(a, 'git checkout -f gitgo')\n assert_equal \"b content\", File.read(method_root.path(a, \"bshasum\"))\n assert_equal \"c content\", File.read(method_root.path(a, \"cshasum\"))\n \n # fetch for c leaves changes unmerged\n sh(c, 'git fetch')\n sh(c, 'git checkout -f gitgo')\n assert_equal false, File.exists?(method_root.path(c, \"bshasum\"))\n assert_equal \"c content\", File.read(method_root.path(c, \"cshasum\"))\n \n # manual merge fixes\n sh(c, 'git merge gitgo origin/gitgo')\n sh(c, 'git checkout -f gitgo')\n assert_equal \"b content\", File.read(method_root.path(c, \"bshasum\"))\n assert_equal \"c content\", File.read(method_root.path(c, \"cshasum\"))\n end", "def command\n @command ||= case copy_strategy\n when :checkout\n source.checkout(revision, destination)\n when :export\n source.export(revision, destination)\n end\n end", "def we_have_a_command_with_two_subcommands(options = {})\n lambda {\n @run_results = { :add => nil, :rename => nil, :base => nil }\n @app.command :remote do |c|\n\n c.switch :f\n\n c.desc \"add a remote\"\n c.command [:add,:new] do |add|\n\n Array(options[:flags]).each { |_| add.flag _ }\n Array(options[:switches]).each { |_| add.switch _ }\n add.action do |global_options,command_options,args|\n @run_results[:add] = [global_options,command_options,args]\n end\n end\n\n c.desc \"rename a remote\"\n c.command :rename do |rename|\n rename.action do |global_options,command_options,args|\n @run_results[:rename] = [global_options,command_options,args]\n end\n end\n\n c.action do |global_options,command_options,args|\n @run_results[:base] = [global_options,command_options,args]\n end\n end\n ENV['GLI_DEBUG'] = 'true'\n }\n end", "def pull_on_operand_branch *args\n self.on_operand_branch :pull, *args\n end", "def git_push_origin\n ErrorEmittingExecutor.execute(\"git push origin -u #{BRANCH_NAME}\")\nend", "def run!\n ssh commands(:default)\n end", "def optional_pull\n if ARGV.include?(\"--pull\")\n puts %x(feature pull)\n end\nend", "def local\n db_dump\n sync_local\n system_lists\n commit_git_repo(\"~/backup\")\n end", "def commands; end", "def command_runner cmd:, repo:nil, branch:nil\n status = run_cmd(cmd)\n status\n end", "def push!\n notify.write(\"Pushing to origin\")\n proj.push('origin', proj_branch)\n proj.push('origin', report_branch)\n end", "def pull_changes\n\t\t\tsystem \"cd projects/#{name} && git pull origin\"\n\t\t\tProcessHelper::get_used_ports\n\t\tend", "def commands\n @commands ||= source.checkout(revision, configuration[:deploy_release])\n end", "def subcommand() __subcommand__ end", "def cmd; end", "def sync_cmd\n warn(\"Legacy call to #sync_cmd cannot be preserved, meaning that \" \\\n \"test files will not be uploaded. \" \\\n \"Code that calls #sync_cmd can now use the transport#upload \" \\\n \"method to transfer files.\")\n end", "def git_push_commits\n shellout(\"git push #{config[:remote]} #{config[:branch]}\")\n end", "def command\n raise NotImplementedError\n end", "def git_fetch\n Command.new(\"git\", \"fetch\", \"--tags\").run!.raise!\nend", "def rsync_command\n if @config[:rsync][:direction] == 'up'\n from = absolute_path(@config[:local_path])\n to = @config.ssh_user_and_host + ':' + @config[:remote_path]\n else\n from = @config.ssh_user_and_host + ':' + @config[:remote_path]\n to = absolute_path(@config[:local_path])\n end\n \"rsync #{rsync_command_options.join(' ')} '#{from}/' '#{to}'\"\n end", "def execute\n if (!self.pull_request_id)\n current = GitHub::PullRequest.current\n self.pull_request_id = current.number if current\n end\n self.pull_request_id ||= cli.prompt(\"Pull Request ID: \")\n GitHub.connect do\n unless deployable? || @force\n CLI.say 'Pull request status checks have not passed. Cannot be marked deployable.'\n exit!\n end\n\n merge_result = merge\n add_deployable_label if config.deployable_label && merge_result\n end\n end", "def original_run_command; end", "def commands\n abstract!\n end", "def git_fetch\n Command.new(\"git\", \"fetch\", \"--tags\", \"-f\").run!.raise!\nend", "def fetch_origin_task\n sh git, 'fetch', remote\n end", "def cmd(*args) self.class.cmd(*args) end", "def method_missing(cmd, *args)\n command(cmd.to_s, *args)\n end", "def command\n logger.debug(\"#{copy_strategy}\")\n @command ||= case copy_strategy\n when :checkout\n source.checkout(revision, destination)\n when :export\n source.export(revision, destination)\n end\n end", "def git_commit_push(host, branch, message, git_repo_path)\n git_on(host, \"commit -m \\\"#{message}\\\"\", git_repo_path)\n git_push(host, branch, git_repo_path)\nend", "def method_missing(name, *args, &block)\n if name.to_s.end_with?('_cmd')\n execute_heroku proxy_cmd_str\n else\n super\n end\n end", "def local arg, options = {}\n if arg.class == Symbol\n self.__commands << options.merge({:command => self.send(arg), :type => :local, :from => self.__name})\n else\n self.__commands << options.merge({:command => arg, :type => :local, :from => self.__name})\n end\n end", "def commands\n all = {\n 'clearev' => 'Clear the event log',\n 'drop_token' => 'Relinquishes any active impersonation token.',\n 'execute' => 'Execute a command',\n 'getpid' => 'Get the current process identifier',\n 'getprivs' => 'Attempt to enable all privileges available to the current process',\n 'getuid' => 'Get the user that the server is running as',\n 'getsid' => 'Get the SID of the user that the server is running as',\n 'getenv' => 'Get one or more environment variable values',\n 'kill' => 'Terminate a process',\n 'pkill' => 'Terminate processes by name',\n 'pgrep' => 'Filter processes by name',\n 'ps' => 'List running processes',\n 'reboot' => 'Reboots the remote computer',\n 'reg' => 'Modify and interact with the remote registry',\n 'rev2self' => 'Calls RevertToSelf() on the remote machine',\n 'shell' => 'Drop into a system command shell',\n 'shutdown' => 'Shuts down the remote computer',\n 'steal_token' => 'Attempts to steal an impersonation token from the target process',\n 'suspend' => 'Suspends or resumes a list of processes',\n 'sysinfo' => 'Gets information about the remote system, such as OS',\n 'localtime' => 'Displays the target system local date and time',\n }\n reqs = {\n 'clearev' => [\n COMMAND_ID_STDAPI_SYS_EVENTLOG_OPEN,\n COMMAND_ID_STDAPI_SYS_EVENTLOG_CLEAR\n ],\n 'drop_token' => [COMMAND_ID_STDAPI_SYS_CONFIG_DROP_TOKEN],\n 'execute' => [COMMAND_ID_STDAPI_SYS_PROCESS_EXECUTE],\n 'getpid' => [COMMAND_ID_STDAPI_SYS_PROCESS_GETPID],\n 'getprivs' => [COMMAND_ID_STDAPI_SYS_CONFIG_GETPRIVS],\n 'getuid' => [COMMAND_ID_STDAPI_SYS_CONFIG_GETUID],\n 'getsid' => [COMMAND_ID_STDAPI_SYS_CONFIG_GETSID],\n 'getenv' => [COMMAND_ID_STDAPI_SYS_CONFIG_GETENV],\n 'kill' => [COMMAND_ID_STDAPI_SYS_PROCESS_KILL],\n 'pkill' => [\n COMMAND_ID_STDAPI_SYS_PROCESS_KILL,\n COMMAND_ID_STDAPI_SYS_PROCESS_GET_PROCESSES\n ],\n 'pgrep' => [COMMAND_ID_STDAPI_SYS_PROCESS_GET_PROCESSES],\n 'ps' => [COMMAND_ID_STDAPI_SYS_PROCESS_GET_PROCESSES],\n 'reboot' => [COMMAND_ID_STDAPI_SYS_POWER_EXITWINDOWS],\n 'reg'\t => [\n COMMAND_ID_STDAPI_REGISTRY_LOAD_KEY,\n COMMAND_ID_STDAPI_REGISTRY_UNLOAD_KEY,\n COMMAND_ID_STDAPI_REGISTRY_OPEN_KEY,\n COMMAND_ID_STDAPI_REGISTRY_OPEN_REMOTE_KEY,\n COMMAND_ID_STDAPI_REGISTRY_CREATE_KEY,\n COMMAND_ID_STDAPI_REGISTRY_DELETE_KEY,\n COMMAND_ID_STDAPI_REGISTRY_CLOSE_KEY,\n COMMAND_ID_STDAPI_REGISTRY_ENUM_KEY,\n COMMAND_ID_STDAPI_REGISTRY_SET_VALUE,\n COMMAND_ID_STDAPI_REGISTRY_QUERY_VALUE,\n COMMAND_ID_STDAPI_REGISTRY_DELETE_VALUE,\n COMMAND_ID_STDAPI_REGISTRY_QUERY_CLASS,\n COMMAND_ID_STDAPI_REGISTRY_ENUM_VALUE,\n ],\n 'rev2self' => [COMMAND_ID_STDAPI_SYS_CONFIG_REV2SELF],\n 'shell' => [COMMAND_ID_STDAPI_SYS_PROCESS_EXECUTE],\n 'shutdown' => [COMMAND_ID_STDAPI_SYS_POWER_EXITWINDOWS],\n 'steal_token' => [COMMAND_ID_STDAPI_SYS_CONFIG_STEAL_TOKEN],\n 'suspend' => [COMMAND_ID_STDAPI_SYS_PROCESS_ATTACH],\n 'sysinfo' => [COMMAND_ID_STDAPI_SYS_CONFIG_SYSINFO],\n 'localtime' => [COMMAND_ID_STDAPI_SYS_CONFIG_LOCALTIME],\n }\n filter_commands(all, reqs)\n end", "def git_pull(remote = '')\n mysystem(\"git pull #{remote}\")\n end", "def execute_hook(command); end", "def command\n @command ||= source.checkout(revision, configuration[:release_path])\n end", "def remote(params)\n case (params[:command])\n when \"status\"\n return node_status(params)\n when \"auth\"\n return auth(params)\n when \"resource_status\"\n return resource_status(params)\n when \"create_cluster\"\n return create_cluster(params)\n when \"set_corosync_conf\"\n if set_cluster_conf(params)\n return \"Succeeded\"\n else\n return \"Failed\"\n end\n when \"cluster_start\"\n return cluster_start(params)\n when \"cluster_stop\"\n return cluster_stop(params)\n when \"resource_start\"\n return resource_start(params)\n when \"resource_stop\"\n return resource_stop(params)\n when \"check_gui_status\"\n return check_gui_status(params)\n end\nend", "def scm_pull(uri,dest=nil)\n if dest\n sh 'svn', 'checkout', uri, dest\n else\n sh 'svn', 'checkout', uri\n end\n end", "def remote_command(command, password = nil)\n Net::SSH.start(remote_ip, 'git', :password => password) do |ssh|\n output = ssh.exec!(\"cd #{remote_app_name}\")\n unless output =~ /No such file or directory/\n ssh.exec(\"cd #{remote_app_name} && #{command}\")\n else\n puts \"Your application has not yet been deployed to your Webby.\"\n puts \"To issue remote commands from the Webby, you must first push your application.\"\n end\n end\n end", "def cli_base_cmd\n \"#{cli} -n #{network} -i '#{identity}' -p #{password}\"\n end", "def git(args, &block)\n Sprout::GitTask.define_task(args, &block)\nend", "def run_local(cmd)\n system(cmd)\n end", "def push_actions(input_cmd)\n @ips.each do |ip|\n if @yaml_file[input_cmd].class == Hash\n up_file(ip,@yaml_file[input_cmd])\n else\n up_exec(ip,@yaml_file[input_cmd])\n end\n end\n end", "def set_push_origin_url push_origin_url\n\n path_to_dot_git = File.join( @git_folder_path, \".git\" )\n git_loggable_cmd = \"git --git-dir=#{path_to_dot_git} --work-tree=#{@git_folder_path} remote set-url --push origin\"\n git_set_push_origin_url_cmd = \"#{git_loggable_cmd} #{push_origin_url}\"\n log.info(x) { \"[git] set push origin url command without url => #{git_loggable_cmd}\" }\n %x[#{git_set_push_origin_url_cmd}];\n log.info(x) { \"[git] has set the remote origin url for pushing.\" }\n\n end", "def push(_branch)\n puts 'TODO: Implement Git.push'\n end", "def supercommand!() __supercommand__ end", "def build_remote_cmd(task, cmd_str, input, given_opts, ssh_opts)\n Remote::Cmd.new(cmd_str, ssh_opts)\n end", "def push_to_server(local_branch, remote_branch, opts = {})\n if opts[:local]\n logger.debug('Not pushing to the server because the user selected local-only.')\n elsif not has_a_remote?\n logger.debug('Not pushing to the server because there is no remote.')\n elsif local_branch == config.master_branch\n logger.warn('Not pushing to the server because the current branch is the mainline branch.')\n else\n opts[:prepush].call if opts[:prepush]\n\n push(remote.name, local_branch, remote_branch, :force => opts[:force])\n\n opts[:postpush].call if opts[:postpush]\n end\n end", "def cmds\n pry(Git::Multi::Commands)\nend", "def command_uri\n return \"/api_#{@command_name}.php\"\n end", "def build_remote_cmd cmd, options={}\n cmd = sh_cmd cmd\n cmd = env_cmd cmd\n cmd = sudo_cmd cmd, options\n cmd = ssh_cmd cmd, options\n end", "def git_on(host, git_sub_command, git_repo_path, opts = {})\n git_command = \"git --git-dir=#{git_repo_path}/.git --work-tree=#{git_repo_path} #{git_sub_command}\"\n\n on(host, git_command, opts)\nend", "def push\n unless system(\"cd #{repo_path};git push origin #{branch}\")\n raise GitCloud::GitException.new(\"Push\")\n end\n end", "def remote\n hg('paths').scan(/^(?:default|default-push)\\s+=\\s+(\\S.*)/).map{ |match| match.last }\n end", "def test_no_gitgo_no_remote_gitgo\n assert !sh(b, 'git branch -a').include?('gitgo')\n \n sh(b, 'git branch gitgo')\n sh(b, 'git checkout gitgo')\n method_root.prepare(b, \"shasum\") {|io| io << \"content\" }\n sh(b, 'git add shasum')\n sh(b, 'git commit -m \"added document\"')\n \n sh(b, 'git checkout master')\n sh(b, 'git push origin gitgo')\n \n assert sh(b, 'git branch').include?('gitgo') \n assert sh(a, 'git branch').include?('gitgo')\n \n sh(a, 'git checkout gitgo')\n assert_equal \"content\", File.read(method_root.path(a, \"shasum\"))\n end", "def execute\n if (!self.pull_request_id)\n current = GitHub::PullRequest.current\n self.pull_request_id = current.number if current\n end\n self.pull_request_id ||= cli.prompt(\"Pull Request ID: \")\n GitHub.connect do\n if config.deployable_label\n with_labelling do\n merge\n end\n else\n merge\n end\n end\n end", "def call(*command); end", "def commands\n\t\t\t\t{\n\t\t\t\t\t'notify_pushover_help'\t\t\t\t\t=> \"Displays help\",\n\t\t\t\t\t'notify_pushover_start'\t\t\t\t\t=> \"Start notify_pushoverer plugin after saving settings.\",\n\t\t\t\t\t'notify_pushover_stop'\t\t\t\t\t=> \"Stop notifying for new sessions.\",\n\t\t\t\t\t'notify_pushover_test'\t\t\t\t\t=> \"Send test message to make sure configuration is working.\",\n\t\t\t\t\t'notify_pushover_save'\t\t\t\t\t=> \"Save Settings to YAML File #{Notify_pushover_yaml}.\",\n\t\t\t\t\t'notify_pushover_set_app_key'\t\t\t=> \"Sets pushover app API key.\",\n\t\t\t\t\t'notify_pushover_set_user_key'\t \t\t=> \"Sets pushover user(s) key.\",\n\t\t\t\t\t'notify_pushover_show_parms'\t\t\t=> \"Shows currently set parameters.\"\n\t\t\t\t}\n\t\t\tend", "def command\n raise NotImplementedError, \"`command' is not implemented by #{self.class.name}\"\n end", "def git(*args)\n system \"git \" + args.join(\" \")\nend", "def subcommands(cmd); end", "def subcommands(cmd); end", "def pull\n fetch\n merge\n end" ]
[ "0.68151647", "0.622344", "0.6195468", "0.6187363", "0.6181452", "0.6162007", "0.61189204", "0.60621804", "0.60489327", "0.59954864", "0.5980596", "0.59374505", "0.5903741", "0.5845923", "0.58328164", "0.58097005", "0.5806688", "0.57864654", "0.5780313", "0.57355386", "0.5712109", "0.56703746", "0.5664317", "0.5663183", "0.56474763", "0.5643905", "0.56357336", "0.5633922", "0.5633344", "0.5624022", "0.5617171", "0.56105864", "0.5610226", "0.5610226", "0.5610226", "0.5610226", "0.5610226", "0.5610226", "0.5603464", "0.55928314", "0.5582172", "0.55592626", "0.5557331", "0.55515516", "0.55439514", "0.5541264", "0.55288285", "0.55278116", "0.5522763", "0.55208576", "0.55169576", "0.55066335", "0.5491179", "0.5490362", "0.54780126", "0.54665697", "0.544561", "0.5444182", "0.5443296", "0.54411936", "0.54367286", "0.5435248", "0.5426313", "0.54204863", "0.5418285", "0.54173595", "0.54143846", "0.5405114", "0.538164", "0.53680784", "0.535662", "0.53528786", "0.5351042", "0.5349286", "0.5343778", "0.5337399", "0.5336394", "0.5331445", "0.5327489", "0.53239125", "0.5317031", "0.5309596", "0.53083444", "0.5289863", "0.52884865", "0.5287987", "0.5284631", "0.52842736", "0.5275971", "0.5270168", "0.52700645", "0.5265583", "0.5264427", "0.52581817", "0.5253867", "0.52506864", "0.5245283", "0.52440315", "0.52381593", "0.52381593", "0.523772" ]
0.0
-1
Each path is expanded, since these refer to local paths and are being shellquoted. This will also remove any trailing `/` from each path, as we don't want rsync's "trailing / on source directories" behavior. This method is used by RSync::Local and RSync::Push.
def paths_to_push directories.map { |dir| "'#{File.expand_path(dir)}'" }.join(" ") end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def relativize_paths(paths)\n return paths unless relativize_paths?\n paths.map do |path|\n path.gsub(%r{^#{@directory}/}, '')\n end\n end", "def cleanup_paths(*paths)\n #.gsub(%r{#{@locations[:root]}/#{@locations[:root]}}, @locations[:root])\n paths.join('/').gsub(/[\\/]{2,}/,'/')\n end", "def expand_all path\n real_path = VirtualLayer.realpath(path)\n elems = real_path.split('/'); elems.shift # throw away the first element which is empty for a FQ pathname\n if path[-1] == '/'\n filt_fn = ->(p) { VirtualLayer.directory?(p) }\n else\n filt_fn = ->(p) { p }\n end\n result = rejoin(walk_globs(elems)).flatten.select(&filt_fn).sort\n\n if path[0] == '/'\n result\n else\n cwd = VirtualLayer.pwd\n result.map {|p| p[(cwd.length+1)..] }\n end\nend", "def join_paths(paths)\n paths.join('/').gsub(%r{/+}, '/')\n end", "def normalize_paths(paths)\n # do the hokey-pokey of path normalization...\n paths = paths.collect do |path|\n path = path.\n gsub(\"//\", \"/\"). # replace double / chars with a single\n gsub(\"\\\\\\\\\", \"\\\\\"). # replace double \\ chars with a single\n gsub(%r{(.)[\\\\/]$}, '\\1') # drop final / or \\ if path ends with it\n\n # eliminate .. paths where possible\n re = %r{[^/\\\\]+[/\\\\]\\.\\.[/\\\\]}\n path.gsub!(re, \"\") while path.match(re)\n path\n end\n\n # start with longest path, first\n paths = paths.uniq.sort_by { |path| - path.length }\n end", "def join_paths(*args)\n paths = []\n full_path = []\n temp_paths = []\n args.each {|x| temp_paths << x }\n temp_paths.flatten!\n temp_paths.each do |x|\n unless x.nil?\n paths << x.to_s.dup\n end\n end\n if paths[0].start_with?('/')\n absolute_path = true\n else\n absolute_path = false\n end\n paths.each do |path|\n unless path.nil?\n path.strip!\n path.slice!(0) while path.start_with?('/')\n path.chop! while path.end_with?('/')\n full_path << path\n end\n end\n full_path_string = full_path.join('/')\n full_path_string.slice!(0) while full_path_string.start_with?('/')\n full_path_string.chop! while full_path_string.end_with?('/')\n full_path_string.insert(0, '/') if absolute_path == true\n full_path_string\n end", "def remove_leading_slash(path); end", "def mungle_paths(paths)\n return paths if terraform.pre_0_12?\n\n paths.map do |path|\n File.directory?(path) ? path : File.dirname(path)\n end.uniq\n end", "def normalize_paths(paths)\n paths = [paths] unless paths.is_a?(Array)\n paths.map(&:dup).map do |path|\n raise ArgumentError.new(\"Invalid path: #{path}\") unless valid_path?(path)\n # Strip leading slash from extension path\n path.gsub!(/^\\/(?=\\*.)/, '')\n # Escape some valid special characters\n path.gsub!(/[.+$\"]/) {|s| '\\\\' + s}\n # Replace * wildcards with .* regex fragment\n path.gsub!(/\\*/, '.*')\n \"^#{path}#{END_URL_REGEX}\"\n end\nend", "def cleanpath_aggressive\n path = @path\n names = []\n pre = path\n while r = chop_basename(pre)\n pre, base = r\n case base\n when '.'\n when '..'\n names.unshift base\n else\n if names[0] == '..'\n names.shift\n else\n names.unshift base\n end\n end\n end\n if File.basename(pre).include? '/'\n names.shift while names[0] == '..'\n end\n Path.new(prepend_prefix(pre, File.join(*names)))\n end", "def cleanpath\n names = []\n split('/').each do |name|\n case name\n when '..'\n names.pop\n when '.'\n when ''\n else\n names.push name\n end\n end\n names.join('/')\n end", "def paths_to_pull\n sep = mode == :ssh ? \":\" : \"::\"\n directories.map do |dir|\n \"#{sep}'#{dir.sub(%r{^~/}, \"\").sub(%r{/$}, \"\")}'\"\n end.join(\" \").sub(%r{^#{sep}}, \"\")\n end", "def adjust_rsync_path(path)\n path.gsub(/^(\\w):/) { \"/cygdrive/#{$1}\" }\n end", "def cleanpath\n path = @path\n names = []\n pre = path\n while r = chop_basename(pre)\n pre, base = r\n case base\n when '.'\n when '..'\n names.unshift base\n else\n if names[0] == '..'\n names.shift\n else\n names.unshift base\n end\n end\n end\n if /#{SEPARATOR_PAT}/o =~ File.basename(pre)\n names.shift while names[0] == '..'\n end\n self.class.new(prepend_prefix(pre, File.join(*names)))\n end", "def sanitized_path(*paths)\n safe_paths = paths.map do | path_name |\n path_name.strip.tap do |name|\n # Finally, replace all non alphanumeric, underscore\n # or periods with underscore\n name.gsub! /[^\\w\\-]/, '_'\n end\n end\n\n File.join(safe_paths)\n end", "def expand_path(path)\n if Rscons.phony_target?(path)\n path\n elsif path.is_a?(Array)\n path.map do |path|\n expand_path(path)\n end\n else\n path.sub(%r{^\\^\\^(?=[\\\\/])}, Rscons.application.build_dir).sub(%r{^\\^(?=[\\\\/])}, @build_root).gsub(\"\\\\\", \"/\")\n end\n end", "def remove_extra_slashes\n self.home = StringConstructor.sanitized_filepath self.home\n end", "def scrub_path(p)\n np = \"\"\n for i in 0..(p.size-1)\n c = p[i]\n if c == '/'\n c = '\\\\'\n end\n np += c\n end\n np\nend", "def unify_path(s)\r\n p = s.frozen? ? s.dup : s\r\n p.gsub!( /\\\\/, '/' )\r\n p = \"#{$1.upcase}/#{$POSTMATCH}\" if p =~ REGEX_DISK\r\n if RUBY_PLATFORM =~ REGEX_CYGWIN\r\n\tif p =~ REGEX_CYGDRIVE\r\n\t p = \"/cygdrive/#{$1.upcase}/#{$POSTMATCH}\" \r\n\telse\r\n\t p.sub!( REGEX_DISK2, '/cygdrive/\\1/' ) if @name == 'PATH'\r\n\tend\r\n end\r\n return p\r\n end", "def transform_paths(attrs)\n [:stdout_logfile, :stderr_logfile].each do |key|\n value = attrs.send key\n path = Pathname.new(value)\n next if value.empty? || path.absolute?\n new_value = \"#{attrs.working_dir}/#{path}\"\n attrs.send \"#{key}=\".to_sym, new_value\n end\n end", "def sanitize_path(path)\n # joining (e.g. `foo + \"/\" + bar`)\n path = path.gsub(%r{^/+}, \"/\")\n\n # remove leading and trailing slash\n path.sub(%r{^/}, \"\").sub(%r{/$}, \"\")\n end", "def clean_path(directory)\n directory.gsub(/\\/\\//, '/')\n end", "def join_path(path)\n if path.include?('\\\\') && path.include?('/')\n path.gsub('\\\\', '/')\n else\n path\n end\n end", "def sanitize_path(path)\n # joining (e.g. `foo + \"/\" + bar`)\n path = path.gsub(/^\\/+/, '/')\n\n # remove leading and trailing slash\n return path.sub(/^\\//, '').sub(/\\/$/, '')\n end", "def simplify_path(path)\n stack = []\n result = ''\n\n path.split('/').each do |dir|\n if dir == '' || dir == '.'\n next\n elsif dir == '..'\n stack.pop()\n else\n stack.push(dir)\n end\n end\n\n while stack.length > 0\n result = '/' + stack.pop() + result\n end\n\n return '/' if result == ''\n\n result\nend", "def escape_dirname\n mgsub( [ [/[\\s\\:\\)\\(\\?\\,]+/, \"-\"], [/\\*/, \"star\"] ] )\n end", "def unglobify(glob)\n chars = glob.split(\"\")\n\n chars = smoosh(chars)\n\n curlies = 0\n escaping = false\n string = chars.map do |char|\n if escaping\n escaping = false\n char\n else\n case char\n when \"**\"\n \"([^/]+/)*\"\n when '*'\n \".*\"\n when \"?\"\n \".\"\n when \".\"\n \"\\.\"\n\n when \"{\"\n curlies += 1\n \"(\"\n when \"}\"\n if curlies > 0\n curlies -= 1\n \")\"\n else\n char\n end\n when \",\"\n if curlies > 0\n \"|\"\n else\n char\n end\n when \"\\\\\"\n escaping = true\n \"\\\\\"\n else\n char\n end\n end\n end\n\n '(\\A|\\/)' + string.join + '\\Z'\n end", "def simplify_path(path)\n path_tokens = path.split(\"/\").reject{ |x| x.empty? || x == \".\" }\n stack = []\n path_tokens.each{ |x|\n if x == \"..\"\n stack.pop if stack.any?\n else\n stack.push(x)\n end\n }\n\n \"/\" << stack.join(\"/\")\nend", "def toPathList(arr); arr.join(File::PATH_SEPARATOR) end", "def normalize(path)\n path.gsub(/\\\\/, \"/\")\n end", "def _SplitAndJoinParts(path, pop) \n pathParts = path.split(\"/\")[0..-(pop+1)]\n \n result = JoinPaths(pathParts)\n \n # we face an absolute linux part\n if(path.start_with?(\"/\"))\n result = \"/\" + result\n end\n \n return result\n end", "def clean_path(path)\n if path\n (path[0] != '/' ? path.insert(0, '/') : path).gsub(/\\/{2,}/, '/')\n end\n end", "def normalize_path(path)\n path = \"/#{path}\"\n path.squeeze!('/')\n path.sub!(%r{/+\\Z}, '')\n path = '/' if path == ''\n path\n end", "def clean_path(path)\n\t\t\tif @posix_support\n\t\t\t\treturn path\n\t\t\telse\n\t\t\t\treturn path.gsub(/\\//,'\\\\')\n\t\t\tend\n\t\tend", "def relative_path(path)\n # replace array referenced IN the path\n first_pass = path.gsub(/\\/([^\\/]+)\\[\\d+\\]\\//i,\"/*/\")\n # replace array references AT THE END of the path too\n first_pass.gsub(/\\/([^\\/]+)\\[\\d+\\]$/,\"/*\")\n end", "def clean_path_info(path_info)\n parts = path_info.split(PATH_SEPS)\n\n clean = []\n\n # Walk over each part of the path\n parts.each do |part|\n # Turn `one//two` or `one/./two` into `one/two`.\n next if part.empty? || part == \".\"\n\n if part == \"..\"\n # Turn `one/two/../` into `one`\n clean.pop\n else\n # Add simple folder names to the clean path.\n clean << part\n end\n end\n\n # If the path was an absolute path (i.e. `/` or `/one/two`),\n # add `/` to the front of the clean path.\n clean.unshift \"/\" if parts.empty? || parts.first.empty?\n\n # Join all the clean path parts by the path separator.\n ::File.join(*clean)\n end", "def join(*args)\n args.unshift self\n result = args.pop\n result = VirtualPath.new(result) unless VirtualPath === result\n return result if result.absolute?\n args.reverse_each {|arg|\n arg = VirtualPath.new(arg) unless VirtualPath === arg\n result = arg + result\n return result if result.absolute?\n }\n result\n end", "def normalize_path(path)\n path.sub(%r{^/}, '').tr('', '')\n end", "def chop_leading_slash filename\n filename.sub %r{^/}, \"\"\n end", "def reduce_path(path)\n if path =~ /^(https?:\\/\\/.+)(\\/.*)/\n prefix = $1\n path = $2\n relative = false\n else\n prefix = nil\n relative = path[0] != '/'\n end\n\n while path.sub!(/\\/*[^\\/]+\\/+\\.\\./, ''); end\n while path.sub!(/\\/+\\.\\/+/, '/'); end\n path = path[2..-1] if path[0..1] == './'\n while path.sub!(/\\/\\//, '/'); end\n\n path = path[1..-1] if relative and path[0] == '/'\n path = prefix + path if prefix\n path\n end", "def normalize_path(path)\n path = \"/#{path}\"\n path.squeeze!('/')\n path.sub!(%r{/+\\Z}, '')\n path = '/' if path == ''\n path\n end", "def clean_path(*args)\n path = File.join(args.to_a.compact)\n Pathname.new(path).cleanpath.to_s\n end", "def to_local(path)\n local_abs_paths = []\n path.to_s.split(/\\s+/).each do |p|\n if p =~ /^#{remote}/\n p.sub!(/^#{remote}/, '')\n p.slice!(0) if p =~ /^\\//\n p = \"#{local}/#{p}\"\n else\n if Pathname.new(p).absolute?\n # No action required\n else\n p = \"#{local}/#{p}\"\n end\n end\n local_abs_paths << p\n end\n local_abs_paths\n end", "def rsync_path_escape( path )\n if (@os == :mac)\n # '\"' + path + '\"'\n path\n else\n # Adapt to other OSs if necessary\n # '\"' + path + '\"'\n path\n end\n end", "def expand_path(subpath)\n if subpath[0] == ALT_SEPARATOR\n result = []\n else\n result = pwd.dup\n end\n\n if subpath.include?(ALT_SEPARATOR) || subpath =~ NAVIGATION\n # filesystem-like subpath\n # apply Unix-style directory navigation shortcuts\n # ge rid of successive //// and other oddities\n pieces = subpath.split(ALT_SEPARATOR).select { |p| !p.nil? && !p.empty? }\n pieces.each do |piece|\n case piece\n when '..' then result.pop\n when '.' then nil\n else result.push(piece)\n end\n end\n\n CMDB.join(result)\n else\n # standard dotted notation\n # get rid of successive .... and other oddities\n pieces = CMDB.split(subpath).select { |p| !p.nil? && !p.empty? }\n result += pieces\n end\n\n CMDB.join(result)\n end", "def join(*args)\n args.unshift self\n result = Path.new(args.pop)\n return result if result.absolute?\n args.reverse_each { |arg|\n arg = Path.new(arg)\n result = arg / result\n return result if result.absolute?\n }\n result\n end", "def relative!\n @string.gsub!(/(?<!:)#{separator * 2}/, separator)\n @string[/\\A#{separator}|^/] = \"\"\n\n self\n end", "def uniPath(source)\n source.gsub(/\\\\/, File::SEPARATOR)\nend", "def shorten_paths(string_with_paths)\n $LOAD_PATH.inject(string_with_paths) { |string, base_path| string.gsub(base_path.chomp('/'), '…') }\n end", "def cleaned_relative_path\n @cleaned_relative_path ||=\n relative_path[0..-extname.length - 1]\n .sub(collection.relative_directory, \"\")\n .gsub(%r!\\.*\\z!, \"\")\n end", "def simplify_path(path)\n return '' if path.empty?\n\n start_with_slash = path[0] == '/'\n stack = []\n stack << '' if start_with_slash\n tokens = path.split('/')\n tokens.each do |token|\n case token\n when '..'\n stack.pop if stack[-1] != ''\n\n when '.', ''\n next\n else\n stack.push token\n end\n end\n\n return '/' if stack.length == 1 && stack[0] == ''\n\n stack.join('/')\nend", "def expanded\n raise \"You need to set a path root\" unless @root.path\n result = []\n\n each do |path|\n path = File.expand_path(path, @root.path)\n\n if @glob && File.directory?(path)\n result.concat files_in(path)\n else\n result << path\n end\n end\n\n result.uniq!\n result\n end", "def prepare(path)\n path.delete_prefix('/').gsub(%r{//}, '/').gsub(%r{/+\\z}, '')\n end", "def clean_paths\n cached_used = used_files\n glob_options = File::FNM_DOTMATCH | File::FNM_CASEFOLD\n files = Pathname.glob(root + \"**/*\", glob_options).map(&:to_s)\n\n files.reject! do |candidate|\n candidate = candidate.downcase\n candidate.end_with?('.', '..') || cached_used.any? do |path|\n path = path.downcase\n path.include?(candidate) || candidate.include?(path)\n end\n end\n files\n end", "def windows_safe_path(*pieces)\n path = File.join(*pieces)\n\n if File::ALT_SEPARATOR\n path.gsub(File::SEPARATOR, File::ALT_SEPARATOR)\n else\n path\n end\n end", "def unslashed(path)\n path.sub! /\\/$/, '' if path.end_with? '/'\n return path\n end", "def win_slashify(path)\n path.gsub(File::SEPARATOR, (File::ALT_SEPARATOR || '\\\\'))\n end", "def collect_paths(*paths)\n raw = [] # all paths and globs\n plus = Set.new # all paths to expand and add\n minus = Set.new # all paths to remove from plus set\n\n # assemble all globs and simple paths, reforming our glob notation to ruby globs\n paths.each do |paths_container|\n case (paths_container)\n when String then raw << (FilePathUtils::reform_glob(paths_container))\n when Array then paths_container.each {|path| raw << (FilePathUtils::reform_glob(path))}\n else raise \"Don't know how to handle #{paths_container.class}\"\n end\n end\n\n # iterate through each path and glob\n raw.each do |path|\n\n dirs = [] # container for only (expanded) paths\n\n # if a glob, expand it and slurp up all non-file paths\n if path.include?('*')\n # grab base directory only if globs are snug up to final path separator\n if (path =~ /\\/\\*+$/)\n dirs << FilePathUtils.extract_path(path)\n end\n\n # grab expanded sub-directory globs\n expanded = @file_wrapper.directory_listing( FilePathUtils.extract_path_no_aggregation_operators(path) )\n expanded.each do |entry|\n dirs << entry if @file_wrapper.directory?(entry)\n end\n\n # else just grab simple path\n # note: we could just run this through glob expansion but such an\n # approach doesn't handle a path not yet on disk)\n else\n dirs << FilePathUtils.extract_path_no_aggregation_operators(path)\n end\n\n # add dirs to the appropriate set based on path aggregation modifier if present\n FilePathUtils.add_path?(path) ? plus.merge(dirs) : minus.merge(dirs)\n end\n\n return (plus - minus).to_a.uniq\n end", "def canonical_path\n p = path.gsub(/\\/+/,'/')\n p.length > 1 ? p.chomp('/') : p\n end", "def relativize_path(path)\n path.to_s.gsub(/^\\/?#{Regexp.escape(root_path.to_s)}\\/?/, '')\n end", "def sanitize_path(path)\n newpath = path.gsub(/\\/+/, '/')\n while newpath.gsub!(%r{([^/]+)/\\.\\./?}) { |match|\n $1 == '..' ? match : ''\n } do end\n newpath.gsub(%r{/\\./}, '/').sub(%r{/\\.\\z}, '/')\n end", "def force_trailing_slash\n force_slash :slash\n end", "def force_no_trailing_slash\n force_slash :noslash\n end", "def path_as_r_glob\n path.map {|p| \"#{p}/**/#{self.base_as_r}\"}\n end", "def clean_path(path)\n parts = []\n parts = path.split SEPS\n clean = []\n parts.each do |part|\n next if part.empty? || part == '.'\n part == '..' ? clean.pop : clean << part\n end\n @path = File.join(*clean)\n end", "def expand_path( path )\n File.expand_path( path.gsub( /^\\/+/, '' ), self.link.path.gsub( /\\/*$/, '/' ) ).gsub( /^C:/, '')\n end", "def local_directories\n settings[:input].map do |dir|\n File.join(File.expand_path(dir.to_s), \"\") # always use a trailing '/' with s3cmd\n end\n end", "def path_expanded path\n end", "def normalize_path(path); end", "def normalize_path(path); end", "def merge_path(base, rel)\n\n # RFC2396, Section 5.2, 5)\n # RFC2396, Section 5.2, 6)\n base_path = split_path(base)\n rel_path = split_path(rel)\n\n # RFC2396, Section 5.2, 6), a)\n base_path << '' if base_path.last == '..'\n while i = base_path.index('..')\n base_path.slice!(i - 1, 2)\n end\n\n if (first = rel_path.first) and first.empty?\n base_path.clear\n rel_path.shift\n end\n\n # RFC2396, Section 5.2, 6), c)\n # RFC2396, Section 5.2, 6), d)\n rel_path.push('') if rel_path.last == '.' || rel_path.last == '..'\n rel_path.delete('.')\n\n # RFC2396, Section 5.2, 6), e)\n tmp = []\n rel_path.each do |x|\n if x == '..' &&\n !(tmp.empty? || tmp.last == '..')\n tmp.pop\n else\n tmp << x\n end\n end\n\n add_trailer_slash = !tmp.empty?\n if base_path.empty?\n base_path = [''] # keep '/' for root directory\n elsif add_trailer_slash\n base_path.pop\n end\n while x = tmp.shift\n if x == '..'\n # RFC2396, Section 4\n # a .. or . in an absolute path has no special meaning\n base_path.pop if base_path.size > 1\n else\n # if x == '..'\n # valid absolute (but abnormal) path \"/../...\"\n # else\n # valid absolute path\n # end\n base_path << x\n tmp.each {|t| base_path << t}\n add_trailer_slash = false\n break\n end\n end\n base_path.push('') if add_trailer_slash\n\n return base_path.join('/')\n end", "def sanitize_file_path(entry)\n parts = entry.name.split(File::SEPARATOR)\n parts.shift\n parts.join(File::SEPARATOR)\n end", "def ensure_leading_slash(path); end", "def trim(path)\n path.to_s.sub(/^\\/*/, \"\")\n end", "def sanitize_path\n gsub(/[\\/: ]/,'_')\n end", "def sanitized_dirname\n @remote.gsub(/[^@\\w\\.-]/, '-')\n end", "def normalize_paths\n new_sass = \"\"\n sass.each_line do |line|\n line = SassLine.new(@epub, self, line)\n line.normalize_paths if line.has_path?\n new_sass += \"#{line.to_s}\\n\"\n end\n\n self.sass = new_sass\n end", "def clean_path(path)\n path.sub(/^\\//,'')\n end", "def normalize_path(p) # NOTE BOOTSTRAP: was action::base::escape_windows_path\n p.tr(\"\\\\\", \"/\")\n end", "def sanitize(path_array)\n path_array.map do |path|\n path = path.gsub(/{(.*) => (.*)}/, '\\2')\n path.strip\n end\n end", "def omit_slashes\n omit_leading_slash\n .omit_trailing_slash\n end", "def windows_safe_path_join(*args)\n ::File.join(args).gsub(::File::SEPARATOR, ::File::ALT_SEPARATOR || File::SEPARATOR)\nend", "def expand(path)\n (root_path/trim(path)).to_s\n end", "def collect_path_string(dir_set)\n path = \"/\"\n dir_set.each { |dir| path += \"#{dir}/\" }\n path\n end", "def rto(a, b)\n\tPathname.new(File.join a, '..', b).cleanpath.to_s\nend", "def relative_non_audio_file_paths\n absolute_non_audio_file_paths.map { |p| p.sub(\"#{path.dirname}/\", \"\") }\n end", "def sanitize_path path\n require 'pathname'\n dot = Pathname.new('.').expand_path\n\n path.reject do |item|\n path = Pathname.new(item).expand_path\n is_reject = nil\n relative = nil\n begin\n relative = path.relative_path_from(dot).to_s\n rescue ArgumentError\n # On Windows, sometimes crosses different drive letters.\n is_reject = true\n else\n is_reject = relative.start_with? '..'\n end\n is_reject\n end\n end", "def munge(value)\n if value.is_a?(String) && value =~ /[\\\\\\/]$/\n @path_ends_with_slash = true\n end\n super\n end", "def normalize_path(path)\n return '' if path.eql? '<>'\n path =~ PATH\n $~[1].to_s.downcase + normalize_local_part($~[9]) + \"@\" + $~[12].downcase\n end", "def simplify_path(str)\n directory_names = str.split('/')\n stack = Stack.new\n\n directory_names.each do |name|\n next if name == '.' || name.empty?\n next stack.pop if name == '..'\n stack.push(\"/#{name}\")\n end\n\n result = ''\n until stack.empty?\n result.prepend(stack.pop || '')\n end\n result == '' ? '/' : result\nend", "def sanitize_path(path)\n path.gsub(/\\.\\.(?=$|\\/)/, '') unless path.nil?\n end", "def strip_slashes\n self.gsub(/(^\\/|\\/$)/,'')\n end", "def join_and_expand_path(*parts)\n File.expand_path(File.join(parts))\n end", "def paths\n names = Array.new\n each_tarball_entry { |entry| names << Pathname.new(entry).cleanpath.to_s }\n names - ['.']\n end", "def convert_glob_to_absolute(glob); end", "def Join(paths)\n pathsToJoin = [@RelativePath]\n if(paths.respond_to?(:length))\n paths.each do |path|\n pathsToJoin.concat(path.RelativePath)\n end \n else\n pathsToJoin.push(paths.RelativePath)\n end\n \n copy = CreateCopy()\n copy.RelativePath = JoinPaths(pathsToJoin)\n \n return copy\n end", "def path_join(base, path)\n return path if path_is_absolute(path)\n base.gsub(/[\\/]+$/, '') + '/' + path.gsub(/^[\\/]+/, '')\n end", "def omnibus_expand_path(*paths)\n dir = File.expand_path(File.join(paths))\n dir = \"\" unless dir && File.directory?(dir)\n dir\nend", "def path(*elements) #Create a path from the elements\n#-------------------------------------------------------------------------------\n path=elements.join('/').strip #Remove leading and trailing whitespace\n while path.gsub!('//','/'); end #Remove duplicate slashes\n return path\nend", "def without_slashes\n self.\n without_leading_slash.\n without_trailing_slash\n end" ]
[ "0.6812318", "0.6662711", "0.64938563", "0.64875567", "0.6461957", "0.64167035", "0.6322109", "0.6319573", "0.62081707", "0.6161062", "0.61464655", "0.6045176", "0.6031419", "0.5928399", "0.5923", "0.59223986", "0.5892843", "0.5880533", "0.58543104", "0.5844329", "0.58434963", "0.5843389", "0.58405536", "0.5804338", "0.57693744", "0.5763129", "0.5751334", "0.56660104", "0.5661061", "0.5650678", "0.56308866", "0.56168467", "0.5586977", "0.5584477", "0.5578709", "0.5572574", "0.5572352", "0.55604213", "0.5554822", "0.555279", "0.554332", "0.55309385", "0.5525277", "0.5523345", "0.5517749", "0.55167466", "0.5510466", "0.55090636", "0.5505657", "0.55011433", "0.5499409", "0.5487085", "0.54821324", "0.5478764", "0.5476069", "0.54704505", "0.54688334", "0.5465154", "0.54536873", "0.54478765", "0.54305893", "0.54218775", "0.5419579", "0.54122686", "0.5409444", "0.5404414", "0.5401786", "0.5389727", "0.53716284", "0.53716284", "0.5371454", "0.53641593", "0.5359292", "0.5354469", "0.5352748", "0.53523767", "0.534907", "0.534714", "0.5347135", "0.53443366", "0.53395206", "0.53378695", "0.5329875", "0.5327893", "0.5307951", "0.5306908", "0.53042305", "0.53033507", "0.5282311", "0.5277713", "0.5276924", "0.52707034", "0.5262051", "0.525806", "0.52451134", "0.5238297", "0.5230634", "0.5226557", "0.52182883", "0.5217168" ]
0.5694741
27
Return the number of positive amino acids (R and K) in an AA sequence.
def num_pos @num_neg ||= @seq.count("RK") end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def acidic_count(amino_acid_sequence)\n count = 0\n comp = amino_acid_sequence.composition\n ACIDIC_AMINO_ACIDS.each do |acidic|\n if comp[acidic]\n count += comp[acidic]\n end\n end\n return count\n end", "def basic_count(amino_acid_sequence)\n count = 0\n comp = amino_acid_sequence.composition\n BASIC_AMINO_ACIDS.each do |basic|\n if comp[basic]\n count += comp[basic]\n end\n end\n return count\n end", "def amino_acid_number\n @seq.length\n end", "def score_aces(cards_aces, score_without_aces)\n # first, assume all \"ace\" cards score as 1\n aces_count = cards_aces.count\n return 0 if aces_count.zero?\n\n # check if we can convert one ace card to 11\n if (score_without_aces + aces_count <= 11)\n 11 + (aces_count - 1)\n else\n # all ace cards still score as 1\n aces_count\n end\n end", "def isDNA?(fasta)\n seq = File.read(fasta, 10000).split(\"\\n\").grep(/^[^>]/).join\n seq.upcase.count(\"ACTGNU\").to_f / seq.upcase.count(\"ACDEFGHIKLMNPQRSTVWYZ\") > 0.90\nend", "def isDNA?(fasta)\n seq = File.read(fasta, 10000).split(\"\\n\").grep(/^[^>]/).join\n seq.upcase.count(\"ACTGNU\").to_f / seq.upcase.count(\"ACDEFGHIKLMNPQRSTVWYZ\") > 0.90\nend", "def countAtoms(seq)\n\t\t\t\to = 0\n\t\t\t\tn = 0\n\t\t\t\tc = 0\n\t\t\t\th = 0\n\t\t\t\ts = 0\n\t\t\t\tp = 0\n\t\t\t\tse = 0\n\t\t\t\tseq.each_char do |aa|\n\t\t\t\t\to = o + MS::Feature::AA::ATOM_COUNTS[aa][:o]\n\t\t\t\t\tn = n + MS::Feature::AA::ATOM_COUNTS[aa][:n]\n\t\t\t\t\tc = c + MS::Feature::AA::ATOM_COUNTS[aa][:c]\n\t\t\t\t\th = h + MS::Feature::AA::ATOM_COUNTS[aa][:h]\n\t\t\t\t\ts = s + MS::Feature::AA::ATOM_COUNTS[aa][:s]\n\t\t\t\t\tp = p + MS::Feature::AA::ATOM_COUNTS[aa][:p]\n\t\t\t\t\tse = se + MS::Feature::AA::ATOM_COUNTS[aa][:se]\n\t\t\t\tend\n\t\t\t\treturn o,n,c,h,s,p,se\n\t\t\tend", "def amino_acid (bases)\n case bases\n when /^TT[TCY]$/\n return \"F\"\n when /^TT[AGR]$/\n return \"L\"\n when /^CT.$/\n return \"L\"\n when /^AT[TCAHYWM]$/\n return \"I\"\n when \"ATG\"\n return \"M\"\n when /^GT.$/\n return \"V\"\n when /^TC.$/\n return \"S\"\n when /^CC.$/\n return \"P\"\n when /^AC.$/\n return \"T\"\n when /^GC.$/\n return \"A\"\n when /^TA[TCY]$/\n return \"Y\"\n when /^TA[AGR]$/\n return \"*\"\n when /^T[GR]A$/\n return \"*\"\n when /^CA[TCY]$/\n return \"H\"\n when /^CA[AGR]$/\n return \"Q\"\n when /^AA[TCY]$/\n return \"N\"\n when /^AA[AGR]$/\n return \"K\"\n when /^GA[TCY]$/\n return \"D\"\n when /^GA[AGR]$/\n return \"E\"\n when /^TG[TCY]$/\n return \"C\"\n when \"TGG\"\n return \"W\"\n when /^CG.$/\n return \"R\"\n when /^AG[TCY]$/\n return \"S\"\n when /^[AM]G[AGR]$/\n return \"R\"\n when /^GG.$/\n return \"G\"\n when /^[ATW][CGS][CTY]$/\n return \"S\"\n when /^[TCY]T[AGR]$/\n return \"L\"\n else\n return \"#\"\n end\n end", "def calculate_total(cards)\n\tarr = cards.map { |e| e[1] }\n\n\ttotal = 0\n\tarr.each do |value|\n\t\tif value == 'A'\n\t\t\ttotal += 11\n\t\telsif value.to_i == 0 #only works for J, Q, K\n\t\t\ttotal += 10\n\t\telse\n\t\t\ttotal += value.to_i\n\t\tend\n\tend\n\t#Code to make Aces work\n\tarr.select{|e| e == \"A\"}.count.times do\n\t\ttotal -=10 if total > 21\n\tend\n\n\tif arr.include?(\"A\") && total > 21\n\t\ttotal -= 10\n\tend\n\n\ttotal\nend", "def get_hand_score\n score = 0\n \n # Add up score of non-aces\n values = hand.map{|card| card.value}\n values.each do |val|\n if Array(2..10).include?(val.to_i)\n score += val.to_i\n elsif [\"J\", \"Q\", \"K\"].include?(val)\n score += 10\n end\n end\n\n # deal with the aces\n values.count(\"A\").times do\n if score + 11 <= 21\n score += 11\n else\n score += 1\n end\n end\n\n return score\n end", "def calculate_total(cards)\r\n\ttotal = 0\r\n\tarr = cards.map {|e| e[1]}\r\n\tarr.each do |val|\r\n\t\tif val == 'A'\r\n\t\t\ttotal += 11\r\n\t\telsif val.to_i == 0 # J,Q,K\r\n\t\t\ttotal += 10\r\n\t\telse \r\n\t\t\ttotal += val.to_i\r\n\t\tend\r\n\tend\r\n\r\n\t#correct for aces\r\n\tarr.select {|e| e=='A'}.count.times do\r\n\t\ttotal -= 10 if total > 21\r\n\tend\r\n\r\n\ttotal\r\nend", "def residue_count\n counted = []\n # N-terminal\n n_term = @seq[0].chr\n if PK[:nterm].key? n_term.to_sym\n counted << {\n :num => 1,\n :residue => n_term.to_sym,\n :pK => PK[:nterm][n_term.to_sym],\n :positive => positive?(n_term)\n }\n elsif PK[:normal].key? n_term.to_sym\n counted << {\n :num => 1,\n :residue => n_term.to_sym,\n :pK => PK[:normal][n_term.to_sym],\n :positive => positive?(n_term)\n }\n end\n # Internal\n tmp_internal = {}\n @seq[1,(@seq.length-2)].each_byte do |x|\n aa = x.chr.to_sym\n if PK[:internal].key? aa\n if tmp_internal.key? aa\n tmp_internal[aa][:num] += 1\n else\n tmp_internal[aa] = {\n :num => 1,\n :residue => aa,\n :pK => PK[:internal][aa],\n :positive => positive?(aa.to_s)\n }\n end\n end\n end\n tmp_internal.each do |aa, val|\n counted << val\n end\n # C-terminal\n c_term = @seq[-1].chr\n if PK[:cterm].key? c_term.to_sym\n counted << {\n :num => 1,\n :residue => c_term.to_sym,\n :pK => PK[:cterm][c_term.to_sym],\n :positive => positive?(c_term)\n }\n end\n counted\n end", "def dnaSequence s\n hash, diff = Hash.new(0), Hash.new(0)\n diff[[0, 0, 0]] = 1\n\n sum = 0\n s.chars.each { |c|\n hash[c] += 1\n res = [hash['A'] - hash['C'], hash['C'] - hash['G'], hash['G'] - hash['T']]\n sum += diff[res]\n diff[res] += 1\n }\n sum\nend", "def count_dna dna\n DNA.keys.map { |nt| dna.count nt }\n end", "def get_aa_array(initial_position = 0)\n @aa_array = []\n require_sequence = @dna_sequence[initial_position..-1].tr('-','N')\n base_array = []\n require_sequence.each_char {|base| base_array << base}\n while (base_array.length>=3) do\n base_3= \"\"\n 3.times{base_3 += base_array.shift}\n @aa_array<< amino_acid_2(base_3)\n end\n end", "def rna_to_amino_acid(rna)\n # Protein Translation Problem: Translate an RNA string into an amino acid string.\n # Input: An RNA string Pattern and the array GeneticCode.\n # Output: The translation of Pattern into an amino acid string Peptide. \n\n r_to_c_h = rna_to_codon_hash\n # puts r_to_c_h\n i = 0\n codon_length = 3\n amino_acid = \"\"\n while (codon = rna.slice(i, codon_length)) do\n # puts codon\n # puts r_to_c_h[codon.to_sym]\n break if codon.empty?\n amino_acid += r_to_c_h[codon.to_sym].to_s\n i += codon_length\n end\n return amino_acid\n end", "def has_aces\n if @cards.length == 2 and @cards[0].is_ace and @cards[1].is_ace\n return 1\n end\n return nil\n end", "def countA(string)\n counter = 0\n string.each_char do |char|\n if char == \"a\"\n counter +=1\n end\n end\n return counter\nend", "def amino_acid_2 (bases)\n bases_to_aa = []\n aa_list = []\n base1 = bases[0].to_list\n base2 = bases[1].to_list\n base3 = bases[2].to_list\n l1 = base1.size - 1\n l2 = base2.size - 1\n l3 = base3.size - 1\n (0..l1).each do |n1|\n b1 = base1[n1]\n (0..l2).each do |n2|\n b2 = base2[n2]\n (0..l3).each do |n3|\n b3 = base3[n3]\n bases_all = b1 + b2 + b3\n bases_to_aa << bases_all\n end\n end\n end\n\n bases_to_aa.each do |base|\n case base\n when /^TT[TCY]$/\n aa = \"F\"\n when /^TT[AGR]$/\n aa = \"L\"\n when /^CT.$/\n aa = \"L\"\n when /^AT[TCAHYWM]$/\n aa = \"I\"\n when \"ATG\"\n aa = \"M\"\n when /^GT.$/\n aa = \"V\"\n when /^TC.$/\n aa = \"S\"\n when /^CC.$/\n aa = \"P\"\n when /^AC.$/\n aa = \"T\"\n when /^GC.$/\n aa = \"A\"\n when /^TA[TCY]$/\n aa = \"Y\"\n when /^TA[AGR]$/\n aa = \"*\"\n when /^T[GR]A$/\n aa = \"*\"\n when /^CA[TCY]$/\n aa = \"H\"\n when /^CA[AGR]$/\n aa = \"Q\"\n when /^AA[TCY]$/\n aa = \"N\"\n when /^AA[AGR]$/\n aa = \"K\"\n when /^GA[TCY]$/\n aa = \"D\"\n when /^GA[AGR]$/\n aa = \"E\"\n when /^TG[TCY]$/\n aa = \"C\"\n when \"TGG\"\n aa = \"W\"\n when /^CG.$/\n aa = \"R\"\n when /^AG[TCY]$/\n aa = \"S\"\n when /^[AM]G[AGR]$/\n aa = \"R\"\n when /^GG.$/\n aa = \"G\"\n when /^[ATW][CGS][CTY]$/\n aa = \"S\"\n when /^[TCY]T[AGR]$/\n aa = \"L\"\n else\n aa = \"-\"\n end\n aa_list << aa\n end\n aa_out = aa_list.uniq.join\n return aa_out\n end", "def ace_count\n buf = 0.chr * 12 # sizeof(ACL_SIZE_INFORMATION)\n\n unless GetAclInformation(@acl, buf, buf.size, AclSizeInformation)\n raise Error, get_last_error\n end\n\n buf[0, 4].unpack('L')[0]\n end", "def value(hand)\n # Sorting hack to get aces at the very end so we count them last\n hand.sort_by { |c| c.to_i != 0 ? c : c[0] - 81 }.reverse().inject(0) do |total,cur|\n if cur.to_i != 0\n total + cur # 2-10 case\n elsif [\"J\",\"Q\",\"K\"].include? cur\n total + 10 # J,Q, or K\n elsif cur == \"A\"\n if (total+11) > 21\n total + 1 # Count ace as 1\n else\n total+11 # Count ace as 11\n end\n end\n end\n end", "def count_a(word)\n\tcounter = 0\n \ti = 0\n \twhile i < word.length\n if word[i] == \"a\" || word[i] == \"A\"\n counter += 1\n end\n i += 1\n end\n return counter\nend", "def additional?(cleaved_amino_acids)\n cleaved_amino_acids.window_search(1) do |aa|\n if basic_count(aa) == 1\n return true\n elsif acidic_count(aa) == 1\n return false\n end\n end\n return nil\n end", "def total\n total = 0\n aces = 0\n @hand.each do |card|\n case card[0]\n when 2..10 then total += card[0]\n when 'A' then aces += 1\n else total += 10\n end\n end\n total += add_aces(total, aces)\n total\n end", "def has_ace\n for card in @cards\n return 1 if card.is_ace\n end\n return nil\n end", "def calculate_total(cards)\n total = 0\n value_of_cards = cards.map{|e| e[1]}\n value_of_cards.each do |value|\n if value == \"A\"\n total += 11\n elsif value.to_i == 0\n total +=10 # handle J, Q, K\n else\n total += value.to_i\n end\n # corrct Ace condition\n if total > 21\n value_of_cards.select{|e| e == \"A\"}.count.times do\n total -= 10\n end\n end\n end\n total\nend", "def ana4(str1, str2)\n return false unless str1.length == str2.length\n letters = Hash.new(0)\n i = 0\n while i < str1.length\n letters[str1[i]] += 1\n letters[str2[i]] -= 1\n i += 1\n end\n letters.values.all? { |value| value == 0 }\nend", "def count_a(word)\n i = 0\n count = 0\n while( i < word.length)\n if(word[i] == \"a\" or word[i] == \"A\")\n count += 1\n end\n i+=1\n end\n return count\n\nend", "def count_a(word)\n counter = 0\n i = 0\n while i < word.length\n if word[i] == 'a' || word[i] == 'A'\n counter += 1\n end\n i += 1\n end\n return counter\nend", "def valid_anagram_counter(s, t)\n return false if s.length != t.length || s.empty? || t.empty?\n \n counter_arr = Array.new(256, 0)\n \n # can't check all of them together coz first string might have string that might add to the positive value\n for i in (0...s.length)\n counter_arr[s[i].ord] += 1\n counter_arr[t[i].ord] -= 1\n end\n \n counter_arr.each do |a|\n return false if a != 0\n end\n true\nend", "def card_total array\r\n i = 0\r\n total = 0\r\n\tace_value = 0\r\n\tace_array = []\r\n\tarray_test = []\r\n\ttotal = (array_num_total array) + (face_card_total array)\r\n\tace_array = array.select { |item| item[0] == 'A' }\r\n\tarray_test = array.each { |item| item[0] }\r\n\tif (ace_array.length == 1) && (total == 10) \r\n\t total = 21\r\n\t\treturn total\r\n\tend\r\n\tif ace_array.eql?(array_test)\r\n\t total = 10 + ace_array.length\r\n\t\treturn total\r\n\tend\r\n\t while i < ace_array.length\r\n\t\t if total + 11 >= 21\r\n\t\t\t ace_value = 1\r\n\t\t\telse\r\n\t\t\t ace_value = 11\r\n\t\t\tend\r\n total = total + ace_value \r\n\t\t\ti = i + 1\r\n\t\tend\r\n total\r\nend", "def occ(seq, b)\n # löchen alles anstatt was in b drin ist\n return seq.gsub(/^#{b}/, \"\").length\n end", "def countABC(str)\n if(str.length == 3)\n return 1 if (str == \"abc\") || (str == \"aba\")\n return 0\n end\n first_three = str[0..2]\n if first_three = \"abc\" || first_three = \"aba\"\n return 1 + countABC(str[3..-1])\n else\n return 0 + countABC(str[1..-1])\n end\nend", "def number_of_awards(text)\n result = 0\n @awards.each do |a|\n if text.downcase.include?(a)\n result += 1\n end\n end\n return result\nend", "def count()\n count = 0\n # skip digit 0\n (1..(ALL_DIGITS-1)).each do |i|\n if (@data[i])\n count += 1\n end\n end\n count\n end", "def get_hand_value(hand)\n hand_values = hand.map { |card| card[0]} \n \n total = 0\n #check if there are any Aces\n hand_values.each do |value|\n if value == 'A'\n total += 11\n elsif value.to_i == 0 # this is for J, Q, K\n total += 10\n else\n total += value.to_i\n end\n end\n # To accomodate Aces, subtract 10 from the total per Ace if the total is >21\n hand_values.select{|value| value == \"A\"}.count.times do \n total -= 10 if total >21\n end\n total\nend", "def is_ace?(card)\n\t\tcard == \"A\" ? true : false\n\tend", "def calculate_total(cards)\r\n # [['H', '3'], ['S', 'Q'], ... ]\r\n\r\n arr = cards.map{|e| e[1]}\r\n \r\n total = 0\r\n arr.each do |value|\r\n if value == \"A\"\r\n total += 11\r\n elsif value.to_i == 0 # J, Q, K\r\n total += 10\r\n else\r\n total += value.to_i\r\n end\r\n # Logic for Aces\r\n end\r\n arr.select{|e| e == \"A\"}.count.times do\r\n total -= 10 if total > 21\r\n end\r\n\r\n return total\r\nend", "def count_a(word)\n count = 0\n i = 0\n\n while i < word.length\n if word[i] == 'a' || word[i] == 'A'\n count += 1\n end\n i += 1\n end\n\n return count\nend", "def count_signs\n # suskaiciuojami visi zenklai\n temp = 0\n @signs.size.times do |i|\n temp += 1 if @signs[i] != 0\n end\n temp\n end", "def lexigram_counter(sequencetext)\n @sequencetext = sequencetext\n\t@lexigrams = lexigram_searcher(@sequencetext)\n\tif (@lexigrams === [\"no letters remain after processing\"])\n\t @lexigrams_count = 0\n else\n @lexigrams_count = @lexigrams.count.to_s\n end\n end", "def count_a(word)\n count = 0\n \n i = 0 \n while i < word.length\n char = word[i]\n \n if char == \"a\"\n count += 1\n \n elsif char == \"A\"\n count += 1\n end\n \n i += 1\n end\n \n return count\nend", "def count_a(word)\n count = 0\n \n i = 0\n while i < word.length\n char = word[i]\n \n if char == \"a\" || char == \"A\"\n count += 1\n end\n \n i += 1\n end \n \n return count\nend", "def value()\n sum = 0\n # Partition the array by string and integer then reverse to put aces at back\n @cards.partition{|x| x.is_a? String}.map(&:sort).flatten.reverse_each do |i|\n if [\"Q\", \"J\", \"K\"].include?(i)\n sum += 10\n elsif i == \"A\"\n if sum + 11 > 21\n sum += 1\n else\n sum += 11\n end\n else \n sum += i\n end\n end \n return sum\n end", "def generate_aasequences\n (0..self.sequence.length-1).each do |i|\n AAsequence.create(:seq_id=> self.seq_id,\n :amino_acid=>self.sequence[i],\n :original_position=>i)\n end\n end", "def count_a(word)\n\n count = 0\n i = 0\n while i < word.length \n if word[i] == 'a' || word[i] == 'A'\n count += 1\n end\n \n i += 1\n end\n return count\nend", "def count_and_say(sequence)\n\treturn 0 if sequence == nil\n\tsequence = sequence.to_s\n\tn = sequence.to_s.size\n result = ''\n\ti = 1\n\trepeat = sequence[0]\n\ttimes = 1\n\twhile (i<=n) do\n\t\tif sequence[i] == repeat\n\t\t\ttimes += 1\n else\n \tresult += times.to_s + repeat.to_s\n \ttimes = 1\n repeat \t= sequence[i].to_i\n end\n i+=1\n end \n\treturn result \nend", "def count_a(word)\n count = 0\n i = 0\n while i < word.length\n char = word[i]\n if char == \"a\" || char == \"A\"\n count += 1\n end\n i += 1\n end\n return count\nend", "def count_nucleotides dna\n bases_count = {\n 'A' => 0,\n 'C' => 0, \n 'T' => 0,\n 'G' => 0,\n }\n \n \n #\n dna.each_char do |x|\n if bases_count.key? base\n bases_count[ base ] += 1\n else \n puts \"#{base} not a valid nucleotide\"\n end # if\n end # DNA.each_char end\n\n bases_count.each do |key, val|\n puts \"#{key} : #{val}\"\n end #bases_count.each end\n \n\nend", "def checkArray(a)\n\tn = a.length-1\n\tcount = 0\n\tfor i in 0..n do\n\t\tfor j in (i+1)..n do\n\t\t\tfor k in (j+1)..n do\n\t\t\t\tif (a[i] + a[j] + a[k] == 0)\n\t\t\t\t\tcount += 1\n\t\t\t\t\treturn count;\n\t\t\t\telse\n\t\t\t\t\treturn count;\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\nend", "def solution(s)\n return 0 if s.empty?\n t = 0\n ('A'..'Z').to_a.each do |c|\n t += s.count(c)\n end\n t + 1\nend", "def counts\n {\n \"A\" => 0,\n \"G\" => 0,\n \"C\" => 0,\n \"T\" => 0\n }\n end", "def letter_count(letter)\n @letter_counts ||= compute_counts\n @letter_counts[letter[0] - ?a]\n end", "def count_chars a\n\tc = 0\n\ta.each do |s|\n\t\tc += s.length\t\t#this returns c\n\tend\t\t\t\t\t\t#but this returns a\n\tc \t\t\t\t\t\t#so this returns c (again)\nend", "def NameScore( s )\n\talphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ]\n\n\tsum = 0\n\n\tfor i in ( 0 .. s.length-1 )\n\t \tsum += alphabet.index( s[i] )+1\n\tend\n\n\treturn sum\nend", "def check_csfasta(fasta)\n # length is the total read lengh + 2\n # cat *.csfasta | perl -ne 'next if /^#/;$i++;if ($i%2==0) {print unless \n # length($_)==52} else {print unless /^>\\d+_\\d+\\_\\d+\\_(F|R)(3|5)(-P2)*\\n$/}'\n # | more\n length = get_bp_length(fasta) + 2\n i = 0\n output = \"\"\n File.open(fasta).each do |l|\n next if /^#/.match(l)\n i = i + 1\n if ( i % 2 == 0 ) && ( l.size != length ) &&\n !/^>\\\\d+_\\\\d+_\\\\d+_(F|R)(3|5)(-P2)*\\n$/.match(l)\n output = output + l\n end\n end\n output\n end", "def calculate_num_adjs(num_rooms, num_chairs, num_wings)\n\t\t \t#residue is how many higher rooms will have an \"extra\"\n\t\t \tresidue = num_wings % num_rooms;\n\n\t\t \t#q is how many each room should have minimum\n\t\t \t#the 1 represents the chair\n\t\t \t#num_wings / num_rooms is how wing allocations per room we can definitely do\n\t\t \tq = 1 + num_wings / num_rooms; #this will naturally floor()\n\n\t\t \textra = 0; #assume no extra\n\t\t \t#if in upper lot of rooms, assign 1 extra wing\n\t\t \tif (residue != 0) && (@num_rooms_assigned <= residue)\n\t\t \t\textra = 1;\n\t\t \tend\n\t\t \t\n\t\t \treturn (q + extra);\n\t\t end", "def calculate_score(hand_of_cards)\n card_values = hand_of_cards.map{|card_value| card_value[1]}\n total = 0 \n card_values.each do |card_value| \n if card_value == \"ACE\"\n total+= 11\n elsif card_value.to_i == 0 #For suits ie Jester, Queen\n total+= 10\n else \n total+= card_value.to_i\n end\n end \n\n#adjust for Aces\n card_values.select{|card| card == \"ACE\"}.count.times do \n total-=10 if total > 21\n end \n total\nend", "def rule_inSequence c\n val(c) == ((@land[suit(c)][-1]||-1) +1 )\n end", "def alsquiz_count\n self.alsquiznr.nil? ? 0 : 1\n end", "def peptide_mass_with_amino_acids(peptide, amh)\n mass = 0\n peptide.chars.each do |pep|\n mass += amh[pep]\n end\n return mass\n end", "def count_nucleotides(data)\n ['A', 'C', 'G', 'T'].map {|nucleotid| data.count(nucleotid)} * ' '\nend", "def card_count(input)\n count = 0\n\n return false if input.size > CARDS_IN_A_DECK\n\n played_cards = input.chars\n\n played_cards.each do |input|\n if input == '2' || input == '3' || input == '4' || input == '5' || input == '6'\n count += 1\n elsif input == 'T' || input == 'J' || input == 'Q' || input == 'K' || input == 'A'\n count -= 1\n end\n end\n\n # return false if more_than_four_of_each_rank_played(played_cards)\n #\n # count += case card\n # when '2', '3', '4', '5', '6'\n # 1\n # when 'T', 'J', 'Q', 'K', 'A'\n # -1\n # else\n # 0\n # end\n\n return count\nend", "def character_count(char)\n char.each_codepoint.sum { |codepoint| BASIC_PLANE.include?(codepoint) ? 1 : 2 }\n end", "def val_count(cards)\n\t\t\"123456789TJQK\".chars.collect{|char| cards.count {|card| card.val == char}}\n\tend", "def anagrams(a, b)\n a_count = Hash.new(0)\n a.each_char do |ch|\n a_count[ch] += 1\n end\n\n b_count = Hash.new(0)\n b.each_char do |ch|\n b_count[ch] += 1\n end\n\n count = 0\n ('a'..'z').each do |ch|\n count += (a_count[ch] - b_count[ch]).abs\n end\n\n p count\nend", "def is_isogram(s)\narr = [ ]\nb = \"a\"..\"z\"\nb.map do |x| p arr << s.downcase.split(\"\").count(x)\nend\narr.include?(2) || arr.include?(3) ? false : true\nend", "def empty_counter\n counts = {}\n ('a'..'z').each {|letter| counts[letter] = 0}\n counts\n end", "def number_of_arvs_given(patient_id, visit_date)\n obs = EmastercardDb.find_all_observations_by_encounter(patient_id,\n Emastercard::Concepts::ARVS_DISPENSED,\n Emastercard::Encounters::ART_VISIT)\n .where(encounter_datetime: visit_date.strftime('%Y-%m-%d 00:00:00')..visit_date.strftime('%Y-%m-%d 23:59:59'))\n .first\n\n return nil unless obs\n\n obs[:value_text]&.to_i || obs[:value_numeric]\n end", "def number_of_r(str)\n #coun the letters \"r\" in the string\n str.count(\"r\")\nend", "def valid_acn?\n return false unless @acn.is_a?(String)\n return false if (@acn =~ /^[0-9]{9}$/).nil?\n weighting = [8,7,6,5,4,3,2,1]\n chksum = 0\n (0..7).each do |d|\n chksum += @acn[d].to_i * weighting[d]\n end\n return (10 - chksum % 10) % 10 == @acn[8].to_i\n rescue => e\n puts \"Error: #{e.class}\\n#{e.backtrace.join(\"\\n\")}\"\n return false\n end", "def fasta_with_lengths(fasta_fn)\n tmp_file = register_new_tempfile('positive_peaks_formatted.fa')\n File.open(fasta_fn){|f|\n f.each_line.slice_before(/^>/).each{|hdr, *lines|\n seq = lines.map(&:strip).join\n tmp_file.puts \"#{hdr.strip}:#{seq.size}\"\n tmp_file.puts seq\n }\n }\n tmp_file.close\n tmp_file.path\nend", "def anagram_detection(parent, child)\n window_length = child.length\n ctr = 0\n 0.upto(parent.length - window_length).each do |idx|\n sub_str = parent[idx...(idx + window_length)]\n ctr += 1 if anagrams?(child, sub_str)\n end\n \n ctr\nend", "def count_nucleotides dna\n\n if dna.every? { |c| print if c != ('A' || 'C' || 'G' || 'T') }\n puts \"Invalid character detected\"\n else\n puts \"A: #{dna.count('A')}\"\n puts \"C: #{dna.count('C')}\"\n puts \"G: #{dna.count('G')}\"\n puts \"T: #{dna.count('T')}\"\n end\n\nend", "def alternating_char string\n arr = string.chars\n count = 0\n arr.each_with_index do |x,xi|\n if xi > 0\n if arr[xi-1] == 'A'\n count +=1 unless x == 'B'\n else\n count +=1 unless x == 'A'\n end\n end\n end\n count\nend", "def instability_index\n @instability_index ||=\n begin\n instability_sum = 0.0\n i = 0\n while @seq[i+1] != nil\n aa, next_aa = [@seq[i].chr.to_sym, @seq[i+1].chr.to_sym]\n if DIWV.key?(aa) && DIWV[aa].key?(next_aa)\n instability_sum += DIWV[aa][next_aa]\n end\n i += 1\n end\n round((10.0/amino_acid_number.to_f) * instability_sum, 2)\n end\n end", "def calculate_total(cards) # [['H', '3'], ['S', 'Q']...]\n\tarr = cards.map{|e| e[1] }\n\n total = 0\n arr.each do |value|\n if value == \"A\"\n \ttotal += 11\n elsif value.to_i == 0 #J, Q, K\n \t\ttotal += 10\n else\n \ttotal += value.to_i\n end\n end\n\n #correct for Aces when total is over 21\n arr.select{|e| e == \"A\"}.count.times do\n \ttotal -= 10 if total > 21\n end\n\n total\nend", "def ae_count(str)\n count = {\"a\"=>0, \"e\"=>0}\n\n str.each_char do |char|\n if (char == \"a\" || char == \"e\")\n count[char] += 1\n end\n end\n\n return count\nend", "def discover_input_sequence_type(sequence)\n # Index of the first newline char.\n start = sequence.index(/\\n/)\n # Remove the sequence FASTA header.\n seq = sequence.slice(start..-1).gsub!(/\\n/, '')\n\n if seq =~ /[EQILFPeqilfp]+/\n type = \"amino_acid\"\n else\n # Length of the sequence minus the FASTA header.\n len = seq.length.to_f\n\n na_percent = 15.0\n counts = []\n\n counts << (seq.count(\"Aa\").to_f / len) * 100\n counts << (seq.count(\"Tt\").to_f / len) * 100\n counts << (seq.count(\"Uu\").to_f / len) * 100\n\n counts << (seq.count(\"Gg\").to_f / len) * 100\n counts << (seq.count(\"Cc\").to_f / len) * 100\n\n counts << (seq.count(\"Nn\").to_f / len) * 100\n\n counts.reject! { |c| c < na_percent }\n if (!counts.empty?)\n type = \"nucleic_acid\"\n else\n type = \"amino_acid\"\n end\n end\n type\n end", "def hand_score(hand)\n\tcards= {\"A\"=>4, \"K\"=>3, \"Q\"=>2, \"J\"=>1}\n \tscore = 0\n \thand.each_char { |char| score += cards[char.upcase] }\n \treturn score\nend", "def score\n score = 0\n aces_count = 0\n @hand_contents.each do |card|\n if card.type == :face\n score += 10\n elsif card.type == :ace\n aces_count += 1\n score += 11\n elsif card.type == :number\n score += card.rank.to_i\n end\n end\n\n while score > 21 && aces_count > 0\n score -= 10\n aces_count -= 1\n end\n score\n end", "def count_rulings(card)\n ruling_arr = scryfall.rulings(card['id']) \n \"(#{ruling_arr.length})\"\n end", "def get_num_strokes(stroke_index, course_handicap)\n strokes = 0\n # loop until calc'd stroke_index is bigger than this person's handicap\n # Rails.logger.debug('stroke_index: ' + stroke_index.to_s)\n # Rails.logger.debug('course_handicap: ' + course_handicap.to_s)\n\n until stroke_index > course_handicap do\n if stroke_index <= course_handicap\n strokes += 1\n end\n # add 18 to stroke_index, if it's still smaller than the handicap, we will loop again\n stroke_index += 18\n end\n\n return strokes\n end", "def AA\n puts 'Alluring Aura'\n AA = gets.chomp.to_i\n AA\n end", "def amino_acid_mass_hash\n {\n \"G\" => 57, \"A\" => 71, \"S\" => 87, \"P\" => 97, \"V\" => 99,\n \"T\" => 101, \"C\" => 103, \"I\" => 113, \"L\" => 113, \"N\" => 114,\n \"D\" => 115, \"K\" => 128, \"Q\" => 128, \"E\" => 129, \"M\" => 131,\n \"H\" => 137, \"F\" => 147, \"R\" => 156, \"Y\" => 163, \"W\" => 186,\n }\n end", "def calculate_total(cards)\n total = 0\n cards.each do |c|\n if (1..10).include?(c.last.to_i)\n total += c.last.to_i\n elsif c.last == 'K' || c.last == 'Q' || c.last == 'J'\n total += 10\n elsif c.last == 'A'\n if total > 10\n total += 1\n else\n total += 11\n end\n end\n end\n total\nend", "def count_arara(num)\n\tnum_adak = (num/2).floor\n\tnum_anane = num%2\n\tphrase = \"adak \"*num_adak + \"anane\"*num_anane\n\tphrase = phrase.sub(/[\" \"]\\Z/, \"\")\n\tphrase\nend", "def exact_matches(other_code)\n exact_matches = 0\n @seq.each_with_index do |letter, index|\n exact_matches += 1 if self.is_exact_match?(other_code, index)\n end\n exact_matches\n end", "def bonus_anagram?(str1, str2)\n counts = Hash.new(0)\n\n str1.chars.each { |letter| counts[letter] += 1 }\n str2.chars.each { |letter| counts[letter] -= 1 }\n\n counts.values.all? { |value| value == 0 }\nend", "def find_missing_number(sequence)\n if sequence == \"\"\n return 0\n end\n # remove whitespaces and convert to array\n sequence = sequence.gsub(/\\s+/, \",\").split(\",\")\n\n # string to array\n # sequence = sequence.split(\",\")\n\n # sort by integer value\n sequence = sequence.sort_by(&:to_i)\n # sort string\n # sequence = sequence.chars.sort.join\n puts sequence \n\n \n if sequence[0].to_i != 1\n return 1\n elsif\n sequence[0].to_i == 1 && sequence.length == 1\n return 1\n elsif\n sequence.count(\"a-zA-Z\") > 0\n return 1\n elsif\n sequence == \"\"\n return 0\n elsif\n sequence[0].to_i == 2\n return 1\n else\n \n for i in 1..sequence.length - 1\n\n check = sequence[i].to_i - sequence[i - 1].to_i\n\n if check > 1\n missNum = sequence[i - 1].to_i + 1\n return missNum\n end\n\n end\n if check == 1\n return 0\n end\n end\nend", "def solution(a)\n return 0 unless a || a.empty?\n num_hash = {}\n a.each do |num|\n if !num_hash.has_key?(num)\n num_hash[num] = 1\n end\n end\n return num_hash.keys.size\nend", "def calculate_total(cards)\n arr = cards.map{|e| e[1]}\n \n total = 0 \n arr.each do |value|\n if value == \"A\"\n total += 11\n elsif value.to_i == 0\n total += 10 \n else \n total += value.to_i\n end \n end \n \n # Modified the Ace value \n arr.select{|e| e = \"A\"}.count.times do \n total -= 10 if total > 21 \n end \n \n total \nend", "def remove_non_amino_acids(sequence)\n sequence.gsub(Nonstandard_AA_re, '')\n end", "def total_hard_accels\n self.inject(0) do |accum,trip|\n accum += trip.hard_accels_count\n accum\n end\n end", "def card_total(hand)\n total = 0\n ace = hand.select {|x| x[0] == 'A'}\n # Calculation of hand without aces.\n if ace == []\n hand.each do |x|\n x = x[0..-2].to_i\n x == 0? total += 10 : total += x\n end\n total\n else\n # Calculation of hand with ace(s)\n # Delete aces from hand array\n ace.each do |a|\n hand.each {|x| hand.delete(a) if x == a}\n end\n # Calculate hand without aces\n hand.each do |x|\n x = x[0..-2].to_i\n x == 0? total += 10 : total += x\n end\n ace.each {|a| hand << a}\n # Add the value of ace(s) to the current total\n nr_ace = ace.length\n case nr_ace\n when 1\n total <= 10? total += 11 : total += 1\n when 2\n total <= 9? total += 12 : total += 2\n when 3\n total <= 8? total += 13 : total += 3\n else\n total <= 7? total += 14 : total += 4\n end\n total \n end\nend", "def countingValleys(n, s)\n valleys = 0\n pre = 0\n ac = 0\n for i in 0..n\n pre = ac\n ac += val(s[i]) \n valleys +=1 if pre == -1 && ac == 0\n end\n return valleys\nend", "def count_nucleotides(input)\n dna = []\n\n bases = {\n \"A\" => 0,\n \"C\" => 0,\n \"T\" => 0,\n \"G\" => 0,\n }\n\n input.upcase.chars.each do |letter|\n # puts \"Checking for letter: #{letter}\"\n\n is_nucleotides = false\n\n bases.each do |key, value|\n # puts \"The key: #{key} add the value: #{value}.\"\n\n if letter == key\n bases[key] += 1\n is_nucleotides = true\n end\n end #bases.each\n\n if is_nucleotides == false\n dna.push \"#{letter} is not a nucleotide.\"\n end\n\n end #input.chars\n\n bases.each do |key, value|\n dna.push \"#{key}, #{value}\"\n end\n\n puts dna.uniq\n # puts bases\nend", "def calculate_points(cards_in_hands)\n points = 0\n cards_without_ace = cards_in_hands.select {|card| card[1] != 'A'}\n cards_with_ace = cards_in_hands.select {|card| card[1] == 'A'}\n cards_without_ace.each do |card|\n if card[0].to_i !=0\n points += card[0].to_i\n else\n points += 10\n end\n end\n if cards_with_ace.empty?\n return points\n else\n ace_sets = [11, 1].repeated_permutation(cards_with_ace.length).to_a\n ace_sets_sum_arr = []\n ace_sets.each do |arr|\n arr_sum = 0\n arr.each {|v| arr_sum = arr_sum + v}\n ace_sets_sum_arr.push(arr_sum)\n end\n ace_sets_sum_arr.sort!.uniq!\n ace_sets_sum_arr.map! {|num| num + points}\n if ace_sets_sum_arr.include?(21)\n points = 21\n return points\n else\n lt_21_arr = ace_sets_sum_arr.select {|v| v < 21}\n gt_21_arr= ace_sets_sum_arr.select {|v| v > 21}\n if lt_21_arr.empty?\n points = gt_21_arr.first\n return points\n else\n points = lt_21_arr.last\n return points\n end\n end\n end\nend", "def count_as(string)\n string_array = string.split(\"\")\n count = 0\n\n string_array.each do |letter|\n if letter == \"a\"\n count += 1\n end\n end\n\n count\nend", "def count_letters (name, counts)\n sum = 0\n $alphabet.each_with_index { |val, index| counts[index] += name.count(val) }\n counts\nend" ]
[ "0.7483294", "0.74113756", "0.71197534", "0.6365894", "0.62830573", "0.6223864", "0.6124915", "0.5964618", "0.5955391", "0.59027463", "0.59025335", "0.585989", "0.5812948", "0.57828134", "0.57761735", "0.5698144", "0.5671942", "0.5661504", "0.56376785", "0.5630795", "0.56074804", "0.5561115", "0.5529324", "0.5481998", "0.5477205", "0.5477164", "0.54323184", "0.54313457", "0.54303813", "0.54202324", "0.54183644", "0.5411137", "0.53829956", "0.53400797", "0.5335087", "0.53308505", "0.53144115", "0.5299376", "0.5294012", "0.5281724", "0.52806956", "0.5277515", "0.5276328", "0.5275402", "0.5271628", "0.52653104", "0.5265165", "0.5261587", "0.5259147", "0.52573085", "0.5256627", "0.5256167", "0.52392167", "0.52264345", "0.52122283", "0.5205852", "0.51987106", "0.51983225", "0.5194496", "0.5179995", "0.5165025", "0.51616967", "0.5148254", "0.5141678", "0.5135572", "0.5128045", "0.51250327", "0.51215404", "0.511979", "0.5116647", "0.5114319", "0.5108907", "0.5095461", "0.50892067", "0.5084313", "0.50817096", "0.5075664", "0.50641537", "0.50579053", "0.50551146", "0.50493866", "0.50438195", "0.50429875", "0.5041784", "0.5036274", "0.5033738", "0.5032974", "0.5032819", "0.5032556", "0.50295734", "0.5024988", "0.50128907", "0.50116175", "0.5008432", "0.500549", "0.50034565", "0.50025535", "0.49972406", "0.4993287", "0.4990271" ]
0.599255
7
Return the number of residues in an AA sequence.
def amino_acid_number @seq.length end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def acidic_count(amino_acid_sequence)\n count = 0\n comp = amino_acid_sequence.composition\n ACIDIC_AMINO_ACIDS.each do |acidic|\n if comp[acidic]\n count += comp[acidic]\n end\n end\n return count\n end", "def basic_count(amino_acid_sequence)\n count = 0\n comp = amino_acid_sequence.composition\n BASIC_AMINO_ACIDS.each do |basic|\n if comp[basic]\n count += comp[basic]\n end\n end\n return count\n end", "def countAtoms(seq)\n\t\t\t\to = 0\n\t\t\t\tn = 0\n\t\t\t\tc = 0\n\t\t\t\th = 0\n\t\t\t\ts = 0\n\t\t\t\tp = 0\n\t\t\t\tse = 0\n\t\t\t\tseq.each_char do |aa|\n\t\t\t\t\to = o + MS::Feature::AA::ATOM_COUNTS[aa][:o]\n\t\t\t\t\tn = n + MS::Feature::AA::ATOM_COUNTS[aa][:n]\n\t\t\t\t\tc = c + MS::Feature::AA::ATOM_COUNTS[aa][:c]\n\t\t\t\t\th = h + MS::Feature::AA::ATOM_COUNTS[aa][:h]\n\t\t\t\t\ts = s + MS::Feature::AA::ATOM_COUNTS[aa][:s]\n\t\t\t\t\tp = p + MS::Feature::AA::ATOM_COUNTS[aa][:p]\n\t\t\t\t\tse = se + MS::Feature::AA::ATOM_COUNTS[aa][:se]\n\t\t\t\tend\n\t\t\t\treturn o,n,c,h,s,p,se\n\t\t\tend", "def residue_count\n counted = []\n # N-terminal\n n_term = @seq[0].chr\n if PK[:nterm].key? n_term.to_sym\n counted << {\n :num => 1,\n :residue => n_term.to_sym,\n :pK => PK[:nterm][n_term.to_sym],\n :positive => positive?(n_term)\n }\n elsif PK[:normal].key? n_term.to_sym\n counted << {\n :num => 1,\n :residue => n_term.to_sym,\n :pK => PK[:normal][n_term.to_sym],\n :positive => positive?(n_term)\n }\n end\n # Internal\n tmp_internal = {}\n @seq[1,(@seq.length-2)].each_byte do |x|\n aa = x.chr.to_sym\n if PK[:internal].key? aa\n if tmp_internal.key? aa\n tmp_internal[aa][:num] += 1\n else\n tmp_internal[aa] = {\n :num => 1,\n :residue => aa,\n :pK => PK[:internal][aa],\n :positive => positive?(aa.to_s)\n }\n end\n end\n end\n tmp_internal.each do |aa, val|\n counted << val\n end\n # C-terminal\n c_term = @seq[-1].chr\n if PK[:cterm].key? c_term.to_sym\n counted << {\n :num => 1,\n :residue => c_term.to_sym,\n :pK => PK[:cterm][c_term.to_sym],\n :positive => positive?(c_term)\n }\n end\n counted\n end", "def occ(seq, b)\n # löchen alles anstatt was in b drin ist\n return seq.gsub(/^#{b}/, \"\").length\n end", "def countingValleys(n, s)\n valleys = 0\n pre = 0\n ac = 0\n for i in 0..n\n pre = ac\n ac += val(s[i]) \n valleys +=1 if pre == -1 && ac == 0\n end\n return valleys\nend", "def countNumIntran(res)\n\t\tiCount = 0\n\n\t\tif res == nil || res.length == 0\n\t\t\treturn iCount\n\t\tend\n\n\t\tres.each do |constituent|\n\t\t\t# verify Intransitive Verb Phrase\n\t\t\tif(constituent.pos == @vp)\n\t\t\t\t# (or no immediate children at all)\n\t\t\t\tif(constituent.children == nil || !constituent.has_children?)\n\t\t\t\t\tiCount = iCount + 1\n\t\t\t\telse\n\t\t\t\t\t# whose immediate (top-level) constituents include no NPs\n\t\t\t\t\t# containsNps = false\n\t\t\t\t\t# constituent.children.each do |child|\n\t\t\t\t\t# \tif(child.pos == @np)\n\t\t\t\t\t# \t\tcontainsNps = true\n\t\t\t\t\t# \t\tbreak\n\t\t\t\t\t# \tend\n\t\t\t\t\t# end\n\n\t\t\t\t\t# # no top-level constituents found\n\t\t\t\t\t# if(!containsNps)\n\t\t\t\t\t# \tiCount = iCount + 1\n\t\t\t\t\t# end\n\t\t\t\tend\n\t\t\tend\n\n\t\t\tiCount = iCount + countNumIntran(constituent.children)\n\t\tend\n\t\treturn iCount\n\tend", "def count_dna dna\n DNA.keys.map { |nt| dna.count nt }\n end", "def ace_count\n buf = 0.chr * 12 # sizeof(ACL_SIZE_INFORMATION)\n\n unless GetAclInformation(@acl, buf, buf.size, AclSizeInformation)\n raise Error, get_last_error\n end\n\n buf[0, 4].unpack('L')[0]\n end", "def count\n @atlas.count\n end", "def n_of_contact\n cnt = 0\n pre = false\n contacts.each_with_index do |c, i|\n next if i.zero?\n\n cnt += 1 if (pre != c[1]) && c[1]\n pre = c[1]\n end\n cnt\n end", "def countNumX(res, x)\n\t\tsCount = 0\n\n\t\tif res == nil || res.length == 0\n\t\t\treturn sCount\n\t\tend\n\n\t\t# res is an array of constiuents\n\t\tres.each do |constituent|\n\t\t\tif(constituent.pos == x)\n\t\t\t\tsCount = sCount + 1\n\t\t\tend\n\n\t\t\t#search children\n\t\t\tsCount = sCount + countNumX(constituent.children, x)\n\t\tend\n\n\t\treturn sCount\n\tend", "def solution(a)\n return 0 unless a || a.empty?\n num_hash = {}\n a.each do |num|\n if !num_hash.has_key?(num)\n num_hash[num] = 1\n end\n end\n return num_hash.keys.size\nend", "def countNumDitran(res)\n\t\tdCount = 0\n\n\t\tif res == nil || res.length == 0\n\t\t\treturn dCount\n\t\tend\n\n\t\t# make sure to not count, for example, NP-SBJ\n\n\t\tres.each do |constituent|\n\t\t\t# verify Ditransitive Verb Phrase\n\t\t\t# looking for exactly two immediate constituents of type NP\n\t\t\tif(constituent.has_children? && constituent.children.length == 2 && constituent.pos == @vp)\n\t\t\t\tif(constituent.children[0].pos == @np && constituent.children[1].pos == @np)\n\t\t\t\t\tdCount = dCount + 1\n\t\t\t\tend\n\t\t\tend\n\n\t\t\tdCount = dCount + countNumDitran(constituent.children)\n\t\tend\n\n\t\treturn dCount\n\tend", "def subarray_count(subarray)\n\t\t\t\t\teach_cons(subarray.length).count(subarray)\n\t\t\t end", "def count\n @rarray.length\n end", "def length\n len = 0\n @locations.each do |x|\n if x.sequence\n len += x.sequence.size\n else\n len += (x.to - x.from + 1)\n end\n end\n len\n end", "def isDNA?(fasta)\n seq = File.read(fasta, 10000).split(\"\\n\").grep(/^[^>]/).join\n seq.upcase.count(\"ACTGNU\").to_f / seq.upcase.count(\"ACDEFGHIKLMNPQRSTVWYZ\") > 0.90\nend", "def run\n # Digits 1,4,7,8 have 2,4,3,7 segments respectively\n @list.map{|line| line[1]}.flatten.map(&:length).filter{|len| [2, 4, 3, 7].include?(len)}.count\n end", "def get_number_of_states\n return @dfa.get_number_of_states\n end", "def number_of_zeros\r\n total_zeros = 0\r\n @seminarians.each do |sem|\r\n zeros = sem.number_of_zeros\r\n total_zeros += zeros\r\n end\r\n\r\n #Divide by 2 to correct the fact that each was counted twice\r\n return total_zeros/2\r\n end", "def size\n @sequence.size\n end", "def count()\n count = 0\n # skip digit 0\n (1..(ALL_DIGITS-1)).each do |i|\n if (@data[i])\n count += 1\n end\n end\n count\n end", "def isDNA?(fasta)\n seq = File.read(fasta, 10000).split(\"\\n\").grep(/^[^>]/).join\n seq.upcase.count(\"ACTGNU\").to_f / seq.upcase.count(\"ACDEFGHIKLMNPQRSTVWYZ\") > 0.90\nend", "def number_of(val)\n res = 0\n @array.each { |row| row.each { |v| res +=1 if v == val } }\n res\n end", "def count_chars a\n\tc = 0\n\ta.each do |s|\n\t\tc += s.length\t\t#this returns c\n\tend\t\t\t\t\t\t#but this returns a\n\tc \t\t\t\t\t\t#so this returns c (again)\nend", "def getNbRecompense\n return 0\n end", "def count_a(word)\n\tcounter = 0\n \ti = 0\n \twhile i < word.length\n if word[i] == \"a\" || word[i] == \"A\"\n counter += 1\n end\n i += 1\n end\n return counter\nend", "def num_bases\n self.map { |chr,n| n }.sum\n end", "def number_of_arvs_given(patient_id, visit_date)\n obs = EmastercardDb.find_all_observations_by_encounter(patient_id,\n Emastercard::Concepts::ARVS_DISPENSED,\n Emastercard::Encounters::ART_VISIT)\n .where(encounter_datetime: visit_date.strftime('%Y-%m-%d 00:00:00')..visit_date.strftime('%Y-%m-%d 23:59:59'))\n .first\n\n return nil unless obs\n\n obs[:value_text]&.to_i || obs[:value_numeric]\n end", "def size\n @sequence.size\n end", "def count\n\t\treturn UserAssoziation.where(:assoziation_id => self.id).count\n\tend", "def residues\n @rs\n end", "def digit_count(titles)\n Math.log10(titles.size).to_i + 1\n end", "def valleyCounter(n,s)\n currentAltitude = 0\n lastAltitude = 0\n index = 0\n numberOfValleys = 0\n s.each_char do |char|\n if char == \"U\"\n currentAltitude += 1\n lastAltitude = currentAltitude - 1\n else\n currentAltitude -= 1\n lastAltitude = currentAltitude + 1\n end\n if currentAltitude == 0 && lastAltitude < 0\n numberOfValleys += 1\n end\n end\n puts numberOfValleys\nend", "def solution(a)\n h = {}\n a.each do |num|\n h[num] ? h[num] += 1 : h[num] = 1\n end\n h.keys.count\nend", "def instability_index\n @instability_index ||=\n begin\n instability_sum = 0.0\n i = 0\n while @seq[i+1] != nil\n aa, next_aa = [@seq[i].chr.to_sym, @seq[i+1].chr.to_sym]\n if DIWV.key?(aa) && DIWV[aa].key?(next_aa)\n instability_sum += DIWV[aa][next_aa]\n end\n i += 1\n end\n round((10.0/amino_acid_number.to_f) * instability_sum, 2)\n end\n end", "def find_solution_count(lines, look_ahead=3)\n init = Struct.new(:value, :length).new\n init.value = 0\n init.length = 1\n\n running_lengths = Array[init]\n\n for i in 0..lines.length - 1 do\n current = Struct.new(:value, :length).new\n current.value = lines[i]\n current.length = running_lengths.inject(0) { |sum, item|\n current.value <= item.value + look_ahead ?\n sum += item.length : sum\n }\n\n running_lengths.unshift current\n\n if running_lengths.length > look_ahead\n running_lengths.pop\n end\n end\n\n # running_lengths contains values for 180, 179, and 178, in that order.\n return running_lengths[0].length\nend", "def affirmation_count\n @affirmations.inject(0) do |sum, affirmation|\n sum + affirmation.affirmation_count\n end\n end", "def chromosome_count(genome_array)\n ccount = Hash.new(0)\n genome_array.each {|entry| ccount[entry[1]] += 1}\n ccount.each {|chromosome, count| puts \"Chromosome \" + chromosome.to_s + \" has \" + count.to_s + \" SNP data points\" }\n total = 0\n ccount.values.each {|count| total+= count }\n puts \"----\"\n puts total.to_s + \" total data points\"\n return ccount\nend", "def count_numbers(n)\n\tarray = (1..n).to_a\n\tcount = 0\n\tarray.each do |number|\n\t\ts = english_number(number)\n\t\tcount +=s.scan(/[A-Za-z]/).count\n\tend\n\treturn count\nend", "def score_aces(cards_aces, score_without_aces)\n # first, assume all \"ace\" cards score as 1\n aces_count = cards_aces.count\n return 0 if aces_count.zero?\n\n # check if we can convert one ace card to 11\n if (score_without_aces + aces_count <= 11)\n 11 + (aces_count - 1)\n else\n # all ace cards still score as 1\n aces_count\n end\n end", "def term_subauthority_count\n term_subauthorities.size\n end", "def length\n reduce(0) {|sum,_| sum + 1 }\n end", "def entry_addenda_count\n entries.size + addendas.values.flatten.size\n end", "def count_no\n rsvp.no.count\n end", "def countSubst(path)\n count = 0\n path.each do | atom |\n if @atoms[atom].size > 2 then\n count += (@atoms[atom].size - 2)\n end\n end\n count\n end", "def ab_counts(_experiment, _alternative)\n raise \"Not implemented\"\n end", "def lexigram_counter(sequencetext)\n @sequencetext = sequencetext\n\t@lexigrams = lexigram_searcher(@sequencetext)\n\tif (@lexigrams === [\"no letters remain after processing\"])\n\t @lexigrams_count = 0\n else\n @lexigrams_count = @lexigrams.count.to_s\n end\n end", "def sequence_length\n id_line('SEQUENCE_LENGTH')\n end", "def subjects_count\n subject_count = 0\n self.slots.each do |slot|\n subject_count += slot.subjects.count unless slot.cancelled?\n end\n return subject_count\n end", "def symbolic_count(count); end", "def count_a(word)\n counter = 0\n i = 0\n while i < word.length\n if word[i] == 'a' || word[i] == 'A'\n counter += 1\n end\n i += 1\n end\n return counter\nend", "def count(n,ar)\r\n result = Array.new(100){|x| x = 0}\r\n ar.each { |x| result[x] = result[x]+1 }\r\n return result\r\nend", "def number_indents\n 0\n end", "def count\n values.inject(0){|m, v| m + v.length}\n end", "def dnaSequence s\n hash, diff = Hash.new(0), Hash.new(0)\n diff[[0, 0, 0]] = 1\n\n sum = 0\n s.chars.each { |c|\n hash[c] += 1\n res = [hash['A'] - hash['C'], hash['C'] - hash['G'], hash['G'] - hash['T']]\n sum += diff[res]\n diff[res] += 1\n }\n sum\nend", "def part1()\n @seats = @input.map(&:dup)\n until rules_part1() == 0\n end\n count = 0\n @seats.each { |row| count += row.count('#') }\n count\nend", "def num_exact_matches(code)\n matches = 0\n @pegs.each_with_index {|peg, i| matches += 1 if peg == code[i] }\n return matches\n end", "def countA(string)\n counter = 0\n string.each_char do |char|\n if char == \"a\"\n counter +=1\n end\n end\n return counter\nend", "def calculate_num_adjs(num_rooms, num_chairs, num_wings)\n\t\t \t#residue is how many higher rooms will have an \"extra\"\n\t\t \tresidue = num_wings % num_rooms;\n\n\t\t \t#q is how many each room should have minimum\n\t\t \t#the 1 represents the chair\n\t\t \t#num_wings / num_rooms is how wing allocations per room we can definitely do\n\t\t \tq = 1 + num_wings / num_rooms; #this will naturally floor()\n\n\t\t \textra = 0; #assume no extra\n\t\t \t#if in upper lot of rooms, assign 1 extra wing\n\t\t \tif (residue != 0) && (@num_rooms_assigned <= residue)\n\t\t \t\textra = 1;\n\t\t \tend\n\t\t \t\n\t\t \treturn (q + extra);\n\t\t end", "def count(chr = nil, start = nil, stop = nil)\n num = 0\n self.each(chr, start, stop) { |entry| num += 1 }\n return num\n end", "def number_counting_seq(n)\r\n\r\nend", "def count_signs\n # suskaiciuojami visi zenklai\n temp = 0\n @signs.size.times do |i|\n temp += 1 if @signs[i] != 0\n end\n temp\n end", "def segment_count\n @segments.length\n end", "def counts\n @rules.inject(Hash.new(0)) do |counts, (lhs, rhs)|\n counts[lhs] += 2 if lhs == @start\n rhs.each { |node| counts[node.value] += 1 if nonterm? node.value }\n counts\n end\n end", "def cnts a\n r = []\n found = false\n a.each do |x|\n r.each do |y|\n if y[0] === x\n y[1] += 1\n found = true\n break\n end\n end\n if !found\n r.push([x, 1])\n else\n found = false\n end\n end\n r\nend", "def count_no\n rsvp.no.count\n end", "def count_consonants\n text.scan(/[bcdfghjklmnpqrstvwxyz]/).length\n end", "def lines_counter\n f = File.open('peliculas.txt', 'r')\n print f.readlines.length\n f.close\nend", "def cc_count\n stats = self.association_stats\n stats['cc_conditions'] + stats['cc_loops'] + stats['cc_questions'] +\n stats['cc_sequences'] + stats['cc_statements']\n end", "def get_aa_array(initial_position = 0)\n @aa_array = []\n require_sequence = @dna_sequence[initial_position..-1].tr('-','N')\n base_array = []\n require_sequence.each_char {|base| base_array << base}\n while (base_array.length>=3) do\n base_3= \"\"\n 3.times{base_3 += base_array.shift}\n @aa_array<< amino_acid_2(base_3)\n end\n end", "def count_a(word)\n i = 0\n count = 0\n while( i < word.length)\n if(word[i] == \"a\" or word[i] == \"A\")\n count += 1\n end\n i+=1\n end\n return count\n\nend", "def count_code(str)\n count_coe = 0\n (str.size - 3).times do |i|\n slice = str[i..(i+1)] + str[(i+3)]\n if slice == \"coe\"\n count_coe += 1\n end\n end\n return count_coe\nend", "def count\n to_a.size\n end", "def count\n to_a.size\n end", "def solution(s)\n return 0 if s.empty?\n t = 0\n ('A'..'Z').to_a.each do |c|\n t += s.count(c)\n end\n t + 1\nend", "def get_bp_length(fasta_path)\n return `tail -1 #{fasta_path} | wc | awk '{ print $NF}'`.to_i - 2\n end", "def standards_counts\n standards = {}\n standards.default(0)\n\n self.breaches.each do |b|\n standards[b.subject] += 1\n end\n return standards\n end", "def length; count end", "def food_consumption\n return residents.length * 2\n end", "def count\n Jhead.call(\"-c\", @match, @pattern).split(\"\\n\").size\n end", "def value_count\n $capitals.values.length\nend", "def character_count(array)\nend", "def letters_to_count(min, max)\n count = 0\n (min..max).each do |number|\n count += to_words(number).downcase.count(\"a-z\")\n end\n count\nend", "def num_pos\n @num_neg ||= @seq.count(\"RK\")\n end", "def count_a(word)\n count = 0\n i = 0\n\n while i < word.length\n if word[i] == 'a' || word[i] == 'A'\n count += 1\n end\n i += 1\n end\n\n return count\nend", "def solution(a)\n return a.count(a.max)\nend", "def val_count(cards)\n\t\t\"123456789TJQK\".chars.collect{|char| cards.count {|card| card.val == char}}\n\tend", "def sumofint(arr)\n combi = (0..9).to_a.combination(3).to_a.map{|e| e.reduce(:+)}\n _n, s = arr\n combi.select{ |e| e == s }.length\nend", "def count_a(word)\n count = 0\n \n i = 0 \n while i < word.length\n char = word[i]\n \n if char == \"a\"\n count += 1\n \n elsif char == \"A\"\n count += 1\n end\n \n i += 1\n end\n \n return count\nend", "def lengthOfSequence(element)\n\nend", "def count_a(word)\n\n count = 0\n i = 0\n while i < word.length \n if word[i] == 'a' || word[i] == 'A'\n count += 1\n end\n \n i += 1\n end\n return count\nend", "def nr_of_regions\n ConnectedComponents.new(in_use_graph).count\n end", "def count_nucleotides(data)\n ['A', 'C', 'G', 'T'].map {|nucleotid| data.count(nucleotid)} * ' '\nend", "def count(chr = nil, start = nil, stop = nil) \n num = 0\n self.each(chr, start, stop) { |entry| num += 1 }\n num\n end", "def apartment_count\n apartments.length\n end", "def count \n puts \"Tu as scrappé #{@result_scrap.count} élémént(s)\"\n return @result_scrap.count\n end", "def creation_counter(sequencetext)\n @sequencetext = sequencetext\n\t@creations = creation_searcher(@sequencetext)\n\tif (@creations === [\"no letters remain after processing\"])\n\t @creations_count = 0\n else\n @creations_count = @creations.count.to_s\n end\n end", "def bc_count\n \t@generic.size + @initial.size + @final.size + @cyclic.size\n end" ]
[ "0.73948544", "0.7297782", "0.69801915", "0.6814103", "0.5902533", "0.5879276", "0.57900685", "0.5719953", "0.5716063", "0.5603393", "0.5584541", "0.55838674", "0.5531532", "0.5525034", "0.55025285", "0.55020696", "0.5500859", "0.5495017", "0.54446185", "0.543454", "0.5386478", "0.538318", "0.53749853", "0.5365217", "0.5345374", "0.53365654", "0.5330307", "0.528358", "0.52812546", "0.5278579", "0.52769476", "0.52625847", "0.5256484", "0.5249783", "0.52329373", "0.52274907", "0.52216434", "0.5220808", "0.5210386", "0.51992685", "0.5197852", "0.51964134", "0.51902443", "0.51889706", "0.51819056", "0.5181403", "0.5180271", "0.51796037", "0.51680434", "0.5166263", "0.51613736", "0.5161295", "0.5161055", "0.515832", "0.5156144", "0.51507497", "0.51496744", "0.5149035", "0.51287115", "0.5126101", "0.5123085", "0.5121549", "0.51196426", "0.5119485", "0.51181924", "0.5098522", "0.50942117", "0.5093008", "0.5084916", "0.5082307", "0.5080978", "0.50799954", "0.50625116", "0.5055019", "0.50544906", "0.50544906", "0.50418836", "0.504175", "0.5032045", "0.503095", "0.502751", "0.5025213", "0.50236356", "0.50228125", "0.5017449", "0.5016258", "0.50155765", "0.50137883", "0.5010635", "0.5005778", "0.5005467", "0.50016266", "0.49995103", "0.49979123", "0.49953926", "0.49948043", "0.49943402", "0.49906206", "0.4989691", "0.4986177" ]
0.65121734
4
Return the number of atoms in a sequence. If type is given, return the number of specific atoms in a sequence.
def total_atoms(type=nil) if !type.nil? type = type.to_sym if /^(?:C|H|O|N|S){1}$/ !~ type.to_s raise ArgumentError, "type must be C/H/O/N/S/nil(all)" end end num_atom = {:C => 0, :H => 0, :O => 0, :N => 0, :S => 0} each_aa do |aa| ATOM[aa].each do |t, num| num_atom[t] += num end end num_atom[:H] = num_atom[:H] - 2 * (amino_acid_number - 1) num_atom[:O] = num_atom[:O] - (amino_acid_number - 1) if type.nil? num_atom.values.inject(0){|prod, num| prod += num } else num_atom[type] end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def quantity(type=NonEmpty)\n grep(type).inject(0){ |sum, spot| sum + spot.item.count }\n end", "def countAtoms(seq)\n\t\t\t\to = 0\n\t\t\t\tn = 0\n\t\t\t\tc = 0\n\t\t\t\th = 0\n\t\t\t\ts = 0\n\t\t\t\tp = 0\n\t\t\t\tse = 0\n\t\t\t\tseq.each_char do |aa|\n\t\t\t\t\to = o + MS::Feature::AA::ATOM_COUNTS[aa][:o]\n\t\t\t\t\tn = n + MS::Feature::AA::ATOM_COUNTS[aa][:n]\n\t\t\t\t\tc = c + MS::Feature::AA::ATOM_COUNTS[aa][:c]\n\t\t\t\t\th = h + MS::Feature::AA::ATOM_COUNTS[aa][:h]\n\t\t\t\t\ts = s + MS::Feature::AA::ATOM_COUNTS[aa][:s]\n\t\t\t\t\tp = p + MS::Feature::AA::ATOM_COUNTS[aa][:p]\n\t\t\t\t\tse = se + MS::Feature::AA::ATOM_COUNTS[aa][:se]\n\t\t\t\tend\n\t\t\t\treturn o,n,c,h,s,p,se\n\t\t\tend", "def related_count(type)\n cyc.talk(\"(length (#{type.to_s.gsub(\"_\",\"-\")} #{self.to_cyc}))\").to_i\n end", "def joinees_count_by_type(type)\n self.joinees.by_type(type).count\n end", "def number_of(type)\n game_entities.select{|entity| entity.class == type }.size\n end", "def node_count(type = nil)\n if type\n value = @db.m_get(\"node#{type}\")\n if value\n value.to_i\n end\n else\n @db.m_get(\"n\").to_i\n end\n end", "def count_sections(type = nil)\n if type\n sections.all.select { |section| section.type == type }.size\n else\n sections.size\n end\n end", "def inviters_count_by_type(type)\n self.inviters.by_type(type).count\n end", "def length(item_type = nil)\n item_type ||= :item\n case item_type\n when :entry\n # Return the number of top-level entries (items and sections)\n self.entries.length\n when :item\n # Return the number of list items as the sum of list items in each entry\n self.entries.reduce(0) { |count, entry| count + entry.length(:item) }\n when :section\n # Return the number of top-level sections\n self.sections.length\n end\n end", "def get_job_count(type='scanner')\n job_count = 0\n framework.jobs.each do |k, j|\n if j.name =~ /#{type}/\n job_count = job_count + 1\n end\n end\n return job_count\n end", "def count_tokens(type)\n token_tuples(type).count\nend", "def get_type_count(token, type=nil)\n raise \"Cannot predict with no type\" if not (token.type or type)\n type = token.type if not type\n\n return 0 if not word_types[token.lemma]\n word_types[token.lemma][type] || 0\n end", "def acidic_count(amino_acid_sequence)\n count = 0\n comp = amino_acid_sequence.composition\n ACIDIC_AMINO_ACIDS.each do |acidic|\n if comp[acidic]\n count += comp[acidic]\n end\n end\n return count\n end", "def count\n @type_variants.values.reduce(0) { |m, o| m + o.size }\n end", "def quantity_of_type(word_type)\n trains.count {|train| train.type == word_type}\n end", "def basic_count(amino_acid_sequence)\n count = 0\n comp = amino_acid_sequence.composition\n BASIC_AMINO_ACIDS.each do |basic|\n if comp[basic]\n count += comp[basic]\n end\n end\n return count\n end", "def count_tiles(type)\n count = 0\n @screen.each do |row|\n row.each do |tile_id|\n next if tile_id.nil?\n\n count += 1 if tile_id == type\n end\n end\n count\n end", "def count_unit_type unit_type\n count = 0\n warrior.listen.each do |unit|\n count += 1 if unit.to_s.to_sym == unit_type\n end\n return count\n end", "def size\n @atoms.size\n end", "def count\n __types__.count\n end", "def get_length(type_str)\n type_str.gsub(/^\\D+/, '').to_i\n end", "def type_count\n @game_objects.type_count\n end", "def plus_one(type)\n case type\n when \"association\" then @num_associations = @num_associations + 1\n when \"builtin\" then @num_builtin = @num_builtin + 1\n when \"unknown\" then @num_unknown = @num_unknown + 1\n when \"validator\" then @num_validator = @num_validator + 1; @num_custom = @num_custom + 1\n when \"model_defined\" then @num_model_defined = @num_model_defined + 1; @num_custom = @num_custom + 1\n when \"gem\" then @num_gem = @num_gem + 1\n end\n @total_validators = @total_validators + 1 \n end", "def length(item_type = nil)\n item_type ||= :item\n # List items return an item length of 1 to enable summation of list/section lengths\n item_type == :item ? 1 : super(item_type)\n end", "def sizeof(type)\n size_ptr = Pointer.new(:ulong_long)\n align_ptr = Pointer.new(:ulong_long)\n NSGetSizeAndAlignment(type, size_ptr, align_ptr)\n size_ptr[0]\n end", "def residue_count\n counted = []\n # N-terminal\n n_term = @seq[0].chr\n if PK[:nterm].key? n_term.to_sym\n counted << {\n :num => 1,\n :residue => n_term.to_sym,\n :pK => PK[:nterm][n_term.to_sym],\n :positive => positive?(n_term)\n }\n elsif PK[:normal].key? n_term.to_sym\n counted << {\n :num => 1,\n :residue => n_term.to_sym,\n :pK => PK[:normal][n_term.to_sym],\n :positive => positive?(n_term)\n }\n end\n # Internal\n tmp_internal = {}\n @seq[1,(@seq.length-2)].each_byte do |x|\n aa = x.chr.to_sym\n if PK[:internal].key? aa\n if tmp_internal.key? aa\n tmp_internal[aa][:num] += 1\n else\n tmp_internal[aa] = {\n :num => 1,\n :residue => aa,\n :pK => PK[:internal][aa],\n :positive => positive?(aa.to_s)\n }\n end\n end\n end\n tmp_internal.each do |aa, val|\n counted << val\n end\n # C-terminal\n c_term = @seq[-1].chr\n if PK[:cterm].key? c_term.to_sym\n counted << {\n :num => 1,\n :residue => c_term.to_sym,\n :pK => PK[:cterm][c_term.to_sym],\n :positive => positive?(c_term)\n }\n end\n counted\n end", "def size\n\t\t@db.llen @type\n\tend", "def number_of_types\n return GameData::Type.all.size\n end", "def number_of_types\n return GameData::Type.all.size\n end", "def discover_input_sequence_type(sequence)\n # Index of the first newline char.\n start = sequence.index(/\\n/)\n # Remove the sequence FASTA header.\n seq = sequence.slice(start..-1).gsub!(/\\n/, '')\n\n if seq =~ /[EQILFPeqilfp]+/\n type = \"amino_acid\"\n else\n # Length of the sequence minus the FASTA header.\n len = seq.length.to_f\n\n na_percent = 15.0\n counts = []\n\n counts << (seq.count(\"Aa\").to_f / len) * 100\n counts << (seq.count(\"Tt\").to_f / len) * 100\n counts << (seq.count(\"Uu\").to_f / len) * 100\n\n counts << (seq.count(\"Gg\").to_f / len) * 100\n counts << (seq.count(\"Cc\").to_f / len) * 100\n\n counts << (seq.count(\"Nn\").to_f / len) * 100\n\n counts.reject! { |c| c < na_percent }\n if (!counts.empty?)\n type = \"nucleic_acid\"\n else\n type = \"amino_acid\"\n end\n end\n type\n end", "def num_types\n return @num_types unless @num_types.nil?\n @num_types = ((num_types_m1 + 1) % 65536)\n @num_types\n end", "def count(chr = nil, start = nil, stop = nil)\n num = 0\n self.each(chr, start, stop) { |entry| num += 1 }\n return num\n end", "def size\n @sequence.size\n end", "def get_entity_count(type)\n @tracker.count(type)\n end", "def length(item_type = nil)\n item_type ||= :item\n # The item length of a list is the length of the items property, avoiding the need to sum list entry lengths\n item_type == :item ? self.items.length : super(item_type)\n end", "def size\n @sequence.size\n end", "def count_unique_tokens(type)\n token_tuples(type).uniq.count\nend", "def length\n\t\tself.atoms[0].distance_to(self.atoms[1])\n\tend", "def count(chr = nil, start = nil, stop = nil) \n num = 0\n self.each(chr, start, stop) { |entry| num += 1 }\n num\n end", "def type_count\n type_count = {}\n self.each do |go|\n if type_count[go.class].nil?\n type_count[go.class] = 1\n else\n type_count[go.class] += 1\n end\n end\n return type_count\n end", "def count\n defined_types.size\n end", "def my_count(*args)\n count = 0\n if args[0]\n my_each do |x|\n count += 1 if x == args[0]\n end\n elsif !block_given?\n count = size\n elsif !args[0]\n my_each do |x|\n count += 1 if yield x\n end\n end\n count\n end", "def num_nitro\n @num_nitro ||= total_atoms :N\n end", "def total_annotations_count(source_type)\n 0\n end", "def total_annotations_count(source_type)\n count = 0\n \n count += self.count_annotations_by(source_type)\n \n # TODO: get counts for resources, methods, parameters and representations.\n \n return count\n end", "def my_count(pattern = nil)\n if(block_given?)\n counter = 0\n self.my_each do |x|\n counter += 1 if yield(x)\n end\n return counter\n else\n if(pattern.nil?)\n return self.length \n else\n counter = 0\n self.my_each do |x|\n counter += 1 if x == pattern\n end\n return counter\n end\n end\n \n end", "def complete_count(type=nil)\n if type.class == String && block_given?\n @j_del.java_method(:completeCount, [Java::java.lang.String.java_class,Java::IoVertxCore::Handler.java_class]).call(type,(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ar.result : nil) }))\n return self\n end\n raise ArgumentError, \"Invalid arguments when calling complete_count(#{type})\"\n end", "def size\n @type.size\n end", "def calculate_rank(type, news)\n case type\n when :like\n news.like_count += 1\n return 2\n when :unlike\n news.unlike_count += 1\n return -1\n when :watch\n news.watch_count += 1\n return 1\n when :share\n news.share_count += 1\n return 4\n when :comment\n news.comment_count += 1\n return 3\n when :report\n if admin_logged_in?\n return 2\n end\n return 5\n when :focus # ?��??��?\n return 3\n end\n end", "def count(options = {})\r\n options.stringify_keys!\r\n options.assert_valid_keys(*%W[moType keyword])\r\n resp = connection.get(custom_method_collection_url(:count, options), headers)\r\n resp.body.to_i\r\n end", "def type_size\n @type.size\n end", "def length\n len = 0\n @locations.each do |x|\n if x.sequence\n len += x.sequence.size\n else\n len += (x.to - x.from + 1)\n end\n end\n len\n end", "def countType _obj, _args\n \"_obj countType _args;\" \n end", "def amino_acid_number\n @seq.length\n end", "def get_count(input)\n input.count('aeiou')\nend", "def count(resource_type)\n path = '/api/' + resource_type.to_s\n response = http_get(path,{limit: '1'})\n response[\"meta\"][\"total_count\"]\n end", "def n_of_contact\n cnt = 0\n pre = false\n contacts.each_with_index do |c, i|\n next if i.zero?\n\n cnt += 1 if (pre != c[1]) && c[1]\n pre = c[1]\n end\n cnt\n end", "def length\n case @type\n when :data\n return 0 if self.empty?\n 1\n when :list\n @data[:list].length\n end\n end", "def my_count\n if block_given?\n num = 0\n self.my_each{|item| num += 1 if yield(item)}\n num\n else\n # if no block given return size of array\n self.length\n end\n end", "def my_count(args = nil)\n count = 0\n my_each do |item|\n if block_given?\n count += 1 if yield(item)\n elsif args\n count += 1 if item == args\n else\n count = length\n end\n end\n count\n end", "def get_role_count(role, includeme=true, options={})\n osops_search(\n search_string=role,\n one_or_all=:all,\n include_me=includeme,\n order=[:role],\n safe_deref=nil,\n current_node=nil,\n options\n ).length\n end", "def my_count n = nil\n if block_given?\n truths = 0\n self.my_each {|o| truths += 1 if yield(o)}\n truths\n elsif n.nil?\n self.length\n else\n my_count {|x| x==n}\n end\n end", "def sumdet(tipo)\n\t\t\tsuma=0\n\t\t\teach_determinante {|det|\n\t\t\t\t\tif tipo=='M'\n\t\t\t\t\t\tsuma+=1 if det=='Ma' or det=='Mp'\n\t\t\t\t\telsif tipo=='FD'\n\t\t\t\t\t\tsuma+=1 if det=='FD'\n\t\t\t\t\telsif tipo=='C'\n\t\t\t\t\t\tsuma+=1 if det=='C' or det=='FC' or det=='CF'\n\t\t\t\t\telsif tipo=='Cn'\n\t\t\t\t\t\tsuma+=1 if det=='Cn'\n\t\t\t\t\telsif tipo=='F'\n\t\t\t\t\t\tsuma+1 if det=='F'\n\t\t\t\t\telse\n\t\t\t\t\t\tdet=det.gsub(/[ap]/,'')\n\t\t\t\t\t\tsuma+=1 if det=~/#{tipo}/\n\t\t\t\t\tend\n\t\t\t}\n\t\t\tsuma\n\t\tend", "def get_role_count(role, includeme=true, options={})\n options = {\n :search_string => role,\n :include_me => includeme,\n :order => [:role],\n :safe_deref => nil,\n :current_node => nil,\n :one_or_all => :all\n }.merge(options)\n opsit_search(options).length\n end", "def result_count_by_type\n ret = Hash.new {|h, k| h[k] = 0}\n result_ids.group_by(&:first).each do |scope, ids|\n ret[scope] += ids.size\n end\n ret\n end", "def count(index, types, query, options=nil)\n query = {'q' => query} if query.is_a?(String)\n resp = get do |req|\n req.url \"#{index}/#{types}/_count\", query\n req.body = options if options\n end\n resp.body\n end", "def find_type(type)\n\ttype_return = type.inject({}) { |k, v| k[v] = type.count(v); k }\n\ttype_return.select { |k,v| v == mode_return.values.max }.keys\nend", "def active_count(type=nil)\n if type.class == String && block_given?\n @j_del.java_method(:activeCount, [Java::java.lang.String.java_class,Java::IoVertxCore::Handler.java_class]).call(type,(Proc.new { |ar| yield(ar.failed ? ar.cause : nil, ar.succeeded ? ar.result : nil) }))\n return self\n end\n raise ArgumentError, \"Invalid arguments when calling active_count(#{type})\"\n end", "def number_of_endpoints(type)\n case type\n when :source then API.MIDIEntityGetNumberOfSources(@resource)\n when :destination then API.MIDIEntityGetNumberOfDestinations(@resource)\n end\n end", "def count_and_say(sequence)\n\treturn 0 if sequence == nil\n\tsequence = sequence.to_s\n\tn = sequence.to_s.size\n result = ''\n\ti = 1\n\trepeat = sequence[0]\n\ttimes = 1\n\twhile (i<=n) do\n\t\tif sequence[i] == repeat\n\t\t\ttimes += 1\n else\n \tresult += times.to_s + repeat.to_s\n \ttimes = 1\n repeat \t= sequence[i].to_i\n end\n i+=1\n end \n\treturn result \nend", "def size\n Integer.new.tap do |count|\n each { |element| count += 1 }\n end\n end", "def types_sum(instances)\n result = {}\n instances.each do |id,name,type|\n result[type] = []\n end\n instances.each do |id,name,type|\n result[type] << id\n end\n result.each do |type,list|\n result[type] = result[type].length\n end\n result\nend", "def my_count(e = nil)\n count = 0\n if !e.nil?\n self.my_each do |x|\n if x == e\n count = count + 1\n end\n end\n elsif block_given?\n self.my_each do |x|\n if yield x\n count = count + 1\n end\n end\n else\n count = self.length\n end\n count\n end", "def count(*_args)\n to_a.size\n end", "def get_and_tally_counter_of type, counter\n t = counter[type]\n counter[type] = counter[type] + 1\n t\n end", "def lengthOfSequence(element)\n\nend", "def my_count(arg = nil)\n count = 0\n if block_given?\n my_each do |val|\n count += 1 if yield(val)\n end\n count\n elsif arg.nil?\n length\n else\n my_each do |val|\n count += 1 if val == arg\n end\n count\n end\n end", "def size\n if @size.nil?\n @size = @mset.inject(0) do |total, pair|\n value = pair[1]\n if value.is_a? Array\n total + value.size\n else\n total + 1\n end\n end\n end\n\n @size\n end", "def size_of frame_type\n @avi.indices.select { |m|\n Frame.new(nil, m[:id], m[:flag]).is? frame_type\n }.size\n end", "def search( type, synset )\n\t\tfound, depth = self.traverse( type ).with_depth.find {|ss,depth| synset == ss }\n\t\treturn depth\n\tend", "def badges_count_for_type(badge_type)\n\t self.badges.where(:badge_type => badge_type).count\n end", "def count_code(string)\n count = 0\n empty = []\n (string.size - 3).times do |i|\n slice = string[i..(i + 3)]\n if slice == \"code\" \n count += 1\n end\n end\n return count \nend", "def length\n count = 0\n each { count += 1 }\n count\n end", "def find_type(type)\n type_return = type.inject({}) { |k, v| k[v] = type.count(v); k }\n type_return.select { |k, v| v == mode_return.values.max }.keys\nend", "def countNumX(res, x)\n\t\tsCount = 0\n\n\t\tif res == nil || res.length == 0\n\t\t\treturn sCount\n\t\tend\n\n\t\t# res is an array of constiuents\n\t\tres.each do |constituent|\n\t\t\tif(constituent.pos == x)\n\t\t\t\tsCount = sCount + 1\n\t\t\tend\n\n\t\t\t#search children\n\t\t\tsCount = sCount + countNumX(constituent.children, x)\n\t\tend\n\n\t\treturn sCount\n\tend", "def amount_trains(type_of_train)\n @trains.select { |train| train.type == type_of_train }\n end", "def count\n @count || first[N]\n end", "def size(input); end", "def count\n to_a.size\n end", "def count\n to_a.size\n end", "def mailCount count_type=nil\n # Init the email count to start fresh every time this is called\n total_count = 0\n\n # Get the total count of emails in the Exchange inboxes\n exch_count = exchangeMailCount\n total_count += exch_count\n \n # Get the total count of emails in the IMAP inboxes\n imap_count = imapMailCount\n total_count += imap_count\n\n @email_count = total_count\n puts total_count\n growlNotify\n return @email_count.to_s\n end", "def count_code(str)\n times = 0\n str.size.times do |n|\n if n != (str.size - 1) && n != (str.size - 2) && n != (str.size - 3) && str[n] == \"c\" && str[n + 1] == \"o\" && str[n + 3] == \"e\"\n times += 1\n end\n end\n return times\nend", "def count\n @flags.size\n end", "def number_of(val)\n res = 0\n @array.each { |row| row.each { |v| res +=1 if v == val } }\n res\n end", "def count(line)\n\t\tpos = 0\n\t\twhile (pos < line.length)\n\t\t\t# if marker, decompress and count length\n\t\t\t# else add 1 to length, for normal character\n\t\t\tif line[pos] == \"(\"\n\t\t\t\t# substring containing only the marker\n\t\t\t\tmarker = line[pos, line[pos, line.length - pos].index(\")\") + 1]\n\t\t\t\tlen = marker[/(?<=\\()\\d+/].to_i\n\t\t\t\trepeat = marker[/\\d+\\)$/].to_i\n\t\t\t\t@length += repeat * len\n\n\t\t\t\t# move pos onto next piece of data\n\t\t\t\tpos += marker.length + len\n\t\t\telse\n\t\t\t\t@length += 1\n\t\t\t\tpos += 1\n\t\t\tend\n\t\tend\n\tend", "def child_count(type=nil)\n if ((type != Resource::RESOURCE) && (type != Resource::LEARNING_COLLECTION) && (type != Resource::COLLECTION_OBJECT) && (type != Resource::EXHIBITION))\n type = nil\n end\n if (type == nil)\n responses = Resource.where(\"in_response_to_resource_id = ? AND response_banned_on IS ?\", self.id, nil)\n return self.children.length - responses.length\n end\n\n # TODO: cache this\n r = ResourceHierarchy.joins(:child_resource).where(\"resources.resource_type = ? AND resource_hierarchies.resource_id = ?\", type, self.id)\n return r.length\n end", "def on_call_count(context, expression)\n retval = process(expression, context)\n\n unless retval.is_a?(XML::NodeSet)\n raise TypeError, 'count() can only operate on NodeSet instances'\n end\n\n return retval.length.to_f\n end", "def count\n Jhead.call(\"-c\", @match, @pattern).split(\"\\n\").size\n end", "def countSubst(path)\n count = 0\n path.each do | atom |\n if @atoms[atom].size > 2 then\n count += (@atoms[atom].size - 2)\n end\n end\n count\n end", "def superclass_count(node)\n count = 0\n n = node\n while n = n.superclass\n count += 1\n end\n count\n end" ]
[ "0.63567305", "0.63145524", "0.61980516", "0.60390794", "0.59796715", "0.5946256", "0.5850562", "0.5831301", "0.58186245", "0.5765675", "0.5749233", "0.56758785", "0.56386787", "0.56018287", "0.5587829", "0.55661076", "0.5442579", "0.5369471", "0.53659385", "0.53339356", "0.5318279", "0.5309525", "0.5293663", "0.5271166", "0.52670354", "0.52658474", "0.5250372", "0.52255136", "0.52255136", "0.5219671", "0.52031803", "0.51969075", "0.51588905", "0.5139046", "0.51292", "0.5103269", "0.5084313", "0.5061929", "0.50412136", "0.50383735", "0.50019276", "0.49982104", "0.49955198", "0.49839973", "0.4981724", "0.49797106", "0.49768573", "0.49625438", "0.49498352", "0.49481088", "0.49405694", "0.49402434", "0.49336", "0.49093822", "0.49086234", "0.4903098", "0.4902922", "0.48775533", "0.4855987", "0.48557663", "0.4809878", "0.48018986", "0.47876275", "0.47765154", "0.4776458", "0.47712332", "0.47701535", "0.47694328", "0.47677505", "0.4754456", "0.4751845", "0.47431535", "0.47397533", "0.47362", "0.4736061", "0.47358245", "0.47274935", "0.47215015", "0.47209588", "0.47150344", "0.47018588", "0.469621", "0.46904618", "0.46879646", "0.4658844", "0.46558487", "0.46503913", "0.46484315", "0.46450123", "0.46450123", "0.46444345", "0.46441403", "0.46438345", "0.4639622", "0.46365854", "0.46315062", "0.46306235", "0.4613403", "0.46129137", "0.4611742" ]
0.68754864
0
Return the number of carbons.
def num_carbon @num_carbon ||= total_atoms :C end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def car_count\n self.cars.length\n end", "def show_cars_count\n puts \"cars count: #{cars.size}\"\n end", "def show_cars_count\n puts \"cars count: #{self.cars.size}\"\n end", "def num_bombs\n count = 0\n (0...9).each do |ro|\n (0...9).each do |co|\n if @grid[ro][co] == :B\n count += 1 \n end\n end\n end\n count\n end", "def get_wheel_count \n \t Car_wheel #Return number of wheels\n end", "def bike_count\n bikes.count\n end", "def total_birds\n birds.count\n end", "def lots_count\t\t\n lots.count\n end", "def number_of_councils\n payer_breakdown && payer_breakdown.select{ |p| p[:organisation_type] == 'Council' }.size\n end", "def number_of_bottles\n bottles = self.line_items.inject(0) {|bottles, line_item| bottles + line_item.quantity}\n end", "def number_of_bottles\n bottles = self.line_items.inject(0) {|bottles, line_item| bottles + line_item.quantity}\n end", "def count_drinks_customer()\n @drinks.count\n end", "def numbers_of_planes\n\t\t@landed_planes.count \n\tend", "def door_count; end", "def num_gears\n num = 0\n group_instances.each { |g| num += g.gears.count}\n num\n end", "def head_count\n clients.map(&:headOfHousehold?).count(true)\n end", "def no_of_cards\r\n @card_list.no_of_cards\r\n end", "def no_of_cards\r\n @card_list.no_of_cards\r\n end", "def no_of_cards\n @card_list.no_of_cards\n end", "def no_of_cards\n @card_list.no_of_cards\n end", "def no_of_cards\n @card_list.no_of_cards\n end", "def carbs_consumed\n\t\t@snack_carbs.values.reduce(0, :+)\n\tend", "def count\n @monkeys.count\n end", "def customers_count()\n return customers().length()\n end", "def count_places\n COUNT_PLACES\n end", "def climb_count\n self.climbs.inject(0) do |sum, climb|\n sum += climb.block_1 if climb.block_1\n sum += climb.block_2 if climb.block_2\n sum += climb.block_3 if climb.block_3\n sum += climb.block_4 if climb.block_4\n sum\n end\n end", "def count_customers\n return customers().length\n end", "def num_tankoubon; end", "def total_orbit_count(orbit_map)\n count = 0\n orbit_map.each{|satellite, _|\n central_objects = orbit_count(orbit_map, satellite)\n # puts \"Satellite %s orbits %d objects\" % [satellite, central_objects]\n count += central_objects\n }\n count\nend", "def num_of_customers\n total_customers = self.customers\n return total_customers.size\n end", "def espacios_disponibles_carros\n Space.where(sp_state: false, sp_type: 'CARRO').count\n end", "def no_of_cards\n @cards.length\n end", "def bike_count\n\t\tbikes.count #+ broken_bikes.count\n\tend", "def count\n @cards.count\n end", "def number_of_bettors\n if defined? @recent_goal.bets.count\n @recent_goal.bets.count\n else\n 0\n end \n end", "def count_bombs(neighbors)\n num = 0\n neighbors.each do |neighbor|\n num += 1 if @actual_board[neighbor.first][neighbor.last].is_bomb?\n end\n num\n end", "def num_oxygen\n @num_oxygen ||= total_atoms :O\n end", "def count\n return cards.length \n end", "def count\n @cards.length\n end", "def dinosaur_count\n @@count += 1\n end", "def dinosaurii_count\n @@count += 1\n end", "def count\n @cards.size\n end", "def count\n @cards.size\n end", "def spicy_count\n self.spicies.size\n end", "def count\n cards.count\n end", "def count\n @cards.length\n end", "def river_count\n return @fishes.count\nend", "def getNbRecompense\n return 0\n end", "def count\n @atlas.count\n end", "def comic_count\r\n \tsorted_articles.length\r\n end", "def number_of_cases\n fee_quantity_for('BANOC') + 1\n end", "def count\n @cards.count\n end", "def count\n @cards.count\n end", "def count\n @cards.count\n end", "def total_cards\n cards.count\n end", "def numCards\n\t\t@cards.reduce(0) {|memo, card| memo += card.copies}\n\tend", "def count\n @deck.size\n end", "def count\n @count\n end", "def dinosaurus_count\n @@count += 1\n end", "def num_of_customers()\n customers.size\nend", "def num_neighbors\r\n @neighbors.count\r\n end", "def gc\n s = codons.map { |c| c.nuc_codon[2] }.join\n ((s.count('G')+s.count('C')).to_f/codons.count).round(4)\n end", "def stock_count\n sql = \"SELECT * FROM cars\n WHERE shop_id = $1\"\n value = [@id]\n cars = SqlRunner.run(sql, value)\n result_array = cars.map{|car| Car.new(car)}\n count = result_array.count\n return count\n end", "def num_doctors\n doctors.count\n end", "def count; end", "def count; end", "def count; end", "def count\n lib.tcidbrnum( @db )\n end", "def count_bottles(bottles)\n puts \"There are #{bottles.count} bottles on the wall.\"\n end", "def get_colony_numbers\n show do\n title \"Count colonies with CFU software\"\n note \"In the gel room, load up the CFU software and prepare the camera.\"\n note \"For each plate: take a picture of the plate, drag the image into the CFU, and record the number of colonies\"\n \n operations.each do |op|\n if op.temporary[:valid_params?]\n plate = op.input(\"Plate\").item\n get \"number\", var: \"n#{plate.id}\", label: \"Number of colonies on #{plate}\", default: 5\n select [\"normal\", \"contamination\", \"lawn\"], var: \"s#{plate}\", label: \"Choose whether there is contamination, a lawn, or whether it's normal.\", default: 0\n end\n end\n end \n end", "def count\n @deck.count\n end", "def bc_count\n \t@generic.size + @initial.size + @final.size + @cyclic.size\n end", "def bank_count\n return @battlers.size\n end", "def orbit_count(orbit_map, satellite)\n count = 0\n while satellite = orbit_map[satellite]\n count += 1\n end\n count\nend", "def joinees_count\n self.joinees.count\n end", "def count\n @count ||= 0\n @count += 1\n end", "def n\n @clensing_data.size\n end", "def nr_of_regions\n ConnectedComponents.new(in_use_graph).count\n end", "def numConnections\n if activeConnections? then do\n n = 0\n @connectedClients.each {|client| n += 1 }\n return n\n else\n return 0\n end\n end", "def total_no_of_customers()\n @@no_of_customers += 1\n puts \"Total number of customers: #@@no_of_customers\"\n end", "def num_cookmarks\n Rcpref.where([\"recipe_id = ? AND in_collection = ?\", self.id, true]).count\n end", "def fish_count()\n return @fish.length()\n end", "def count\n count = 0\n each do |data|\n count += 1\n end\n count\n end", "def count\n\t\tputs \"Counting number of entries in the CIDR cache table ...\" if @verbose\n\t\tcnt=0\n\t\t@known_cidr_blks.keys.map do |key|\n\t\t\tif is_cidr?(key)\n\t\t\t\tcnt=cnt+1\n\t\t\tend\n\t\tend\n\t\tputs \"Current number of CIDR object entries: #{cnt}\" if @verbose\n\t\treturn cnt\n\trescue => ee\n\t\tputs \"Exception on method #{__method__}: #{ee}\" if @verbose\n\tend", "def borrowed_books_count\n @borrowed_books.length\n end", "def borrowed_books_count\n @borrowed_books.length\n end", "def bond_count( child_model = nil )\n filter = {\n :parent_model => self.class.to_s,\n :parent_id => id,\n :manual => true,\n :relation => 1\n }\n filter.merge :child_model => child_model if child_model\n Bond.count filter\n end", "def cc_count\n stats = self.association_stats\n stats['cc_conditions'] + stats['cc_loops'] + stats['cc_questions'] +\n stats['cc_sequences'] + stats['cc_statements']\n end", "def hidratos_carbono\r\n hc = 0\r\n @lista_alimentos.each do |i|\r\n hc += i.carbohidratos\r\n end\r\n return hc\r\n end", "def zone_count\n da_zones=zones\n count = da_zones.count\n da_zones.each{ |z| count += z.zone_count }\n count\n end", "def total_no_of_customers()\n @@no_of_customers += 1\n puts \"Total number of customers: #@@no_of_customers\"\n end", "def countNbVides()\n @nbVides = 0\n\n @grille.each do |ligne|\n ligne.each do |c|\n if( c[\"value\"] == nil)\n @nbVides += 1\n end\n end\n end\n end", "def count\n @count\n end", "def count\n @count\n end", "def count\n @count\n end", "def number_of_calories\n self.ingredients.sum(\"calories\")\n end", "def trip_count()\n self.trips().length()\n end", "def calculate_num_children\n for x in @lattice do\n for c in @lattice.lower_covers[x] do\n if @irreducibles.contain?(c) then\n @num_children[x] += 1\n end\n end\n end\n end", "def count\r\n @pitches.size\r\n end", "def get_num_bingos\n check_and_mark_left_x\n check_and_mark_right_x\n check_horizontal_bingos\n check_vertical_bingos\n @num_bingos\n end" ]
[ "0.7277891", "0.71840256", "0.71306664", "0.7058281", "0.65940386", "0.65794706", "0.6518702", "0.64791226", "0.6458497", "0.6451858", "0.6451858", "0.64388806", "0.64099425", "0.64028925", "0.6386796", "0.6382967", "0.63799137", "0.63799137", "0.6376489", "0.6376489", "0.6376489", "0.63497776", "0.63207304", "0.6317984", "0.6290669", "0.6281755", "0.6271635", "0.62665975", "0.62526804", "0.6242696", "0.62419957", "0.6239737", "0.622215", "0.62198293", "0.62171483", "0.62120444", "0.62024003", "0.62004906", "0.6194204", "0.6183843", "0.6150518", "0.61497796", "0.61497796", "0.61433494", "0.6118408", "0.61151534", "0.6105361", "0.61022824", "0.60984", "0.6096455", "0.6092639", "0.60493326", "0.60493326", "0.60493326", "0.6049138", "0.603883", "0.6020437", "0.601435", "0.6001817", "0.59951013", "0.5986336", "0.5981665", "0.5976483", "0.5967334", "0.59582335", "0.59582335", "0.59582335", "0.5942545", "0.59267825", "0.59261394", "0.59137124", "0.5913504", "0.59130484", "0.5912351", "0.59057194", "0.59036666", "0.58957016", "0.58950967", "0.58924156", "0.5891857", "0.58870006", "0.5886958", "0.587951", "0.586586", "0.58615416", "0.58615416", "0.5858903", "0.5856569", "0.5850993", "0.5844658", "0.5838121", "0.5837363", "0.58366907", "0.58366907", "0.58366907", "0.5833097", "0.5832615", "0.58237845", "0.58202314", "0.58161455" ]
0.5889996
80
Return the number of nitrogens.
def num_nitro @num_nitro ||= total_atoms :N end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def number_of_concept_genres(login=nil)\n count_by_frbr(login, :has_as_its_genre, :how_many_concepts?) \n end", "def number_of_concept_genres(login=nil)\n count_by_frbr(login, :has_as_its_genre, :how_many_concepts?) \n end", "def count\n count = 0\n\n each do |node|\n count += 1\n end\n\n return count\n end", "def getNbRecompense\n return 0\n end", "def num_of_tickets()\n result = films()\n @number_of_tickets = result.count\n end", "def number_of_improvisors(login=nil)\n count_by_frbr(login, :is_improvised_by, :how_many_roles?) \n end", "def number_of_improvisors(login=nil)\n count_by_frbr(login, :is_improvised_by, :how_many_roles?) \n end", "def count_no\n rsvp.no.count\n end", "def number_of_notators(login=nil)\n count_by_frbr(login, :is_notated_by, :how_many_roles?) \n end", "def count_no\n rsvp.no.count\n end", "def number_of_bottles\n bottles = self.line_items.inject(0) {|bottles, line_item| bottles + line_item.quantity}\n end", "def number_of_bottles\n bottles = self.line_items.inject(0) {|bottles, line_item| bottles + line_item.quantity}\n end", "def count(n)\n sum = 1\n n.prime_division.each do |x|\n sum *= (x[1] + 1)\n end\n sum\n end", "def count\n number_of_trees + number_of_networks\n end", "def nbSommets()\n return @sommets.count()\n end", "def n\n @reps.size\n end", "def get_num_rides(rides)\n return rides.length\nend", "def count_item\n count = 0\n @g_net.each do |followers|\n count += 1 unless !followers or followers.empty?\n end\n count\n end", "def lots_count\t\t\n lots.count\n end", "def count()\n return @i\n end", "def how_many\n return @@total_samurais\n end", "def count \n puts \"Tu as scrappé #{@result_scrap.count} élémént(s)\"\n return @result_scrap.count\n end", "def calculate_nicotin\n (Smoke.by_user(self.id).sum(:counted) * cigaret_nicotin).convert_to('milligram')\n .to_i\n .round(2)\n end", "def inviters_count\n self.inviters.count\n end", "def num_funding_rounds\n self.funding_rounds.count\n end", "def num_funding_rounds\n self.funding_rounds.count\n end", "def number_of_sellers(login=nil)\n count_by_frbr(login, :is_sold_by, :how_many_roles?) \n end", "def njobs\n @njobs.to_i\n end", "def number_of_commissioners(login=nil)\n count_by_frbr(login, :is_commissioned_by, :how_many_roles?) \n end", "def number_of_votes\n self.votes.size\n end", "def n\n x.size\n end", "def digit_count(titles)\n Math.log10(titles.size).to_i + 1\n end", "def count\n @count || first[N]\n end", "def number_of_reviews\n self.reviews.count\n end", "def num_ratings\n ratings.count\nend", "def count\n @count\n end", "def count\n count = 0\n each do |data|\n count += 1\n end\n count\n end", "def ntCount\n return @ntIndex.length\n end", "def how_many_students\n number = roster.length\n \"There are #{number} students in our class\"\nend", "def my_count n = nil\n if block_given?\n truths = 0\n self.my_each {|o| truths += 1 if yield(o)}\n truths\n elsif n.nil?\n self.length\n else\n my_count {|x| x==n}\n end\n end", "def count_genes()\n self.regulatory_elements.map {|reg| reg.gene_id}.to_set.count\n end", "def num_questions\n n = 0\n self.sections.each do |s|\n n+= s.questions.size()\n end\n return n\n end", "def count_students\n students.size\n end", "def count_students\n students.size\n end", "def count\n @count ||= get_count\n end", "def num_students\n self.students.count\n end", "def number_of_works_realised_through(login=nil)\n count_by_frbr(login, :is_realisation_of, :how_many_works?) \n end", "def numEnts\n num = 1\n num += @lfn_ents.size if @lfn_ents\n return num\n end", "def disgems_count\n Recommendable.config.ratable_classes.inject(0) do |sum, klass|\n sum + disgemd_count_for(klass)\n end\n end", "def number_of_tickets_bought() # working in terminal - console (eg.: customer1.number_of_tickets_bought)\n return films.count\n end", "def get_num\n\t\treturn @num_users\n\tend", "def total_count\n @total_count ||= @possibility_distribution.inject(0) { |sum, n| sum + n.last }\n end", "def count\n @count ||= 0\n @count += 1\n end", "def get_number_of_cpu\n return `cat /proc/cpuinfo | grep processor | wc -l`.to_i\n end", "def trip_count()\n self.trips().length()\n end", "def processors_count\n @processors.length\n end", "def total_num_team_reviews\n team_review_counts.inject(:+)\n end", "def number_of_realisations(login=nil)\n count_by_frbr(login, :is_realised_through, :how_many_expressions?) \n end", "def countNumDitran(res)\n\t\tdCount = 0\n\n\t\tif res == nil || res.length == 0\n\t\t\treturn dCount\n\t\tend\n\n\t\t# make sure to not count, for example, NP-SBJ\n\n\t\tres.each do |constituent|\n\t\t\t# verify Ditransitive Verb Phrase\n\t\t\t# looking for exactly two immediate constituents of type NP\n\t\t\tif(constituent.has_children? && constituent.children.length == 2 && constituent.pos == @vp)\n\t\t\t\tif(constituent.children[0].pos == @np && constituent.children[1].pos == @np)\n\t\t\t\t\tdCount = dCount + 1\n\t\t\t\tend\n\t\t\tend\n\n\t\t\tdCount = dCount + countNumDitran(constituent.children)\n\t\tend\n\n\t\treturn dCount\n\tend", "def likes_count\n Recommendable.config.ratable_classes.inject(0) do |sum, klass|\n sum + liked_count_for(klass)\n end\n end", "def nb_opinions() opinion_ids.size end", "def num_questions\n n = 0\n sections.each do |s|\n n += s.questions.size\n end\n n\n end", "def count_total()\n self.regulatory_elements.count\n end", "def total_votes\n num_of_votes = self.votes.count\n return num_of_votes\n end", "def number_of_work_influences(login=nil)\n count_by_frbr(login, :is_influenced_by, :how_many_works?) \n end", "def count \n trips.length\n end", "def simber_count(n)\n lower_range = 10**(n - 1)\n upper_range = (10**n) - 1\n count = 0\n (lower_range..upper_range).each do |i|\n count += 1 if simber_check(i)\n end\n count\nend", "def number_of_performers(login=nil)\n count_by_frbr(login, :is_performed_by, :how_many_roles?) \n end", "def number_of_performers(login=nil)\n count_by_frbr(login, :is_performed_by, :how_many_roles?) \n end", "def get_number\n @number_of_repos\n end", "def number_of_commissioned_works(login=nil)\n count_by_frbr(login, :has_commissioned, :how_many_works?) \n end", "def votes_count\n votes.size\n end", "def count_tickets\n tickets = self.tickets\n total_tickets = tickets.count\n return total_tickets\n end", "def number_of_sales\n product_sales = self.sales\n num_of_sales = product_sales.length\n return num_of_sales\n end", "def size\n counter = 0\n each { |node| counter += 1 }\n return counter\n end", "def node_count(type = nil)\n if type\n value = @db.m_get(\"node#{type}\")\n if value\n value.to_i\n end\n else\n @db.m_get(\"n\").to_i\n end\n end", "def count\n\t\t\t\t# CPU count can change during the program runtime\n\t\t\t\tcpuinfo.count { |x| x.start_with?('processor') }\n\t\t\tend", "def number_readied\n readied_cards.count\n end", "def n\n @clensing_data.size\n end", "def number_of_sales\n array_sales = sales\n num_sales = array_sales.length\n puts \"#{num_sales} #{name} were sold\"\n return num_sales\n end", "def get_ingredient_counts\n otc = 0\n legend = 0\n self.ingredients.each do |ingredient|\n if ingredient.get_base_item.drug_class == 'legend'\n legend += 1\n elsif ingredient.get_base_item.drug_class == 'over_the_counter'\n otc += 1\n end\n end\n self.number_legend_ingredients = legend\n self.number_otc_ingredients = otc\n end", "def number_of_superwork_influences(login=nil)\n count_by_frbr(login, :is_influenced_by, :how_many_superworks?) \n end", "def num_researched\n @num_researched ||= worth_counting { count_researched }\nend", "def gems_count\n Recommendable.config.ratable_classes.inject(0) do |sum, klass|\n sum + gemd_count_for(klass)\n end\n end", "def number_of_councils\n payer_breakdown && payer_breakdown.select{ |p| p[:organisation_type] == 'Council' }.size\n end", "def get_number_of_voices()\n # If there is no number of voices set, set it to 2.\n if @metadata[:number_of_voices] == nil\n @metadata[:number_of_voices] = 2\n end\n return @metadata[:number_of_voices]\n end", "def count\n @count\n end", "def count\n @count\n end", "def count\n @count\n end", "def battlers_number\n return @battlers_number.sum\n end", "def count\n each.size\n end", "def rating_count\n search_by_itemprop('ratingCount').to_i\n end", "def count\n each.count\n end", "def num_tankoubon; end", "def processor_count\n @processor_count.value\n end", "def not_visitors_count\n self.not_visitors.count\n end", "def occurences_count\n\t\t\t\t\t\tHash.new(0).tap do |result|\n\t\t\t\t\t\t each { |item| result[item] += 1 }\n\t\t\t\t\t\tend\n\t\t\t\tend", "def reviews_count\n\t\treviews.size\n\tend", "def number_of_concept_influences(login=nil)\n count_by_frbr(login, :is_influenced_by, :how_many_concepts?) \n end", "def number_of_concept_influences(login=nil)\n count_by_frbr(login, :is_influenced_by, :how_many_concepts?) \n end" ]
[ "0.68646866", "0.68646866", "0.6578251", "0.6530618", "0.64941645", "0.6474515", "0.6474515", "0.64725417", "0.6360934", "0.63361204", "0.63211834", "0.63211834", "0.63051116", "0.62940323", "0.6272964", "0.62563336", "0.6251159", "0.6243836", "0.6237959", "0.62242717", "0.6208473", "0.62068444", "0.61981803", "0.6192294", "0.6192239", "0.6192239", "0.6188558", "0.61827314", "0.616738", "0.6165309", "0.61589736", "0.6138511", "0.61355555", "0.6130826", "0.6126029", "0.6108112", "0.60935175", "0.60786015", "0.6076098", "0.60727364", "0.6072509", "0.6066953", "0.60661346", "0.60661346", "0.6059171", "0.60537463", "0.60533094", "0.60493064", "0.6043568", "0.60427445", "0.6041326", "0.60410726", "0.60378623", "0.60341406", "0.6031807", "0.60229445", "0.6011633", "0.6007235", "0.6005681", "0.60052073", "0.6005005", "0.5998929", "0.5995428", "0.5984283", "0.59841865", "0.5984133", "0.5977256", "0.5955976", "0.595573", "0.59521186", "0.5947599", "0.59450793", "0.59449947", "0.5944901", "0.59438866", "0.5934564", "0.59327894", "0.59312695", "0.59309554", "0.5927182", "0.5925455", "0.59187186", "0.59172124", "0.59155667", "0.59153926", "0.5909674", "0.5907231", "0.5907231", "0.5907231", "0.5905513", "0.5902907", "0.5894329", "0.5891811", "0.5889927", "0.58885336", "0.588827", "0.58846396", "0.5883207", "0.58826214", "0.58826214" ]
0.7361511
0
Return the number of oxygens.
def num_oxygen @num_oxygen ||= total_atoms :O end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def size\n @gens.size\n end", "def size\n @gens.size\n end", "def lots_count\t\t\n lots.count\n end", "def length\n @gens.length\n end", "def length\n @gens.length\n end", "def nb_opinions() opinion_ids.size end", "def count\n @ole.Count\n end", "def count\n @ole.Count\n end", "def count\n @ole.Count\n end", "def count\n @ole.Count\n end", "def count\n @ole.Count\n end", "def count\n @ole.Count\n end", "def count\n @ole.Count\n end", "def count\n @ole.Count\n end", "def total_count\n object.nodes.size\n end", "def n\n x.size\n end", "def size\n count = 0\n visit_nodes do\n count += 1\n end\n count\n end", "def shape_count\n\t\treturn @shapes.length\n\tend", "def length\n\n count_objects()\n end", "def num_nitro\n @num_nitro ||= total_atoms :N\n end", "def num_gears\n num = 0\n group_instances.each { |g| num += g.gears.count}\n num\n end", "def size\n @components.values.inject(0) { |component_count, attribute| component_count + attribute.size }\n end", "def length\n @main_generator.length\n end", "def n\n @clensing_data.size\n end", "def nbSommets()\n return @sommets.count()\n end", "def count\n @atlas.count\n end", "def count\n count = 0\n\n each do |node|\n count += 1\n end\n\n return count\n end", "def numEnts\n num = 1\n num += @lfn_ents.size if @lfn_ents\n return num\n end", "def size\n num_geometries\n end", "def omission_count\n @omissions.size\n end", "def num_connections\n @num_connections ||= @doc.xpath('/person/num-connections').text\n end", "def num_neighbors\r\n @neighbors.count\r\n end", "def length\n genes.length\n end", "def n\n points.size\n end", "def nr_of_regions\n ConnectedComponents.new(in_use_graph).count\n end", "def hydrogen_count\n @ob.implicit_hydrogen_count + @ob.explicit_hydrogen_count\n end", "def count()\n @list_of_positions.length\n end", "def node_count\n @nodes.length - 1\n end", "def game_objects_count\n @game_objects.count\n end", "def size\n counter = 0\n each { |node| counter += 1 }\n return counter\n end", "def number_of_verts\n\t\t@number_of_verts ||= begin\n\t\t\tsize = 0\n\t\t\t@primitives.each do |primitive|\n\t\t\t\tprimitive[:verts].each do |index|\n\t\t\t\t\tvert = @verts[index]\n\t\t\t\t\tsize += vert[:vector].length\n\t\t\t\tend\n\t\t\tend\n\t\t\tsize\n\t\tend\n\tend", "def size\n count = 0\n @properties.each do |gid, values|\n if ! values.empty?\n count += 1\n end\n end\n return count\n end", "def count_objects\n ObjectSpace.count_objects\n end", "def objects_count\n @objects_count ||= objects.size\n end", "def size\n @count\n end", "def size\n @count\n end", "def processors_count\n @processors.length\n end", "def object_shape_count\n ::RubyVM::YJIT.runtime_stats[:object_shape_count]\n end", "def nbHypotheses()\n\t\treturn @grillesHypothese.count\n\tend", "def count_objects\n count = 0\n @objects.keys.each do |key|\n count += @objects[key].length\n end\n\n return count\n end", "def count\n underlying_array.length\n end", "def size\n return @examples.length\n end", "def length; count end", "def number_of_exons\n unless defined?(@number_of_exons)\n @number_of_exons = field_fetch('Number of exons', @d0).to_i\n end\n @number_of_exons\n end", "def length\n @count\n end", "def points_len()\n if @handle.ptr == nil\n raise \"this is disposed\"\n end\n result = Native.GraphComponentState_points_len(@handle.ptr)\n result\n end", "def object_count\n 0\n end", "def count\n @count ||= 0\n @count += 1\n end", "def joinees_count\n self.joinees.count\n end", "def length\n each.count\n end", "def count; end", "def count; end", "def count; end", "def number_of_bottles\n bottles = self.line_items.inject(0) {|bottles, line_item| bottles + line_item.quantity}\n end", "def number_of_bottles\n bottles = self.line_items.inject(0) {|bottles, line_item| bottles + line_item.quantity}\n end", "def length\n count\n end", "def count\n to_a.size\n end", "def count\n to_a.size\n end", "def size\n @n\n end", "def size\n @n\n end", "def num_points\n @size * @size\n end", "def count\n each.size\n end", "def count_genes()\n self.regulatory_elements.map {|reg| reg.gene_id}.to_set.count\n end", "def emittersCount\n\n @emitters.length\n\n end", "def ntCount\n return @ntIndex.length\n end", "def count\n all.size\n end", "def size\n all_nodes.length\n end", "def door_count; end", "def count\r\n @internal_list.length\r\n end", "def size\n C.LLVMCountParams(@fun)\n end", "def number_of_people\n\t\tusers.length\n\tend", "def count\n # implement in subclasses\n end", "def count\n each.count\n end", "def how_many_on_bus\n return @passengers.length\n end", "def size()\n #This is a stub, used for indexing\n end", "def size()\n #This is a stub, used for indexing\n end", "def number_of_sales\n return sales.length\n end", "def num_tankoubon; end", "def size\n @nodes.length\n end", "def size\n @nodes.length\n end", "def num_lines() @line_indices.length + 1 end", "def size\n Integer.new.tap do |count|\n each { |element| count += 1 }\n end\n end", "def number_of_sales\n product_sales = self.sales\n num_of_sales = product_sales.length\n return num_of_sales\n end", "def length\n @array_specs.spec_count\n end", "def count(options = {})\n @owner.ids_for_outbound(@reflection.options[:property]).size\n end", "def number_of_sales\n return self.sales.length\n end", "def numVertices\n @vertices.size\n end", "def numVertices\n @vertices.size\n end", "def num_doctors\n doctors.count\n end", "def orangeCount\n return @oranges\n end" ]
[ "0.6822128", "0.6822128", "0.6805353", "0.6792886", "0.6792886", "0.671845", "0.66310984", "0.66310984", "0.66310984", "0.66310984", "0.66310984", "0.66310984", "0.66310984", "0.66310984", "0.6570404", "0.6523384", "0.65066195", "0.6486188", "0.6468808", "0.6466652", "0.6459477", "0.63646", "0.63633066", "0.6354993", "0.63545984", "0.63347286", "0.6332499", "0.6328465", "0.6322793", "0.6318714", "0.6316104", "0.6313365", "0.630145", "0.62846893", "0.6277713", "0.62688607", "0.6267298", "0.62541807", "0.6249631", "0.623403", "0.6225705", "0.62196463", "0.62088406", "0.6199286", "0.6177536", "0.6177536", "0.6176894", "0.61620146", "0.6157767", "0.6154855", "0.61434025", "0.6130424", "0.6129874", "0.6121904", "0.61155975", "0.61147296", "0.61134785", "0.6113317", "0.6112796", "0.6110571", "0.60985863", "0.60985863", "0.60985863", "0.6094312", "0.6094312", "0.60900813", "0.6085834", "0.6085834", "0.6083416", "0.6083416", "0.6082413", "0.60822374", "0.60402", "0.6038011", "0.6032429", "0.60244703", "0.60217905", "0.60136265", "0.6013278", "0.6007153", "0.60067815", "0.6003497", "0.60002893", "0.600017", "0.599907", "0.599907", "0.59970385", "0.5995252", "0.5995161", "0.5995161", "0.59803545", "0.59737545", "0.5963604", "0.59628904", "0.5957223", "0.5956719", "0.59512836", "0.59512836", "0.5941027", "0.5938066" ]
0.6822373
0
Return the number of sulphurs.
def num_sulphur @num_sulphur ||= total_atoms :S end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def total_susus_global\n susus = Susu.all.count\n end", "def how_many\n return @@total_samurais\n end", "def spicy_count\n self.spicies.size\n end", "def dinosaurii_count\n @@count += 1\n end", "def num_shelf\n\t\tputs \"Library has #{@shelves.length} shelves\"\n\tend", "def dinosaurus_count\n @@count += 1\n end", "def count_sparsity\n (1 - count_edge.to_f/(count_user*count_item))*100\n end", "def total_sprees\n ranked_sprees.to_i + social_sprees.to_i\n end", "def count \n trips.length\n end", "def dinosaur_count\n @@count += 1\n end", "def count \n puts \"Tu as scrappé #{@result_scrap.count} élémént(s)\"\n return @result_scrap.count\n end", "def fish_count()\n return @fish.length()\n end", "def num_of_tracks\n\t\t@tracks.count\t \n\tend", "def smells_count\n smells.length\n end", "def count; end", "def count; end", "def count; end", "def number_of_sales\n return sales.length\n end", "def num_ships\n @grid.reduce(0) { |acc, el| acc + el.count(:S) }\n end", "def length\n count(:up)\n end", "def nbSommets()\n return @sommets.count()\n end", "def count_students\n students.size\n end", "def count_students\n students.size\n end", "def count\n each.size\n end", "def count\n @count\n end", "def number_of_sales\n return sales.length\n # counter = 0\n # FarMar::Sale.all.each do |i|\n # if i.product_id == self.id\n # counter += 1\n # end\n # end\n # return counter\n end", "def sheep_count(num)\n \nend", "def numberOfLaws\n @@numberOfLaws\n end", "def number_of_sales #returns the number of times this product has been sold.\n\t\tsales\n\t\treturn sales.length\n\n\tend", "def count\n @count ||= 0\n @count += 1\n end", "def count\n each.count\n end", "def number_of_sales\n array_sales = sales\n num_sales = array_sales.length\n puts \"#{num_sales} #{name} were sold\"\n return num_sales\n end", "def count_signs\n # suskaiciuojami visi zenklai\n temp = 0\n @signs.size.times do |i|\n temp += 1 if @signs[i] != 0\n end\n temp\n end", "def num_tankoubon; end", "def number_of_sales\n sales.length\n end", "def number_of_sales\n sales.length\n end", "def count_rulings(card)\n ruling_arr = scryfall.rulings(card['id']) \n \"(#{ruling_arr.length})\"\n end", "def food_count()\nreturn @stomach.count()\nend", "def count_no\n rsvp.no.count\n end", "def count()\n return @i\n end", "def students_scheduled\n self.lessons.size\n end", "def number_of_splice_sites\n unless defined?(@number_of_splice_sites)\n @number_of_splice_sites = \n field_fetch('Number of splice sites', @d0).to_i\n end\n @number_of_splice_sites\n end", "def count\n @count\n end", "def count\n @count\n end", "def count\n @count\n end", "def count\n @target.count.to_i\n end", "def state_count\n @states.size\n end", "def number_of_sales\n sales.count\n end", "def number_of_sales\n sales.count\n end", "def count_no\n rsvp.no.count\n end", "def count\n run.count\n end", "def track_count\n return @tracks.length\n end", "def count_losses\n loss_no = 0\n Battle.where(\"movie_loser\" => self.id).each do\n loss_no += 1 \n end\n return loss_no\n end", "def size\n @count\n end", "def size\n @count\n end", "def length\n @count\n end", "def number_of_songs()\n return songs.length\n end", "def number_of_songs()\n return songs.length\n end", "def ship_count\n count = []\n @rows.each do |row|\n count << row.count('s')\n end\n count.reduce(:+)\n end", "def count\n all.size\n end", "def num_non_responsive\n @hops.find_all { |hop| !hop.ping_responsive }.size\n end", "def count\n @count || first[N]\n end", "def count\n @count ||= 0\n end", "def count\n count = 0\n each do |data|\n count += 1\n end\n count\n end", "def get_total_snpinfo_boxes\n return @snpinfo_tracks.length\n end", "def number_of_sales\n sales.count\n end", "def number_of_sales\n sales.count\n end", "def number_of_zeros\r\n total_zeros = 0\r\n @seminarians.each do |sem|\r\n zeros = sem.number_of_zeros\r\n total_zeros += zeros\r\n end\r\n\r\n #Divide by 2 to correct the fact that each was counted twice\r\n return total_zeros/2\r\n end", "def count\n end", "def count\n end", "def num_states\n@state.size\nend", "def number_of_sales\n product_sales = self.sales\n num_of_sales = product_sales.length\n return num_of_sales\n end", "def length\n each.count\n end", "def counts\r\n @counts\r\n end", "def count\r\n @pitches.size\r\n end", "def shoe_count\n count = @shoe.count\n positive = count >= 0\n \"Current Deck Count: #{positive ? \"+\" : \"-\"}#{count.abs}\"\n end", "def fortress_squads_num\n return 0 unless fortress_status\n squads = Array.new\n fortress_cells.each do |cell|\n squads << cell.squad unless cell.squad_id.blank?\n end\n return squads.size\n end", "def count()\n @list_of_positions.length\n end", "def length\n count = 0\n each { count += 1 }\n count\n end", "def num_uniques\n visitors.count\n end", "def num_uniques\n visitors.count\n end", "def num_uniques\n visitors.count\n end", "def lots_count\t\t\n lots.count\n end", "def length; count end", "def wins()\n\t\tself.as_regular_contestants.select{|c| c.win()}.size()\n\tend", "def number_of_senator\n\ta = Legislator.where(\"title=?\",\"Sen\")\n\tputs \"Senators:\" +\"#{a.count}\"\nend", "def number_of_sales\n return self.sales.length\n end", "def length\n count\n end", "def get_site_count\r\n site_name ? 1 : 0\r\n end", "def total_workouts\n set_sport_by_user.count || 0\n end", "def count\n all.count\n end", "def n\n @reps.size\n end", "def num_states\n @state.size\n end", "def num_states\n @state.size\n end", "def duns_number; end", "def get_total_games_played\n return games.size\n end", "def hand_count\n @hand_count ||= 0\n end", "def hand_count\n @hand_count ||= 0\n end", "def data_count\n @episodes.sum { |_, v| v.length }\n end", "def stargazers_count\n self.watchers_count\n end" ]
[ "0.6834224", "0.6822347", "0.679203", "0.6628784", "0.6579925", "0.6576353", "0.65345216", "0.6468602", "0.6458979", "0.6440525", "0.63977396", "0.6358515", "0.63417405", "0.63160545", "0.6304613", "0.6304613", "0.6304613", "0.6280699", "0.6275606", "0.62723404", "0.6271254", "0.6269669", "0.6269669", "0.62658775", "0.6265505", "0.6263332", "0.6242143", "0.6240221", "0.62374115", "0.6228916", "0.6215891", "0.6213637", "0.621008", "0.620198", "0.61938566", "0.61938566", "0.6187333", "0.6179381", "0.6178175", "0.6170697", "0.6166597", "0.61509585", "0.61347425", "0.61347425", "0.61347425", "0.6127639", "0.61250705", "0.61216617", "0.61216617", "0.61129886", "0.6112943", "0.6102362", "0.6101995", "0.6101551", "0.6101551", "0.6096237", "0.60952544", "0.60952544", "0.60942245", "0.60925436", "0.60911214", "0.6074772", "0.60641414", "0.6063313", "0.60540974", "0.60488826", "0.60488826", "0.6040371", "0.60397214", "0.60397214", "0.60382825", "0.6037691", "0.60318166", "0.6029181", "0.60210097", "0.60185105", "0.6011365", "0.6010116", "0.6008704", "0.60018843", "0.60018843", "0.60018843", "0.59980285", "0.5994454", "0.59940696", "0.59916323", "0.5989653", "0.5989122", "0.5985842", "0.598504", "0.5980519", "0.59771216", "0.59718585", "0.59718585", "0.59704477", "0.5968162", "0.5954899", "0.5954899", "0.5951168", "0.5951162" ]
0.81454146
0
Calculate molecular weight of an AA sequence. _Protein Mw is calculated by the addition of average isotopic masses of amino acids in the protein and the average isotopic mass of one water molecule._
def molecular_weight @mw ||= begin mass = WATER_MASS each_aa do |aa| mass += AVERAGE_MASS[aa.to_sym] end (mass * 10).floor().to_f / 10 end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def molecular_weight\n Bio::AminoAcid.weight(self)\n end", "def weight\n @mass * @hopper.size\n end", "def calculateWeight word\n letters = word.split\n weight = 0\n hash_alphabet = generateHashWithLetterAndWeight()\n letters.each do |letter|\n (/[[:upper:]]/.match(letter)) ? weight += hash_alphabet[letter.downcase].to_i * 2 : weight += hash_alphabet[letter.downcase].to_i\n end\n weight\n end", "def mass(weight)\n return weight / FREE_FALL_ACCELERATION\n end", "def weight\n return nil if mass.nil?\n mass / 1000.0\n end", "def word_weighted_average(word, type)\n basic_prob = word_prob(word, type)\n\n totals = total_word_count(word)\n\n (@weight * @assumed_prob + totals * basic_prob) / (@weight + totals)\n end", "def calculated_strain\n strain_th = willpower\n strain_th += race.strain_threshold if race && race.strain_threshold\n # Then increase based on selected talents.\n talent_alterations.each do |_talent_id, stat|\n stat.each do |type, value|\n strain_th += value['count'] if type == :strain\n end\n end\n strain_th\n end", "def peptide_mass_with_amino_acids(peptide, amh)\n mass = 0\n peptide.chars.each do |pep|\n mass += amh[pep]\n end\n return mass\n end", "def prom_weight\n if pet_histories.length > 0\n promw= pet_histories.sum(:weight)\n promw/pet_histories.length\n else\n \"0\"\n end\n end", "def weight(text)\n weight = @emphasis[:multiplier]\n\n if text.length >= @emphasis[:long_words_threshold]\n weight *= @emphasis[:long_words]\n end\n\n if text[0,1] == text[0,1].upcase\n weight *= @emphasis[:upper_case]\n end\n\n weight += vowels(text)\n weight += consonants(text)\n weight\n end", "def weighted_probability(word)\n word = (Word === word ? word : get(word))\n\n p = BigDecimal.new(1)\n p = p * probability(word)\n p = p * file_probability(word, 1)\n #p = p * lexicon_weight(word)\n #p = p * weight_length(word)\n #p = p * weight_stem(word)\n #p = p * weight_plural(word)\n p\n end", "def peptide_mass(peptide)\n mass = 0\n amh = amino_acid_mass_hash()\n peptide.chars.each do |pep|\n mass += amh[pep]\n end\n return mass\n end", "def calc_total_weight\n 0\n end", "def weight_in_stones\n\t\t((@weight * 2.20462) / 14).to_i\n\tend", "def weight\n\t\tweight = 0\n\t\tself.order_line_items.each do |item|\n\t\t\tweight += item.quantity * item.product.weight\n\t\tend\n\t\treturn weight\n\tend", "def rounded_weight\n @atomic_mass.round(4)\n end", "def total_weight\r\n\t\t@items.inject(0.0) { |sum, i| sum + i.total_unit_weight * i.quantity }\r\n\tend", "def bmi\n ( weight.to_f / ( (height.to_f)**2 ) ) * 703.0\n end", "def weight\n @parents.inject(1) { |res, p| res + p.weight * @parent_multiplier }\n end", "def calculated_wounds\n wound_th = brawn\n wound_th += race.wound_threshold if race && race.wound_threshold\n # Then increase based on selected talents.\n talent_alterations.each do |_talent_id, stat|\n stat.each do |type, value|\n wound_th += value if type == :wound\n end\n end\n wound_th\n end", "def proton_mass\r\n mass(HYDROGEN) - mass(ELECTRON)\r\n end", "def calculate_bmi weight, height\n (weight.to_f / (height.to_f * height.to_f)) * 703\nend", "def compute_weighted_center_of_mass(map, pieces)\n #cx = (x0*w0 + x1*w1 + ... + xn*wn) / (w0 + w1 + ... wn)\n total_weight = 0\n cx = 0\n cy = 0\n pieces.each do |loc|\n site = map.site(loc)\n total_weight += site.strength\n cx += loc.x*site.strength\n cy += loc.y*site.strength\n end\n return [cx / total_weight, cy / total_weight]\nend", "def weightedsum\n ws = 0\n @inputs.each_index { |i| ws = ws + @inputs[i]*@weights[i] }\n ws\n end", "def average(note_array, weighting_array)\n if(note_array.length > 0 && note_array.length == weighting_array.length)\n note_som = 0\n weig_som = 0;\n\n for index in 0...note_array.length\n note_som += note_array[index] * weighting_array[index]\n weig_som += weighting_array[index]\n end\n\n per_cent = (note_som / weig_som) * 100 / 20\n puts \"La moyenne est de #{per_cent} %.\"\n else puts \"Le nombre de notes n'est pas égal au nombre de pondération.\"\n end\nend", "def weight\n product_weight * quantity\n end", "def weight\n product_weight * quantity\n end", "def measure() @measure ||= (nb_weight == 0.0 ? 0.0 : sum_weight / nb_weight) end", "def weight\n num_motions.zero? ? 0.5 : total_score.fdiv(max_score)\n end", "def prot\n\t\tsuma = 0\n\t\tx = 0\n\t\tcantidad = 0\n\n\t\t@alimentos.each do |i|\n\t\t\tcantidad = @gramos[x].valor / (i.proteinas + i.lipidos + i.carbohidratos)\n\t\t\tsuma += i.proteinas * cantidad\n\t\t\tx += 1\n\t\tend\t\n\n\t\treturn ((suma * 100) / gramos_total).round(2)\n\tend", "def weight\n if @weight\n @weight\n else\n @confines.length\n end\n end", "def weight\n if @weight\n @weight\n else\n @confines.length\n end\n end", "def unit_weight\n (unit_area * product_thickness * 2.5).round(2)\n end", "def weight\n sides.map(&:weight).reduce(&:+)\n end", "def calculate_bmi(height,weight)\n ( weight / ( (height/100) * (height/100) ) )\n end", "def strain_threshold\n strain_th = self.willpower\n if self.race && self.race.strain_threshold\n strain_th += self.race.strain_threshold\n end\n # Then increase based on selected talents.\n self.talent_alterations.each do |talent_id, stat|\n stat.each do |type, value|\n if type == :strain\n strain_th += value['count']\n end\n end\n end\n strain_th\n end", "def ca_plus_mse\n total_formative * (100 - examweight)/100\n end", "def mass\n (detail[:area] * material.thickness * material.density / 1000).ceil\n end", "def weight\n order_lines.inject(0) { |sum, l| sum + l.weight }\n end", "def weight_in_words\n wt_kg = self.E16_01.to_f # in kg\n wt_lb = self.E16_88.to_f\n wt_in_lbs = wt_lb > 0 ? wt_lb : wt_kg*2.20462262\n \"%s lbs - %d kg\" % [((wt_in_lbs < 100) ? wt_in_lbs.round(1) : wt_in_lbs.round), wt_kg]\n end", "def weighted_sum\n index = 0\n sum = 0\n\n while index < id_digits.size\n sum += id_digits[index] * CHARACTER_WEIGHTS[index]\n index += 1\n end\n\n sum\n end", "def weight\n self.ingredients.map{|i| i.quantity}.reduce(:+)\n end", "def weight\n return @weight\n end", "def compute_weight object\n object.line_items.map { |li| (li.variant.weight || 0) * li.quantity }.sum\n end", "def mass(peptide)\n mass = 0\n for i in 0..peptide.length-1\n mass += peptide[i].to_i\n end\n mass\nend", "def measurement_weight\n [\n ['ounce'],\n ['pounds']\n ]\n end", "def total_weight\n line_items.map(&:weight).sum\n end", "def total_weight\n order_items.collect { |oi| oi.weight }.inject { |sum, x| sum + x } || 0\n end", "def weight; end", "def parent_ion_mass(charge=1)\r\n (mass(nterm) + ladder.last + mass(cterm) + charge * proton_mass)/charge\r\n end", "def calc_secondary_attributes\n self.san = self.pow * 5\n self.idea = self.int * 5\n self.health = ((self.siz+self.con)/2.0).ceil\n self.luck = self.pow * 5\n self.know = self.edu * 5 \n self.magic = self.pow\n end", "def mass\n @ob.get_exact_mass - (@ob.get_total_charge * Rubabel::MASS_E)\n end", "def total_mass\n sum = 0\n @bodies.each{ |body| body[:mass] += sum}\n sum\n end", "def weight\n questions.reduce(0) { |memo, question| question.weight > 0 ? memo + question.weight : memo }\n end", "def apply_usage_weights(word_hash)\n max_usage = @word_list.values.max.to_f\n max_usage = 1 if max_usage == 0\n\n weighted_array = word_hash.map do |word, bigram_score|\n usage_score = @word_list[word].to_f / max_usage\n [word, (bigram_score * (1 - @alpha)) + (usage_score * @alpha)]\n end\n\n Hash[weighted_array]\n end", "def get_total_weight(line_items)\n line_items.map do |li|\n # use default item weight if the weight is not defined for a product\n item_weight = li.variant.weight.nil? ? self.preferred_default_item_weight : li.variant.weight\n item_weight * li.quantity\n end.sum\n end", "def primary_weight(code_point)\n byte0 = code_point - MIN_4_BOUNDARY\n\n if byte0 < 0\n byte1 = code_point / FINAL_3_COUNT\n byte0 = code_point % FINAL_3_COUNT\n\n byte2 = byte1 / MEDIAL_COUNT\n byte1 %= MEDIAL_COUNT\n\n # spread out, leaving gap at start\n byte0 = MIN_TRAIL + byte0 * FINAL_3_MULTIPLIER\n\n # offset\n byte1 += MIN_TRAIL\n byte2 += MIN_PRIMARY\n\n (byte2 << 16) + (byte1 << 8) + byte0\n else\n byte1 = byte0 / FINAL_4_COUNT\n byte0 %= FINAL_4_COUNT\n\n byte2 = byte1 / MEDIAL_COUNT\n byte1 %= MEDIAL_COUNT\n\n byte3 = byte2 / MEDIAL_COUNT\n byte2 %= MEDIAL_COUNT\n\n # spread out, leaving gap at start\n byte0 = MIN_TRAIL + byte0 * FINAL_4_MULTIPLIER\n\n # offset\n byte1 += MIN_TRAIL\n byte2 += MIN_TRAIL\n byte3 += MIN_4_PRIMARY\n\n (byte3 << 24) + (byte2 << 16) + (byte1 << 8) + byte0\n end\n end", "def smr_woman(settings)\n smr = 655.1 + (9.563 * settings[:weight].to_f)\n smr += (1.850 * settings[:height].to_f)\n smr - (4.676 * settings[:age].to_f)\n end", "def compute_weighted_overall_score\n (Player::Feedback::FIT_WEIGHT * avg_fit_score +\n Player::Feedback::PUNC_WEIGHT * avg_punctuality_score +\n Player::Feedback::SKILL_WEIGHT * avg_skill_score +\n Player::Feedback::PERS_WEIGHT * avg_personality_score)\n end", "def weight\n return data.weight\n end", "def get_total_weight(line_items)\n line_items.map do |li|\n # use default item weight if the weight is not defined for a product\n item_weight = li.variant.weight.nil? ? self.preferred_default_item_weight : li.variant.weight\n item_weight * li.quantity\n end.sum\n end", "def get_total_weight(line_items)\n line_items.map do |li|\n # use default item weight if the weight is not defined for a product\n item_weight = li.variant.weight.nil? ? self.preferred_default_item_weight : li.variant.weight\n item_weight * li.quantity\n end.sum\n end", "def bsa\n Math.sqrt( height.to_f * weight.to_f / 3131.0 )\n end", "def character_weight\n total_weight = 0\n items = Inventory.where(character_id: self.id)\n items.each do |i|\n x = Equipment.find(i.equipment_id).weight\n total_weight += x if x \n end\n total_weight\n end", "def bmi_calc height, weight\n return (weight / height**2).to_i\nend", "def weight\n @weight || @confines.length\n end", "def totalProteina \n\t\tprot = 0\n\t\ttotal = 0\n\t\t@platos.each do |alimento|\n\t\t\tprot += alimento.proteinas\n\t\tend\n\t\treturn prot.round(2)\n\tend", "def promedios\n promedio = (@nota1.to_f + @nota2.to_f + @nota3.to_f) / 3\n promedio\n end", "def total_m3_biogas\n\t\t(calculations.collect(&:calc_m3_biogas).sum).round 2\n\tend", "def weighted_score\n score * metric.weight\n end", "def weightage\n return unless exams.first.nil?\n exams.first.weightage\n end", "def total_mass\n mass = 0\n @bodies.each do |body|\n mass += body.mass\n end\n return mass\n end", "def total_weight(order)\n weight = 0\n order.line_items.each do |line_item|\n line_item.variant.weight ? weight += (line_item.quantity * line_item.variant.weight) : 0\n end\n weight\n end", "def weight w=nil\n if w.nil?\n @weight\n else\n @weight = w\n end\n end", "def total_weight\n\t\tif catogery_id == 1\n\t\t\tfomular_1 * amount_qty\n\t\telsif category_id == 2\n\t\t\tfomular_2 * amount_qty\n\t\telsif category_id == 3\n\t\t\tfomular_3 * amount_qty\n\t\telse\n\t\t\t0\n\t\tend\n\tend", "def weight\n 0\n end", "def porcentaje_proteinas\n auxNodo1 = @lista_alimentos.head\n auxNodo2 = @gramos.head\n porcentaje_prot = 0\n while(auxNodo1 != nil && auxNodo2 != nil)\n porcentaje_prot += (auxNodo1.value.proteinas * auxNodo2.value) / 100\n auxNodo1 = auxNodo1.next\n auxNodo2 = auxNodo2.next\n end\n return porcentaje_prot.round(1)\n end", "def suggested_mash_ratio\n (preboil_volume_gallons + (preboil_volume_gallons*2 + 2*WATER_RETENTION_COEFFICIENT *\n preboil_volume_gallons * @total_grain_weight_lbs)**0.5) / @total_grain_weight_lbs\n end", "def proteinas\n food = @ingredientes.head\n protein = 0.0\n while food != nil do\n protein += food[:value].proteinas * (food[:value].gramos / 1000.0)\n food = food[:next]\n end\n protein * (100.0 / @total_nutricional)\n end", "def calculate_num_adjs(num_rooms, num_chairs, num_wings)\n\t\t \t#residue is how many higher rooms will have an \"extra\"\n\t\t \tresidue = num_wings % num_rooms;\n\n\t\t \t#q is how many each room should have minimum\n\t\t \t#the 1 represents the chair\n\t\t \t#num_wings / num_rooms is how wing allocations per room we can definitely do\n\t\t \tq = 1 + num_wings / num_rooms; #this will naturally floor()\n\n\t\t \textra = 0; #assume no extra\n\t\t \t#if in upper lot of rooms, assign 1 extra wing\n\t\t \tif (residue != 0) && (@num_rooms_assigned <= residue)\n\t\t \t\textra = 1;\n\t\t \tend\n\t\t \t\n\t\t \treturn (q + extra);\n\t\t end", "def male_body_fat\n converted_weight = 1.082 * user_weight\n converted_waist = 4.15 * user_waist\n added_converted_weight = 94.42 + converted_weight\n lean_body_weight = added_converted_weight - converted_waist\n lean_diff = user_weight - lean_body_weight\n lean_diff_times_100 = lean_diff * 100\n body_fat = lean_diff_times_100 / user_weight\n return body_fat\n end", "def weight\n 2 # ounces\n end", "def prot\n\t\tgrtotal = 0\n\t\tsum = 0\n\t\t#itera en las dos listas a la vez para poder calcular las\n\t\t#proteinas dependiendo de la cantidad y tambien suma\n\t\t#todas las cantidades para poder calcular el porcentaje\n\t\t#despues\n\t\t@lista.zip(@listagr).each do |normal, gr|\n\t\t\tgrtotal += gr\n\t\t\tcant = gr/1000.0\n\t\t\tsum += normal.prot*cant \n\t\tend\n\t\t(sum*100)/grtotal\n\tend", "def calculate_weighted_sum(base, weight_factors); end", "def total_unit_weight\r\n\t\ttotal = self.unit_weight\r\n\r\n\t\tliovs = self.line_item_option_values\r\n\t\tliovs.each do |cur_liov|\r\n\t\t\ttotal += cur_liov.extra_weight\r\n\t\tend\r\n\r\n\t\ttotal\r\n\tend", "def total_unit_weight\r\n\t\ttotal = self.unit_weight\r\n\r\n\t\tliovs = self.line_item_option_values\r\n\t\tliovs.each do |cur_liov|\r\n\t\t\ttotal += cur_liov.extra_weight\r\n\t\tend\r\n\r\n\t\ttotal\r\n\tend", "def calc_weight(mod, acc)\n fuel = calc_fuel(mod)\n fuel <= 0 ? acc : calc_weight(fuel, acc + fuel)\nend", "def mass(consider_electron_masses = true)\n mss = inject(0.0) do |sum,(el,cnt)| \n sum + (Mspire::Mass::Element::MONO[el]*cnt)\n end\n mss -= (Mspire::Mass::ELECTRON * charge) if consider_electron_masses\n mss\n end", "def calculate_calories(bodyweight)\n\ttotal_calories = bodyweight * 13\n\treturn total_calories\nend", "def score(do_logging=false)\n # penalize really short or long phrases\n duration_penalty = case \n when duration >= 4 then 0\n when duration == 3 then -100\n when duration == 2 then -400\n when duration <= 1 then -800\n end\n duration_penalty += case \n when length >= 12 then -1*((length*4)**1.25)\n when (length >= 3 and length < 12) then 0\n when length == 2 then -150\n when length <= 1 then -400\n end\n total = duration_penalty\n\n # first penalize for the total distance\n total -= DIST_WEIGHT*total_distance\n\n # now add a premium for similarity to other phrases\n filtered_similarity = @phrase_similarity.select{ |x| x > 0.3 }\n if filtered_similarity.empty?\n similarity = 0.0\n mean_similarity = 0.0\n similarity_weight = 0\n else\n mean_similarity = filtered_similarity.inject(0.0){|s,x| s+x} / filtered_similarity.length.to_f\n similarity = (self.length**SIM_A) * (filtered_similarity.length**SIM_B) / (10.0**(SIM_C*mean_similarity)) \n similarity_weight = 2\n total += similarity_weight*similarity\n end\n\n # finally, subtract a penalty for being significantly different from the mean phrase length\n total -= DUR_DEV_WEIGHT*duration_deviance\n\n puts \"\\t\\tscore (#{sprintf(\"%2d\", @start_idx)}-#{sprintf(\"%2d\", @end_idx)}): #{sprintf(\"% 4d\", duration_penalty)} \" +\n \"- #{DIST_WEIGHT}*#{sprintf(\"%5.1f\", total_distance)} \" +\n \"+ #{similarity_weight}*((#{sprintf(\"%2d\", self.length)}^#{SIM_A.round})*(#{filtered_similarity.length}^#{SIM_B.round})\" + \n \"/(10.0^(#{SIM_C.round}*#{sprintf(\"%4.3f\", mean_similarity)}))) \" +\n \"- #{DUR_DEV_WEIGHT}*#{sprintf(\"%5.3f\", duration_deviance)} \" +\n \"= #{sprintf(\"% 4d\", duration_penalty)} \" +\n \"- #{sprintf(\"% 6.1f\", DIST_WEIGHT*total_distance)} \" +\n \"+ #{sprintf(\"% 7.3f\", similarity_weight*similarity)} \" +\n \"- #{sprintf(\"% 6.1f\", DUR_DEV_WEIGHT*duration_deviance)} \" +\n \"= #{sprintf(\"% 6.1f\", total)}\" if do_logging\n\n return total\n end", "def weight\n if box\n box.weight * self.quantity\n else\n raise \"Weight not known.\"\n end\n end", "def skill_mp_cost(skill)\r\n (skill.mp_cost * mcr).to_i\r\n end", "def total_weight\n order_items.inject(BigDecimal(0)) { |t,i| t + i.total_weight}\n end", "def amino_acid_mass_hash\n {\n \"G\" => 57, \"A\" => 71, \"S\" => 87, \"P\" => 97, \"V\" => 99,\n \"T\" => 101, \"C\" => 103, \"I\" => 113, \"L\" => 113, \"N\" => 114,\n \"D\" => 115, \"K\" => 128, \"Q\" => 128, \"E\" => 129, \"M\" => 131,\n \"H\" => 137, \"F\" => 147, \"R\" => 156, \"Y\" => 163, \"W\" => 186,\n }\n end", "def strength\n MSPhysics::Newton::Hinge.get_strength(@address)\n end", "def calculate(height, weight)\n bmi = (weight / height) / height.to_f;\nend", "def to_mass(amount)\n liquid ? (amount * specific_weight) : amount\n end", "def kcalproteinas\n\t\t\t@proteinas * 4\n\t\tend", "def calc_mp_cost(skill)\n cost = 0\n cost += skill.mp_cost\n cost += maxmp * skill.mp_cost_per / 100\n cost += (base_spi + @spi_plus) * skill.base_spi_mp_cost\n cost += (base_atk + @atk_plus) * skill.base_atk_mp_cost\n cost /= 2 if half_mp_cost\n cost.to_i\n end", "def mutate(genome)\r\n\t\tgenome.map! {|weight|\r\n\t\t\tif (rand(0..1.0) < @mutation_rate)\r\n\t\t\t\tweight + rand(-1..Params::MAX_PERTURBATION)\r\n\t\t\telse\r\n\t\t\t\tweight\r\n\t\t\tend\r\n\t\t}\r\n\tend" ]
[ "0.7229752", "0.60174626", "0.59964734", "0.5925158", "0.5860306", "0.57346463", "0.5703239", "0.5697059", "0.56761897", "0.5663131", "0.5591569", "0.55661243", "0.5384147", "0.53690857", "0.5359473", "0.5354546", "0.53224325", "0.53134286", "0.52998465", "0.5292222", "0.52825296", "0.52825254", "0.5279842", "0.52620786", "0.52616096", "0.5259909", "0.5259909", "0.52589935", "0.5244925", "0.5240172", "0.52334034", "0.52334034", "0.52243716", "0.5216524", "0.5215743", "0.5193702", "0.51864624", "0.5176712", "0.5176417", "0.5150214", "0.5146932", "0.51418734", "0.5124578", "0.5090163", "0.50766057", "0.50695294", "0.50633615", "0.50594515", "0.5057634", "0.505225", "0.50469583", "0.50266796", "0.5025911", "0.501502", "0.50105745", "0.5007139", "0.5007001", "0.50042826", "0.4984058", "0.49839297", "0.49802396", "0.49802396", "0.49708462", "0.4969718", "0.49656385", "0.49579367", "0.4957621", "0.4950046", "0.49435398", "0.49427047", "0.4932098", "0.49105707", "0.49097914", "0.490484", "0.48906252", "0.48649892", "0.485677", "0.48503348", "0.4845599", "0.48259047", "0.4825552", "0.48174122", "0.48095855", "0.48088023", "0.48054665", "0.48054665", "0.48046777", "0.47976157", "0.47954404", "0.4779995", "0.4779029", "0.47735557", "0.47712797", "0.47689784", "0.4767874", "0.47547144", "0.4753204", "0.47530577", "0.47519448", "0.4738014" ]
0.71202606
1
Claculate theoretical pI for an AA sequence with bisect algorithm. pK value by Bjelqist, et al. is used to calculate pI.
def theoretical_pI charges = [] residue_count().each do |residue| charges << charge_proc(residue[:positive], residue[:pK], residue[:num]) end round(solve_pI(charges), 2) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def p(i, j, k)\n n = neighbours(i, k)\n if n.include?(j) then\n this_move_value = 0.0\n other_possible_moves_summed_value = 0.0\n @state.transaction do\n this_move_value = @state[:trails][[i, j]]\n other_possible_moves_summed_value = n.inject(0){|sum, n| sum + (@state[:trails][[i, n]]**@alpha)*(heuristic_value(i, n)**@beta)}\n end\n probability = (this_move_value**@alpha)*(heuristic_value(i, j)**@beta)/ (other_possible_moves_summed_value)\n return probability\n else\n return 0.0\n end\n end", "def calc_imc(a, p)\n\taqd = (a * a) / 10000\n\timc = p / aqd\n\tr_imc(imc)\nend", "def solve_pI charges\n state = {\n :ph => 0.0,\n :charges => charges,\n :pI => nil,\n :ph_prev => 0.0,\n :ph_next => 14.0,\n :net_charge => 0.0\n }\n error = false\n # epsilon means precision [pI = pH +_ E]\n epsilon = 0.001\n\n loop do\n # Reset net charge\n state[:net_charge] = 0.0\n # Calculate net charge\n state[:charges].each do |charge_proc|\n state[:net_charge] += charge_proc.call state[:ph]\n end\n\n # Something is wrong - pH is higher than 14\n if state[:ph] >= 14.0\n error = true\n break\n end\n\n # Making decision\n temp_ph = 0.0\n if state[:net_charge] <= 0.0\n temp_ph = state[:ph]\n state[:ph] = state[:ph] - ((state[:ph] - state[:ph_prev]) / 2.0)\n state[:ph_next] = temp_ph\n else\n temp_ph = state[:ph]\n state[:ph] = state[:ph] + ((state[:ph_next] - state[:ph]) / 2.0)\n state[:ph_prev] = temp_ph\n end\n\n if (state[:ph] - state[:ph_prev] < epsilon) &&\n (state[:ph_next] - state[:ph] < epsilon)\n state[:pI] = state[:ph]\n break\n end\n end\n\n if !state[:pI].nil? && !error\n state[:pI]\n else\n raise \"Failed to Calc pI: pH is higher than 14\"\n end\n end", "def icc_1_k_ci(alpha=0.05)\n per=1-(0.5*alpha)\n fu=icc_1_f.f*Distribution::F.p_value(per, @df_wt, @df_bt)\n fl=icc_1_f.f.quo(Distribution::F.p_value(per, @df_bt, @df_wt))\n [1-1.quo(fl), 1-1.quo(fu)]\n end", "def solution(a, b, k)\n first_dividend = a\n remainder = first_dividend%k\n\n while remainder != 0 && first_dividend <= b do\n first_dividend += 1\n remainder = first_dividend%k\n end\n\n remainder == 0 ? (b - first_dividend) / k + 1 : 0\nend", "def solution(a, b, k)\n return (b / k) - ((a - 1) / k)\nend", "def p_value(p, a, b, rmin = 0, rmax = 1)\n fail 'a <= 0' if a <= 0\n fail 'b <= 0' if b <= 0\n fail 'rmin == rmax' if rmin == rmax\n fail 'p <= 0' if p <= 0\n fail 'p > 1' if p > 1\n\n precision = 8.88e-016\n max_iterations = 256\n\n ga = 0\n gb = 2\n\n i = 1\n while ((gb - ga) > precision) && (i < max_iterations)\n guess = (ga + gb) / 2.0\n result = cdf(guess, a, b)\n\n if (result == p) || (result == 0)\n gb = ga\n elsif result > p\n gb = guess\n else\n ga = guess\n end\n\n fail 'No value' if i == max_iterations\n\n i += 1\n end\n\n rmin + guess * (rmax - rmin)\n end", "def icc_1_1_ci(alpha=0.05)\n per=1-(0.5*alpha)\n \n fu=icc_1_f.f*Distribution::F.p_value(per, @df_wt, @df_bt)\n fl=icc_1_f.f.quo(Distribution::F.p_value(per, @df_bt, @df_wt))\n \n [(fl-1).quo(fl+k-1), (fu-1).quo(fu+k-1)]\n end", "def native_kendalTauish_cost( pi )\n EpsSrraNative::rank_aggergate_upperW(@n){ |u,v| pi.pref(u,v) == @w[u][v] ? 0 : 1 } \n end", "def get_AIBC(i)\n @@tam = @medidas.length\n if i >= @@tam\n return 0\n else\n return (((@medidas[i] - @medidas[0]) + (@medidas[i - 1] - @medidas[0])) / 24) + get_AIBC(i + 1)\n end\n end", "def ukp4(ukpi)\n n = ukpi[:n]\n c = ukpi[:c]\n items = ukpi[:items].clone\n\n g = Array.new(c+1, 0)\n sort_items_by_profitability!(items)\n\n items.each do | item |\n pi = item[:p]\n wi = item[:w]\n max_xi = Rational(c, wi).floor\n z = pi\n y = wi\n max_xi.times do\n if g[y] == 0 then\n g[y] = z\n else\n z = g[y]\n end\n z += pi\n y += wi\n end\n\n break if g[c] != 0\n end\n\n g\nend", "def adjust_prob(hash, position)\n hash.each_key do | pos |\n diff = (pos - position).abs\n # 1 Mb is the cut off on either side\n cutoff = 1000000\n if diff < cutoff\n adj = hash[pos] * (diff/cutoff)\n hash[pos] = adj.to_i\n end\n end\n hash\nend", "def irenergeticoKJp\n vag=(valorenergeticoKJp() * 100) / 8400\n vag.round(2)\n end", "def p(trigram)\n\n bigram = trigram[1..2]\n unigram = trigram[2..2]\n # see which case we fall into for this backoff scheme\n if @counts.include?(trigram)\n # p1 function, trigram exists\n return pML(trigram, @discount)\n else\n ngram = nil\n beta_gram = nil\n alpha = 0\n if @counts.include?(bigram)\n # p2 function, no trigram but bigram exists\n ngram = bigram\n beta_gram = trigram[0..1] # the words used to help generate a beta-set of zero-count trigram\n # alpha mass redistribution\n alpha = @weights[:p2] * (1 - pML(trigram, @discount))\n else\n # p3 function, no trigram or bigram\n ngram = unigram\n beta_gram = trigram[0..0] # the words used to help generate a beta-set of zero-count bigrams\n # alpha mass redistribution\n alpha = @weights[:p3] * (1 - pML(trigram, @discount))\n end\n\n numerator = pML(ngram) \n denominator = @beta_gram_cache.fetch(beta_gram, nil) \n if not denominator\n dgram = nil\n sum = 0\n @vocab.each do |v| # all permutations of vocab words\n dgram = beta_gram + [v]\n # that are zero-count ngrams of (w,w_i-1,w_i-2) or (w,w_i-1)\n if not @counts.include?(dgram)\n # should be part of the sum of pML(w|w_i-1) or pML(w)\n sum += pML(dgram.drop(1)) # drop w_i-2 or w_i-1 as needed\n end\n end\n\n @beta_gram_cache.store(beta_gram, sum)\n denominator = sum\n end\n\n if denominator == 0 then return 0 end\n return alpha * numerator / denominator\n end\n\n end", "def proportional(error)\n return @kp*error\n end", "def p_value(pr,k)\n GSL::Cdf.tdist_Pinv(pr,k)\n end", "def p(k)\n k = k.to_f\n output = 0.0\n if k == 1\n output = 1/@N\n else\n output = 1/(k*(k-1))\n end\n return output\n end", "def p(n)\r\n (return @ps[n]) if @ps[n]\r\n\r\n sum = 0\r\n @pk.each_with_index do |k, i|\r\n if k > n\r\n break\r\n end\r\n sign = ( i % 4 <= 1 ? 1 : -1)\r\n sum += sign * p( n - k )\r\n sum %= 1_000_000 #keep it under control\r\n end\r\n @ps[n] = sum\r\n return sum\r\n end", "def solution(a, b, k)\n # write your code in Ruby 2.2\n e = b / k\n s = (a-1) / k\n\n e - s\nend", "def fitness\n return @fitness if @fitness\n\n cls = (options[:kappa]).times.map { |i| [] }\n @data.each_with_index { |g, i| cls[g].push i}\n\n p_b2 = cls.map { |c| penalty_before(c) }\n p_a2 = cls.map { |c| penalty_after(c) }\n\n impr2 = p_b2.zip(p_a2).map do |b,a|\n b > 0 ? ((b - a)/b) : 0\n end.inject(0,:+)\n\n @fitness = impr2\n end", "def probability(n, k)\n probability = fact(n) / fact(k) * fact(n - k) * (1.0/6.0) ** k * (5.0/6.0) ** (n-k)\n return probability\n end", "def probability_of_collision k, n\n 1 - Math.exp((-k**2.0) / (2.0 * n))\n end", "def alg4(max_value)\n perimeters = Hash.new 0\n (6..max_value/2).each do |p_sub|\n p = p_sub * 2\n (p_sub-1..3).each do |a|\n b = p * (p - 2*a) / (2.0 * (p-a))\n # avoid double counting\n break if b > a\n\n if b > 0 && b == b.to_i\n #puts \"debug: adding perimeter #{p} = #{a} + #{b} + ...\"\n perimeters[p] += 1\n end\n end\n end\n return perimeters\nend", "def err_asymptotic( x, alpha )\n for k in 2...x.size do\n ek = (x[k-2]-alpha).abs\n ekp1 = (x[k-1]-alpha).abs \n ekp2 = (x[k] -alpha).abs\n p = Math::log(ekp1/ekp2)/Math::log(ek/ekp1)\n puts \"k = #{k}, order p = #{p}\"\n end\nend", "def ukp3(ukpi, ret_table = true)\n n = ukpi[:n]\n c = ukpi[:c]\n items = ukpi[:items].clone\n\n # step one\n g = Array.new(c+1, 0)\n d = Array.new(c+1, n-1)\n sort_items_by_profitability!(items)\n\n gy_col = nil\n dy_col = nil\n if ret_table then\n gy_col = Array.new(c+1) { [] }\n dy_col = Array.new(c+1) { [] }\n end\n\n ys = y_star(items, true)\n min_necessary_steps = ys < c+1 ? ys : c+1\n # step two to six\n min_necessary_steps.times do | y |\n if ret_table then\n gy_col[y] << g[y]\n dy_col[y] << d[y]\n end\n items.each_with_index do | item, j |\n if y - item[:w] >= 0 && j <= d[y - item[:w]] then\n v = g[y - item[:w]] + item[:p]\n if v > g[y] then\n g[y] = v\n d[y] = j\n if ret_table then\n gy_col[y] << g[y]\n dy_col[y] << d[y]\n end\n end\n end\n end\n end\n\n if min_necessary_steps != c+1 then\n extra_capacity = c - ys\n c1, a1 = items[0][:p], items[0][:w]\n qt_best_item_used = Rational(extra_capacity, a1).ceil\n space_used_by_best_item = qt_best_item_used*a1\n profit_generated_by_best_item = qt_best_item_used*c1\n g[c] = g[c-space_used_by_best_item] + profit_generated_by_best_item\n end\n\n table = \"y\\tg(y)\\t\\td(y)\\n\"\n if ret_table then\n (c+1).times do | y |\n table << \"#{y}\\t#{gy_col[y].join(' ')}\\t\\t#{dy_col[y].join(' ')}\\n\"\n end\n end\n \n if ret_table then\n table\n else\n g\n end\nend", "def CPI\n if self.spent_hours>0 and self.estimated_hours>0\n earned_value= (self.completed_percent * self.estimated_hours)/100\n actual_cost=self.spent_hours\n return (earned_value/actual_cost)\n else\n return 0\n end\n\n rescue\n return 0\n end", "def score_for( kinployee )\n @kinployment.preferred_availability <= kinployee.availability ?\n 1.0 :\n 0.0\n end", "def bps(basis_points)\n basis_points * 0.0001\n end", "def irenergeticoKcalp\n vag=(valorenergeticoKcalp() * 100) / 2000\n vag.round(2)\n end", "def binomial_coefficient_multiplicative(n,k)\n return 1 if (k==0 or k==n)\n k=[k, n-k].min\n (1..k).inject(1) {|ac, i| (ac*(n-k+i).quo(i))}\n end", "def partition(cv, fv, bs, cp)\n # best cut point\n cp_best = nil\n \n # binary subset at the best cut point\n cv1_best, cv2_best = nil, nil\n fv1_best, fv2_best = nil, nil\n bs1_best, bs2_best = nil, nil\n \n # best information gain\n gain_best = -100.0\n ent_best = -100.0\n ent1_best = -100.0\n ent2_best = -100.0\n \n # try each potential cut point\n bs.each do |b|\n # binary split\n cv1_try, cv2_try, fv1_try, fv2_try, bs1_try, bs2_try = \n binary_split(cv, fv, bs, b)\n \n # gain for this cut point\n ent_try = get_marginal_entropy(cv)\n ent1_try = get_marginal_entropy(cv1_try)\n ent2_try = get_marginal_entropy(cv2_try)\n gain_try = ent_try - \n (cv1_try.size.to_f/cv.size) * ent1_try - \n (cv2_try.size.to_f/cv.size) * ent2_try\n \n #pp gain_try\n if gain_try > gain_best\n cp_best = b\n cv1_best, cv2_best = cv1_try, cv2_try\n fv1_best, fv2_best = fv1_try, fv2_try\n bs1_best, bs2_best = bs1_try, bs2_try\n \n gain_best = gain_try\n ent_best = ent_try\n ent1_best, ent2_best = ent1_try, ent2_try\n end\n end \n \n # to cut or not to cut?\n #\n # Gain(A,T;S) > 1/N * log2(N-1) + 1/N * delta(A,T;S)\n if cp_best\n n = cv.size.to_f\n k = cv.uniq.size.to_f\n k1 = cv1_best.uniq.size.to_f\n k2 = cv2_best.uniq.size.to_f\n delta = Math.log2(3**k-2)-(k*ent_best - k1*ent1_best - k2*ent2_best)\n \n # accept cut point\n if gain_best > (Math.log2(n-1)/n + delta/n)\n # a: record cut point\n cp << cp_best\n \n # b: recursively call on subset\n partition(cv1_best, fv1_best, bs1_best, cp)\n partition(cv2_best, fv2_best, bs2_best, cp)\n end\n end\n end", "def kali(panjang_arr,a)\n\ttotal=1\n\t(0..(panjang_arr-1)).each do |i|\n\t\ttotal=total*a[i]\n\tend\n\treturn total\nend", "def binomial_coefficient(n, k)\n return 1 if n == k || k == 0\n return n if k == 1\n return -1 if n < k\n\n # calculate factorials\n fact_n = (2..n).inject(1) { |carry, i| carry * i }\n fact_k = (2..k).inject(1) { |carry, i| carry * i }\n fact_n_sub_k = (2..(n - k)).inject(1) { |carry, i| carry * i }\n\n fact_n / (fact_k * fact_n_sub_k)\n end", "def k_value(r_A)\n if !@adj || r_A < 2100\n K_VALUE\n elsif r_A > 2400\n 16\n else\n 24\n end\n end", "def calculate_expected_dominant_offspring(xAA_AA, xAA_Aa, xAA_aa, xAa_Aa, xAa_aa, xaa_aa, offspring_each = 2)\r\n xAA_AA_prob = offspring_each.to_f * xAA_AA * 1 \r\n xAA_Aa_prob = offspring_each.to_f * xAA_Aa * 1 \r\n xAA_aa_prob = offspring_each.to_f * xAA_aa * 1 \r\n xAa_Aa_prob = offspring_each.to_f * xAa_Aa * 0.75 \r\n xAa_aa_prob = offspring_each.to_f * xAa_aa * 0.5 \r\n xaa_aa_prob = offspring_each.to_f * xaa_aa * 0 \r\n return xAA_AA_prob + xAA_Aa_prob + xAA_aa_prob + xAa_Aa_prob + xAA_aa_prob + xAa_aa_prob + xaa_aa_prob\r\nend", "def binomial(n,k)\n return 1 if n-k <= 0\n return 1 if k <= 0\n fact(n) / ( fact(k) * fact( n - k ) )\n end", "def hiv_protease(aa_array,start_aa=1)\n out_hash = {}\n sdrm = {}\n sdrm[23] = ['L',['I']]\n sdrm[24] = ['L',['I']]\n sdrm[30] = ['D',['N']]\n sdrm[32] = ['V',['I']]\n sdrm[46] = ['M',['I','L','V']]\n sdrm[47] = ['I',['V','A']]\n sdrm[48] = ['G',['V','M']]\n sdrm[50] = ['I',['V','L']]\n sdrm[53] = ['F',['L']]\n sdrm[54] = ['I',['V','L','M','T','A','S']]\n sdrm[73] = ['G',['S','T','C','A']]\n sdrm[76] = ['L',['V']]\n sdrm[82] = ['V',['A','T','S','F','L','C','M']]\n sdrm[83] = ['N',['D']]\n sdrm[84] = ['I',['V','A','C']]\n sdrm[85] = ['I',['V']]\n sdrm[88] = ['N',['D','S']]\n sdrm[90] = ['L',['M']]\n aa_length = aa_array.size\n end_aa = start_aa + aa_length - 1\n (start_aa..end_aa).each do |position|\n array_position = position - start_aa\n if sdrm.keys.include?(position)\n wt_aa = sdrm[position][0]\n test_aa = aa_array[array_position]\n if test_aa.size == 1\n unless wt_aa == test_aa\n if sdrm[position][1].include?(test_aa)\n out_hash[position] = [wt_aa,test_aa]\n end\n end\n else\n test_aa_array = test_aa.split(\"/\")\n if (test_aa_array & sdrm[position][1])\n out_hash[position] = [wt_aa,test_aa]\n end\n end\n end\n end\n return out_hash\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 bs(a, b)\n if (b - a) == 1\n if a == 0\n pab = 1\n qab = 1\n else\n pab = ((6 * a)-5) * ((2 * a)-1) * ((6 * a)-1)\n qab = (a * a) * (a * $c3)\n end\n\n tab = pab * (13591409 + (545140134 * a))\n\n if a & 1 == 1\n tab = -tab\n end\n else\n m = 0\n m = ((a + b) / 2).round(0)\n\n pam, qam, tam = bs(a, m)\n pmb, qmb, tmb = bs(m, b)\n\n pab = pam * pmb\n qab = qam * qmb\n tab = qmb * tam + pam * tmb\n end\n return pab, qab, tab\nend", "def probA0(bit)\n\n # not quite zero, to avoid paying infinitely large\n # penalty when calculating score (div by zero)\n if bit == 0\n return 0.999999\n else #bit == 1\n # This value can be used to tweak coverage vs\n # exclusivity of modules\n return 0.000005\n end\nend", "def calc_B(b, k, v, n, g)\n (modpow(g, b, n) + k * v) % n\n end", "def problem_78\n n = 1\n p_cache = [1]\n\n generate = lambda do |k|\n ret = 0\n sign = 0\n Integer.generalized_pentagonals do |gp|\n if k < gp\n false # Need to exit ruby1.8, can't break...\n else\n if sign >= 0\n ret += p_cache[k-gp]\n else\n ret -= p_cache[k-gp]\n end\n sign += (sign == 1) ? -3 : 1 # 4 states + + - -\n end\n end\n p_cache[k] = ret % 100_000_000\n ret\n end\n\n p = 1\n loop do\n r = generate.call(p)\n# puts \"#{p} #{generate.call(p)}\"\n break if r % 1_000_000 == 0\n p += 1\n end\n p\nend", "def solution(k, a)\n count = 0\n current = 0\n a.each { |length| \n current += length\n if current >= k\n current = 0\n count += 1\n end\n }\n count\nend", "def k_closest_a(points, k)\n points.sort_by { |point| point[0]**2 + point[1]**2 }[0,k]\nend", "def get_icdf(prob)\n if prob.class == Array\n inv_vals = []\n for i in (0 ...prob.length)\n check_range(prob[i])\n inv_vals[i] = (find_root(prob[i], @n/2, 0.0, @n)).floor\n end\n return inv_vals\n else\n check_range(prob)\n return (find_root(prob, @n/2, 0.0, @n)).floor\n end\n end", "def divisible_by(a, b, k)\n a = k if a < k\n\n x = ((b-a)/k)\n x += 1 if a % k == 0\n\n #n = 0\n #(a..b).each do |i|\n # n += 1 if i % k == 0\n #end\n return x\nend", "def solution(k, m, a)\n from = a.max\n to = a.inject(:+)\n min = from\n while from <= to\n mid = (from + to) / 2\n if check(mid, k, m, a)\n min = mid\n to = mid - 1\n else\n from = mid + 1\n end\n end\n min\nend", "def calculate_primiera(hand1, hand2)\r\n res = [0,0]\r\n #p hand1\r\n #p hand2\r\n # first get the max card on each suit\r\n max_pt = []\r\n [hand1, hand2].each do |curr_hand|\r\n # reset max\r\n max_pt << {:D => 0, :B => 0, :C => 0, :S => 0 }\r\n curr_hand.each do |lbl|\r\n points = @deck_information.get_card_points(lbl)\r\n suit = @deck_information.get_card_segno(lbl)\r\n if points > max_pt.last[suit]\r\n # max on suit\r\n max_pt.last[suit] = points\r\n end\r\n end\r\n #p max_pt.last\r\n end\r\n # using inject, 0 is the first value of the accumulator sum, tha assume the\r\n # value of the block provided. x assume each value of the max_pt.first\r\n # x becomes a pair like max_pt.first.each{|k,v|}. For example x = [:S, 21]\r\n arr_sum_points = []\r\n max_pt.each do |maxitem|\r\n arr_sum_points << maxitem.inject(0) do |sum, x|\r\n if x[1] > 0 and sum >= 0 \r\n sum + x[1]\r\n else\r\n # this is a particular case, we don't have points on a particular suit\r\n # in this case there is no primiera. Then stay on -1.\r\n sum = -1\r\n end\r\n end\r\n end\r\n #p arr_sum_points\r\n if arr_sum_points[0] > arr_sum_points[1]\r\n #primiera on the first hand\r\n res[0] = 1\r\n res[1] = 0\r\n elsif arr_sum_points[0] == arr_sum_points[1]\r\n # same points, primiera is not assigned\r\n res[0] = 0\r\n res[1] = 0\r\n else\r\n #primiera on the second hand\r\n res[0] = 0\r\n res[1] = 1\r\n end \r\n #p res\r\n return res\r\n end", "def ri(p,i,n,a,s)\n j = 0\n v = nil\n h = nil\n k = nil\n while i > 0\n k = n-j-1\n h = b(k)\n v = b(j) * h\n i -= v\n j += 1\n end\n i += v\n j -= 1\n p[a-1] = j + 1 + s\n y = (i-1-((i-1)/h)*h) + 1\n w = (i-y) / h + 1\n\n if j > 1\n ri(p,w,j,a+1,s) \n elsif j == 1\n p[a] = s+1\n end\n\n if k > 1\n ri(p,y,k,a+j+1,s+j+1)\n elsif k==1\n p[a+j] = s+j+2\n end\n end", "def kaprekar?(k)\n=begin\n sqr = k**2\n digits = k.to_s.length\n right_n_digits = sqr.to_s[(0-digits)..-1].to_i\n left_digits = sqr.to_s[0..(1-digits)].to_i\n left_digits + right_n_digits == k\n=end\n n = Math.log10(k).to_i + 1\n value = k**2 \n k == value % (10**n) + value / (10**n) \nend", "def kaprekar?(k)\n return false if !k.is_a?(Integer) || k < 1\n\n n = k.to_s.length\n k_squared = (k**2).to_s\n\n first_part = k_squared.length.even? ? k_squared[0..(n - 1)] : k_squared[0..(n - 2)]\n second_part = k_squared[-n..-1]\n\n first_part.to_i + second_part.to_i == k\nend", "def get_icdf(p)\n check_range(p)\n return @lower + p.to_f * (@upper - @lower)\n end", "def min_unfairness (candy, n, k)\n # First, sorting the array\n candy.sort!\n\n # puts candy.inspect\n\n # Initialize with the first and k element \n min = candy[k-1] - candy[0]\n\n # For each subsequential k elements, we have to find the min. unfairness\n for i in 1..(n-k) \n # puts \"i=#{i} n[i+k]=#{candy[i+k-1]} n[i]=#{candy[i]} : #{candy[i+k-1] - candy[i]} | min=#{min}\"\n min = candy[i+k-1] - candy[i] if candy[i+k-1] - candy[i] < min\n end\n\n return min\nend", "def ukp_rec2(ukpi)\n n = ukpi[:n]\n c = ukpi[:c]\n items = ukpi[:items].clone\n\n g = Array.new(c+1, nil)\n d = Array.new(c+1, n-1)\n sort_items_by_profitability!(items)\n\n ukp_aux2(items, c, g, d)\n\n g\nend", "def calculate (bs, ap, buffer)\r\n\t\tpair_key = \"#{bs}-#{ap}\"\r\n\t\t@price_histogram[pair_key] = {} if !@price_histogram[pair_key]\r\n\t\t@price_histogram_topx[pair_key] = [] if !@price_histogram_topx[pair_key]\r\n\t\t\r\n\t # age histograms\r\n\t @price_histogram[pair_key].each do |k,v|\r\n\t \t@price_histogram[pair_key][k] = v * ap\r\n\t end\r\n\t # age histograms in top10 list\r\n\t @price_histogram_topx[pair_key].each do |t|\r\n\t \tt[1] = t[1] * ap\r\n\t end\r\n\t \t\r\n\t # calculate which bucket in the histogram the price belongs to\r\n\t bucket = (buffer[P].close / bs).to_i * bs\r\n\t # increase the bucket counter\r\n\t @price_histogram[pair_key][bucket] = (@price_histogram[pair_key][bucket] ? @price_histogram[pair_key][bucket] : 0) + 1\r\n\t\t# if the bucket belongs to the top10 list, increase the counter there too\r\n\t\tcorrected = false\r\n\t\t@price_histogram_topx[pair_key].each do |t|\r\n\t\t\tif t[0] == bucket\r\n\t\t\t\tt[1] = @price_histogram[pair_key][bucket]\r\n\t\t\t\tcorrected = true\r\n\t\t\t\tbreak\r\n\t\t\tend\r\n\t\tend\r\n\t\t\r\n\t\t# add the bucket to the top 10 (if we haven't increased an existing one)\r\n\t\tif !corrected\r\n\t\t\t@price_histogram_topx[pair_key].push([bucket,@price_histogram[pair_key][bucket]])\r\n\t\tend\r\n\t\t# re-sort the top10 prices by counter\r\n\t\t@price_histogram_topx[pair_key] = @price_histogram_topx[pair_key].sort_by { |k| -1 * k[1] }\r\n\t\t# chop off the last element to keep top10 array at the right length\r\n\t\tif @price_histogram_topx[pair_key].count > 10\r\n\t\t\t@price_histogram_topx[pair_key].pop\r\n\t\tend\r\n\t\t\r\n\t\t# is there a signal? compare current & previous bucket...\r\n\t\tbucket_current = (buffer[P].close / bs).to_i * bs\r\n\t\tbucket_previous = (buffer[P-1].close / bs).to_i * bs\r\n\t\t# ... if exiting a top10 bucket and entering a regular one - we have a signal!\r\n\t\tif bucket_current != bucket_previous && @price_histogram_topx[pair_key].map{ |t| t[0] }.include?(bucket_previous) && !@price_histogram_topx[pair_key].map{ |t| t[0] }.include?(bucket_current)\r\n\t\t\tif bucket_current > bucket_previous\r\n\t\t\t\treturn \"b\"\r\n\t\t\telse\r\n\t\t\t\treturn \"s\"\r\n\t\t\tend\r\n\t\telse\r\n\t\t\treturn \"h\"\r\n\t\tend\r\n\tend", "def solve112(target_proportion)\n bouncy_proportion = 0\n total_bouncy = 0\n num = 0\n while bouncy_proportion < target_proportion\n num += 1\n if bouncy?(num)\n total_bouncy += 1\n bouncy_proportion = 1.0*total_bouncy/num\n end\n end\n puts target_proportion, num\nend", "def masterwork_prob_bonus; 0; end", "def calc(n, k)\n fac(n) / (fac(k) * fac(n - k)) * ((1.0/6.0)**k * (5.0/6.0)**(n-k)) * 100\n end", "def calc_pv()\n i = @i / 100.0\n #Initial contribution\n pvf = @fv / ((1 + i) ** @n)\n #Present value of annuity\n pva = (@pmt/i) * (1-(1/((1+i)**@n)))\n @pv = (pvf + pva) * (-1)\n #Round\n @pv = (@pv*100).round / 100.0\n end", "def aa_comp(aa_code=nil)\n if aa_code.nil?\n aa_map = {}\n IUPAC_CODE.keys.each do |k|\n aa_map[k] = 0.0\n end\n aa_map.update(aa_comp_map){|k,_,v| round(v, 1) }\n else\n round(aa_comp_map[aa_code], 1)\n end\n end", "def puppy_golden_age(arr)\r\n puppies = 0 # set the var for puppies born for later comparison\r\n years = [] # set empty array to later push the results of the comparison\r\n\r\n arr.each_with_index do |x, i| # looping through entire array. could have used #each_index without x.\r\n for i2 in i + 1...arr.length # set up loop for i2 which is needed to compare all elements in array above i1 and for return of second index. i + 1 protects against the return of the same index twice. see written test 3.\r\n if puppies < arr[i..i2].reduce(&:+) # comparison of the value puppies with the sum of the elements in arr where index > i.\r\n puppies = arr[i..i2].reduce(&:+) # if the net gain between these two indices is > the previous value for puppies, the new gain becomes the value\r\n years = [i, i2] # sets the indicies for the larger gain compared here: puppies < arr[i..i2].reduce(&:+)\r\n end\r\n end\r\n end\r\n\r\n years # when the loop is complete, the largest gain and their indicies will be set for the variables puppies/ years. question asks for the index of the years.\r\nend", "def stat_com(q, i, j, b)\n z = zz = 1\n k = i\n while(k <= j)\n zz = zz * q * k / (k - b)\n z = z + zz\n k += 2\n end\n z\n end", "def apply_apci(val, data = nil)\n value = if val.is_a?(Symbol)\n ActionType[val]\n else\n val\n end\n\n if value > 15\n self.apci = (value >> 6) & 0b1111\n self.data = value & 0b111111\n false\n else\n self.apci = value\n if data && data[0] && data[0] <= 0b111111\n self.data = data[0]\n true\n else\n self.data = 0\n false\n end\n end\n rescue => e\n raise ArgumentError, \"Bad apci value: #{data}\"\n end", "def irenergeticoKJ\n vag=(valorenergeticoKJ() * 100) / 8400\n vag.round(2)\n end", "def cdf(k,n,pr)\n #(0..x.floor).inject(0) {|ac,i| ac+pdf(i,n,pr)}\n Math.regularized_beta(1-pr,n - k,k+1)\n end", "def is_pent?(k)\n # 3 * n**2 - n - 2k = 0 where n is an integer\n # 1 +- sqrt(1 - 4*3*(-2k)) / 6\n # 1 + 24*k must be a perfect square and 1 + sqrt(24*k) % 6 == 0\n (Math.sqrt(1 + 24*k).to_i)**2 == 1 + 24*k &&\n (1 + Math.sqrt(1 + 24*k)) % 6 == 0\nend", "def binom(n, k)\n return 1 if k.zero? || (n - k).zero?\n return n if k == 1 || n - k == 1\n\n factorial(n) / (factorial(k) * factorial(n - k))\n end", "def ppmi(c, verbose: false, eps: 1e-8)\n ppmi = Numo::SFloat.zeros(c.shape)\n n = c.sum\n s = c.sum(axis: 1)\n total = c.size\n count = 0\n\n c.shape[0].times do |i|\n c.shape[1].times do |j|\n pmi = Math.log2(c[i, j] * n / (s[i] * s[j] + eps))\n ppmi[i, j] = [0.0, pmi].max\n\n if verbose\n count += 1\n if (count % (total.to_f / 100)).zero?\n printf(\"%.1f%% done\\n\", 100 * count / total)\n end\n end\n end\n end\n\n ppmi\nend", "def validate_acc(acc, bik)\n # Для проверки контрольной суммы перед расчётным счётом\n # добавляются три последние цифры БИКа банка.\n acc = bik[-3..-1] + acc\n\n # Вычисляется контрольная сумма со следующими весовыми\n # коэффициентами: (7,1,3,7,1,3,7,1,3,7,1,3,7,1,3,7,1,3,7,1,3,7,1)\n coeff = \"71371371371371371371371\"\n crc = 0\n\n 0.upto(22) do |i|\n tmp_pro = acc[i, 1].to_i * coeff[i, 1].to_i\n crc += (tmp_pro.to_s[tmp_pro.to_s.size - 1, 1]).to_i\n end\n\n # Вычисляется контрольное число как остаток от деления контрольной суммы на 10\n # Контрольное число сравнивается с нулём. В случае их равенства расчётного\n # счёт считается правильным.\n crc % 10 == 0\n end", "def luckBalance(k, contests)\n balance = 0\n nonimportant = contests.select{|x| x[1] == 0}.map{|y| y[0]}\n if nonimportant.length > 0\n balance += nonimportant.reduce(:+)\n end\n soimportant = contests.select{|x| x[1] == 1}.map{|y| y[0]}.sort{|a,b| b<=>a }\n p soimportant\n soimportant.each_with_index do |v, i|\n if i<k\n balance +=v\n else\n balance -=v\n end\n end\n return balance\nend", "def jacobi(n, a, b, x0, error, n_max)\n n = n - 1\n\n x = Array.new(n + 1)\n for k in (0..n_max)\n (0..n).each do |i|\n sumatoria = (0..n).inject(0) do |sum, j|\n if j.eql?(i)\n sum\n else\n sum + a[i][j] * x0[j]\n end\n end\n\n x[i] = (b[i] - sumatoria).fdiv(a[i][i])\n end\n\n resta = x.map.with_index { |xi, i| xi - x0[i] }\n modulo = Math::sqrt(resta.inject(0) { |sum, i| sum + i ** 2 })\n if modulo < error\n puts \"Una solucion aproximada es X = #{x}.\"\n return x\n end\n\n x0.replace(x)\n end\n\n puts \"Se alcanzo el numero maximo de iteraciones n_max pero no la tolerancia.\"\nend", "def obp \n\t\t# prevent divide by zero\n\t\tif (self[:at_bats] != 0)\t\t\n\t\t\t((self[:hits] + self[:walks] + self[:hit_by_pitch])/(self[:at_bats] + self[:walks] + self[:hit_by_pitch] + self[:sacrifice_flies].to_f)).round(3)\n\t\telse\n\t\t\t0\n\t\tend\n\tend", "def aliphatic_index\n aa_map = aa_comp_map\n @aliphatic_index ||= round(aa_map[:A] +\n 2.9 * aa_map[:V] +\n (3.9 * (aa_map[:I] + aa_map[:L])), 2)\n end", "def pandigital(i)\n while i >= 0\n digits = i.to_s.length\n checking = [*\"1\"..digits.to_s]\n sorted_i = i.to_s.split(\"\").sort\n if checking == sorted_i && prime?(i)\n return i\n end\n i -= 2\n end\nend", "def div_h_p_nr(a,b)\n p = 0\n\n @bits.times do\n if p < 0\n # (i-a) shift combined pa register left one bit\n pa = ((p<<@bits)|a)<<1\n # (ii-a) p=p+b\n a = pa & @mA\n p = signed((pa & @mP) >> @bits)\n p += b\n else\n # (i-b) shift combined pa register left one bit\n pa = ((p<<@bits)|a)<<1\n # (ii-b) p=p-b\n a = pa & @mA\n p = signed((pa & @mP) >> @bits)\n p -= b\n if (p < 0)\n# Tests pass if the following is uncommented\n# # (iv) restore p\n# p += b\n else\n # (iii) if p >= 0\n a |= 1\n end\n end\n end\n # FIXME - need a test case that exercises this last step\n if p < 0\n p += b\n end\n [lo(a),lo(p)]\n end", "def fleiss(matrix)\n debug = true\n\n # n Number of rating per subjects (number of human raters)\n n = checkEachLineCount(matrix) # PRE : every line count must be equal to n\n i_N = matrix.size\n k = matrix[0].size\n\n if debug\n puts \"#{n} raters.\"\n puts \"#{i_N} subjects.\"\n puts \"#{k} categories.\"\n end\n\n # Computing p[]\n p = [0.0] * k\n (0...k).each do |j|\n p[j] = 0.0\n (0...i_N).each {|i| p[j] += matrix[i][j] } \n p[j] /= i_N*n \n end\n\n puts \"p = #{p.join(',')}\" if debug\n\n # Computing f_P[] \n f_P = [0.0] * i_N\n\n (0...i_N).each do |i|\n f_P[i] = 0.0\n (0...k).each {|j| f_P[i] += matrix[i][j] * matrix[i][j] } \n f_P[i] = (f_P[i] - n) / (n * (n - 1)) \n end \n\n puts \"f_P = #{f_P.join(',')}\" if debug\n\n # Computing Pbar\n f_Pbar = sum(f_P) / i_N\n puts \"f_Pbar = #{f_Pbar}\" if debug\n\n # Computing f_PbarE\n f_PbarE = p.inject(0.0) { |acc,el| acc + el**2 }\n\n puts \"f_PbarE = #{f_PbarE}\" if debug \n\n kappa = (f_Pbar - f_PbarE) / (1 - f_PbarE)\n puts \"kappa = #{kappa}\" if debug \n\n kappa \nend", "def ig_ind\n\t\taibc(@datos[0]).each_with_index.map{ |ind, i| (ind/aibc(@datos[1])[i])*100 }\n\tend", "def pmt(i, n, pv)\n return pv / ((1 - (1 / (1 + i) ** n )) / i)\n end", "def metodo_biseccion\n i = 0\n c_ant = 0\n c_act = 0\n\n # Valor inicial de A.\n factor = get_signo(@ecuacion.last.to_i) * -1\n a = ((@ecuacion.last.to_i.abs / @ecuacion.first.to_i.abs) ** (1.0/@grado)).to_i * factor;\n b = obtiene_valor_b(a)\n resultado = false\n\n loop do\n i += 1\n c_ant = c_act\n c_act = (a + b)/2.0\n\n if evaluar_funcion(c_act) >= 0\n a = c_act\n else\n b = c_act\n end\n\n if (c_act - c_ant).abs <= 0.001\n resultado = [c_ant, c_act, i]\n end\n\n break if (c_act - c_ant).abs <= 0.001\n end\n return resultado\n end", "def naive_algorithm(arr)\n\tproduct = 0\n\tarr.each do |i|\n\t arr.each do |j|\n\t \tp = arr[i] * arr[j]\n\t \tproduct = p if product < p\n\t end\t\n\tend\t\t\n\tproduct\nend", "def sigma(inta, intx, intb, pw)\n ttl = 0\n for i in 1..intx\n ttl += (inta*intx+intb)\n end\n if(pw == 1)\n return ttl\n end\n if(pw > 1)\n ttl=ui_pow(ttl, pw)\n return ttl\n end\n if(pw == 0)\n return 1\n end\nend", "def angle_bisect(angle1, angle2)\n \t bisector = (2 * Math::PI + angle1 + angle2).abs / 2.0\n \t if angle_delta(bisector, angle1) >= (Math::PI / 2.0)\n \t bisector = (angle1 + angle2).abs / 2.0\n \t end\n \t return bisector\n \tend", "def calculate_optimal_k\n k=0\n @k_optimal = Array.new(@size)\n (3..@size).each{|n|\n k+=1 while(cost(n,k)<cost(n,k+1))\n @k_optimal[n]=k\n }\n end", "def mof(i, p)\n arr = []\n x_swap = []\n (0..(p-2)).each do |x|\n arr.push((i**x) % p)\n end\n (1..(p-1)).each do |n|\n x_swap.push((arr.index {|item| n == item }) % 12 )\n end\n return x_swap\nend", "def calc_parab_y(x_in, fp_in)\r\n # - - - - - - - - - - - - - - - -\r\n lcy = (x_in * x_in) / (fp_in * 4.0)\r\n lcy\r\n end", "def prize\n return nil if self.performance.category.kimu?\n\n # Try to match points to a prize range for the contest round\n JUMU_PRIZE_POINT_RANGES[self.performance.contest.round - 1].each do |prize, point_range|\n if point_range.include?(self.points)\n return prize\n end\n end\n # Points not found in any prize range\n return nil\n end", "def probability_exact\n\t\t str_format=\"%0#{nr}b\"\n\t\t combinations=2**nr\n\t\t #p str_format\n\t\t total_w=combinations.times.map do |i|\n comb=sprintf(str_format,i)\n w_local=comb.length.times.inject(0) do |ac,j|\n sgn=comb[j]==\"0\" ? -1 : 1\n\t\t\t\t ac+(j+1)*sgn\n end\n\t\t end.sort\n\n \t\t total_w.find_all do |v| \n if @tails==:both\n v<=-w.abs or v>=w.abs\n elsif @tails==:left\n v<=w\n elsif @tails==:right\n \t\t\t\t v>=w\n end\n \t\t end.count/(combinations.to_f)\n end", "def score(hill)\n n = hill.size\n k = 2 * hill.tapecount\n\n # pre-compute \"positive scaled i-vs-j duel points\" matrix D\n dp = NMatrix.zeros(n)\n hill.id_pairs do |idA, progA, idB, progB|\n t = hill.results(progA, progB).reduce(:+)\n if t > 0\n dp[idA,idB] = @weightf.call(t.to_f, k.to_f)\n else\n dp[idB,idA] = @weightf.call(-t.to_f, k.to_f)\n end\n end\n\n # initialize base score from raw points\n s = NMatrix.zeros([n, 1])\n hill.each_with_index { |p, i| s[i,0] = (hill.points(p) + (n-1)) / (2 * (n-1)) }\n\n # iterate until convergence, or for maximum number of steps\n (1 .. 100).each do |_|\n ps = s\n s = dp.dot(ps)\n s = s / s.sum.to_f * (n/2)\n break if (s - ps).abs.mean.to_f < 0.000001\n end\n\n Hash[hill.each_with_index.map { |p, i| [p, 100 * s[i,0]] }]\n end", "def bonAppetit(n, k, b, ar)\n sum = 0\n non_split_item = ar[k]\n ar.each do |value|\n sum += value\n end\n # get sum - the item not split\n new_sum = (sum - non_split_item)\n b == new_sum / 2 ? \"Bon Appetit\" : b - (new_sum / 2)\nend", "def ukp2(ukpi, ret_table = true)\n n = ukpi[:n]\n c = ukpi[:c]\n items = ukpi[:items].clone\n\n # step one\n g = Array.new(c+1, 0)\n d = Array.new(c+1, n-1)\n sort_items_by_profitability!(items)\n\n gy_col = nil\n dy_col = nil\n if ret_table then\n gy_col = Array.new(c+1) { [] }\n dy_col = Array.new(c+1) { [] }\n end\n\n # step two to six\n (c+1).times do | y |\n if ret_table then\n gy_col[y] << g[y]\n dy_col[y] << d[y]\n end\n items.each_with_index do | item, j |\n if y - item[:w] >= 0 && j <= d[y - item[:w]] then\n v = g[y - item[:w]] + item[:p]\n if v > g[y] then\n g[y] = v\n d[y] = j\n if ret_table then\n gy_col[y] << g[y]\n dy_col[y] << d[y]\n end\n end\n end\n end\n end\n\n table = \"y\\tg(y)\\t\\td(y)\\n\"\n if ret_table then\n (c+1).times do | y |\n table << \"#{y}\\t#{gy_col[y].join(' ')}\\t\\t#{dy_col[y].join(' ')}\\n\"\n end\n end\n \n if ret_table then\n table\n else\n g\n end\nend", "def imc\n\t\tnum = (@peso/(@talla*@talla)).round(2)\n\t\tif num < 18.5\n\t\t\tnum #- Bajo peso\"\n\t\telsif num > 18.5 and num < 24.9\n\t\t\tnum #- Adecuado\"\n\t\telsif num > 25.0 and num < 29.9\n\t\t\tnum #- Sobrepeso\"\n\t\telsif num > 30.0 and num < 34.9\n\t\t\tnum #Obesidad grado 1\"\n\t\telsif num > 35.0 and num < 39.9\n\t\t\tnum #- Obesidad grado 2\"\n\t\telsif num > 40\n\t\t\tnum #- Obesidad grado 2\"\n\t\tend\t\t\t\n\tend", "def solution(a)\r\n n=a.size\r\n i=1\r\n for k in a.sort do\r\n\tif k!=i \r\n\t then \r\n\t return 0\r\n\t break;\r\n\tend\r\n i+=1;\r\n end\t\r\n return 1 if a.inject(:+) ==n*(n+1)/2;\r\nend", "def bisect_on_angle(angle)\n label = angle.is_a?(Symbol) ? angle : angle.label\n\n # if self is angle A, these are sides [:b, :c]\n other_labels = sides.map(&:label) - [label]\n other_sides = [send(other_labels.first), send(other_labels.last)]\n degrees = send(\"angle_#{label}\".to_sym).to_numeric\n\n # Calculate the length of the bisector of this angle\n bisector = bisector_length(send(label), other_sides.first, other_sides.last)\n\n # segment of AC with ratio of BA\n line_segment1 = side_from_sas(other_sides.first, (degrees / 2), bisector)\n\n # segment of AC with ratio of BC\n line_segment2 = side_from_sas(other_sides.last, (degrees / 2), bisector)\n\n # return the resulting triangles formed by the bisection\n [\n self.class.new(line_segment1, other_sides.first.length, bisector, precision: precision),\n self.class.new(line_segment2, other_sides.last.length, bisector, precision: precision)\n ]\n end", "def solve(l,p,c)\n\tif( l*c >= p )\n\t\treturn 0\n\telse \n\t\t#the optimal strategy is to pick the\n\t\t#geometric mean and not the average\n\t\tmean = Math.sqrt(l*p)\n\t\t# pick a = c * l :\n\t\tval1 = solve(mean,p,c)\n\t\t# pick a = p / c :\n\t\tval2 = solve(l,mean,c)\n\t\t\n\t\treturn 1 + [val1,val2].max\n\tend\nend", "def preprovide_saily_kainsi(akamatsu_demoniacally)\n gibbergunyah_nutcrack(mollycot_copolymerization, capitulator_polyphylogeny, overjob)\n lid_polytonalism(pneumoenteritis_ribby)\n pricklefish(overdraft, phleboplasty_poleaxe)\n end", "def p005(upper_bound = 20)\n # This builds on the idea that any value which is a multiple of another value can be used instead of it\n # Also that the lowest common multiple is a product of the minimal set of prime-multiples that cover the factors\n # So e.g. the lowest common multiple of 1..6 would be 5 x 2 x 2 x 3 = 60, where 2 appears twice because 2 x 2 = 4\n required_factors = (2..upper_bound).to_a\n required_primes = {}\n required_factors.each do |factor|\n required_primes.merge!(Prime.prime_division(factor).to_h) do |_prime_factor, old_multiple, new_multiple|\n [old_multiple, new_multiple].max\n end\n end\n required_primes.reduce(1) { |common_multiple, prime_multiple| common_multiple * prime_multiple[0]**prime_multiple[1] }\nend", "def minimumBribes(q)\n sum = 0\n q.each_with_index do |v,i|\n if v-(1+i) > 2\n puts \"Too chaotic\"\n return\n end\n bound = [v-2,0].max\n (bound..i-1).each do |j|\n sum+=1 if q[j] > v\n end\n end\n puts sum\nend", "def peta\n big_self * PETA\n end", "def aofn( n )\n# Guaranteed in this context...\n# return 0 unless n.coprime?( 10 )\n\n x, k = 1, 1\n until 0 == x\n x = (10*x + 1) % n\n k += 1\n end\n\n k\n end", "def primary_weight(code_point)\n byte0 = code_point - MIN_4_BOUNDARY\n\n if byte0 < 0\n byte1 = code_point / FINAL_3_COUNT\n byte0 = code_point % FINAL_3_COUNT\n\n byte2 = byte1 / MEDIAL_COUNT\n byte1 %= MEDIAL_COUNT\n\n # spread out, leaving gap at start\n byte0 = MIN_TRAIL + byte0 * FINAL_3_MULTIPLIER\n\n # offset\n byte1 += MIN_TRAIL\n byte2 += MIN_PRIMARY\n\n (byte2 << 16) + (byte1 << 8) + byte0\n else\n byte1 = byte0 / FINAL_4_COUNT\n byte0 %= FINAL_4_COUNT\n\n byte2 = byte1 / MEDIAL_COUNT\n byte1 %= MEDIAL_COUNT\n\n byte3 = byte2 / MEDIAL_COUNT\n byte2 %= MEDIAL_COUNT\n\n # spread out, leaving gap at start\n byte0 = MIN_TRAIL + byte0 * FINAL_4_MULTIPLIER\n\n # offset\n byte1 += MIN_TRAIL\n byte2 += MIN_TRAIL\n byte3 += MIN_4_PRIMARY\n\n (byte3 << 24) + (byte2 << 16) + (byte1 << 8) + byte0\n end\n end" ]
[ "0.5462763", "0.5442878", "0.5347153", "0.5302049", "0.5289266", "0.51673424", "0.51580364", "0.514113", "0.5125691", "0.5110864", "0.51021624", "0.5093386", "0.50421435", "0.49688026", "0.4938162", "0.49120304", "0.4909912", "0.4881527", "0.48788646", "0.48482218", "0.48473886", "0.480878", "0.4787242", "0.47743368", "0.47734544", "0.47294652", "0.47282636", "0.47279343", "0.47265628", "0.4725067", "0.47137272", "0.46622342", "0.4650989", "0.4631223", "0.46288884", "0.46212822", "0.46120483", "0.4602543", "0.45929274", "0.45928806", "0.4592826", "0.4574749", "0.45625532", "0.45606524", "0.4554849", "0.4550028", "0.45493156", "0.45477998", "0.45434082", "0.45269048", "0.45204684", "0.4512929", "0.45108438", "0.4504959", "0.44931698", "0.44906703", "0.44855478", "0.44841343", "0.4482828", "0.4482755", "0.44694084", "0.44598833", "0.44562516", "0.4456138", "0.44543722", "0.44476277", "0.44431418", "0.4440815", "0.44397995", "0.4432254", "0.44316536", "0.44285318", "0.44280785", "0.442751", "0.44207647", "0.44206324", "0.4417708", "0.44141144", "0.4402849", "0.4399447", "0.43956313", "0.4392152", "0.43892154", "0.43882126", "0.43861544", "0.43829843", "0.43825147", "0.4382249", "0.43749028", "0.43668094", "0.43667123", "0.43556365", "0.43522826", "0.43461922", "0.43420568", "0.43397093", "0.4337711", "0.433552", "0.43330538", "0.43278277" ]
0.5590275
0
Return estimated half_life of an AA sequence. _The halflife is a prediction of the time it takes for half of the amount of protein in a cell to disappear after its synthesis in the cell. ProtParam relies on the "Nend rule", which relates the halflife of a protein to the identity of its Nterminal residue; the prediction is given for 3 model organisms (human, yeast and E.coli)._
def half_life(species=nil) n_end = @seq[0].chr.to_sym if species HALFLIFE[species][n_end] else { :ecoli => HALFLIFE[:ecoli][n_end], :mammalian => HALFLIFE[:mammalian][n_end], :yeast => HALFLIFE[:yeast][n_end] } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def calculate_expected_dominant_offspring(xAA_AA, xAA_Aa, xAA_aa, xAa_Aa, xAa_aa, xaa_aa, offspring_each = 2)\r\n xAA_AA_prob = offspring_each.to_f * xAA_AA * 1 \r\n xAA_Aa_prob = offspring_each.to_f * xAA_Aa * 1 \r\n xAA_aa_prob = offspring_each.to_f * xAA_aa * 1 \r\n xAa_Aa_prob = offspring_each.to_f * xAa_Aa * 0.75 \r\n xAa_aa_prob = offspring_each.to_f * xAa_aa * 0.5 \r\n xaa_aa_prob = offspring_each.to_f * xaa_aa * 0 \r\n return xAA_AA_prob + xAA_Aa_prob + xAA_aa_prob + xAa_Aa_prob + xAA_aa_prob + xAa_aa_prob + xaa_aa_prob\r\nend", "def last_possible_defense_semester\n study_length * 2\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n number_of_deaths = (@population * (@population_density/500)).floor\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths()\r\n # predicted deaths is solely based on population density\r\n # Not the same as before but more accurate\r\n number_of_deaths = (@population * (@population_density / 500)).floor\r\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n end", "def predicted_deaths\n death_toll = (population * death_multiplier).floor\n print \"#{state} will lose #{death_toll} people in this outbreak\"\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 50\n number_of_deaths = (@population * (@population_density / 50).floor * 0.1).floor\n else\n number_of_deaths = (@population * 0.05).floor\n end\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 50\n number_of_deaths = (@population * (@population_density / 50).floor * 0.1).floor\n else\n number_of_deaths = (@population * 0.05).floor\n end\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n end", "def predicted_deaths\n multiplier = 0\n if @population_density >= 200\n multiplier = 0.4\n elsif @population_density >= 150\n multiplier = 0.3\n elsif @population_density >= 100\n multiplier = 0.2\n elsif @population_density >= 50\n multiplier = 0.1\n else\n multiplier = 0.05\n end\n number_of_deaths = (@population * multiplier).floor\n # end\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @range != 5.0\n number_of_deaths = (@population * (0.5-(@range/10.0))).floor\n else number_of_deaths = (@population * (@range/100)).floor\n end\n\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n death_quotient = 1\n if @population_density >= 200\n death_quotient = 0.4\n elsif @population_density >= 150\n death_quotient = 0.3\n elsif @population_density >= 100\n death_quotient = 0.2\n elsif @population_density >= 50\n death_quotient = 0.1\n else\n death_quotient = 0.05\n end\n\n number_of_deaths = (@population * death_quotient).floor\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def calculate_prediction_likelihood(away_team_goals_conceded, away_team_goals_scored, home_team_goals_conceded, home_team_goals_scored)\n delta = (home_team_goals_scored - away_team_goals_conceded).abs + (home_team_goals_conceded - away_team_goals_scored).abs\n DSHelpers.reverse_normalize_value(delta,0, 8.0,1.0)\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n density = 200\n multiplier = 0.4\n until @population_density >= density\n if @population_density < 50\n return print \"#{@state} will lose #{(@population * 0.05).floor} people in this outbreak\"\n end\n density -= 50\n multiplier -= 0.1\n end\n number_of_deaths = (@population * multiplier).floor\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 200\n float = 0.4\n elsif @population_density >= 150\n float = 0.3\n elsif @population_density >= 100\n float = 0.2\n elsif @population_density >= 50\n float = 0.1\n else\n float = 0.05\n end\n\n number_of_deaths = (@population * float).floor\n \n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\r\n # predicted deaths is solely based on population density \r\n if @population_density >= 200\r\n number_of_deaths = (@population * 0.4).floor\r\n elsif @population_density < 50\r\n number_of_deaths = (@population * 0.05).floor\r\n else\r\n increment = (@population_density/50).floor\r\n number_of_deaths=(@population * (increment * 0.1)).floor\r\n end\r\n\r\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n\r\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 200\n number_of_deaths = (@population * 0.4).floor\n elsif @population_density < 50\n number_of_deaths = (@population * 0.05).floor\n else\n number_of_deaths = (@population*((@population_density/50).floor)*(0.1)).floor\n end\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if population_density >= 200\n death_constant = 0.4\n elsif population_density >= 150\n death_constant = 0.3\n elsif population_density >= 100\n death_constant = 0.2\n elsif population_density >= 50\n death_constant = 0.1\n else\n death_constant = 0.05\n end\n\n number_of_deaths = (population * death_constant).floor\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 200\n percentage = 0.4\n elsif @population_density >= 150\n percentage = 0.3\n elsif @population_density >= 100\n percentage = 0.2\n elsif @population_density >= 50\n percentage = 0.1\n else\n percentage = 0.05\n end\n \n number_of_deaths = (@population * percentage).floor\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\r\n\r\n number_of_deaths = (population * 0.05).floor\r\n \r\n 4.times do |i|\r\n if population_density >= 50*(i+1)\r\n number_of_deaths = (population * 0.1*(i+1)).floor\r\n end\r\n end\r\n print \"#{state} will lose #{number_of_deaths} people in this outbreak\"\r\n\r\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n death_factor = case @population_density.floor\n when 0..49\n 0.05\n when 50..99\n 0.1\n when 100..149\n 0.2\n when 150..199\n 0.3\n else\n 0.4\n end\n number_of_deaths = (@population * death_factor).floor\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 200\n number_of_deaths = (@population * 0.4).floor\n elsif @population_density < 200 && @population_density >= 50\n number_of_deaths = (@population * ((@population_density/50).floor*0.1)).floor\n else\n number_of_deaths = (@population * 0.05).floor\n end\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths # Its gonna predict number of deaths based on population density by muliplying population by given factor, for each state\n array = [50, 100, 150, 200].reverse\n array.each do |end_of_range|\n if @population_density >= end_of_range\n number_of_deaths = ( @population * end_of_range / 500 )\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n break\n else\n number_of_deaths = (@population * 0.05).floor\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n break\n end\n end\n end", "def predicted_deaths\r\n \r\n # predicted deaths is solely based on population density\r\n \r\n if @population_density >= 200\r\n n = 0.4\r\n\r\n elsif @population_density >= 150\r\n n = 0.3\r\n\r\n elsif @population_density >= 100\r\n n = 0.2\r\n\r\n elsif @population_density >= 50\r\n n = 0.1\r\n\r\n else\r\n n = 0.05\r\n\r\n end\r\n \r\n number_of_deaths = (@population * n).floor\r\n\r\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n\r\n end", "def predicted_deaths\r\n # predicted deaths is solely based on population density\r\n number_of_deaths=0\r\n density=[200,150,100,50,0]\r\n death_percentage=[0.4, 0.3, 0.2, 0.1, 0.05]\r\n\r\n density.each_index do |index|\r\n if @population_density >= density[index]\r\n number_of_deaths = (@population * death_percentage[index]).floor\r\n break\r\n end\r\n end\r\n=begin\r\n if @population_density >= 200\r\n number_of_deaths = (@population * 0.4).floor\r\n elsif @population_density >= 150\r\n number_of_deaths = (@population * 0.3).floor\r\n elsif @population_density >= 100\r\n number_of_deaths = (@population * 0.2).floor\r\n elsif @population_density >= 50\r\n number_of_deaths = (@population * 0.1).floor\r\n else\r\n number_of_deaths = (@population * 0.05).floor\r\n end\r\n=end\r\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n\r\n end", "def haldane_equation(p_inert, p_alv, half_time, dt)\n schreiner_equation(p_inert, p_alv, half_time, 0, dt)\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density > 200\n number_of_deaths = (@population * 0.4).floor\n elsif @population_density <= 200 && @population_density >= 50\n number_of_deaths = (@population * (@population_density/50 * 0.1)).floor\n else\n number_of_deaths = (@population * 0.05).floor\n end\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths(factor)\r\n # predicted deaths is solely based on population density\r\n number_of_deaths = (@population * factor).floor\r\n \r\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n end", "def predicted_deaths\r\n # predicted deaths is solely based on population density\r\n if @population_density > 200\r\n number_of_deaths = (@population * 0.4).floor\r\n elsif @population_density <= 200 && @population_density >= 50\r\n number_of_deaths = @population * ((@population_density/50) * 0.1).floor\r\n else\r\n number_of_deaths = (@population * 0.05).floor\r\n end\r\n\r\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n\r\n end", "def pri_toff\n team_stats.goals_per_game / team_stats.opp_avg_goals_per_game\n end", "def predicted_deaths(this)\r\n # predicted deaths is solely based on population density\r\n case @population_density\r\n when 200..\r\n number_of_deaths = (@population * 0.4).floor\r\n when 150..200\r\n number_of_deaths = (@population * 0.3).floor\r\n when 100..150\r\n number_of_deaths = (@population * 0.2).floor\r\n when 50..100\r\n number_of_deaths = (@population * 0.1).floor\r\n when 0..50\r\n number_of_deaths = (@population * 0.05).floor\r\n end\r\n\r\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 200\n death_loss = 0.4\n elsif @population_density >= 150\n death_loss = 0.3\n elsif @population_density >= 100\n death_loss = 0.2\n elsif @population_density >= 50\n death_loss = 0.1\n else\n death_loss = 0.05\n end\n\n number_of_deaths = (@population * death_loss).floor\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n death_factor = if @population_density >= 200\n 0.4\n elsif @population_density >= 150\n 0.3\n elsif @population_density >= 100\n 0.2\n elsif @population_density >= 50\n 0.1\n else\n 0.05\n end\n\n number_of_deaths = (@population * death_factor).floor\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\r\n # predicted deaths is solely based on population density\r\n\r\n if @population_density >= 200\r\n multiplier = 0.4\r\n elsif @population_density >= 150\r\n multiplier = 0.3\r\n elsif @population_density >= 100\r\n multiplier = 0.2\r\n elsif @population_density >= 50\r\n multiplier = 0.1\r\n else\r\n multiplier = 0.05\r\n end\r\n\r\n number_of_deaths = (@population * multiplier).floor\r\n\r\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n\r\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n population_multiplier = 0\n\n case @population_density\n when (200..Float::INFINITY) then population_multiplier = 0.4\n when (150...200) then population_multiplier = 0.3\n when (100...150) then population_multiplier = 0.2\n when (50...100) then population_multiplier = 0.1\n else population_multiplier = 0.05\n end\n\n number_of_deaths = (@population * population_multiplier).floor\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n case @population_density\n when 0..49\n multiplier_factor = 0.05\n when 50..99\n multiplier_factor = 0.1\n when 100..149\n multiplier_factor = 0.2\n when 150..199\n multiplier_factor = 0.3\n else\n multiplier_factor = 0.4\n end\n \n number_of_deaths = (@population * multiplier_factor).floor\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 200\n multiplier = 0.4\n elsif @population_density >= 150\n multiplier = 0.3\n elsif @population_density >= 100\n multiplier = 0.2\n elsif @population_density >= 50\n multiplier = 0.1\n else\n multiplier = 0.05\n end\n number_of_deaths = (@population * multiplier).floor\n \n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 200\n multiplier = 0.4\n elsif @population_density >= 150\n multiplier = 0.3\n elsif @population_density >= 100\n multiplier = 0.2\n elsif @population_density >= 50\n multiplier = 0.1\n else\n multiplier = 0.05\n end\n\n number_of_deaths = (@population * multiplier).floor\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n\n\n if @population_density >= 200\n rate = 0.4\n elsif @population_density >= 150\n rate = 0.3\n elsif @population_density >= 100\n rate = 0.2\n elsif @population_density >= 50\n rate = 0.1\n else\n rate = 0.05\n end\n number_of_deaths = (@population * rate).floor\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n\n number_of_deaths = case\n when @population_density >= 200\n @population * 0.4\n when @population_density >= 50\n @population * 0.1 * (@population_density.to_i/50)\n else\n @population * 0.05\n end\n\n print \"#{@state} will lose #{number_of_deaths.floor} people in this outbreak\"\n\n end", "def predicted_deaths\n if @population_density >= 200\n multiplier = 0.4\n elsif @population_density >= 150\n multiplier = 0.3\n elsif @population_density >= 100\n multiplier = 0.2\n elsif @population_density >= 50\n multiplier = 0.1\n else\n multiplier = 0.05\n end\n number_of_deaths = (@population * multiplier).floor\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n \n if @population_density >= 200\n death_multiplier = 0.4\n elsif @population_density >= 150\n death_multiplier = 0.3\n elsif @population_density >= 100\n death_multiplier = 0.2\n elsif @population_density >= 50\n death_multiplier = 0.1\n else\n death_multiplier = 0.05\n end\n\n number_of_deaths = (@population * death_multiplier).floor\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 200\n death_rate = 0.4\n elsif @population_density >= 150\n death_rate = 0.3\n elsif @population_density >= 100\n death_rate = 0.2\n elsif @population_density >= 50\n death_rate = 0.1\n else\n death_rate = 0.05\n end\n \n number_of_deaths = (@population * death_rate).floor\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths # this is going to print out the deaths for each state on the outbreak which is going to be based on population and population density\n \n death_percent = 0.1 if @population_density >= 50\n death_percent = 0.2 if @population_density >= 100\n death_percent = 0.3 if @population_density >= 150\n death_percent = 0.4 if @population_density >= 200\n death_percent = 0.05 if @population_density < 50\n number_of_deaths = (@population * death_percent).floor\n \n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n \n end", "def dampening_half_time\n return nil if dampening.nil? || dampening_routemap_configured?\n if dampening.is_a?(Array) && !dampening.empty?\n dampening[0].to_i\n else\n default_dampening_half_time\n end\n end", "def fitness\n 0 - length_penalty - spelling_penalty\n end", "def predicted_deaths\r\n # predicted deaths is solely based on population density\r\n if @population_density >= 200\r\n death_factor = 0.4\r\n elsif @population_density >= 150\r\n death_factor = 0.3\r\n elsif @population_density >= 100\r\n death_factor = 0.2\r\n elsif @population_density >= 50\r\n death_factor = 0.1\r\n else\r\n death_factor = 0.05\r\n end\r\n number_of_deaths = (@population * death_factor).floor\r\n\r\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n\r\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n rate = case @population_density\n when(200..9999) then 0.4\n when(150..199) then 0.3\n when(100..149) then 0.2\n when(50..99) then 0.1\n else 0.05\n end\n\n number_of_deaths = (@population * rate).floor\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n end", "def predicted_deaths\r\n # predicted deaths is solely based on population density\r\n case @population_density\r\n when 200..Float::INFINITY\r\n rate = 0.4\r\n when 150..199\r\n rate = 0.3\r\n when 100..149\r\n rate = 0.2\r\n when 50..99\r\n rate = 0.2\r\n else\r\n rate = 0.05\r\n end\r\n\r\n number_of_deaths = (@population * rate).floor\r\n\r\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n\r\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 200\n factor = 0.4\n elsif @population_density >= 150\n factor = 0.3\n elsif @population_density >= 100\n factor = 0.2\n elsif @population_density >= 50\n factor = 0.1\n else\n factor = 0.05\n end\n\n number_of_deaths = (@population * factor).floor\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n\n number_of_deaths = case @population_density\n when 0..49 then (@population * 0.05).floor\n when 50..99 then (@population * 0.1).floor\n when 100..149 then (@population * 0.2).floor\n when 150..199 then (@population * 0.3).floor\n else (@population * 0.4).floor\n end\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def lo_hi_age(life_stage)\n AGE_RE.match(life_stage) or warn \"Funny life_stage #{life_stage.inspect}\"\n lo_age, hi_age, yr = [Float($1), ($2==\"up\" ? 120.0 : Float($2)), $3]\n lo_age, hi_age = lo_age/12, hi_age/12 if (yr == 'mo')\n [lo_age, hi_age]\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if (@population_density >= 50) && (@population_density < 200)\n death_rate = ((@population_density / 50).floor).to_f\n number_of_deaths = ((death_rate / 10) * @population).to_i\n elsif @population_density >= 200\n number_of_deaths = (@population * 0.4).floor\n else\n number_of_deaths = (@population * 0.05).floor\n end\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 200\n factor = 0.4\n elsif @population_density >= 150\n factor = 0.3\n elsif @population_density >= 100\n factor = 0.2\n elsif @population_density >= 50\n factor = 0.1\n else\n factor = 0.05\n end\n number_of_deaths = (@population * factor).floor\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n end", "def predicted_deaths\r\n # predicted deaths is solely based on population density\r\n\r\n coefficient = case @population_density\r\n when 200..15000 then 0.4\r\n when 150..199 then 0.3\r\n when 100..149 then 0.2\r\n when 50..99 then 0.1\r\n else 0.05\r\n end\r\n\r\n number_of_deaths = @population * coefficient\r\n print \"#{@state} will lose #{number_of_deaths.floor} people in this outbreak\"\r\n\r\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 200\n prediction = 0.4\n elsif @population_density >= 150\n prediction = 0.3\n elsif @population_density >= 100\n prediction = 0.2\n elsif @population_density >= 50\n prediction = 0.1\n else\n prediction = 0.05\n end\n\n print \"#{@state} will lose #{(prediction * @population).floor} people in this outbreak\"\n\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n case @population_density\n when 1..49 then death_factor = 0.05\n when 50..99 then death_factor = 0.1\n when 100..149 then death_factor = 0.2\n when 150..199 then death_factor = 0.3\n else death_factor = 0.4\n end\n \n deaths = (@population*death_factor).floor\n \n print \"#{@state} will lose #{deaths} people in this outbreak\"\n\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 200\n factor = 0.4\n elsif @population_density >= 150\n factor = 0.3\n elsif @population_density >= 100\n factor = 0.2\n elsif @population_density >= 50\n factor = 0.1\n else\n factor = 0.05\n end\n number_of_deaths = (@population * factor).floor\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak and will spread across the state in #{@speed} months.\\n\\n\"\n end", "def predicted_deaths\r\n # predicted deaths is solely based on population density \r\n\r\n # multiplier when population density is less than 50\r\n multiplier = 0.05\r\n\r\n # sets new population density variable to have a mximum of 200\r\n max_pop = 200\r\n population_density_temp = [@population_density, max_pop].min\r\n \r\n multiplier = 0.1 * (population_density_temp / 50).floor if population_density_temp >= 50\r\n\r\n number_of_deaths = (@population * multiplier).floor\r\n\r\n\r\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n\r\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n number_of_deaths =\n if @population_density >= 200\n (@population * 0.4).floor\n elsif @population_density >= 150\n (@population * 0.3).floor\n elsif @population_density >= 100\n (@population * 0.2).floor\n elsif @population_density >= 50\n (@population * 0.1).floor\n else\n (@population * 0.05).floor\n end\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\r\n\r\n #(population_density, population, state) <--- deleted, not necessary\r\n # predicted deaths is solely based on population density\r\n\r\n #idx = 0.4 if population_density >= 200\r\n #idx = 0.3 if population_density >= 150\r\n \r\n case population_density\r\n when 0..49 then idx = 0.05\r\n when 50..99 then idx = 0.1\r\n when 100..150 then idx = 0.2\r\n when 151..200 then idx = 0.3\r\n else idx = 0.4\r\n end\r\n\r\n\r\n # if population_density >= 200\r\n # idx = 0.4\r\n # #number_of_deaths = (population * 0.4).floor\r\n # elsif population_density >= 150\r\n # idx = 0.3\r\n # #number_of_deaths = (population * 0.3).floor\r\n # elsif population_density >= 100\r\n # idx = 0.2\r\n # #number_of_deaths = (population * 0.2).floor\r\n # elsif population_density >= 50\r\n # idx = 0.1\r\n # #number_of_deaths = (population * 0.1).floor\r\n # else\r\n # idx = 0.05\r\n # #number_of_deaths = (population * 0.05).floor\r\n # end\r\n\r\n number_of_deaths = (population * idx).floor\r\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n\r\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n STATE_FORMULA.each do |state_size, calculation|\n if @population_density >= calculation[:pop_density]\n return number_of_deaths = (@population * calculation[:deaths]).floor\n end\n end\n number_of_deaths = (@population * 0.05).floor\n end", "def predicted_deaths\r\n # predicted deaths is solely based on population density\r\n factor = case @population_density\r\n when 0...50 then 0.05\r\n when 50...100 then 0.1\r\n when 100...150 then 0.2\r\n when 150...200 then 0.3\r\n else 0.4\r\n end\r\n number_of_deaths = (@population * factor).floor\r\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 200\n factor = 0.4\n elsif @population_density >= 150\n factor = 0.3\n elsif @population_density >= 100\n factor = 0.2\n elsif @population_density >= 50\n factor = 0.1\n else\n factor = 0.05\n end\n\n number_of_deaths = (@population * factor).floor\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 200\n factor = 0.4\n elsif @population_density >= 150\n factor = 0.3\n elsif @population_density >= 100\n factor = 0.2\n elsif @population_density >= 50\n factor = 0.1\n else\n factor = 0.05\n end\n\n number_of_deaths = (@population * factor).floor\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n \n if @population_density >= 50\n multiplication_factor = (@population_density.fdiv(50)).floor.fdiv(10)\n # (density / 50), rounded down to int, then divided by 10\n # ex: 200 / 50 = 4, 4/10 = 0.4\n # ex: 185 / 50 = 3.7, rounded to 3, 3/10 = 0.3\n else # if population density < 50\n multiplication_factor = 0.05\n end\n \n \n \n number_of_deaths = (@population * multiplication_factor).floor\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 200\n deaths= 0.4\n elsif @population_density >= 150\n deaths= 0.3\n elsif @population_density >= 100\n deaths= 0.2\n elsif @population_density >= 50\n deaths= 0.1\n else\n deaths= 0.05\n end\n number_of_deaths = (@population * deaths).floor\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 200\n \tdecimal = 0.4\n elsif @population_density >= 150\n \tdecimal = 0.3\n elsif @population_density >= 100\n \tdecimal = 0.2\n elsif @population_density >= 50\n \tdecimal = 0.1\n else\n \tdecimal = 0.05\n end\n\n number_of_deaths = (@population * decimal).floor\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\r\n # predicted deaths is solely based on population density\r\n \r\n \r\n\r\n if @population_density >= 200\r\n x = 0.4\r\n\r\n elsif @population_density >= 150\r\n x = 0.3\r\n elsif @population_density >= 100\r\n x = 0.2\r\n\r\n elsif @population_density >= 50\r\n x = 0.1\r\n\r\n else\r\n x = 0.05\r\n end\r\n number_of_deaths = (@population * x).floor \r\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n\r\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 200\n (@population * 0.4).floor\n elsif @population_density >= 150\n (@population * 0.3).floor\n elsif @population_density >= 100\n (@population * 0.2).floor\n elsif @population_density >= 50\n (@population * 0.1).floor\n else\n (@population * 0.05).floor\n end\n\n # print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n \n if @population_density >= 200\n number_of_deaths = num_death_setter(0.4)\n elsif @population_density >= 150\n number_of_deaths = num_death_setter(0.3)\n elsif @population_density >= 100\n number_of_deaths = num_death_setter(0.2)\n elsif @population_density >= 50\n number_of_deaths = num_death_setter(0.1)\n else\n number_of_deaths = num_death_setter(0.5)\n end\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def hps\n self.total_healing.to_f / self.encounter.duration_in_seconds\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 200\n factor = 0.4\n elsif @population_density >= 150\n factor = 0.3\n elsif @population_density >= 100\n factor = 0.2\n elsif @population_density >= 50\n factor = 0.1\n else\n factor = 0.05\n end\n\n print \"#{@state} will lose #{(@population * factor).floor} people in this outbreak\"\n\n end", "def predicted_deaths\r\n # predicted deaths is solely based on population density\r\n\r\n estimated_deaths = case @population_density\r\n when 0...50 then 0.05\r\n when 50...100 then 0.1\r\n when 100...150 then 0.2\r\n when 150...200 then 0.3\r\n else 0.4\r\n end\r\n\r\n number_of_deaths = (@population * estimated_deaths).floor\r\n\r\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n\r\n # if @population_density >= 200\r\n # number_of_deaths = (@population * 0.4).floor\r\n # elsif @population_density >= 150\r\n # number_of_deaths = (@population * 0.3).floor\r\n # elsif @population_density >= 100\r\n # number_of_deaths = (@population * 0.2).floor\r\n # elsif @population_density >= 50\r\n # number_of_deaths = (@population * 0.1).floor\r\n # else\r\n # number_of_deaths = (@population * 0.05).floor\r\n # end\r\n\r\n # print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n\r\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n case @population_density\n when 0...50 then number_of_deaths = calc_density(0.05)\n when 50...100 then number_of_deaths = calc_density(0.1)\n when 100...150 then number_of_deaths = calc_density(0.2)\n when 150...200 then number_of_deaths = calc_density(0.3)\n else number_of_deaths = calc_density(0.4)\n end\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\r\n # predicted deaths is solely based on population density\r\n number_of_deaths = case @population_density\r\n when 151...200 then (@population * 0.3).floor\r\n when 101...150 then (@population * 0.2).floor\r\n when 51...100 then (@population * 0.1).floor\r\n when 0...50 then (@population * 0.05).floor\r\n else (@population * 0.4).floor\r\n end \r\n\r\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n\r\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 200\n @decimal = 0.4\n elsif @population_density >= 150\n @decimal = 0.3\n elsif @population_density >= 100\n @decimal = 0.2\n elsif @population_density >= 50\n @decimal = 0.1\n else\n @decimal = 0.05\n end\n\n number_of_deaths = (@population * @decimal).floor\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 200\n x = 0.4\n elsif @population_density >= 150\n x = 0.3\n elsif @population_density >= 100\n x = 0.2\n elsif @population_density >= 50\n x = 0.1\n else\n x = 0.05\n end\n number_of_deaths = (@population * x).floor\n#prints the predicted deaths as number_of_deaths in a sentence\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n # if @population_density >= 200\n # number_of_deaths = (@population * 0.4).floor\n # elsif @population_density >= 150\n # number_of_deaths = (@population * 0.3).floor\n # elsif @population_density >= 100\n # number_of_deaths = (@population * 0.2).floor\n # elsif @population_density >= 50\n # number_of_deaths = (@population * 0.1).floor\n # else\n # number_of_deaths = (@population * 0.05).floor\n # end\n\n def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 200\n num = 0.4\n # number_of_deaths = (@population * 0.4).floor\n elsif @population_density >= 150\n num = 0.3\n elsif @population_density >= 100\n num = 0.2\n elsif @population_density >= 50\n num = 0.1\n else\n num = 0.5\n end\n number_of_deaths = (@population * num + 1).floor\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end\n #formula by population density that predicts the rate of spread of virus by state pop.\n def speed_of_spread#in months\n # We are still perfecting our formula here. The speed is also affected\n # by additional factors we haven't added into this functionality.\n speed = 0.0\n\n if @population_density >= 200\n speed += 0.5\n elsif @population_density >= 150\n speed += 1\n elsif @population_density >= 100\n speed += 1.5\n elsif @population_density >= 50\n speed += 2\n else\n speed += 2.5\n end\n\n puts \" and will spread across the state in #{speed} months.\\n\\n\"\n\n end\n\nend", "def huella\n huella = @alimentos.inject([0,0,0]) do |acc, i|\n if i.kcal_total < 670\n acc[0] += (1.0 * (@gramos[acc[1]].valor / (i.proteinas + i.lipidos + i.carbohidratos)))\n elsif i.kcal_total > 830\n acc[0] += (3.0 * (@gramos[acc[1]].valor / (i.proteinas + i.lipidos + i.carbohidratos)))\n else acc[0] += (2.0 * (@gramos[acc[1]].valor / (i.proteinas + i.lipidos + i.carbohidratos)))\n end\n if (i.gases * 1000.0) < 800\n acc[0] += (1.0 * (@gramos[acc[1]].valor / (i.proteinas + i.lipidos + i.carbohidratos)))\n elsif (i.gases * 1000.0) > 1200\n acc[0] += (3.0 * (@gramos[acc[1]].valor / (i.proteinas + i.lipidos + i.carbohidratos)))\n else\n acc[0] += (2.0 * (@gramos[acc[1]].valor / (i.proteinas + i.lipidos + i.carbohidratos)))\n\t\t\tend\n\n\t\t\tacc[2] += (@gramos[acc[1]].valor / (i.proteinas + i.lipidos + i.carbohidratos))\n acc[1] += 1\n acc\n\t\tend\n\n\t\treturn (huella[0] / (2.0 * huella[2])).round(2)\n\tend", "def predicted_deaths\n # predicted deaths is solely based on population density\n # if @population_density >= 200\n # number_of_deaths = (@population * 0.4).floor\n # elsif @population_density >= 150\n # number_of_deaths = (@population * 0.3).floor\n # elsif @population_density >= 100\n # number_of_deaths = (@population * 0.2).floor\n # elsif @population_density >= 50\n # number_of_deaths = (@population * 0.1).floor\n # else\n # number_of_deaths = (@population * 0.05).floor\n # end\n \n def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 200\n num = 0.4\n # number_of_deaths = (@population * 0.4).floor\n elsif @population_density >= 150\n num = 0.3\n elsif @population_density >= 100\n num = 0.2\n elsif @population_density >= 50\n num = 0.1\n else\n num = 0.5\n end\n number_of_deaths = (@population * num + 1).floor\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end\n #formula by population density that predicts the rate of spread of virus by state pop. \n def speed_of_spread#in months\n # We are still perfecting our formula here. The speed is also affected\n # by additional factors we haven't added into this functionality.\n speed = 0.0\n\n if @population_density >= 200\n speed += 0.5\n elsif @population_density >= 150\n speed += 1\n elsif @population_density >= 100\n speed += 1.5\n elsif @population_density >= 50\n speed += 2\n else\n speed += 2.5\n end\n\n puts \" and will spread across the state in #{speed} months.\\n\\n\"\n\n end\n\nend", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 200\n num = 0.4\n elsif @population_density >= 150\n num = 0.3\n elsif @population_density >= 100\n num = 0.2\n elsif @population_density >= 50\n num = 0.1\n else\n num = 0.05\n end\n\n number_of_deaths = (@population * num).floor\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\r\n # predicted deaths is solely based on population density\r\n case @population_density \r\n inf = 1.0/0\r\n when 200..inf \r\n number_of_deaths = (@population * 0.4).floor\r\n when 150...200\r\n number_of_deaths = (@population * 0.3).floor\r\n when 100...150\r\n number_of_deaths = (@population * 0.2).floor\r\n when 50...100\r\n number_of_deaths = (@population * 0.1).floor\r\n else\r\n number_of_deaths = (@population * 0.05).floor\r\n end\r\n\r\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n\r\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n @number_of_deaths = if @population_density >= 200\n (@population * 0.4).floor\n elsif @population_density >= 150\n (@population * 0.3).floor\n elsif @population_density >= 100\n (@population * 0.2).floor\n elsif @population_density >= 50\n (@population * 0.1).floor\n else\n (@population * 0.05).floor\n end\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n end", "def predicted_deaths\r\n # predicted deaths is solely based on population density\r\n if @population_density >= 200\r\n number_of_deaths = (@population * 0.4).floor\r\n elsif @population_density >= 150\r\n number_of_deaths = (@population * 0.3).floor\r\n elsif @population_density >= 100\r\n number_of_deaths = (@population * 0.2).floor\r\n elsif @population_density >= 50\r\n number_of_deaths = (@population * 0.1).floor\r\n else\r\n number_of_deaths = (@population * 0.05).floor\r\n end\r\n\r\n # number_of_deaths = @population * ((@population_density / 50).floor / 10)\r\n\r\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n\r\n end", "def target_number_of_ama_hearings(time_period)\n decisions_in_days = (time_period.to_f / 1.year) * nonpriority_decisions_per_year\n (decisions_in_days * docket_proportions[:hearing]).round\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n number_of_deaths = 0\n density_hash = {200 => 0.4, 150 => 0.3, 100 => 0.2, 50 => 0.1,0 => 0.05}\n density_hash.each_key { |key|\n if @population_density >= key\n number_of_deaths = (@population * density_hash[key]).floor\n end\n }\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n number_of_deaths =\n if @population_density >= 200\n (@population * 0.4).floor\n elsif @population_density >= 150\n (@population * 0.3).floor\n elsif @population_density >= 100\n (@population * 0.2).floor\n elsif @population_density >= 50\n (@population * 0.1).floor\n else\n (@population * 0.05).floor\n end\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if population_density >= 200\n num = 0.4\n elsif @population_density >= 150\n num = 0.3\n elsif @population_density >= 100\n num = 0.2\n elsif @population_density >= 50\n num = 0.1\n else\n num = 0.05\n end\n number_of_deaths = (@population * num).floor\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n\n case @population_density\n when 0..50\n number_of_deaths = (@population * 0.05).floor\n when 50..100\n number_of_deaths = (@population * 0.1).floor\n when 100..150\n number_of_deaths = (@population * 0.2).floor\n when 150..200\n number_of_deaths = (@population * 0.3).floor\n else\n number_of_deaths = (@population * 0.4).floor\n end\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\r\n # predicted deaths is solely based on population density\r\n if @population_density >= 200\r\n number_of_deaths = (@population * 0.4).floor\r\n elsif @population_density >= 150\r\n number_of_deaths = (@population * 0.3).floor\r\n elsif @population_density >= 100\r\n number_of_deaths = (@population * 0.2).floor\r\n elsif @population_density >= 50\r\n number_of_deaths = (@population * 0.1).floor\r\n else\r\n number_of_deaths = (@population * 0.05).floor\r\n end\r\n\r\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n\r\n end", "def speed_of_spread(predicted_deaths)\n # We are still perfecting our formula here. The speed is also affected\n # by additional factors we haven't added into this functionality.\n speed = 0.0\n\n # I neatened this up, but didn't make another method since it doesn't calculate. \n case @population_density \n\n when 0...50 then speed += 2.5\n when 50...100 then speed += 2.0\n when 100...150 then speed += 1.5\n when 150...200 then speed += 1.0\n else speed += 0.5\n end\n\n puts \" and will spread across the state in #{speed} months.\\n\\n\"\n\n end", "def predicted_deaths\r\n # predicted deaths is solely based on population density\r\n if @population_density >= 200\r\n number_of_deaths = (@population * 0.4).floor\r\n elsif @population_density >= 150\r\n number_of_deaths = (@population * 0.3).floor\r\n elsif @population_density >= 100\r\n number_of_deaths = (@population * 0.2).floor\r\n elsif @population_density >= 50\r\n number_of_deaths = (@population * 0.1).floor\r\n else\r\n number_of_deaths = (@population * 0.05).floor\r\n end\r\n\r\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n\r\n end", "def predicted_deaths\r\n # predicted deaths is solely based on population density\r\n if @population_density >= 200\r\n number_of_deaths = (@population * 0.4).floor\r\n elsif @population_density >= 150\r\n number_of_deaths = (@population * 0.3).floor\r\n elsif @population_density >= 100\r\n number_of_deaths = (@population * 0.2).floor\r\n elsif @population_density >= 50\r\n number_of_deaths = (@population * 0.1).floor\r\n else\r\n number_of_deaths = (@population * 0.05).floor\r\n end\r\n\r\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n\r\n end", "def predicted_deaths\r\n # predicted deaths is solely based on population density\r\n if @population_density >= 200\r\n number_of_deaths = (@population * 0.4).floor\r\n elsif @population_density >= 150\r\n number_of_deaths = (@population * 0.3).floor\r\n elsif @population_density >= 100\r\n number_of_deaths = (@population * 0.2).floor\r\n elsif @population_density >= 50\r\n number_of_deaths = (@population * 0.1).floor\r\n else\r\n number_of_deaths = (@population * 0.05).floor\r\n end\r\n\r\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n\r\n end", "def predicted_deaths\r\n # predicted deaths is solely based on population density\r\n if @population_density >= 200\r\n number_of_deaths = (@population * 0.4).floor\r\n elsif @population_density >= 150\r\n number_of_deaths = (@population * 0.3).floor\r\n elsif @population_density >= 100\r\n number_of_deaths = (@population * 0.2).floor\r\n elsif @population_density >= 50\r\n number_of_deaths = (@population * 0.1).floor\r\n else\r\n number_of_deaths = (@population * 0.05).floor\r\n end\r\n\r\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n\r\n end", "def predicted_deaths\r\n # predicted deaths is solely based on population density\r\n if @population_density >= 200\r\n number_of_deaths = (@population * 0.4).floor\r\n elsif @population_density >= 150\r\n number_of_deaths = (@population * 0.3).floor\r\n elsif @population_density >= 100\r\n number_of_deaths = (@population * 0.2).floor\r\n elsif @population_density >= 50\r\n number_of_deaths = (@population * 0.1).floor\r\n else\r\n number_of_deaths = (@population * 0.05).floor\r\n end\r\n\r\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n\r\n end", "def predicted_deaths\r\n # predicted deaths is solely based on population density\r\n if @population_density >= 200\r\n number_of_deaths = (@population * 0.4).floor\r\n elsif @population_density >= 150\r\n number_of_deaths = (@population * 0.3).floor\r\n elsif @population_density >= 100\r\n number_of_deaths = (@population * 0.2).floor\r\n elsif @population_density >= 50\r\n number_of_deaths = (@population * 0.1).floor\r\n else\r\n number_of_deaths = (@population * 0.05).floor\r\n end\r\n\r\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\r\n\r\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n if @population_density >= 200\n x = 0.4\n elsif @population_density >= 150\n x = 0.3\n elsif @population_density >= 100\n x = 0.2\n elsif @population_density >= 50\n x = 0.1\n else\n x = 0.05\n end\n\n\tnumber_of_deaths = (@population * x).floor\n\t\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n number_of_deaths = if @population_density >= 200\n (@population * 0.4).floor\n elsif @population_density >= 150\n (@population * 0.3).floor\n elsif @population_density >= 100\n (@population * 0.2).floor\n elsif @population_density >= 50\n (@population * 0.1).floor\n else\n (@population * 0.05).floor\n end\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end", "def predicted_deaths\n # (population_density, population, state)\n # predicted deaths is solely based on population density\n if @population_density >= 200\n number_of_deaths = (@population * 0.4).floor\n elsif @population_density >= 150\n number_of_deaths = (@population * 0.3).floor\n elsif @population_density >= 100\n number_of_deaths = (@population * 0.2).floor\n elsif @population_density >= 50\n number_of_deaths = (@population * 0.1).floor\n else\n number_of_deaths = (@population * 0.05).floor\n end\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n #.floor => returns the largest integer less than or equal to float (rounds down to nearest integer)\n end", "def predicted_deaths\n # predicted deaths is solely based on population density\n\n estimated_deaths = case @population_density\n when 0...50 then 0.05\n when 50...100 then 0.1\n when 100...150 then 0.2\n when 150...200 then 0.3\n else 0.4\n end\n\n number_of_deaths = (@population * estimated_deaths).floor\n\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n # if @population_density >= 200\n # number_of_deaths = (@population * 0.4).floor\n # elsif @population_density >= 150\n # number_of_deaths = (@population * 0.3).floor\n # elsif @population_density >= 100\n # number_of_deaths = (@population * 0.2).floor\n # elsif @population_density >= 50\n # number_of_deaths = (@population * 0.1).floor\n # else\n # number_of_deaths = (@population * 0.05).floor\n # end\n\n # print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end" ]
[ "0.5435176", "0.5106106", "0.51055604", "0.5099969", "0.5079222", "0.49448442", "0.49448442", "0.49408907", "0.49173385", "0.49081874", "0.48839054", "0.4853226", "0.4842884", "0.48420635", "0.48389047", "0.48318678", "0.4829914", "0.4829279", "0.48252252", "0.48178998", "0.48138857", "0.48123556", "0.4811641", "0.48085952", "0.4803259", "0.48030576", "0.48028514", "0.4791696", "0.47895664", "0.47851592", "0.4783827", "0.47808632", "0.4779458", "0.47773686", "0.47771144", "0.47756973", "0.477543", "0.47675118", "0.4765858", "0.4763641", "0.4761189", "0.47609532", "0.4757648", "0.47523803", "0.4749808", "0.47483957", "0.47450566", "0.4743984", "0.47435656", "0.47397536", "0.4737693", "0.4736939", "0.47359014", "0.47351605", "0.47295952", "0.47295406", "0.47286853", "0.47269633", "0.4721616", "0.4720891", "0.47202545", "0.47184354", "0.47184354", "0.4715094", "0.47105706", "0.47103503", "0.47081974", "0.4706481", "0.4699564", "0.46987146", "0.4696595", "0.46964955", "0.46929076", "0.4691794", "0.46899903", "0.46868837", "0.46864766", "0.46828514", "0.46813378", "0.46809182", "0.4672334", "0.46694538", "0.46694243", "0.46693793", "0.4667197", "0.46667555", "0.46664557", "0.46659136", "0.4665874", "0.46657008", "0.46647808", "0.46647808", "0.46647808", "0.46647808", "0.46647808", "0.46647808", "0.46641612", "0.4657077", "0.46547985", "0.46513814" ]
0.6273526
0
Calculate instability index of an AA sequence. _The instability index provides an estimate of the stability of your protein in a test tube. Statistical analysis of 12 unstable and 32 stable proteins has revealed [7] that there are certain dipeptides, the occurence of which is significantly different in the unstable proteins compared with those in the stable ones. The authors of this method have assigned a weight value of instability to each of the 400 different dipeptides (DIWV)._
def instability_index @instability_index ||= begin instability_sum = 0.0 i = 0 while @seq[i+1] != nil aa, next_aa = [@seq[i].chr.to_sym, @seq[i+1].chr.to_sym] if DIWV.key?(aa) && DIWV[aa].key?(next_aa) instability_sum += DIWV[aa][next_aa] end i += 1 end round((10.0/amino_acid_number.to_f) * instability_sum, 2) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def aliphatic_index\n aa_map = aa_comp_map\n @aliphatic_index ||= round(aa_map[:A] +\n 2.9 * aa_map[:V] +\n (3.9 * (aa_map[:I] + aa_map[:L])), 2)\n end", "def ig_ind\n\t\taibc(@datos[0]).each_with_index.map{ |ind, i| (ind/aibc(@datos[1])[i])*100 }\n\tend", "def get_AIBC(i)\n @@tam = @medidas.length\n if i >= @@tam\n return 0\n else\n return (((@medidas[i] - @medidas[0]) + (@medidas[i - 1] - @medidas[0])) / 24) + get_AIBC(i + 1)\n end\n end", "def biodiversity_index(specimens)\n hash = Hash.new(0)\n specimens.each {|speci| hash[speci] += 1}\n hash.values.length**2 * hash.min_by{|k, v| v}[1] / hash.max_by{|k, v| v}[1]\nend", "def biodiversity_index(specimens)\n hsh = Hash.new(0)\n\n specimens.each { |ani| hsh[ani] += 1 }\n\n number_of_species = hsh.length\n smallest_population_size = hsh.min.last\n largest_population_size = hsh.max.last\n\n (number_of_species ** 2) * (smallest_population_size / largest_population_size)\n\nend", "def biodiversity_index(specimens)\n counter = Hash.new(0)\n specimens.each do |x|\n counter[x] += 1\n end\nnums = counter.values\n(nums.length ** 2) * nums.min / nums.max\nend", "def ab_counts(_experiment, _alternative)\n raise \"Not implemented\"\n end", "def biodiversity_index(specimens)\n index_hash = Hash.new(0)\n specimens.each {|ele| index_hash[ele]+= 1}\n sorted_index = index_hash.sort_by {|k,v| v}\n index_hash.length**2 * sorted_index[0][1] / sorted_index[-1][1]\nend", "def biodiversity_index(specimens)\n distribution = Hash.new(0)\n specimens.each do |specimen|\n distribution[specimen] += 1\n end\n smallest_population_size = distribution.values.min\n largest_population_size = distribution.values.max\n index = distribution.length ** 2 * smallest_population_size / largest_population_size\nend", "def biodiversity_index(specimens)\n species = Hash.new(0)\n specimens.each do |specimen|\n species[specimen] += 1\n end\n return ((species.size)**2)*(species.values.max / species.values.min)\nend", "def biodiversity_index(specimens)\n hash = Hash.new(0)\n specimens.uniq.each do |sp|\n hash[sp] = specimens.count(sp) \n end\n num_species = specimens.uniq.length\n smallest_pop = hash.values.min \n largest_pop = hash.values.max\n num_species**2 * smallest_pop / largest_pop\nend", "def get_IR_by_count(inst_cnt) \n incon, sample_size = 0.0, 0.0\n \n inst_cnt.values.each do |hcnt|\n cnt = hcnt.values\n incon += cnt.sum-cnt.max\n sample_size += cnt.sum\n end\n \n # inconsistency rate\n (sample_size.zero?) ? 0.0 : incon/sample_size\n end", "def biodiversity_index(specimens)\n all_species = specimens.uniq\n count = {}\n\n all_species.each do |species|\n count[species] = specimens.count(species)\n end\n\n number_of_species = all_species.length\n smallest_population_size = count.values.min \n largest_population_size = count.values.max\n\n number_of_species ** 2 * smallest_population_size / largest_population_size\n \nend", "def biodiversity_index(specimens)\n uniques = specimens.uniq\n species_count = {}\n\n specimens.each do |species|\n species_count[species] = specimens.count(species)\n end\n\n calculate_index(uniques, species_count)\nend", "def anisotropy_index\n @direct_normal_irradiance / extraterrestrial_irradiance\n end", "def biodiversity_index(specimens)\n population_size = Hash.new(0)\n specimens.each do |specimen|\n population_size[specimen] += 1\n end\n\n number_of_species = specimens.uniq.length\n smallest_population_size = population_size.values.min\n largest_population_size = population_size.values.max\n\n number_of_species ** 2 * smallest_population_size / largest_population_size\nend", "def biodiversity_index(specimens)\n number_of_species = specimens.uniq.length\n hsh = Hash.new(0)\n specimens.each do |el|\n hsh[el] += 1\n end\n smallest_population_size = hsh.values.min\n largest_population_size = hsh.values.max\n number_of_species**2 * smallest_population_size / largest_population_size\nend", "def run_align_assess\n filename = self.generate_fasta_alignment_file_for_all\n string = \"./lib/AlignAssess_wShorterID #{filename} P\"\n seq_array = Array.new\n if system(string)\n seq_id_array = self.sequences.map{|s| s.seq_id}\n new_filename = filename + \"_assess\"\n f = File.new(new_filename, \"r\")\n flag = false\n read_row= 999999999\n cur_row = 0\n while (line = f.gets)\n if cur_row > read_row && flag\n if line == \"\\n\"\n flag =false\n else\n seq_array << line.split(\"\\t\")\n end\n elsif line == \"Pair-wise %ID over shorter sequence:\\n\"\n flag=true\n read_row = cur_row + 2\n end\n cur_row +=1\n end\n range = seq_array.length - 1\n #seq_array.each do |row|\n for row_num in 0..range\n for i in 1..range#(row_num) \n PercentIdentity.first_or_create(:seq1_id=>seq_id_array[row_num],\n :seq2_id=>seq_id_array[i],\n :alignment_name => self.alignment_name,\n :percent_id=>seq_array[row_num][i])\n # print \"[#{row_num}:#{i-1}=>#{row[i]}],\"\n end\n #print \"\\n\"\n end\n end\n end", "def dnaSequence s\n hash, diff = Hash.new(0), Hash.new(0)\n diff[[0, 0, 0]] = 1\n\n sum = 0\n s.chars.each { |c|\n hash[c] += 1\n res = [hash['A'] - hash['C'], hash['C'] - hash['G'], hash['G'] - hash['T']]\n sum += diff[res]\n diff[res] += 1\n }\n sum\nend", "def indicator_energia()\n\t\t\t\te = totalCaloricValue() / @alimentsList.length\n\n\t\t\t\tif e < 670\n\t\t\t\t\treturn 1.0\n\t\t\t\telsif e <= 830\n\t\t\t\t\treturn 2.0\n\t\t\t\telse\n\t\t\t\t\treturn 3.0\n\t\t\t\tend\n\t\t\tend", "def acidic_count(amino_acid_sequence)\n count = 0\n comp = amino_acid_sequence.composition\n ACIDIC_AMINO_ACIDS.each do |acidic|\n if comp[acidic]\n count += comp[acidic]\n end\n end\n return count\n end", "def calcShannonEnt(dataSet)\n numEntries = dataSet.size\n labelCounts = {}\n dataSet.each_with_index do |inst, pos|\n label = inst[-1]\n labelCounts[label]=labelCounts.fetch(label,0)+1\n end\n shannonEnt = 0.0\n labelCounts.each_pair do |k, v|\n prob=v.to_f/numEntries\n shannonEnt-=prob*Math.log2(prob)\n end\n shannonEnt\n end", "def assess_insurance()\n\t\tvalues = self.comb_values()\n\t\treturn '0010000' if values.include?('930') #If extra service code 930 (insurance <= $200) is found, return manifest value for $100 ('0010000')\n\t\treturn '0050000' if values.include?('931') #If extra service code 931 (insurance > $200) is found, return manifest value for $500 ('0050000')\n\t\treturn false #If insurance values are not found, return false.\n\tend", "def min_umbrellas(weather)\n indexs = []\n result = 0\n weather.each_with_index do |weather, ind|\n if weather == \"rainy\" || weather == \"thunderstorms\"\n indexs << ind\n end\n end\n result += 1 unless indexs.empty?\n indexs.each_cons(2) do |first, second|\n result += 1 if (second - first) > 1\n end\n result\nend", "def calculate_index(data, gluc)\n aibc = [[],[]]\n data.each do |x|\n\t\t\tt = 0\n\t\t\tx.each_index do |a| \n\t\t\t\tif (a != 0) \n\t\t\t\t\tt += (((x[a] - x[0]) + (x[a - 1] - x[0])) /2)*5 \n\t\t\t\tend \n\t\t\tend \n\t\t\taibc[0] << t\n\t\tend\n\t\tgluc.each do |x|\n\t\t\tt = 0\n\t\t\tx.each_index do |a| \n\t\t\t\tif (a != 0) \n\t\t\t\t\tt += (((x[a] - x[0]) + (x[a - 1] - x[0])) /2)*5\n\t\t\t\tend \n\t\t\tend \n\t\t\taibc[1] << t\n\t\tend\n\t\tigind = []\n\t\taibc[0].each_index { |x| igind << ((aibc[0][x] / aibc[1][x]) * 100)}\n\t\tsuma = 0\n\t\tigind.each{ |x| suma += x}\n\t\t@indexGluc = (suma / igind.length)\n \n end", "def calcIndice\n\t\t# [true,true,false,true]\t\t\t\t[2,1]\n\t\t# [false,true,false,false]\t\t--> \t[1]\n\t\t# [true,true,true,false,true]\t\t\t[3,1]\n\n\t\t@indicesLigne = groupeIndicesGrid(@tab)\n\t\t@indicesColonne = groupeIndicesGrid(@tab.transpose)\n\t\treturn @tab\n\tend", "def index_of_coincidence(matrix)\n\n matrix.inject([]) do |indices, row_letters|\n frequencies = letter_frequencies(row_letters)\n\n indices << (\"A\"..\"Z\").inject(0) { |a,v|\n x = frequencies[v]\n a += x*(x-1)\n a\n } / (row_letters.size * (row_letters.size - 1))\n end\n\nend", "def cycle_index\n stats[:cycle_index]\n end", "def cycle_index\n stats[:cycle_index]\n end", "def apportion\n 385.times do |n|\n state = find_highest_priority\n @seats[state] += 1\n\n seat_number = 51 + n\n puts \"Assigning Seat #{seat_number} to #{state}\"\n end\n\n puts \"Just missed the cut...\"\n state = find_highest_priority\n puts \"Seat 436 would be assigned to #{state}\"\n\n @seats.each do |state, seats|\n printf(\"%20s\\t%3d\\n\", state, seats)\n end\n end", "def legacy_indexes()\n arr = []\n\n # REFACTOR: make to_llo call this one\n hr_op = analysis(Analysis::HR_NAME, lead_pair_name())\n\n # GXX : 0 - 25\n op = analysis(Analysis::APS_NAME, primary_lead_name())\n arr << op.index(Index::APS_12_NAME) # 0\n arr << op.index(Index::APS_OMEGA_NAME)\n arr << op.index(Index::APS_U1_NAME)\n arr << op.index(Index::APS_U2_NAME)\n arr << op.index(Index::APS_U3_NAME)\n arr << op.index(Index::APS_U3xy_NAME) # 5\n arr << op.index(Index::APS_U4_NAME)\n arr << op.index(Index::APS_N1_NAME)\n arr << op.index(Index::APS_N3_NAME)\n arr << hr_op.index(Index::HR_S_NAME)\n arr << hr_op.index(Index::HR_SS_NAME) # 10\n arr << hr_op.index(Index::HR_F_NAME)\n arr << hr_op.index(Index::HR_FF_NAME)\n arr << op.index(Index::APS_A1_NAME)\n arr << op.index(Index::APS_A2_NAME)\n arr << op.index(Index::APS_A3_NAME) # 15\n arr << op.index(Index::APS_A4_NAME)\n arr << op.index(Index::APS_A5_NAME)\n arr << op.index(Index::APS_A55_NAME)\n arr << op.index(Index::APS_N2_NAME)\n arr << op.index(Index::APS_AA12_NAME) # 20\n arr << op.index(Index::APS_AA34_NAME)\n arr << op.index(Index::APS_AA123_NAME)\n arr << op.index(Index::APS_AA1_NAME)\n arr << op.index(Index::APS_AA4_NAME)\n arr << op.index(Index::APS_U5_NAME) # 25\n\n # GYY : 26 - 51\n op = analysis(Analysis::APS_NAME, secondary_lead_name())\n arr << op.index(Index::APS_12_NAME)\n arr << op.index(Index::APS_OMEGA_NAME)\n arr << op.index(Index::APS_U1_NAME)\n arr << op.index(Index::APS_U2_NAME)\n arr << op.index(Index::APS_U3_NAME) # 30\n arr << op.index(Index::APS_U3xy_NAME)\n arr << op.index(Index::APS_U4_NAME)\n arr << op.index(Index::APS_N1_NAME)\n arr << op.index(Index::APS_N3_NAME)\n arr << hr_op.index(Index::HR_S_NAME) # 35\n arr << hr_op.index(Index::HR_SS_NAME)\n arr << hr_op.index(Index::HR_F_NAME)\n arr << hr_op.index(Index::HR_FF_NAME)\n arr << op.index(Index::APS_A1_NAME)\n arr << op.index(Index::APS_A2_NAME) # 40\n arr << op.index(Index::APS_A3_NAME)\n arr << op.index(Index::APS_A4_NAME)\n arr << op.index(Index::APS_A5_NAME)\n arr << op.index(Index::APS_A55_NAME)\n arr << op.index(Index::APS_N2_NAME) # 45\n arr << op.index(Index::APS_AA12_NAME)\n arr << op.index(Index::APS_AA34_NAME)\n arr << op.index(Index::APS_AA123_NAME)\n arr << op.index(Index::APS_AA1_NAME)\n arr << op.index(Index::APS_AA4_NAME) # 50\n arr << op.index(Index::APS_U5_NAME)\n\n # QXY : 52 - 57\n psa_op = analysis(Analysis::PSA_NAME, lead_pair_name())\n arr << psa_op.index(Index::PSA_PPLUS_NAME)\n arr << psa_op.index(Index::PSA_PMINUS_NAME)\n arr << psa_op.index(Index::PSA_WW_NAME)\n arr << psa_op.index(Index::PSA_PWWPLUS_NAME) # 55\n arr << psa_op.index(Index::PSA_PWWMINUS_NAME)\n\n imr_op = analysis(Analysis::IMR_NAME, lead_pair_name())\n arr << imr_op.index(Index::IMR_L_NAME)\n\n # RH : 58 - 59\n op = analysis(Analysis::COH_NAME, lead_pair_name())\n arr << op.index(Index::COH_Q1_NAME)\n arr << op.index(Index::COH_Q2_NAME)\n\n # PIH : 60 -69\n arr << imr_op.index(Index::IMR_D1_NAME) # 60\n arr << imr_op.index(Index::IMR_D2_NAME)\n arr << imr_op.index(Index::IMR_f_NAME)\n arr << imr_op.index(Index::IMR_M1_NAME)\n arr << imr_op.index(Index::IMR_M3_NAME)\n arr << imr_op.index(Index::IMR_M2_NAME) # 65\n arr << imr_op.index(Index::IMR_M4_NAME)\n arr << imr_op.index(Index::IMR_M5_NAME)\n arr << imr_op.index(Index::IMR_M6_NAME)\n arr << imr_op.index(Index::IMR_ff_NAME)\n\n # HA : 70 - 77\n v5_op = analysis(Analysis::AMP_NAME, primary_lead_name())\n ii_op = analysis(Analysis::AMP_NAME, secondary_lead_name())\n arr << v5_op.index(Index::AMP_HYPER_NAME) # 70\n arr << ii_op.index(Index::AMP_HYPER_NAME)\n arr << v5_op.index(Index::AMP_HYPO_NAME)\n arr << ii_op.index(Index::AMP_HYPO_NAME)\n arr << v5_op.index(Index::AMP_NPLUS_NAME)\n arr << ii_op.index(Index::AMP_NPLUS_NAME) # 75\n arr << v5_op.index(Index::AMP_NMINUS_NAME)\n arr << ii_op.index(Index::AMP_NMINUS_NAME)\n\n # VXY : 78 - 102\n op = analysis(Analysis::CCR_NAME, lead_pair_name())\n arr << op.index(Index::CCR_rrr_NAME)\n arr << op.index(Index::CCR_RRR_NAME)\n arr << op.index(Index::CCR_r_NAME) # 80\n arr << op.index(Index::CCR_R_NAME)\n arr << op.index(Index::CCR_RR_NAME)\n arr << op.index(Index::CCR_rr_NAME)\n arr << op.index(Index::CCR_rR_NAME)\n arr << op.index(Index::CCR_RPLUS_NAME) # 85\n arr << op.index(Index::CCR_RMINUS_NAME)\n arr << op.index(Index::CCR_RwPLUS_NAME)\n arr << op.index(Index::CCR_RwMINUS_NAME)\n arr << op.index(Index::CCR_PT1_NAME)\n arr << op.index(Index::CCR_PT2_NAME) # 90\n arr << op.index(Index::CCR_pt1_NAME)\n arr << op.index(Index::CCR_pt2_NAME)\n arr << op.index(Index::CCR_Rn_NAME)\n arr << op.index(Index::CCR_RVVPLUS_NAME)\n arr << op.index(Index::CCR_RVVMINUS_NAME) # 95\n arr << op.index(Index::CCR_RCARET_NAME)\n arr << op.index(Index::CCR_NOTR_NAME)\n arr << op.index(Index::CCR_RNOT_NAME)\n arr << op.index(Index::CCR_r2_NAME)\n arr << op.index(Index::CCR_R2_NAME) # 100\n arr << op.index(Index::CCR_r22_NAME)\n arr << op.index(Index::CCR_RM_NAME)\n\n # Q : 103 - 131\n arr << psa_op.index(Index::PSA_TPLUS_NAME)\n arr << psa_op.index(Index::PSA_TMINUS_NAME)\n arr << psa_op.index(Index::PSA_UPLUS_NAME) # 105\n arr << psa_op.index(Index::PSA_UMINUS_NAME)\n arr << psa_op.index(Index::PSA_WPLUS_NAME)\n arr << psa_op.index(Index::PSA_WMINUS_NAME)\n arr << psa_op.index(Index::PSA_W_NAME)\n arr << psa_op.index(Index::PSA_PPLUS10_NAME) # 110\n arr << psa_op.index(Index::PSA_PPLUS15_NAME)\n arr << psa_op.index(Index::PSA_PPLUSGT15_NAME)\n arr << psa_op.index(Index::PSA_PMINUS10_NAME)\n arr << psa_op.index(Index::PSA_PMINUS15_NAME)\n arr << psa_op.index(Index::PSA_PMINUSGT15_NAME) # 115\n arr << psa_op.index(Index::PSA_VPLUS_NAME)\n arr << psa_op.index(Index::PSA_VMINUS_NAME)\n arr << psa_op.index(Index::PSA_XPLUSPLUS_NAME)\n arr << psa_op.index(Index::PSA_XPLUSMINUS_NAME)\n arr << psa_op.index(Index::PSA_XMINUSMINUS_NAME) # 120\n arr << psa_op.index(Index::PSA_XMINUSPLUS_NAME)\n arr << psa_op.index(Index::PSA_YPLUSPLUS_NAME)\n arr << psa_op.index(Index::PSA_YMINUSMINUS_NAME)\n arr << psa_op.index(Index::PSA_YPLUSMINUS_NAME)\n arr << psa_op.index(Index::PSA_YMINUSPLUS_NAME) # 125\n arr << psa_op.index(Index::PSA_ZPLUS1_NAME)\n arr << psa_op.index(Index::PSA_ZPLUS2_NAME)\n arr << psa_op.index(Index::PSA_ZPLUS3_NAME)\n arr << psa_op.index(Index::PSA_ZMINUS1_NAME)\n arr << psa_op.index(Index::PSA_ZMINUS2_NAME) # 130\n arr << psa_op.index(Index::PSA_ZMINUS3_NAME)\n\n arr\n end", "def basic_count(amino_acid_sequence)\n count = 0\n comp = amino_acid_sequence.composition\n BASIC_AMINO_ACIDS.each do |basic|\n if comp[basic]\n count += comp[basic]\n end\n end\n return count\n end", "def boatswain\n return self.swabbie unless self.swabbie.nil?\n highval = 0\n self.axe.each do |flotsam|\n counter = self.filibuster(flotsam)\n highval = ((highval <=> counter) == 1) ? highval : counter\n end\n \".#{highval + 1}\"\n end", "def offensive_row_for_ai(board)\n offensive_play = {}\n WINNING_COMBINATIONS.each { |offense| offensive_play[offense] = 0 }\n WINNING_COMBINATIONS.each do |offense|\n offense.each do |is_x|\n offensive_play[offense] += 1 if board[is_x] == COMPUTER_MARKER\n if board[is_x] == PLAYER_MARKER\n offensive_play[offense] = 0\n break\n end\n end\n end\n offensive_play\nend", "def calculate_fitness\n return 'done' if @dna == @target_dna\n fit_arr = []\n @target_dna.each_with_index do |e, i|\n fit_arr.push((@dna[i] - e).abs)\n end\n (1 / fit_arr.inject(:+).to_f) * 100\n end", "def get_index(i)\n i/BITS_PER_ITEM\n end", "def get_new_idx(i, n)\n # I use the number 4 here but it correlates to the number of series.\n # For example, I only have \"a\", \"b\", \"c\", and \"d\" series so I use 4.\n (i % 4) * n + (i / 4)\nend", "def stability\n (instability_index <= 40) ? \"stable\" : \"unstable\"\n end", "def agency_abv; end", "def equivalent_level\n parsed_hd = parse_dice(self.class::HIT_DICE)\n \n if parsed_hd[-2] == '-'\n return 1\n else\n return parsed_hd.first + 1 + (parsed_hd.size > 3 ? 1 : 0)\n end\n end", "def giniA(xs)\n\t1 - xs.group_by {|x| x }.inject(0) {|a, (k, v)| a + (v.size.to_f / xs.size) ** 2 }\nend", "def accidentals(input) # Integer or symbol\n key_name = get_key_name(input)\n circle_of_fifths = [:Gb,:Cs,:Ab,:Eb,:Bb,:F,:C,:G,:D,:A,:E,:B,:Fs]\n idx = circle_of_fifths.index(key_name)\n idx-6\n end", "def getAbundants(cap)\n #init array\n abs = []\n #for every number under cap\n for i in 1..cap-1\n #if number is abundant\n if isAbundant(i)\n #add number to abs array\n abs << i\n end\n end\n #return abs\n return abs\nend", "def coding_region_cdna_start\n answer = 0\n \n self.exons.each do |exon|\n if exon == self.translation.start_exon\n answer += self.translation.seq_start\n return answer\n else\n answer += exon.length\n end\n end\n \n end", "def threat_row_for_ai(board)\n defend_spaces = {}\n WINNING_COMBINATIONS.each { |threat| defend_spaces[threat] = 0 }\n WINNING_COMBINATIONS.each do |threat|\n threat.each do |is_x|\n defend_spaces[threat] += 1 if board[is_x] == PLAYER_MARKER\n if board[is_x] == COMPUTER_MARKER\n defend_spaces[threat] = 0\n break\n end\n end\n end\n defend_spaces\nend", "def nobasicas_indice_seq_con_id\n Msip::Ability::NOBASICAS_INDSEQID +\n Mr519Gen::Ability::NOBASICAS_INDSEQID +\n Heb412Gen::Ability::NOBASICAS_INDSEQID +\n Cor1440Gen::Ability::NOBASICAS_INDSEQID\n end", "def getIndexSequence(laneBarcode)\n if !laneIndexed?(laneBarcode)\n return \"\"\n else\n tag = laneBarcode.gsub(/^[1-8]-ID/, \"\")\n return @pipelineHelper.findBarcodeSequence(\"ID\" + tag.to_s) \n end\n end", "def find_alphabetic_index\n @alphabetic_index = AlphabeticIndex.find(params[:id]).current_version\n end", "def iata_code\n @iata_code\n end", "def ig\n\t\tig_ind.reduce(0, :+)/ig_ind.size\n\tend", "def input_to_index(masuk)\n tes=masuk.to_i\n tes=tes-1\n return tes\nend", "def status\n sts = atcmd \"ATAI\"\n sts.to_i(16)\n end", "def calcularIntensidad\n grados = fuzzyfication\n intensidad = defuzzyfication(grados)\n intensidad\n end", "def consensus_iuap(minumum_ratio_for_iup_consensus)\n minumum_ratio_for_iup_consensus\n if @consensus_iuap.nil?\n @consensus_iuap = self.ref_base.downcase\n bases = self.bases\n tmp = String.new\n bases.each do |k,v|\n tmp << k[0].to_s if v/self.coverage > minumum_ratio_for_iup_consensus\n end\n if tmp.length > 0\n @consensus_iuap = Bio::NucleicAcid.to_IUAPC(tmp)\n end\n end \n @consensus_iuap\n end", "def exec_iter_fixed_alpha aggrStats\n iterStats = RunInfo.new\n iterConsensus = Hash.new {|hash, key| hash[key] = 0 }\n \n # NUMBER_OF_ITER times do\n $NUM_AVG_ITER.times do |i| \n # randomly withhold 20% of data\n pick_patients\n \n # find G'\n cover = exec_search \"nCOP_heruistic\"\n \n # store the stats\n iterStats.fillIn cover\n\n # add the cover to the consensus list\n add_to_consensus(iterConsensus, cover)\n end\n \n # compute the average and std for this set of iterations\n aggrStats.fillAggregateStats iterStats\n aggrStats.alpha << $ALPHA\n aggrStats.beta << $BETA\n\n # remember the frequency genes occured\n $selected_genes = iterConsensus\nend", "def hiv_protease(aa_array,start_aa=1)\n out_hash = {}\n sdrm = {}\n sdrm[23] = ['L',['I']]\n sdrm[24] = ['L',['I']]\n sdrm[30] = ['D',['N']]\n sdrm[32] = ['V',['I']]\n sdrm[46] = ['M',['I','L','V']]\n sdrm[47] = ['I',['V','A']]\n sdrm[48] = ['G',['V','M']]\n sdrm[50] = ['I',['V','L']]\n sdrm[53] = ['F',['L']]\n sdrm[54] = ['I',['V','L','M','T','A','S']]\n sdrm[73] = ['G',['S','T','C','A']]\n sdrm[76] = ['L',['V']]\n sdrm[82] = ['V',['A','T','S','F','L','C','M']]\n sdrm[83] = ['N',['D']]\n sdrm[84] = ['I',['V','A','C']]\n sdrm[85] = ['I',['V']]\n sdrm[88] = ['N',['D','S']]\n sdrm[90] = ['L',['M']]\n aa_length = aa_array.size\n end_aa = start_aa + aa_length - 1\n (start_aa..end_aa).each do |position|\n array_position = position - start_aa\n if sdrm.keys.include?(position)\n wt_aa = sdrm[position][0]\n test_aa = aa_array[array_position]\n if test_aa.size == 1\n unless wt_aa == test_aa\n if sdrm[position][1].include?(test_aa)\n out_hash[position] = [wt_aa,test_aa]\n end\n end\n else\n test_aa_array = test_aa.split(\"/\")\n if (test_aa_array & sdrm[position][1])\n out_hash[position] = [wt_aa,test_aa]\n end\n end\n end\n end\n return out_hash\nend", "def icc_1_1_ci(alpha=0.05)\n per=1-(0.5*alpha)\n \n fu=icc_1_f.f*Distribution::F.p_value(per, @df_wt, @df_bt)\n fl=icc_1_f.f.quo(Distribution::F.p_value(per, @df_bt, @df_wt))\n \n [(fl-1).quo(fl+k-1), (fu-1).quo(fu+k-1)]\n end", "def skill_heuristic_calculation(launcher, target, skill, index)\n ::BattleEngine._load_ia_state\n #> Récupération des combattants\n @enemies = ::BattleEngine.get_enemies\n @actors = ::BattleEngine.get_actors\n\n launcher = get_pokemon(launcher)\n target = get_pokemon(target)\n @IA_Info.clear\n @IA_Info[:launcher] = launcher\n @IA_Info[:target] = target\n @IA_Info[:damage] = 0\n @IA_Info[:recoil] = 0\n @IA_Info[:symbol] = skill.symbol\n @IA_Info[:failure] = false\n @IA_Info[:skill] = skill\n heuristic = {:value => 0}\n heuristic[:skill] = index\n heuristic[:skill_data] = skill\n heuristic[:target] = -target.position-1\n heuristic[:faster] = launcher.spd >= target.spd\n BattleEngine::use_skill(launcher, [target], skill) unless special_skill(launcher, target, skill)\n enemy = target.position >= 0 \n enemy = true if seviper_zangoose_detect(launcher, target)\n if @IA_Info[:damage] > 0\n hp_scale = target.hp\n if (hp_scale / launcher.max_hp) > 2\n hp_scale = launcher.hp\n end\n value = @IA_Info[:damage] / hp_scale.to_f - @IA_Info[:recoil] / launcher.hp.to_f\n value *= -1 unless enemy\n heuristic[:value] += value\n end\n if @IA_Info[:other_factor]\n heuristic[:value] += @IA_Info[:other_factor]\n end\n if @IA_Info[:status_factor]\n value = @IA_Info[:status_chance] ? @IA_Info[:status_chance] : 1\n heuristic[:value] += @IA_Info[:status_factor] * value\n end\n if @IA_Info[:randomness]\n heuristic[:value] *= @IA_Info[:randomness]\n end\n heuristic[:damage] = @IA_Info[:damage]\n pc skill.name\n pc heuristic[:value]\n return heuristic\n end", "def get_IG()\n return (get_AIBC(1) / Experimento.new(nil, @glucosa, @glucosa).get_AIBC(1)) * 100\n end", "def pattern_indexes\n self.bits ||= 0\n array = bits.to_s(2).rjust(self.step_count, '0').chars.each_with_index.map do |value, index|\n index if value == '1'\n end\n array.compact\n end", "def compute\n index(@ref, @ref_base, @software, @annotation)\n\n if @err_rate > 0\n bucketized_alignment\n else # software == :star || err_rate == 0\n unbucketized_alignment\n end\n end", "def isDNA?(fasta)\n seq = File.read(fasta, 10000).split(\"\\n\").grep(/^[^>]/).join\n seq.upcase.count(\"ACTGNU\").to_f / seq.upcase.count(\"ACDEFGHIKLMNPQRSTVWYZ\") > 0.90\nend", "def count_ai_battler\n count = -1\n @battle_info.parties.each do |bank|\n count += bank.size\n end\n log_debug(\"Found #{count} AI\")\n return count\n end", "def valleyCounter(n,s)\n currentAltitude = 0\n lastAltitude = 0\n index = 0\n numberOfValleys = 0\n s.each_char do |char|\n if char == \"U\"\n currentAltitude += 1\n lastAltitude = currentAltitude - 1\n else\n currentAltitude -= 1\n lastAltitude = currentAltitude + 1\n end\n if currentAltitude == 0 && lastAltitude < 0\n numberOfValleys += 1\n end\n end\n puts numberOfValleys\nend", "def trataNumeral (n)\n answer = 0;\n match = n.match(/(X{0,3})(IV|IX|VI{0,3}|I{0,3})/)\n s1, s2 = match.captures\n answer = 10 * s1.length\n if s2 == \"IV\"\n answer = answer + 4\n elsif s2 == \"V\"\n answer = answer + 5\n elsif s2 == \"VI\"\n answer = answer + 6\n elsif s2 == \"VII\"\n answer = answer + 7\n elsif s2 == \"VIII\"\n answer = answer + 8\n elsif s2 == \"IX\"\n answer = answer + 9\n else\n answer = answer + s2.length\n end\n return answer * 100\n end", "def solution(x,a)\n counter_hash = {}\n a.each_with_index do |value, index|\n counter_hash[value] = true\n return index if counter_hash.size == x\n end\n -1\nend", "def calculate_accidental_from_pitch(value)\n ACCIDENTALS_FOR_PITCH[value % 12]\n end", "def progress_sorted_index\n [[0,7], [1,7], [1,4], [2,7], [2,4], [3,7], [4,7], [5,7], [3,4], [6,7], [4,4], [7,7]].index(progress_ratio)\n end", "def input_to_index(input)\n return input.to_i - 1\n #idx = [inpu - 1]\n # return idx\nend", "def hipaa_code_active_indicator(crosswalk_record)\n rcc_log.debug \"Obtaining HIPAA code active indicator.\"\n rcc_log.debug \"HIPAA Code Active Indicator: #{crosswalk_record.hipaa_code_active_indicator}\"\n crosswalk_record.hipaa_code_active_indicator\n end", "def next_attestation_detail\n AttestationDetail.find_by_study_plan_id_and_attestation_term(id,\n Attestation.next_for_faculty(index.student.faculty))\n end", "def where_to_put_secret(index)\n (0...48).each do |b|\n if index[b] == 1\n return b\n end\n end\n # I = 0, this is the seed.\n 48\n end", "def store_attained_index\n index = minimum_outstanding_requirement_level-1\n update_attribute(:attained_index, index)\n end", "def calculate_dicsount(index)\n ((index + 1) * 9) / 100.0\nend", "def ami_launch_index\n data[:ami_launch_index]\n end", "def chi2_get_inconsistency_rate(inst_cnt, f2bs)\n # build a new instance count Hash table\n inst_cnt_new = {}\n \n inst_cnt.each do |key, hcnt|\n key_new = key.dup\n f2bs.keys.each do |f|\n if key_new =~ /#{f}:(.*?)\\|/\n v = $1.to_f\n key_new.gsub!(/#{f}:.*?\\|/, \"#{f}:#{get_index(v, f2bs[f])}|\")\n end\n end\n \n hcnt_new = inst_cnt_new[key_new] ||= Hash.new(0)\n inst_cnt_new[key_new] = hcnt_new.merge(hcnt) { |kk, v1, v2| v1+v2 }\n end\n \n get_IR_by_count(inst_cnt_new)\n end", "def test_on_public_characteristic_example\n sample = Stamina::ADL.parse_sample_file(File.expand_path('../characteristic.adl', __FILE__))\n rpnied = Stamina::Induction::RPNI.execute(sample)\n assert_equal 4, rpnied.state_count\n s0, = rpnied.initial_state\n s1 = rpnied.dfa_step(s0, 'b')\n s2 = rpnied.dfa_step(s0, 'a')\n s3 = rpnied.dfa_step(s2, 'b')\n assert_equal true, s0.accepting?\n assert_equal true, s3.accepting?\n assert_equal false, s1.accepting?\n assert_equal false, s2.accepting?\n assert_equal s1, s1.dfa_step('a')\n assert_equal s1, s1.dfa_step('b')\n assert_equal s2, s2.dfa_step('a')\n assert_equal s3, s2.dfa_step('b')\n assert_equal s3, s3.dfa_step('b')\n assert_equal s0, s3.dfa_step('a')\n assert_equal sample.signature, rpnied.signature(sample)\n end", "def calculate_points\n if team.exhibition?\n event.standings_including(team).find_index(self) + 1\n else\n event.standings.find_index(self) + 1\n end\n end", "def sdrm_int(aa_array,start_aa=1)\n out_hash = {}\n sdrm = {}\n sdrm[66] = ['T',['A','I','K']]\n # sdrm[68] = ['L',['V']] not included any more\n sdrm[74] = ['L',['M']]\n sdrm[92] = ['E',['Q']]\n sdrm[95] = ['Q',['K']]\n sdrm[97] = ['T',['A']]\n sdrm[121] = ['F',['Y']]\n sdrm[140] = ['G',['A','S','C']]\n sdrm[143] = [\"Y\",[\"C\",\"H\",\"R\"]]\n sdrm[147] = ['S',['G']]\n sdrm[148] = ['Q',['H','K','R']]\n sdrm[155] = ['N',['S','H']]\n aa_length = aa_array.size\n end_aa = start_aa + aa_length - 1\n (start_aa..end_aa).each do |position|\n array_position = position - start_aa\n if sdrm.keys.include?(position)\n wt_aa = sdrm[position][0]\n test_aa = aa_array[array_position]\n if test_aa.size == 1\n unless wt_aa == test_aa\n if sdrm[position][1].include?(test_aa)\n out_hash[position] = [wt_aa,test_aa]\n end\n end\n else\n test_aa_array = test_aa.split(\"/\")\n if (test_aa_array & sdrm[position][1])\n out_hash[position] = [wt_aa,test_aa]\n end\n end\n\n end\n end\n return out_hash\nend", "def virality\n 0\n end", "def spirit_attack\n attack_bonus = calc_spirit_attack\n attack_bonus > 0 ? (attack_bonus * spi).to_i : 0\n end", "def elems_in_level(index)\n\treturn (Math.sqrt(2*(index+1)-1)-0.5).to_i + 1\nend", "def isDNA?(fasta)\n seq = File.read(fasta, 10000).split(\"\\n\").grep(/^[^>]/).join\n seq.upcase.count(\"ACTGNU\").to_f / seq.upcase.count(\"ACDEFGHIKLMNPQRSTVWYZ\") > 0.90\nend", "def enter_infertility\n @infertility = @p_o_i\n end", "def damage(range)\n range.each.with_index.reduce(0) do |damage, (n, step)|\n if @north_lasers[n] == '|' && step.even? || @south_lasers[n] == '|' && step.odd?\n damage + 1\n else\n damage\n end\n end\n end", "def suggestID(testbed)\n load\n numbers = []\n @@nds.each{|n|\n if n['testbed'] == testbed\n num = (/\\d+/).match(n['hostname'])\n numbers << num[0].to_i if !num.nil?\n end\n }\n numbers.sort!\n n = 1\n n = numbers.last+1 if !numbers.empty?\n return n\n end", "def migratoryBirds(n, ar)\n birds = [0, 0, 0, 0, 0] \n ar.each do |number|\n birds[number-1] += 1 \n end \n return birds.index(birds.max) + 1\nend", "def faculty(i)\n result = 1\n i.times do |index|\n result *= (index + 1)\n end\n result\n end", "def outsense_edist(u, v)\n\n # initialize m and n\n m = u.length\n n = v.length\n\n # create hash of arrays where \n # hash.key holds h and array index holds d\n # thus hash[h][d] = front(h, d) = i\n front = Hash.new(Array.new)\n \n # initialize d with 0 for the first front\n d = 0\n\n # calculate front(0, 0)\n front[0][d] = lcplen(u, v, m, n)\n \n # till front(n - n, d) = m\n while front[n-m][d] != m-1\n\n # increase d\n d += 1\n \n # fronts calculated according to script\n ((-d)..d).each do |h|\n front[h][d] = outsense_next_front(front, h, d, u, v, m, n)\n end\n end\n\n # length of array with hash key m - n (= h) is \n # as long as the index of its last entry (= d) + 1\n return (front[m-n].length - 1)\nend", "def solution(a)\n return 1 if a.count == 0\n \n real_sum = a.inject(:+)\n expected_sum = (a.count + 1) * (a.count + 2) / 2.0\n (expected_sum - real_sum).to_i\nend", "def az_index c\n c.upcase.ord - 'A'.ord\nend", "def solution(a)\n counter = Hash.new(0)\n a.each do |elem|\n counter[elem] += 1\n end\n\n (1..a.size).each do |number|\n return 0 if counter[number] != 1\n end\n\n 1\nend", "def min_umbrellas(weather)\n count, rain, at_home, at_work = 0, [\"rainy\", \"thunderstorms\"], 0, 0\n return 0 if weather.include?(rain[0] == false || weather.include?(rain[1]) == false)\n weather.each_with_index do |x, i|\n if i == 0 && rain.include?(x)\n count += 1\n at_work += 1\n elsif i.odd? == false && rain.include?(x)\n count += 1 if at_home == 0\n at_work += 1 \t \t \n at_home -= 1 if at_home > 0 \n elsif i.odd? && rain.include?(x)\n count += 1 if at_work == 0\n at_home += 1\n at_work -= 1 if at_work > 0\n end\n end\n p count\nend", "def stable?\n (instability_index <= 40) ? true : false\n end", "def get_aa_array(initial_position = 0)\n @aa_array = []\n require_sequence = @dna_sequence[initial_position..-1].tr('-','N')\n base_array = []\n require_sequence.each_char {|base| base_array << base}\n while (base_array.length>=3) do\n base_3= \"\"\n 3.times{base_3 += base_array.shift}\n @aa_array<< amino_acid_2(base_3)\n end\n end", "def test_annuity_credit_results\n @annuity_credit_Value.each { |key, value| assert_in_delta @calc_annuity[@row_number][key], value, 0.03 }\n check_count @calc_annuity\n end", "def to_i(pattern)\n if @value\n result = @value.to_i(pattern)\n result += @variation if @variation\n result\n end\n end", "def get_icdf(prob)\n if prob.class == Array\n inv_vals = []\n for i in (0 ...prob.length)\n check_range(prob[i])\n inv_vals[i] = (find_root(prob[i], @n/2, 0.0, @n)).floor\n end\n return inv_vals\n else\n check_range(prob)\n return (find_root(prob, @n/2, 0.0, @n)).floor\n end\n end", "def native_kendalTauish_cost( pi )\n EpsSrraNative::rank_aggergate_upperW(@n){ |u,v| pi.pref(u,v) == @w[u][v] ? 0 : 1 } \n end", "def letter_index(user_letter)\n letter_indeces =[]\n if user_letter.length > 1\n if user_letter == @word.gsub(/[^0-9A-Za-z]/, '')\n you_win\n letter_indeces = (0...@letters.length).to_a\n end\n else\n @letters.length.times do |i|\n if @letters[i] == user_letter\n letter_indeces << i\n end\n end\n end\n return letter_indeces\n end" ]
[ "0.64629894", "0.61294776", "0.5818332", "0.5763177", "0.56234854", "0.5593739", "0.5575883", "0.5564423", "0.5524716", "0.53492093", "0.5343286", "0.5320034", "0.52854216", "0.5278959", "0.5276254", "0.5217866", "0.52151525", "0.5093001", "0.508744", "0.50860256", "0.5084812", "0.5065111", "0.50382644", "0.5022749", "0.5013891", "0.4955231", "0.49492273", "0.49441713", "0.49441713", "0.49404222", "0.49311158", "0.49275482", "0.49181706", "0.48819265", "0.48798385", "0.4876864", "0.48714137", "0.48380414", "0.47807506", "0.47629362", "0.475155", "0.47440225", "0.47412816", "0.47387904", "0.47364697", "0.47354677", "0.4729944", "0.47251207", "0.4723594", "0.4715135", "0.47081026", "0.4705607", "0.46956873", "0.4693859", "0.4685853", "0.46812296", "0.46808746", "0.46772906", "0.46668017", "0.46667895", "0.46667358", "0.4666426", "0.46605024", "0.46419603", "0.46412155", "0.4634821", "0.46330595", "0.46213695", "0.46207726", "0.45980036", "0.45965734", "0.45943037", "0.4582326", "0.4576408", "0.4572473", "0.4572249", "0.4568882", "0.45638832", "0.45624977", "0.45607156", "0.4558995", "0.45577058", "0.45569804", "0.45539653", "0.45519668", "0.4550119", "0.4548441", "0.45410776", "0.4540181", "0.453517", "0.45322466", "0.4530506", "0.45241055", "0.4516576", "0.45160308", "0.45139694", "0.45067164", "0.45024544", "0.4500686", "0.44980523" ]
0.8551031
0
Return wheter the sequence is stable or not as String (stable/unstable). _Protein whose instability index is smaller than 40 is predicted as stable, a value above 40 predicts that the protein may be unstable._
def stability (instability_index <= 40) ? "stable" : "unstable" end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def stable?\n (instability_index <= 40) ? true : false\n end", "def complete?\n return nil unless ivsat_table\n line = ivsat_table.split(\"\\n\").find{|l| l.include? 'INFO: Sequence completeness:' }\n line && !line.include?('partial')\n end", "def assess_insurance()\n\t\tvalues = self.comb_values()\n\t\treturn '0010000' if values.include?('930') #If extra service code 930 (insurance <= $200) is found, return manifest value for $100 ('0010000')\n\t\treturn '0050000' if values.include?('931') #If extra service code 931 (insurance > $200) is found, return manifest value for $500 ('0050000')\n\t\treturn false #If insurance values are not found, return false.\n\tend", "def stable\n self[:draft] == false && self[:prerelease] == false\n end", "def danceability_str\n if audio_features.danceability > 0.9\n \"Danceability: ⭐⭐⭐\"\n\n elsif audio_features.danceability > 0.75\n \"Danceability: ⭐⭐\"\n\n elsif audio_features.danceability > 0.6\n \"Danceability: ⭐\"\n\n else\n \"\"\n end\n end", "def prefer_stable?\n alias_of.prefer_stable?\n end", "def string\n 1.0\n end", "def state_s\n # return \"审核中\" if approving?\n return \"等待激活中\" if unapproved?\n return \"审核被拒绝\" if rejected?\n return \"展示中\" if opened? and available?\n return \"高亮展示中\" if highlighted? and opened? and available?\n return \"已过期\" if !available?\n return \"未展示\" if closed?\n end", "def to_s\n available.to_s\n end", "def status_text\n case @state\n when 0\n H87Enchant::ST1\n when 1\n H87Enchant::ST2\n when 2\n H87Enchant::STQ\n when 3\n H87Enchant::ST3\n when 4\n H87Enchant::ST4\n when 5\n H87Enchant::ST5\n else\n ; 'ERRORE 01'\n end\n end", "def to_s\n @name + \" Level: \" + @level.to_s + \" Combat Level: \" + getCombatLevel.to_s +\n \"\\nMal rollo pendiente: \" + \n ((@pendingBadConsequence==nil||@pendingBadConsequence.isEmpty)?(\"OK\"):(\"\\n\"+@pendingBadConsequence.to_s))\n end", "def stable_version\n file_to_semver(stable_version_file)\n end", "def to_string\n puts \"*** #{@name} ***\"\n puts \"health: #{@health * 100 / @initial_health}%\"\n puts \"stamina: #{stamina}\"\n puts \"power: #{@initial_power}\"\n puts @is_tired ? \"tired\" : \"not tired\"\n puts @is_dead ? \"dead\" : \"alive\"\n end", "def seq_number?\n @seq_number > NO_SEQ_NUMBER\n end", "def to_s\n to_string(true)\n end", "def to_s\n @string_value ||= calculate_roman_numeral\n end", "def should_to_s(newvalue)\n newvalue.inspect\n end", "def should_to_s(newvalue)\n newvalue.inspect\n end", "def should_to_s(newvalue)\n newvalue.inspect\n end", "def consistent?\n return @grammar.consistent?\n end", "def status_verifikasi\n if self.status_verifikasi_verifikator == 0\n return \"Belum terproses\"\n elsif self.status_verifikasi_verifikator == 1\n return \"Layak\"\n elsif self.status_verifikasi_verifikator == 2\n return \"Tidak Layak\"\n elsif self.status_verifikasi_verifikator == 3\n return \"Perbaikan\"\n end\n end", "def pro?\n (self.pro.to_i == 0) ? false : true\n end", "def str ()\n @strength\n end", "def to_s\n return 'inactive' if inactive?\n\n # try to mimics stat behaviour to minimize readings\n result = status_string\n result += ', got TERM' if got_term?\n result += ', want down' if want_down?\n result += ', want up' if want_up?\n result\n end", "def stable_id\n return self.gene_stable_id.stable_id\n \t\n end", "def should_to_s(newvalue = @should)\n if @latest\n @latest.to_s\n else\n super(newvalue)\n end\n end", "def should_to_s(newvalue = @should)\n if @latest\n @latest.to_s\n else\n super(newvalue)\n end\n end", "def to_s\n label = draft ? '[draft]' : number? ? number: \"(#{serie.next_number})\"\n \"#{serie.value}-#{label}\"\n end", "def to_true_string(value)\n DS::Number.is_i?(value) && value.to_i == 1 ? 'true' : nil\n end", "def should_to_s(value)\n value.inspect\n end", "def should_to_s(value)\n value.inspect\n end", "def should_to_s(value)\n value.inspect\n end", "def should_to_s(value)\n value.inspect\n end", "def should_to_s(value)\n value.inspect\n end", "def should_to_s(value)\n value.inspect\n end", "def get_legal_as_text(color)\n legal = get_legal(color)\n text = \"\"\n legal.each{|row|\n row.each{|stone|\n text << (stone.to_s == \"true\" ? \"1\" : \"0\")\n }\n text << \"\\n\"\n }\n return text\n end", "def xlate_status()\n return STATUS_XLATES[@status] if (STATUS_XLATES.has_key?(@status))\n return(@status.to_s) \n end", "def xlate_status()\n return STATUS_XLATES[@status] if (STATUS_XLATES.has_key?(@status))\n return(@status.to_s) \n end", "def to_s\n puts \"BadConsequence:\"\n puts \" Descripcion: #{@text}.\"\n if(@levels != nil)\n puts \" Niveles: #{@levels}.\"\n end\n \n if(@nVisibleTreasures != nil)\n puts \" Tesoros visibles: #{@nVisibleTreasures}\"\n puts \" Tesoros ocultos: #{@nHiddenTreasures}\"\n end\n \n if(@specificHiddenTreasures != nil)\n puts \" Tesoros visibles especificos: #{@specificVisibleTreasures}\"\n puts \" Tesoros ocultos especificos: #{@specificHiddenTreasures}\"\n end\n \n if(@death)\n puts \" Este monstruo te mata.\"\n end\n end", "def bad_seq? seq\n seq.downcase.include? \"nosequencefound\"\n end", "def _string\n\n _save = self.pos\n while true # choice\n _tmp = apply(:_dbl_string)\n break if _tmp\n self.pos = _save\n _tmp = apply(:_sgl_string)\n break if _tmp\n self.pos = _save\n break\n end # end choice\n\n set_failed_rule :_string unless _tmp\n return _tmp\n end", "def status_string\n if waiting_confirmation?\n return \"À confirmer\"\n elsif confirmed?\n return \"Confirmé\"\n elsif forgiven?\n return \"Pardonné\"\n else\n return \"Rejeté\"\n end\n end", "def report\n (@state.first || NO_ROBOT_PLACED).to_s\n end", "def is_to_s(currentvalue)\n provider.id2name(currentvalue) || currentvalue\n end", "def status\n output = StringIO.new\n output << @game.player.to_s\n output << \"\\n\"\n\n output << \"#{@game.current_room_model.description}\\n\"\n\n treasure = @game.current_room_model.treasure\n output << \"\\nThere is treasure here worth $#{treasure}.\\n\" if treasure && treasure > 0\n\n monster = @game.current_room_model.monster\n if monster\n output << \"\\nDANGER... THERE IS A MONSTER HERE....\\n\\n\"\n output << \"#{@game.current_room_model.monster}\\n\\n\"\n end\n\n if @game.current_room_model.name != \"Exit\"\n output << \"\\nWhat do you want to do? \"\n end\n \n output.string\n end", "def to_s\n @base58check_string ||= Base58.base58check_from_data(self.data_for_base58check_encoding)\n end", "def cheat_status\n if @revealed\n \" \"\n else\n @bombed ? \"X\" : \"*\"\n end\n end", "def unstableRelease?(node)\n return getRelease(node)['type'] != 'stable'\n end", "def to_s\n return '' unless comparison.possible?\n\n output = StringIO.new\n best, *rest = comparison.entries\n rest = Array(rest)\n\n add_best_summary(best, output)\n\n rest.each do |entry|\n add_comparison(entry, best, output)\n end\n\n output.string\n end", "def to_s\n not_implemented\n end", "def info\n stability_bump(raw_info)\n end", "def employeur_to_str\n if self.est_employeur == false\n self.est_employeur = \"Non\"\n elsif self.est_employeur == true\n self.est_employeur = \"Oui\"\n end\n end", "def agc_to_string(agc)\n if agc==AGC_FAST\n return(\"Fast\")\n elsif agc==AGC_SLOW\n return(\"Slow\")\n else\n return(\"Unknown\")\n end\nend", "def evaluate_proquest_status(thesis)\n proquest_status = thesis.authors.map(&:proquest_allowed).uniq\n return 'conflict' if proquest_status.length > 1\n\n proquest_status.first\n end", "def stable_id\n \treturn self.transcript_stable_id.stable_id\n end", "def to_s\n # \"%s <- %s (%0.01f%s, %0.01f)\" % [ consequent, \n # antecedent.join(\" \"), \n # support, \n # num_antecedent_transactions ? \"/#{num_antecedent_transactions}\" : \"\", confidence ]\n \"%s -> %s (%0.01f%s, %0.01f)\" % [ antecedent.join(\" \"),\n consequent, \n support, \n num_antecedent_transactions ? \"/#{num_antecedent_transactions}\" : \"\", confidence ]\n end", "def senpai_title\n \"Senpai\" if grade.senpai?\n end", "def stressed?\n self.stress_state == :stressed.to_s\n end", "def versao?\n \"Versão 1.0\"\n end", "def Poss\r\n poss.cap_first\r\n end", "def indefinite_possessive_pronoun\n return \"its\"\n end", "def to_s\n\t\tself.complaint_number.to_s + \" - \" + self.complainant.to_s\n\tend", "def to_s\n \"[X] #{@text}\" if @correct\n \"[ ] #{@text}\" unless @correct\n end", "def to_s\n \"[X] #{@text}\" if @correct\n \"[ ] #{@text}\" unless @correct\n end", "def running_nexus_pro?\n status['edition_long'] == \"Professional\"\n end", "def get_vehicle_status\n if (@age < 5)\n return \"a service.\"\n end\n return \"to be scrapped.\"\n end", "def status\n return \"skipped\" if skipped?\n return \"never\" if never?\n return \"missed\" if missed?\n return \"covered\" if covered?\n end", "def to_s\n \"Name = #{@name}\\nLevel = #{@combatLevel}\\nCultist Change Level = #{@levelChangeAgainstCultistPlayer}\\nPrize = [\" + @prize.to_s + \"] \\nBad Consequence = \" + @badCons.to_s() + \"\\n\"\n end", "def correct\n\t\tbet_items = self.bet_items\n\t\tcorrect = \" \"\n\t\tself.bet_items.each do |bet_item|\n\n\t\t\tif bet_item.active?\n\t\t\t\tcorrect = bet_item.name\n\t\t\tend\n\t\tend\n\n\t\treturn correct\n\tend", "def is_to_s(currentvalue)\n provider.gid2name(currentvalue) || currentvalue\n end", "def to_s\n NA\n end", "def availability(product)\n product.master.in_stock? ? 'in stock' : 'out of stock'\n end", "def to_s\n pretty_name = @name.to_s.split(/_/).map(&:capitalize).join(\" \")\n on_or_off = on? ? \"on\" : \"off\"\n reachable = reachable? ? \"reachable\" : \"unreachable\"\n \"#{pretty_name} is #{on_or_off} and #{reachable}\"\n end", "def to_s\n\t\ttoBoolean.map{|ligne| ligne.map{|pix| pix ? \".\":\" \"}.join}.join(\"\\n\")\n\tend", "def status\n return 'Appealed' if self.punishment.appealed?\n return 'Closed' if !self.open || self.locked\n return 'Escalated' if self.escalated\n return 'Open'\n end", "def occupied_converter(value)\n if value == true\n \"OCC\"\n else\n \"VAC\"\n end\n end", "def pro?\r\n infoxml = get_info\r\n return infoxml['ispro'] == '1'\r\n end", "def status\n status = \"\"\n if points < 4000\n status = \"Baby Seeder\"\n elsif points < 8000\n status = \"Aspiring Gardener\"\n elsif points < 15000\n status = \"Garden Hero\"\n else\n status = \"Plant Wizard\"\n end\n end", "def latest_stable_tag\n tags = `git tag`.strip.split(\"\\n\").map do |v|\n begin\n Semantic::Version.new(v)\n rescue ArgumentError\n nil\n end\n end.compact.sort.reverse\n (tags.find {|t| !t.pre} || tags.first).to_s\n end", "def verdict\n if self.is_complete?\n return self.status_str.titleize\n elsif self.ready_to_submit?\n return 'Ready to submit'\n elsif self.status_str == 'missing information'\n return \"Waiting on response from #{self.user.name || self.user.email} \"\n elsif ['unopened', 'in review' ].include? self.status_str\n return \"Waiting on response from #{self.current_reviewer.name || self.current_reviewer.email}\"\n elsif next_reviewer.nil?\n return \"Error\"\n else\n return \"Waiting on response from #{next_reviewer.name || next_reviewer.email}\"\n end\n end", "def priority_string\n case priority\n when 0\n \"high\"\n when 1\n \"medium\"\n when 2\n \"low\"\n else\n \"invalid\"\n end\n end", "def to_s\n unknown? ? 'x' : @value.to_s\n end", "def to_s\n (value.zero?) ? '' : \"#{value}#{symbol}\"\n end", "def getBoolean\n if @type == 'a'\n return getBooleanValue().rjust(16, '0')\n end\n\n if @type == 'c'\n return '111'+getBooleanComp()+getBooleanDest()+getBooleanJump()\n end\n\n return \"\"\n end", "def available_version(i)\n p_data = package_info(i)\n\n # nothing is available\n return nil if p_data.empty?\n\n p_data[\"versions\"][\"stable\"]\n end", "def inspect\n\t\t\trval = super\n\t\t\treturn rval unless self.structure_version\n\t\t\tvstring = \"%d.%d\" % [ self.structure_version, self.data_version ]\n\t\t\treturn rval.sub( />$/, \"; version: #{vstring}>\" )\n\t\tend", "def to_s\n constraints.to_sentence\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 boolString(value)\n if value == \"0\"\n return \"false\"\n else\n return \"true\"\n end\n end", "def exemplifies\n if self.alternation_values_examples.any?\n self.alternation_values.first.alternation\n elsif self.coding_frame_examples.any?\n self.coding_frames.first\n elsif self.verbs.any?\n self.verbs.first\n else\n \"other\"\n end\n end", "def state_str\n VN_STATES[state]\n end", "def is_informational?\n code.to_i >= 100 && code.to_i <= 199\n end", "def to_s\n \"#{@value}:#{@is_repeatable}\"\n end", "def string?; end", "def to_s()\n result = nil\n \n if @number < 10\n result = WORD_DICT[@number]\n\n elsif number <= 99\n result = two_least_sig\n \n elsif number == 1000\n result = \"one thousand\"\n\n elsif number % 100 == 0\n result = hundreds_component\n\n elsif number <= 999\n result = \"#{hundreds_component} and #{two_least_sig}\"\n end\n\n return result\n end", "def to_s\n raise RuntimeError.new \"Descriptive record is invalid. Check the contents of 'errors'\" unless self.valid?\n\n # Record type\n # Size: 1\n # Char position: 1\n # Must be 0\n output = @type\n\n # Optional branch number of the funds account\n # Char position: 2-18\n # Size: 17\n # Format: XXX-XXX\n # Blank filled\n output += @bsb.nil? ? \" \" * 17 : @bsb.to_s.ljust(17)\n\n # Sequence number\n # Char position: 19-20\n # Size: 2\n # Zero padded\n output += @reel_sequence\n\n # Name of user financial instituion\n # Size: 3\n # Char position: 21-23\n output += @financial_institution.to_s\n\n # Reserved\n # Size: 7\n # Char position: 24-30\n output += \" \" * 7\n\n # Name of User supplying File\n # Char position: 31-56\n # Size: 26\n # Full BECS character set valid\n # Blank filled\n output += @user_name.to_s.ljust(26)\n\n # Direct Entry User ID\n # Char position: 57-62\n # Size: 6\n # Zero padded\n output += @user_id.to_s.rjust(6, \"0\")\n\n # Description of payments in the file (e.g. Payroll, Creditors etc.)\n # Char position: 63-74\n # Size: 12\n # Full BECS character set valid\n # Blank filled\n output += @description.to_s.ljust(12)\n\n # Date on which the payment is to be processed\n # Char position: 75-80\n # Size: 6\n output += @process_at.strftime(\"%d%m%y\")\n\n # Reserved\n # Size: 40\n # Char position: 81-120\n output += \" \" * 40\n end", "def patient_status_str\n case self.status\n when 0\n return 'New visit' \n when 7 \n return 'Cancelled' \n when 3..5 \n return 'Complete' \n else\n return 'In Process'\n end\n end", "def abstract_embargoed\n return self['abstract_embargoed_bsi'] unless self['abstract_embargoed_bsi'].nil?\n return self['abstract_embargoed_tesim'].first.to_s == \"true\" if self['abstract_embargoed_tesim']\n false\n end", "def to_s\n @to_s ||= [@major, @minor, @tiny].join(\".\")\n end", "def to_s\n value.zero? ? '' : \"#{value}#{symbol}\"\n end" ]
[ "0.59346", "0.55109864", "0.5359347", "0.5294463", "0.5180834", "0.51680654", "0.5112167", "0.51115215", "0.51037943", "0.50916517", "0.50392485", "0.4972031", "0.49627674", "0.49081233", "0.4901036", "0.48808068", "0.4855916", "0.4855916", "0.4855916", "0.48397312", "0.48253822", "0.4803698", "0.48019785", "0.4800915", "0.47603473", "0.47546446", "0.47546446", "0.4748358", "0.47435927", "0.47369927", "0.47369927", "0.47369927", "0.47369927", "0.47369927", "0.47369927", "0.47182384", "0.47118613", "0.47118613", "0.4695205", "0.46942717", "0.46936917", "0.4692488", "0.4689646", "0.46803817", "0.46800312", "0.46786815", "0.4669443", "0.46640164", "0.46633348", "0.4661787", "0.466007", "0.46592495", "0.46571627", "0.465584", "0.46505037", "0.46482262", "0.46416306", "0.46411127", "0.46396276", "0.46362203", "0.4635539", "0.4634847", "0.46344635", "0.46344635", "0.4611743", "0.46040314", "0.46001607", "0.45894378", "0.45824775", "0.45816562", "0.45812082", "0.4578657", "0.4578367", "0.45750844", "0.4569775", "0.45654234", "0.4564367", "0.4562911", "0.4550969", "0.4550553", "0.4546657", "0.4539053", "0.45348528", "0.4529533", "0.45271403", "0.45269513", "0.45263702", "0.4517544", "0.4516494", "0.45149213", "0.45143545", "0.45115936", "0.4510629", "0.45100963", "0.45001826", "0.44969073", "0.44914484", "0.4490914", "0.4483687", "0.44810492" ]
0.6345953
0
Return true if the sequence is stable.
def stable? (instability_index <= 40) ? true : false end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def stable\n self[:draft] == false && self[:prerelease] == false\n end", "def sequential\n return true if hand_to_val.last - hand_to_val.first == 4\n return false \n end", "def consistent?\n return @grammar.consistent?\n end", "def empty_sequence?\n false\n end", "def sequence?(diff=1)\n tmp = self.sort\n \n tmp.upto(tmp.size-2) do |i, val|\n return false unless val + diff == tmp[i+1]\n end\n \n true\n end", "def complete?\n return nil unless ivsat_table\n line = ivsat_table.split(\"\\n\").find{|l| l.include? 'INFO: Sequence completeness:' }\n line && !line.include?('partial')\n end", "def sequence?\n kmer_length = @parent_graph.hash_length\n if kmer_length -1 > @ends_of_kmers_of_node.length\n return false\n else\n return true\n end\n end", "def seq_number?\n @seq_number > NO_SEQ_NUMBER\n end", "def check_sequence(test_seq)\n return !@found_sequences.has_key?(test_seq)\n end", "def already_published?\n return false if Algorithm.where(next: self).empty? # Algorithm has no predecessor yet\n return true\n end", "def is_stable?\n # Every person's partner should match up\n @matches.all? { |k,v| is_matched?(k, v) }\n end", "def reverted?\n version != last_version\n end", "def sticky?\n revision.stickied == 1\n end", "def complete?\n @bytes == [[0, @length - 1, true]]\n end", "def probe?\n self.order == -1\n end", "def no_change_in_version?\n latest_resolvable_version <= existing_version\n end", "def flush?\n return val if val.map(&:suit).uniq.count == 1\n\n false\n end", "def up_to_date_for?(timestamp)\n keys.sort.last >= timestamp\n end", "def sequence?()\n return false unless @component_nodes.length == 2\n return false unless (@component_nodes[0].type == type() or @component_nodes[1].type == type())\n return false if (@component_nodes[0].type == type() and @component_nodes[1].type == type())\n return true\n end", "def sequence?()\n return false unless @component_nodes.length == 2\n return false unless (@component_nodes[0].type == type() or @component_nodes[1].type == type())\n return false if (@component_nodes[0].type == type() and @component_nodes[1].type == type())\n return true\n end", "def valid_sequence?(input)\n compacted_input = input.compact\n input_valid = compacted_input.all? &method(:valid_number?)\n input_valid && input.length == @length && compacted_input == compacted_input.uniq\n end", "def cycle_complete?\n !self.sf_integrity_hash.nil? and !self.acf_integrity_hash.nil?\n end", "def is_straight?\n order_by_value.each_cons(2).all? { |x,y| y.point == x.point + 1 }\n end", "def valid?\n last_found = suit_foundation.last\n return @card.ace? if last_found.nil?\n\n @card.sequentially_larger_than?(last_found)\n end", "def insync?(is)\n is.sort! == should.sort!\n end", "def insync?(is)\n ((@should - is).length == 0)\n end", "def alt_valid_bst?\n self.to_ll.sorted?\n end", "def insync?(current)\n current.sort == should.sort\n end", "def insync?(current)\n current.sort == should.sort\n end", "def insync?(current)\n current.sort == should.sort\n end", "def insync?(current)\n current.sort == should.sort\n end", "def made?\n result >= 0\n end", "def usable?\n\n @trajectory.each do |a_point|\n if a_point.alt > 1000000.0\n return false\n end\n end\n\n return true\n\n end", "def rev?\r\n return @rev\r\n end", "def needs_update\n return true if @clock == 0\n return true if sign.phrase.size > sign.letters.size && @time%(60/sign.tempo) < Manager.period - 0.001\n\n false\n end", "def prefer_stable?\n alias_of.prefer_stable?\n end", "def done?\n (!@no_error_so_far && done_here?) || @index == @sequence.size\n end", "def create_first_version?\n delay_first_version && !previously_new_record? && first_version.nil?\n end", "def acyclic?\n topsort.size == size\n end", "def save_version?\n version_condition_met? && altered?\n end", "def is_compromised\n\t\tif (!@head) then return end\n\t\ttype = @head.get_item().class\n\t\tcurrent = @head\n\t\twhile (current)\n\t\t\tif (!(current.get_item().is_a?(type))) then return true end\n\t\t\tcurrent = current.get_next()\n\t\tend\n\t\treturn false\n\tend", "def up?\n current_value = self.retrieve\n self.class.state_index(current_value) < self.class.state_index(self.should)\n end", "def stale?\n digest != current_digest\n end", "def estConsomable()\n\t\treturn false\n\tend", "def evaluate?(db_sequence, sequence_source)\n score = db_sequence.best_hmm_result_row(sequence_source).fullseq_score\n return (score > self.min_fullseq_score)\n end", "def last_phase?\n @finishing\n end", "def serial?\n @items.any? { |item| item.serial? }\n end", "def crash?\n @position.length != @position.uniq.length\n end", "def up_to_date?\n return not_covered.count > 0 ? false : true\n end", "def valid_sequence?\n sequence.is_a?(Array) && sequence.all? do |e|\n (e.is_a? Numeric) && (e != 0)\n end\n end", "def futur?\n before > 0\n end", "def changed?\n !head || head.id != read_head_id\n end", "def signature_changed?\n signature != stored_signature\n end", "def signature_changed?\n signature != stored_signature\n end", "def sorted?\n !!@sorted\n end", "def solvable?\n steps > 0\n end", "def valid?\n @data_lru.size == @data_ttl.size\n end", "def valid?\n\t\tunless self.has_valid_payload?\n\t\t\tself.log.error \"Corrupted payload in block %d (hash mismatch)\" % [ self.index ]\n\t\t\treturn false\n\t\tend\n\n\t\treturn true if self.genesis?\n\n\t\tunless self.previous_hash_valid?\n\t\t\tself.log.error \"Hash mismatch in block %d\" % [ self.index ]\n\t\t\treturn false\n\t\tend\n\n\t\tunless self.has_valid_proof?\n\t\t\tself.log.error \"Invalid proof-of-work in block %d\" % [ self.index ]\n\t\t\treturn false\n\t\tend\n\n\t\treturn true\n\tend", "def phase_shift? ; @phase_shift ; end", "def plan_consistent?\n # A consistent plan is one in which there are no \n #contradictions in the ordering or binding\n #constraints. A contradiction occurs when both Si-< Sj and Si>-Sj,- hold or\n # both v = A and v = B hold (for two different constants A and B). \n # Both -< and = are transitive, so, for example, a plan\n #with Si -< S2, S2 -< S3, and S3 -< Si is inconsistent.\n\n true \n end", "def insync?(is)\n (is.size == should.size && is.sort == should.sort)\n end", "def saved_version_changes?\n track_altered_attributes ? (version_if_changed - saved_changes.keys).length < version_if_changed.length : saved_changes? # rubocop:disable Layout/LineLength\n end", "def sequential?\n Facter::Options[:sequential]\n end", "def solvable?\n\t\tsteps > 0\n\tend", "def changed?\n !!@previous\n end", "def valid?\n return false if @last_update.nil?\n (@last_update + SecureRandom.random_number(9) + 1 <= Time.now.to_i)\n end", "def valid?\n return false if @last_update.nil?\n (@last_update + SecureRandom.random_number(9) + 1 <= Time.now.to_i)\n end", "def update_version?\n append_version?\n end", "def verify\n if (buffer.offset + @_model.fbe_offset - 4) > buffer.size\n return false\n end\n\n fbe_full_size = read_uint32(@_model.fbe_offset - 4)\n if fbe_full_size < @_model.fbe_size\n return false\n end\n\n @_model.verify\n end", "def verify\n if (buffer.offset + @_model.fbe_offset - 4) > buffer.size\n return false\n end\n\n fbe_full_size = read_uint32(@_model.fbe_offset - 4)\n if fbe_full_size < @_model.fbe_size\n return false\n end\n\n @_model.verify\n end", "def verify\n if (buffer.offset + @_model.fbe_offset - 4) > buffer.size\n return false\n end\n\n fbe_full_size = read_uint32(@_model.fbe_offset - 4)\n if fbe_full_size < @_model.fbe_size\n return false\n end\n\n @_model.verify\n end", "def verify\n if (buffer.offset + @_model.fbe_offset - 4) > buffer.size\n return false\n end\n\n fbe_full_size = read_uint32(@_model.fbe_offset - 4)\n if fbe_full_size < @_model.fbe_size\n return false\n end\n\n @_model.verify\n end", "def done?\n\t\treturn @num_valid == @max_block\n\tend", "def empty?\n @sequence.empty? \n end", "def create_new_version?\n !previously_new_record? || (previously_new_record? && !delay_first_version)\n end", "def insync?(current)\n return false if current.length != should.length\n current_set = Set.new current\n should_set = Set.new should\n current_set == should_set\n end", "def first?\n result = @first[-1]\n @first[-1] = false\n result\n end", "def straight?\n len = @cards.size - 1\n (0...len).each do |i|\n return false unless @cards[i].poker_val == @cards[i + 1].poker_val + 1\n end\n true\n end", "def state_changed?\n peek_state\n !@state_queue.empty?\n end", "def rev?\n if @rxint or @txint or (@rxstate == REV) or (@txstate == REV)\n return true\n else\n return false\n end\n end", "def finished?\n #positions = {:a => 25, :b => 30}\n @position.each do |pl, pos|\n if pos >= @length\n return true\n else\n return false\n end\n end\n end", "def has_cycle\r\n slow_p = @head \r\n fast_p = @head \r\n while slow_p && fast_p && fast_p.next\r\n slow_p = slow_p.next\r\n fast_p = fast_p.next.next\r\n return true if slow_p == fast_p\r\n end\r\n return false\r\n end", "def changed?\n head.nil? or head.id != read_head_id\n end", "def valid?\n @stale == false\n end", "def insync?(is)\n return true\n end", "def update?\n if @w_up_to_date && true #all up_to_date-caches!!!\n @up_to_date = true\n return @up_to_date\n end\n false\n end", "def has_been_used?(table)\n return has_rows?(table) unless has_sequence?(table)\n\n cur_val = select_value(\"SELECT currval('#{table}_id_seq');\").to_i rescue 0\n cur_val > 0\n end", "def stable_id?\n false\n end", "def final_state?\n current_state == final_state\n end", "def check_straight(cards)\n last = nil\n cards.each { |c|\n if last.nil? then\n last = c.face_value\n next\n end\n return false if c.face_value != last + 1\n last = c.face_value\n }\n return true\n end", "def success?\n [\n original_source,\n original_node,\n generated_source,\n generated_node\n ].all?(&:right?) && generated_node.from_right.==(original_node.from_right)\n end", "def pairing_ended?\n end_pairing_on.nil? ? false : (end_pairing_on < DateTime.now)\n end", "def save_version?\n\t\t\t \t\tchanged?\n\t\t\t \tend", "def has_been_used?(table)\n return has_rows?(table) unless has_sequence?(table)\n\n cur_val = select_value(\"SELECT currval('#{table}_id_seq');\").to_i rescue 0\n cur_val > 0\n end", "def collapsing?\n self.begin(0) == self.end(0)\n end", "def end_of_tie?\n true\n end", "def initialized?\n !(version.zero?)\n end", "def old?\n\t\t@mutex.synchronize {\n\t\t\t@old\n\t\t}\n\tend", "def finished?\n<<<<<<< HEAD\n @finished\n=======\n if @track1.index(@players[0]) >= @length\n true\n elsif @track2.index(@players[1]) >= @length\n true\n end\n>>>>>>> upstream/master\n end", "def fixed_step?\n prev_step, prev = nil, nil\n self.indices.sort.each do |i|\n if prev\n curr_step = i - prev\n if prev_step\n return false if prev_step != curr_step\n end\n \n prev_step = curr_step\n end\n \n prev = i\n end\n \n return prev_step\n end" ]
[ "0.6626637", "0.6512906", "0.6167755", "0.6158894", "0.61111784", "0.6092307", "0.60544586", "0.60181403", "0.60051495", "0.60025716", "0.59646", "0.59554505", "0.58984464", "0.5885162", "0.5823181", "0.58019644", "0.5774902", "0.5761803", "0.57541203", "0.57541203", "0.5713406", "0.5703872", "0.56845415", "0.568333", "0.56650907", "0.5646872", "0.56447136", "0.5637914", "0.5637914", "0.5637914", "0.5637914", "0.56287545", "0.55993956", "0.5588767", "0.55836904", "0.55753237", "0.5559914", "0.5542682", "0.5541718", "0.5535725", "0.5534228", "0.55319154", "0.5527768", "0.551729", "0.5516011", "0.5514438", "0.5487833", "0.5487527", "0.5484759", "0.5482883", "0.5480281", "0.54797524", "0.54749227", "0.54749227", "0.54738986", "0.5468144", "0.54679906", "0.54679877", "0.5467015", "0.54579747", "0.5447708", "0.54465", "0.54406184", "0.5439305", "0.54393005", "0.54073906", "0.54073906", "0.5405541", "0.5404821", "0.5404821", "0.5404821", "0.5404821", "0.5401857", "0.5401328", "0.53990835", "0.53921276", "0.5388778", "0.5387291", "0.53843504", "0.5383251", "0.5379904", "0.5378334", "0.53740776", "0.5370702", "0.53679913", "0.536354", "0.5363105", "0.5359267", "0.5352013", "0.5343095", "0.5342466", "0.53380597", "0.5336659", "0.53365207", "0.5336162", "0.53334844", "0.53281236", "0.53214455", "0.53117734", "0.53079015" ]
0.6803989
0
Calculate aliphatic index of an AA sequence. _The aliphatic index of a protein is defined as the relative volume occupied by aliphatic side chains (alanine, valine, isoleucine, and leucine). It may be regarded as a positive factor for the increase of thermostability of globular proteins._
def aliphatic_index aa_map = aa_comp_map @aliphatic_index ||= round(aa_map[:A] + 2.9 * aa_map[:V] + (3.9 * (aa_map[:I] + aa_map[:L])), 2) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def instability_index\n @instability_index ||=\n begin\n instability_sum = 0.0\n i = 0\n while @seq[i+1] != nil\n aa, next_aa = [@seq[i].chr.to_sym, @seq[i+1].chr.to_sym]\n if DIWV.key?(aa) && DIWV[aa].key?(next_aa)\n instability_sum += DIWV[aa][next_aa]\n end\n i += 1\n end\n round((10.0/amino_acid_number.to_f) * instability_sum, 2)\n end\n end", "def get_AIBC(i)\n @@tam = @medidas.length\n if i >= @@tam\n return 0\n else\n return (((@medidas[i] - @medidas[0]) + (@medidas[i - 1] - @medidas[0])) / 24) + get_AIBC(i + 1)\n end\n end", "def acidic_count(amino_acid_sequence)\n count = 0\n comp = amino_acid_sequence.composition\n ACIDIC_AMINO_ACIDS.each do |acidic|\n if comp[acidic]\n count += comp[acidic]\n end\n end\n return count\n end", "def get_aa_array(initial_position = 0)\n @aa_array = []\n require_sequence = @dna_sequence[initial_position..-1].tr('-','N')\n base_array = []\n require_sequence.each_char {|base| base_array << base}\n while (base_array.length>=3) do\n base_3= \"\"\n 3.times{base_3 += base_array.shift}\n @aa_array<< amino_acid_2(base_3)\n end\n end", "def basic_count(amino_acid_sequence)\n count = 0\n comp = amino_acid_sequence.composition\n BASIC_AMINO_ACIDS.each do |basic|\n if comp[basic]\n count += comp[basic]\n end\n end\n return count\n end", "def amino_acid_number\n @seq.length\n end", "def getAlphabeticalPosition()\n \n @alphabeticalPosition = returnPermutationsBefore(@multiLetterDivisor) + 1\n \n end", "def amino_acid (bases)\n case bases\n when /^TT[TCY]$/\n return \"F\"\n when /^TT[AGR]$/\n return \"L\"\n when /^CT.$/\n return \"L\"\n when /^AT[TCAHYWM]$/\n return \"I\"\n when \"ATG\"\n return \"M\"\n when /^GT.$/\n return \"V\"\n when /^TC.$/\n return \"S\"\n when /^CC.$/\n return \"P\"\n when /^AC.$/\n return \"T\"\n when /^GC.$/\n return \"A\"\n when /^TA[TCY]$/\n return \"Y\"\n when /^TA[AGR]$/\n return \"*\"\n when /^T[GR]A$/\n return \"*\"\n when /^CA[TCY]$/\n return \"H\"\n when /^CA[AGR]$/\n return \"Q\"\n when /^AA[TCY]$/\n return \"N\"\n when /^AA[AGR]$/\n return \"K\"\n when /^GA[TCY]$/\n return \"D\"\n when /^GA[AGR]$/\n return \"E\"\n when /^TG[TCY]$/\n return \"C\"\n when \"TGG\"\n return \"W\"\n when /^CG.$/\n return \"R\"\n when /^AG[TCY]$/\n return \"S\"\n when /^[AM]G[AGR]$/\n return \"R\"\n when /^GG.$/\n return \"G\"\n when /^[ATW][CGS][CTY]$/\n return \"S\"\n when /^[TCY]T[AGR]$/\n return \"L\"\n else\n return \"#\"\n end\n end", "def calculate_accidental_from_pitch(value)\n ACCIDENTALS_FOR_PITCH[value % 12]\n end", "def amino_acid_2 (bases)\n bases_to_aa = []\n aa_list = []\n base1 = bases[0].to_list\n base2 = bases[1].to_list\n base3 = bases[2].to_list\n l1 = base1.size - 1\n l2 = base2.size - 1\n l3 = base3.size - 1\n (0..l1).each do |n1|\n b1 = base1[n1]\n (0..l2).each do |n2|\n b2 = base2[n2]\n (0..l3).each do |n3|\n b3 = base3[n3]\n bases_all = b1 + b2 + b3\n bases_to_aa << bases_all\n end\n end\n end\n\n bases_to_aa.each do |base|\n case base\n when /^TT[TCY]$/\n aa = \"F\"\n when /^TT[AGR]$/\n aa = \"L\"\n when /^CT.$/\n aa = \"L\"\n when /^AT[TCAHYWM]$/\n aa = \"I\"\n when \"ATG\"\n aa = \"M\"\n when /^GT.$/\n aa = \"V\"\n when /^TC.$/\n aa = \"S\"\n when /^CC.$/\n aa = \"P\"\n when /^AC.$/\n aa = \"T\"\n when /^GC.$/\n aa = \"A\"\n when /^TA[TCY]$/\n aa = \"Y\"\n when /^TA[AGR]$/\n aa = \"*\"\n when /^T[GR]A$/\n aa = \"*\"\n when /^CA[TCY]$/\n aa = \"H\"\n when /^CA[AGR]$/\n aa = \"Q\"\n when /^AA[TCY]$/\n aa = \"N\"\n when /^AA[AGR]$/\n aa = \"K\"\n when /^GA[TCY]$/\n aa = \"D\"\n when /^GA[AGR]$/\n aa = \"E\"\n when /^TG[TCY]$/\n aa = \"C\"\n when \"TGG\"\n aa = \"W\"\n when /^CG.$/\n aa = \"R\"\n when /^AG[TCY]$/\n aa = \"S\"\n when /^[AM]G[AGR]$/\n aa = \"R\"\n when /^GG.$/\n aa = \"G\"\n when /^[ATW][CGS][CTY]$/\n aa = \"S\"\n when /^[TCY]T[AGR]$/\n aa = \"L\"\n else\n aa = \"-\"\n end\n aa_list << aa\n end\n aa_out = aa_list.uniq.join\n return aa_out\n end", "def rna_to_amino_acid(rna)\n # Protein Translation Problem: Translate an RNA string into an amino acid string.\n # Input: An RNA string Pattern and the array GeneticCode.\n # Output: The translation of Pattern into an amino acid string Peptide. \n\n r_to_c_h = rna_to_codon_hash\n # puts r_to_c_h\n i = 0\n codon_length = 3\n amino_acid = \"\"\n while (codon = rna.slice(i, codon_length)) do\n # puts codon\n # puts r_to_c_h[codon.to_sym]\n break if codon.empty?\n amino_acid += r_to_c_h[codon.to_sym].to_s\n i += codon_length\n end\n return amino_acid\n end", "def AA\n puts 'Alluring Aura'\n AA = gets.chomp.to_i\n AA\n end", "def linearpeptide_score_with_amino_acids(peptide, spectrum, amh)\n # Given a linear peptide Peptide and a spectrum Spectrum, we define LinearScore(Peptide, Spectrum) \n # as the number of masses shared between Linearspectrum(Peptide) and Spectrum. \n\n # Cyclopeptide Scoring Problem: Compute the score of a cyclic peptide against a spectrum.\n # Input: An amino acid string Peptide and a collection of integers Spectrum. \n # Output: The score of Peptide against Spectrum, Score(Peptide, Spectrum). \n\n theoretical_spectrum = linear_spectrum_with_amino_acids(peptide, amh)\n ts_h = array_to_count_hash(theoretical_spectrum)\n es_h = array_to_count_hash(spectrum)\n\n score = 0\n es_h.keys.each do |mass|\n if ts_h.has_key?(mass)\n # If the experimental spectrum has fewer instances of the same mass than theoritical spectrum use that one\n # to calculate the score but if experimental spectrum has more count of the same mass we should be using\n # the count in the theoritical spectrum\n if es_h[mass] <= ts_h[mass]\n score += es_h[mass]\n else\n score += ts_h[mass]\n end\n end\n end\n return score\n end", "def anisotropy_index\n @direct_normal_irradiance / extraterrestrial_irradiance\n end", "def generate_aasequences\n (0..self.sequence.length-1).each do |i|\n AAsequence.create(:seq_id=> self.seq_id,\n :amino_acid=>self.sequence[i],\n :original_position=>i)\n end\n end", "def acosh\n math :acosh\n end", "def run_align_assess\n filename = self.generate_fasta_alignment_file_for_all\n string = \"./lib/AlignAssess_wShorterID #{filename} P\"\n seq_array = Array.new\n if system(string)\n seq_id_array = self.sequences.map{|s| s.seq_id}\n new_filename = filename + \"_assess\"\n f = File.new(new_filename, \"r\")\n flag = false\n read_row= 999999999\n cur_row = 0\n while (line = f.gets)\n if cur_row > read_row && flag\n if line == \"\\n\"\n flag =false\n else\n seq_array << line.split(\"\\t\")\n end\n elsif line == \"Pair-wise %ID over shorter sequence:\\n\"\n flag=true\n read_row = cur_row + 2\n end\n cur_row +=1\n end\n range = seq_array.length - 1\n #seq_array.each do |row|\n for row_num in 0..range\n for i in 1..range#(row_num) \n PercentIdentity.first_or_create(:seq1_id=>seq_id_array[row_num],\n :seq2_id=>seq_id_array[i],\n :alignment_name => self.alignment_name,\n :percent_id=>seq_array[row_num][i])\n # print \"[#{row_num}:#{i-1}=>#{row[i]}],\"\n end\n #print \"\\n\"\n end\n end\n end", "def angle_a\n Angle.new(\n self,\n :a,\n (\n (\n Math.acos((b**2 + c**2 - a**2) / (2.0 * b * c)) * 180\n ) / Math::PI\n )\n )\n end", "def angle\n equation_1 = @wind_velocity * ETA\n apparent_wind_agl = @real_wind_agl - 0.0001\n\n until @variance > equation_1 - 0.001 && @variance < equation_1 + 0.001\n equation_2 = sailboat_transform(apparent_wind_agl)\n\n apparent_wind_agl -= 0.00001\n @variance = equation_1 - equation_2\n end\n puts \"Apparent Wind Angle:\\n#{apparent_wind_agl}\"\n apparent_wind_agl\n end", "def get_almidon\n @_100=((@almidon*100)/@peso)\n #@ir_100=(@_100/90)*100\n @porcion=((@almidon*@gramos_porciones)/@peso)\n #@ir_porcion=(@porcion/90)*100\n [ @almidon , @_100 , 0 , @porcion , 0 ]\n end", "def fetch_ancestral_sequence(start=0,stop=self.length)\n self.genomic_aligns.select{|c| c.find_organism == \"Ancestral sequences\"}.each do |contig|\n puts contig.find_organism\n #return contig.aligned_sequence[start..stop]\n end\n end", "def az_index c\n c.upcase.ord - 'A'.ord\nend", "def show\n @header_class = 'TPA'\n # process parameters\n # should we equate I and L?\n equate_il = (params[:equate_il] == 'equateIL')\n # the sequence or id of the peptide\n seq = params[:id].upcase.gsub(/\\P{ASCII}/, '')\n\n # process the input, convert seq to a valid @sequence\n if seq.match?(/\\A[0-9]+\\z/)\n sequence = Sequence.includes(peptides: { uniprot_entry: %i[taxon] }).find_by(id: seq)\n @original_sequence = sequence.sequence\n else\n sequence = Sequence.single_search(seq, equate_il)\n @original_sequence = seq\n end\n\n # quit if it doensn't contain any peptides\n raise(NoMatchesFoundError, sequence.sequence) if sequence.present? && sequence.peptides(equate_il).empty?\n\n # get the uniprot entries of every peptide\n # only used for the open in uniprot links\n # and calculate the LCA\n if sequence.nil?\n # we didn't find the sequence in the database, so let's try to split it\n long_sequences = Sequence.advanced_single_search(seq, equate_il)\n # calculate possible uniprot entries\n temp_entries = long_sequences.map { |s| s.peptides(equate_il).map(&:uniprot_entry).to_set }\n # take the intersection of all sets\n @entries = temp_entries.reduce(:&)\n # check if the protein contains the startsequence\n @entries.select! { |e| e.protein_contains?(seq, equate_il) }\n\n # Calculate fa summary\n @fa_summary = UniprotEntry.summarize_fa(@entries)\n\n raise(NoMatchesFoundError, seq) if @entries.empty?\n\n @lineages = @entries.map(&:lineage).compact\n else\n @entries = sequence.peptides(equate_il).map(&:uniprot_entry)\n @lineages = sequence.lineages(equate_il, true).to_a\n\n # Get FA summary form cache\n @fa_summary = sequence.calculate_fa(equate_il)\n end\n\n @lca_taxon = Lineage.calculate_lca_taxon(@lineages) # calculate the LCA\n @root = Node.new(1, 'Organism', nil, 'root') # start constructing the tree\n common_hits = @lineages.map(&:hits).reduce(:+)\n @root.data['count'] = common_hits\n last_node = @root\n\n # common lineage\n @common_lineage = [] # construct the common lineage in this array\n l = @lca_taxon.lineage\n found = (@lca_taxon.name == 'root')\n while !found && l.has_next?\n t = l.next_t\n next if t.nil?\n\n found = (@lca_taxon.id == t.id)\n @common_lineage << t\n node = Node.new(t.id, t.name, @root, t.rank)\n node.data['count'] = common_hits\n last_node = last_node.add_child(node)\n end\n\n # distinct lineage\n @lineages.map { |lineage| lineage.set_iterator_position(l.get_iterator_position) }\n @lineages.each do |lineage|\n last_node_loop = last_node\n l = []\n while lineage.has_next?\n t = lineage.next_t\n next if t.nil?\n\n l << t.name # add the taxon name to the lineage\n node = Node.find_by_id(t.id, @root)\n if node.nil? # if the node isn't create yet\n node = Node.new(t.id, t.name, @root, t.rank)\n node.data['count'] = lineage.hits\n last_node_loop = last_node_loop.add_child(node)\n else\n node.data['count'] += lineage.hits\n last_node_loop = node\n end\n end\n end\n\n # don't show the root when we don't need it\n @root.sort_children\n\n # Table stuff\n @table_lineages = []\n @table_ranks = []\n\n @lineages.uniq!\n @table_lineages << @lineages.map { |lineage| lineage.name.name }\n @table_ranks << 'Organism'\n @lineages.map { |lineage| lineage.set_iterator_position(0) } # reset the iterator\n while @lineages[0].has_next?\n temp = @lineages.map(&:next_t)\n unless temp.compact.empty? # don't do anything if it only contains nils\n @table_lineages << temp\n @table_ranks << temp.compact[0].rank\n end\n end\n\n # sort by id from left to right\n root_taxon = Taxon.find(1)\n @table_lineages = @table_lineages.transpose.sort_by { |k| k[1..-1].map! { |lin| lin || root_taxon } }\n\n # sort entries\n @entries = @entries.to_a.sort_by { |e| e.taxon.nil? ? '' : e.taxon.name }\n\n @title = \"Tryptic peptide analysis of #{@original_sequence}\"\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @entries.to_json(only: :uniprot_accession_number, include: [{ ec_cross_references: { only: :ec_number_code } }, { go_cross_references: { only: :go_term_code } }]) }\n # TODO: switch to OJ for higher performance\n # format.json { render json: Oj.dump(@entries, :include => :name, :mode => :rails) }\n end\n rescue SequenceTooShortError\n flash[:error] = 'The sequence you searched for is too short.'\n redirect_to search_single_url\n rescue NoMatchesFoundError => e\n flash[:error] = \"No matches for peptide #{e.message}\"\n redirect_to search_single_url\n end", "def aibc(g)\n\t\t# recibe un vector de datos del alimento\n\t\t# devuelve los aibc del alimento, o glucosa, para cada individuo\n\t\tg.map{ |gi| gi.each_with_index.map{ |gindex, i| if0(gindex, gi[0], gi[i-1]) if i > 0 } }.map{ |gi| gi.reject{ |gij| gij.class == nil::NilClass } }.map{ |ri| ri.reduce(0, :+) }\n\tend", "def suprailiaco\n\t\t(@suprailiaco[0] + @suprailiaco[1] + @suprailiaco[2])/3\n\tend", "def adc_a_a\n end", "def index_of_coincidence(matrix)\n\n matrix.inject([]) do |indices, row_letters|\n frequencies = letter_frequencies(row_letters)\n\n indices << (\"A\"..\"Z\").inject(0) { |a,v|\n x = frequencies[v]\n a += x*(x-1)\n a\n } / (row_letters.size * (row_letters.size - 1))\n end\n\nend", "def peptide_mass_with_amino_acids(peptide, amh)\n mass = 0\n peptide.chars.each do |pep|\n mass += amh[pep]\n end\n return mass\n end", "def ADC(address:)\n signed_a = signed_int(@accumulator)\n signed_m = signed_int(@ram[address])\n signed_sum = signed_a + signed_m\n (signed_sum > 127 || signed_sum < -128) ? set_flag(SR_OVERFLOW) : clear_flag(SR_OVERFLOW)\n\n sum = @accumulator + @ram[address] + (set?(SR_CARRY) ? 1 : 0)\n sum > 0xff ? set_flag(SR_CARRY) : clear_flag(SR_CARRY)\n @accumulator = sum & 0xff\n\n ZN_flags(@accumulator)\n end", "def prop_a\n bases_a / length.to_f\n end", "def avg_route_difficulty area\n avg = 0.0\n keine_angabe = 0\n area.routes.each { |r| \n keine_angabe += 1 unless uiaa_grades.index(r.grade) > 0\n avg += uiaa_grades.index(r.grade) unless uiaa_grades.index(r.grade) == 0 }\n new_uiaa_index = (avg / (area.routes.length - keine_angabe)).round\n uiaa_grades[new_uiaa_index]\n end", "def amic (a)\n array = []\n i = 1\n while i < a\n if (a%i == 0)\n array << i\n end\n i = i+1\n end\n sum = 0\n \n # returns the sum of the elements in the array\n return array.inject(0) { |s,v| s += v } \nend", "def to_i\n\t\t\t(a1.to_i << 96) + (a2.to_i << 64) + (a3.to_i << 32) + a4.to_i\n\t\tend", "def get_alco\n @_100=((@alco*100)/@peso)\n #@ir_100=(@_100/90)*100\n @porcion=((@alco*@gramos_porciones)/@peso)\n #@ir_porcion=(@porcion/90)*100\n [ @alco , @_100 , 0 , @porcion , 0 ]\n end", "def solution(a)\n length = a.length\n sum = (length + 1) * (length + 1 + 1) / 2\n\n sum - a.inject(0) { |acc, e| acc += e }\nend", "def ig_ind\n\t\taibc(@datos[0]).each_with_index.map{ |ind, i| (ind/aibc(@datos[1])[i])*100 }\n\tend", "def return_number(a)\n ((a / 2)**2) * (65 - (a / 2))\nend", "def aaf_index\n @index ||= ActsAsFerret::get_index(aaf_configuration[:name])\n end", "def cadera\n\t\t(@cadera[0] + @cadera[1])/2\n\tend", "def isDNA?(fasta)\n seq = File.read(fasta, 10000).split(\"\\n\").grep(/^[^>]/).join\n seq.upcase.count(\"ACTGNU\").to_f / seq.upcase.count(\"ACDEFGHIKLMNPQRSTVWYZ\") > 0.90\nend", "def am(amida, y, x)\n #p \"==== NOW ===\"\n #p y \n #p x\n #p amida\n\n if y == H \n #p \"=====GOAL\"\n if x + 1 == K\n $cnt = $cnt + 1\n end\n return\n end\n\n if x < W - 1\n to_right_amida = Marshal.load(Marshal.dump(amida))\n to_right_amida[y][x] = 1\n am(to_right_amida, y + 1, x + 1)\n end\n\n to_streight_amida = Marshal.load(Marshal.dump(amida))\n am(to_streight_amida, y + 1, x)\n\n if x > 0\n to_left_amida = Marshal.load(Marshal.dump(amida))\n to_left_amida[y][x - 1] = 1\n am(to_left_amida, y + 1, x - 1)\n end\nend", "def inc_a\n end", "def fasta\n chars = 60\n lines = (length / chars.to_f).ceil\n defline = \">#{accession} #{title}\"\n seqlines = (1..lines).map {|i| to_s[chars * (i - 1), chars]}\n [defline].concat(seqlines).join(\"\\n\")\n end", "def isDNA?(fasta)\n seq = File.read(fasta, 10000).split(\"\\n\").grep(/^[^>]/).join\n seq.upcase.count(\"ACTGNU\").to_f / seq.upcase.count(\"ACDEFGHIKLMNPQRSTVWYZ\") > 0.90\nend", "def write_answer(index)\n middle_digit = @inventory[index]\n @inventory.delete_at(index)\n input_cutoff = @input.to_s.length - @inventory.length - 2\n final_number = @input.to_s[0..input_cutoff] + middle_digit + @inventory.join()\n puts \"The next highest anagram is #{final_number}\"\nend", "def getIndexSequence(laneBarcode)\n if !laneIndexed?(laneBarcode)\n return \"\"\n else\n tag = laneBarcode.gsub(/^[1-8]-ID/, \"\")\n return @pipelineHelper.findBarcodeSequence(\"ID\" + tag.to_s) \n end\n end", "def calculate_a1 point\n distances = []\n main_cluster.points.each do |point1|\n distances << euclidean_distance(point, point1).round(2)\n end\n return 0 if distances.size == 1\n (distances.inject(:+)/(distances.size - 1)).round(2)\n end", "def aligned_position \n \n cigar_line = \"#{self.cigar_line}\"\n \n x = cigar_line.slice!(/^[0-9]*/)\n char = cigar_line.slice!(/^[A-Z]/)\n \n x.nil? ? x = 1 : x = x.to_i\n char == \"X\" ? start = x : start = 0\n \n char = cigar_line.slice!(/[A-Z]$/)\n y = cigar_line.slice!(/[0-9]*$/)\n \n if y.nil?\n y = 1\n else\n y = y.to_i\n end\n \n if char == \"X\"\n stop = self.genomic_align_block.length - y\n else\n stop = self.genomic_align_block.length\n end\n answer = Array.new\n answer.push(start)\n answer.push(stop)\n return answer\n \n end", "def isaac\n r = @randrsl\n aa = @aa\n @cc = @cc+1\n bb = (@bb + (@cc)) & 0xffffffff\n x = y = 0\n\n (0...256).step(4){|i|\n x = @mm[i ]\n aa = ((aa ^ (aa << 13)) + @mm[(i + 128) & 0xff])\n aa &= 0xffffffff\n @mm[i ] = y = (@mm[(x >> 2) & 0xff] + aa + bb) & 0xffffffff\n r[i ] = bb = (@mm[(y >> 10) & 0xff] + x) & 0xffffffff\n x = @mm[i+1]\n aa = ((aa ^ (0x03ffffff & (aa >> 6))) + @mm[(i+1+128) & 0xff])\n aa &= 0xffffffff\n @mm[i+1] = y = (@mm[(x >> 2) & 0xff] + aa + bb) & 0xffffffff\n r[i+1] = bb = (@mm[(y >> 10) & 0xff] + x) & 0xffffffff\n x = @mm[i+2]\n aa = ((aa ^ (aa << 2)) + @mm[(i+2 + 128) & 0xff])\n aa &= 0xffffffff\n @mm[i+2] = y = (@mm[(x >> 2) & 0xff] + aa + bb) & 0xffffffff\n r[i+2] = bb = (@mm[(y >> 10) & 0xff] + x) & 0xffffffff\n x = @mm[i+3]\n aa = ((aa ^ (0x0000ffff & (aa >> 16))) + @mm[(i+3 + 128) & 0xff])\n aa &= 0xffffffff\n @mm[i+3] = y = (@mm[(x >> 2) & 0xff] + aa + bb) & 0xffffffff\n r[i+3] = bb = (@mm[(y >> 10) & 0xff] + x) & 0xffffffff\n }\n\n @bb = bb\n @aa = aa\n end", "def aroma_index\n Aroma.order(:aroma_name)\n end", "def hipaa_code_active_indicator(crosswalk_record)\n rcc_log.debug \"Obtaining HIPAA code active indicator.\"\n rcc_log.debug \"HIPAA Code Active Indicator: #{crosswalk_record.hipaa_code_active_indicator}\"\n crosswalk_record.hipaa_code_active_indicator\n end", "def dnaSequence s\n hash, diff = Hash.new(0), Hash.new(0)\n diff[[0, 0, 0]] = 1\n\n sum = 0\n s.chars.each { |c|\n hash[c] += 1\n res = [hash['A'] - hash['C'], hash['C'] - hash['G'], hash['G'] - hash['T']]\n sum += diff[res]\n diff[res] += 1\n }\n sum\nend", "def calculate_index(data, gluc)\n aibc = [[],[]]\n data.each do |x|\n\t\t\tt = 0\n\t\t\tx.each_index do |a| \n\t\t\t\tif (a != 0) \n\t\t\t\t\tt += (((x[a] - x[0]) + (x[a - 1] - x[0])) /2)*5 \n\t\t\t\tend \n\t\t\tend \n\t\t\taibc[0] << t\n\t\tend\n\t\tgluc.each do |x|\n\t\t\tt = 0\n\t\t\tx.each_index do |a| \n\t\t\t\tif (a != 0) \n\t\t\t\t\tt += (((x[a] - x[0]) + (x[a - 1] - x[0])) /2)*5\n\t\t\t\tend \n\t\t\tend \n\t\t\taibc[1] << t\n\t\tend\n\t\tigind = []\n\t\taibc[0].each_index { |x| igind << ((aibc[0][x] / aibc[1][x]) * 100)}\n\t\tsuma = 0\n\t\tigind.each{ |x| suma += x}\n\t\t@indexGluc = (suma / igind.length)\n \n end", "def aa_comp(aa_code=nil)\n if aa_code.nil?\n aa_map = {}\n IUPAC_CODE.keys.each do |k|\n aa_map[k] = 0.0\n end\n aa_map.update(aa_comp_map){|k,_,v| round(v, 1) }\n else\n round(aa_comp_map[aa_code], 1)\n end\n end", "def alphabet_frequency string, letter\n decode_attempt = c_decode string, letter\n frequency_total_array = []\n $frequencies.each do |key, array|\n frequency_total_array.push((frequency_value(decode_attempt.split(\"\"), key) - $frequencies[key]).abs)\nend\nfrequency_total_array.inject(0, :+)\nend", "def _updateAngle\n\t\t\t\t@angle = (@maxAngle*@idxAngle) - Math::PIH\n\t\t\tend", "def hiv_protease(aa_array,start_aa=1)\n out_hash = {}\n sdrm = {}\n sdrm[23] = ['L',['I']]\n sdrm[24] = ['L',['I']]\n sdrm[30] = ['D',['N']]\n sdrm[32] = ['V',['I']]\n sdrm[46] = ['M',['I','L','V']]\n sdrm[47] = ['I',['V','A']]\n sdrm[48] = ['G',['V','M']]\n sdrm[50] = ['I',['V','L']]\n sdrm[53] = ['F',['L']]\n sdrm[54] = ['I',['V','L','M','T','A','S']]\n sdrm[73] = ['G',['S','T','C','A']]\n sdrm[76] = ['L',['V']]\n sdrm[82] = ['V',['A','T','S','F','L','C','M']]\n sdrm[83] = ['N',['D']]\n sdrm[84] = ['I',['V','A','C']]\n sdrm[85] = ['I',['V']]\n sdrm[88] = ['N',['D','S']]\n sdrm[90] = ['L',['M']]\n aa_length = aa_array.size\n end_aa = start_aa + aa_length - 1\n (start_aa..end_aa).each do |position|\n array_position = position - start_aa\n if sdrm.keys.include?(position)\n wt_aa = sdrm[position][0]\n test_aa = aa_array[array_position]\n if test_aa.size == 1\n unless wt_aa == test_aa\n if sdrm[position][1].include?(test_aa)\n out_hash[position] = [wt_aa,test_aa]\n end\n end\n else\n test_aa_array = test_aa.split(\"/\")\n if (test_aa_array & sdrm[position][1])\n out_hash[position] = [wt_aa,test_aa]\n end\n end\n end\n end\n return out_hash\nend", "def indicator_energia()\n\t\t\t\te = totalCaloricValue() / @alimentsList.length\n\n\t\t\t\tif e < 670\n\t\t\t\t\treturn 1.0\n\t\t\t\telsif e <= 830\n\t\t\t\t\treturn 2.0\n\t\t\t\telse\n\t\t\t\t\treturn 3.0\n\t\t\t\tend\n\t\t\tend", "def synthesize(protein)\n adn = ''\n for a in (0..protein.length-1)\n aminoacido = protein[a,1]\n entropy = rand(100-10) + 10\n \n \n if (@aminoacidos.include?(aminoacido))\n \n adn = adn + @codons[aminoacido][entropy % (@codons[aminoacido].length)]\n end\n \n end\n @synthesize = adn\n end", "def aas(angle_a, angle_b, side_A)\n side_A / Math.sin(deg2rad(angle_a)) * Math.sin(deg2rad(angle_b))\n end", "def overall_aroma_percentage\n overall_aroma = self.aroma_bundles.inject(0) do |memo, bundle|\n memo += bundle.percent if bundle.percent.is_a?(Integer) || bundle.percent.is_a?(BigDecimal)\n memo\n end\n\n return overall_aroma\n end", "def hipaa_code(crosswalk_record = nil, hipaa_code_from_entity = nil)\n rcc_log.debug \"Obtaining HIPAA CODE.\"\n hipaa_code = hipaa_code_from_entity\n if hipaa_code.blank? && crosswalk_record.present?\n hipaa_code = crosswalk_record.hipaa_adjustment_code\n rcc_log.debug \"HIPAA CODE : #{hipaa_code}\"\n end\n hipaa_code.to_s.upcase\n end", "def ais\n p = full_dearmored_ais_payload\n ret = _payload_container(p[0, 6].to_i(2))\n ret.payload_bitstring = p\n ret.fill_bits = last_ais_fill_bits\n ret\n end", "def fasta2anchors(input_file, anchor_length, sequencing_type, output_file)\n\t\tcounter = -1\n\t\tname, mate, seq = nil, nil, nil\n\t\t\n\t\tFile.open(output_file, 'w') do |output|\t\n\t\t\tFile.open(input_file, 'r').each do |line|\n\t\t\t\tcounter += 1\n\t\t\t\t\n\t\t\t\tif counter % 2 == 0\n\t\t\t\t\tif sequencing_type == 'se'\n\t\t\t\t\t\tname, mate = line.strip.match(/(?<=\\>)(\\S*)/).to_s, 1\n\t\t\t\t\telse\n\t\t\t\t\t\tname, mate = line.strip.match(/(?<=\\>)(\\S*)/).to_s.split('/')\n\t\t\t\t\tend\n\t\t\t\telsif counter % 2 == 1\n\t\t\t\t\tseq = line.strip\t\n\n\t\t\t\t\tname_A = \"#{name}_#{mate}_#{seq}_A\"\n\t\t\t\t\tname_B = \"#{name}_#{mate}_#{seq}_B\"\n\t\t\t\t\t\n\t\t\t\t\tseq_A = seq[0..anchor_length - 1]\n\t\t\t\t\tseq_B = seq[-anchor_length..-1]\n\n\t\t\t\t\toutput.puts [\">#{name_A}\", seq_A, \">#{name_B}\", seq_B].join(\"\\n\")\n\t\t\t\t\tname, mate, seq = nil, nil, nil\n\t\t\t\t\tcounter = -1\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def fasta2anchors(input_file, anchor_length, sequencing_type, output_file)\n\t\tcounter = -1\n\t\tname, mate, seq = nil, nil, nil\n\t\t\n\t\tFile.open(output_file, 'w') do |output|\t\n\t\t\tFile.open(input_file, 'r').each do |line|\n\t\t\t\tcounter += 1\n\t\t\t\t\n\t\t\t\tif counter % 2 == 0\n\t\t\t\t\tif sequencing_type == 'se'\n\t\t\t\t\t\tname, mate = line.strip.match(/(?<=\\>)(\\S*)/).to_s, 1\n\t\t\t\t\telse\n\t\t\t\t\t\tname, mate = line.strip.match(/(?<=\\>)(\\S*)/).to_s.split('/')\n\t\t\t\t\tend\n\t\t\t\telsif counter % 2 == 1\n\t\t\t\t\tseq = line.strip\t\n\n\t\t\t\t\tname_A = \"#{name}_#{mate}_#{seq}_A\"\n\t\t\t\t\tname_B = \"#{name}_#{mate}_#{seq}_B\"\n\t\t\t\t\t\n\t\t\t\t\tseq_A = seq[0..anchor_length - 1]\n\t\t\t\t\tseq_B = seq[-anchor_length..-1]\n\n\t\t\t\t\toutput.puts [\">#{name_A}\", seq_A, \">#{name_B}\", seq_B].join(\"\\n\")\n\t\t\t\t\tname, mate, seq = nil, nil, nil\n\t\t\t\t\tcounter = -1\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def adc_a_l\n end", "def discover_input_sequence_type(sequence)\n # Index of the first newline char.\n start = sequence.index(/\\n/)\n # Remove the sequence FASTA header.\n seq = sequence.slice(start..-1).gsub!(/\\n/, '')\n\n if seq =~ /[EQILFPeqilfp]+/\n type = \"amino_acid\"\n else\n # Length of the sequence minus the FASTA header.\n len = seq.length.to_f\n\n na_percent = 15.0\n counts = []\n\n counts << (seq.count(\"Aa\").to_f / len) * 100\n counts << (seq.count(\"Tt\").to_f / len) * 100\n counts << (seq.count(\"Uu\").to_f / len) * 100\n\n counts << (seq.count(\"Gg\").to_f / len) * 100\n counts << (seq.count(\"Cc\").to_f / len) * 100\n\n counts << (seq.count(\"Nn\").to_f / len) * 100\n\n counts.reject! { |c| c < na_percent }\n if (!counts.empty?)\n type = \"nucleic_acid\"\n else\n type = \"amino_acid\"\n end\n end\n type\n end", "def equilibrium_index(a)\n return -1 if a.empty?\n sum = a.inject(:+)\n lsum = 0\n \n a.length.times do |i|\n rsum = sum - lsum - a[i]\n return i if lsum == rsum\n lsum += a[i]\n end\n \n -1\nend", "def get_1CAA()\n caa = get_CAA(1)\n return caa\n end", "def adx(x)\n x * MINIMAP_RATIO + P_X\n end", "def return_number(a)\n ((a / 2)**2) * (65 - (a / 2))\nend", "def hexagonal_index\n (1 + Math.sqrt(1 + 8 * self)) / 4\n end", "def estimate_authority_score(guid,authority)\n out_degrees,in_degrees = @driver.degrees\n weight = 1.0\n if @driver.out_link?(guid)\n weight += 1.0/out_degrees\n end\n weight += @driver.directs(guid).to_f/@driver.total_directs\n weight * authority\n end", "def increase_code\n return unless code == 0 || code.nil?\n self.code = (AbsenceType.where.not(code: [0, nil]).order(code: :asc).last&.code || 0) + 1\n end", "def ir_azucares \n\t\t@ir_azucares = (@azucares/90.to_f)*100\n\t\t@ir_azucares.round(1)\n\tend", "def adc_a_h\n end", "def get_a(b)\n\ta = (1000.0 * b - 1000**2/2.0)/(b - 1000)\n\tif a % 1 == 0\n\t\treturn a\n\tend\n\treturn -1\nend", "def solution(a)\n cars_going_east = [0]\n\n a.each do |direction|\n next_counter = direction.zero? ? cars_going_east.last + 1 : cars_going_east.last\n cars_going_east << next_counter\n end\n\n passings = 0\n a.each_with_index do |direction, index|\n passings += cars_going_east[index] if direction == 1\n end\n\n return -1 if passings > 1000000000\n passings\nend", "def get_absorptance()\n begin\n if (not @construction.check_keyword?(\"ABSORPTANCE\") )\n @construction.set_keyword_value(\"ABSORPTANCE\", \"0.2\" )\n end\n return @construction.get_keyword_value(\"ABSORPTANCE\")\n rescue\n raise(\"Could not get absortance, is this really an exterior wall?\\n #{output}\") \n end\n end", "def transform_anotation(range)\n alphabet_table = { 'A' => 0, 'B' => 1, 'C' => 2, 'D' => 3, 'E' => 4, 'F' => 5, 'G' => 6, 'H' => 7, 'I' => 8, 'J' => 9,\n 'K' => 10, 'L' => 11, 'M' => 12, 'N' => 13, 'O' => 14, 'P' => 15, 'Q' => 16, 'R' => 17, 'S' => 18, 'T' => 19,\n 'U' => 20, 'V' => 21, 'W' => 22, 'X' => 23, 'Y' => 24, 'Z' => 25, 'AA' => 26, 'AB' => 27, 'AC' => 28, 'AD' => 29,\n 'AE' => 30, 'AF' => 31, 'AG' => 32, 'AH' => 33, 'AI' => 34, 'AJ' => 35, 'AK' => 36, 'AL' => 37, 'AM' => 38, 'AN' => 39,\n 'AO' => 40, 'AP' => 41, 'AQ' => 42, 'AR' => 43, 'AS' => 44, 'AT' => 45, 'AU' => 46, 'AV' => 47, 'AW' => 48, 'AX' => 49,\n 'AY' => 50, 'AZ' => 51, 'BA' => 52, 'BB' => 53, 'BC' => 54, 'BD' => 55, 'BE' => 56, 'BF' => 57,\n 'BG' => 58, 'BH' => 59, 'BI' => 60, 'BJ' => 61, 'BK' => 62, 'BL' => 63, 'BM' => 64, 'BN' => 65, 'BO' => 66 }\n range = range.split(':')\n start_row = range[0].split(/([A-Z]+)/)\n start_row.shift\n end_row = range[1].split(/([A-Z]+)/)\n end_row.shift\n column_times = alphabet_table[end_row[0]] - alphabet_table[start_row[0]] + 1\n row_times = end_row[1].to_i - start_row[1].to_i + 1\n { 'shift_num': (start_row[1].to_i) - 1,\n 'column': alphabet_table[start_row[0]],\n 'column_times': column_times,\n 'row_times': row_times }\n end", "def compute_rate_of_autonomous_applicants\n (autonomous_applicants.count / (\n @applicants.count.nonzero? || 1\n ).to_f) * 100\n end", "def get_1DAA()\n daa = get_DAA(1)\n return daa\n end", "def alphabet_position(text)\r\n numbers = \"\"\r\n text.split(\"\").each do |letter|\r\n if is_char_in_alpha(letter) == true\r\n numbers += \"#{letter.upcase.ord - 'A'.ord + 1} \"\r\n end\r\n end\r\n return numbers.strip\r\n\r\nend", "def aligned_sequence \n peptide_member = Ensembl::Compara::Member.find_by_member_id(self.peptide_member_id)\n seq = peptide_member.sequence.sequence\n return nil if seq.nil?\n aln = Ensembl::Compara::AlignSeq.new(seq,self.cigar_line).align\n return Bio::FastaFormat.new(Bio::Sequence::NA.new(aln).to_fasta(\"#{self.member.stable_id}|#{peptide_member.stable_id}\")) \n end", "def calculate\n string.\n each_byte.\n to_a.\n each_with_index.\n map { |byte, index| (index + 1) * byte }.\n reduce(0, :+)\n end", "def adc_a_hl\n end", "def solution(a)\n return 1 if a.count == 0\n \n real_sum = a.inject(:+)\n expected_sum = (a.count + 1) * (a.count + 2) / 2.0\n (expected_sum - real_sum).to_i\nend", "def total\n total = 0\n aces = 0\n @hand.each do |card|\n case card[0]\n when 2..10 then total += card[0]\n when 'A' then aces += 1\n else total += 10\n end\n end\n total += add_aces(total, aces)\n total\n end", "def calcularActitud\n\t\n\t@aptitud = 0\n\t\n\tself.each_with_index do |item, index|\t\n\t\t\t\n\t\t\t\tprincipalTemp = calcularDiagonalPrincipal(index, item)\n\t\t\t\tsecondaryTemp = calcularDiagonalSecundaria(index, item)\n\t\t\t\t#puts \"principal es #{principalTemp}\"\n\t\t\t\t\n\t\t\t\t#puts \"secundario es #{secondaryTemp}\"\t\n\t\t\t\t\n\t\t\t\tprincipalTemp.row(0).each_with_index do |value , newindex|\n\t\t\t\t\n\t\t\t\t\tif (self[value] == principalTemp.row(1)[newindex] && index != value)\n\t\t\t\t\t\t\n\t\t\t\t\t\t@aptitud -=1\n\t\t\t\t\t\t\n\t\t\t\t\tend\n\t\t\t\t\t\t\t\t\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tsecondaryTemp.row(0).each_with_index do |value , newindex|\n\t\t\t\t\t\n\t\t\t\t\tif (self[value] == secondaryTemp.row(1)[newindex] && index != value)\n\t\t\t\t\t\t@aptitud -=1\n\t\t\t\t\tend\n\t\t\t\t\t\t\t\t\n\t\t\t\tend\n\tend\n \n end", "def kali(panjang_arr,a)\n\ttotal=1\n\t(0..(panjang_arr-1)).each do |i|\n\t\ttotal=total*a[i]\n\tend\n\treturn total\nend", "def convert_audio_to_aac(stream, index)\n disposition = (index == 0) ? 'default' : 'none'\n return [ \"-map 0:a:#{stream[:index]}\",\n \"-metadata:s:a:#{index} title='Stereo Track'\",\n \"-metadata:s:a:#{index} language=#{stream[:language]}\",\n \"-disposition:a:#{index} #{disposition}\",\n \"-codec:a:#{index} aac\",\n \"-ar:a:#{index} 48k\",\n \"-ab:a:#{index} 160k\",\n \"-ac:a:#{index} 2\" ]\nend", "def upc_a\n generate_barcode('barcode.upc_a')\n end", "def equil_idcs(a)\n left = 0\n sum = a.inject(:+)\n equils = []\n a.each_with_index do |num, idx|\n sum -= num\n equils << idx if left == sum\n left += num\n end\n equils.empty? ? -1 : equils\nend", "def sumAmi(num)\n\t#initialize total to 0\n\ttotal = 0\n\t#for every number under num\n\tfor i in 1 .. num-1\n\t\t#if it is an amicable number\n\t\tif isAmicable(i)\n\t\t\t#add i to total\n\t\t\ttotal += i\n\t\tend \n\tend\n\t#return total\n\treturn total\nend", "def coding_region_cdna_start\n answer = 0\n \n self.exons.each do |exon|\n if exon == self.translation.start_exon\n answer += self.translation.seq_start\n return answer\n else\n answer += exon.length\n end\n end\n \n end", "def alphabet_position(text)\n r = [*\"a\"..\"z\"] # a~z陣列\n text = text.downcase #轉成小寫\n text_to_array = text.split(\"\") #轉成陣列\n y = text_to_array.map do |i| #對應成陣列index值\n if r.index(i) != nil \n r.index(i) + 1 \n end \n end\n y = y.compact #去除nil\n y = y.join(\" \")\nend", "def ldi_a_mhl\n @a = @mmu[hl]\n self.hl = (hl + 1) & 0xFFFF\n @clock += 2\n end", "def cast_primary_hexagram\n # Determine the lines in the primary hexagram. These lines will be in\n # reverse order since the bottom line is determined first in hexagram\n # casting.\n primary_hexagram_lines = (0...Iching::Hexagram::NUM_LINES).map do\n toss_sum = (0...NUM_COINS).map do\n coin_toss\n end.reduce(:+)\n\n LINE_FOR_TOSS_SUM[toss_sum]\n end\n\n Hexagram.new(primary_hexagram_lines.reverse)\n end", "def acosh\n\t\tresult = Math.acosh(@input)\n\n\t render json: result, status: 200\n\trescue\n\t\trender json: {\"message\": 'Use the format: {\"input\": num}'}, status: 400\n\tend", "def angle_from_arc(arc_length, offset_angle=0.0, precision=1.0)\n index = cumulative_distances(precision, offset_angle).closest_index(arc_length)\n @cumulative_distance_angles[index]\n end" ]
[ "0.6621182", "0.6333505", "0.6068041", "0.6020737", "0.59023076", "0.58319247", "0.56881386", "0.5607501", "0.55861014", "0.5583739", "0.5526599", "0.55243194", "0.5512173", "0.5501506", "0.5465918", "0.5452043", "0.5447528", "0.5445903", "0.5329291", "0.53167236", "0.53114754", "0.52841145", "0.52524966", "0.52359617", "0.5209814", "0.5207733", "0.5190049", "0.5167839", "0.5140379", "0.5132303", "0.51210994", "0.5115332", "0.50974095", "0.506745", "0.5064806", "0.50591046", "0.5050745", "0.5040144", "0.50222594", "0.5017137", "0.5014818", "0.5009025", "0.5007855", "0.49971783", "0.4990712", "0.49893185", "0.49875206", "0.4987183", "0.49808946", "0.4978219", "0.49723402", "0.4957714", "0.4950737", "0.4947151", "0.4942188", "0.49384058", "0.49349338", "0.4932227", "0.4917771", "0.49076146", "0.48972863", "0.48879763", "0.48702896", "0.48678905", "0.48678905", "0.48657754", "0.48637953", "0.48565915", "0.48557913", "0.48456857", "0.48333663", "0.4821499", "0.48160672", "0.48085368", "0.4785688", "0.47848678", "0.4783712", "0.47714332", "0.47706485", "0.47694263", "0.47551668", "0.4754423", "0.47458157", "0.47447234", "0.47429997", "0.4739392", "0.47196582", "0.4712323", "0.47095576", "0.47081077", "0.47012812", "0.4700303", "0.46992546", "0.4696625", "0.46963704", "0.46848562", "0.46846285", "0.4682472", "0.46819925", "0.468084" ]
0.77311355
0
Calculate GRAVY score of an AA sequence. _The GRAVY(Grand Average of Hydropathy) value for a peptide or protein is calculated as the sum of hydropathy values [9] of all the amino acids, divided by the number of residues in the sequence._
def gravy @gravy ||= begin hydropathy_sum = 0.0 each_aa do |aa| hydropathy_sum += HYDROPATHY[aa] end round(hydropathy_sum / @seq.length.to_f, 3) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def raw_gpa\n tot_grade_points/tot_graded_attmp rescue 0.0/0.0\n end", "def get_gpa\n total = registrations.where('grade is not null').inject(0){|sum, c| sum + c.grade}\n if total != 0\n # binding.pry\n final_gpa = total.to_f / (self.registrations.where('grade is not null').count).to_f\n self.update(gpa:final_gpa.round(2))\n puts \"\\nYour total GPA is: #{self.gpa}\"\n else\n puts \"\\nYou dont have any grades yet\"\n end\n\n end", "def get_gpa(text_array)\n resume_as_array = resume_to_array(text_array)\n gpa = nil\n resume_as_array.each_with_index do |t, i|\n if gpa == nil\n if t.include?('gpa') || t.include?('grade') || t.include?('g.p.a')\n gpa = t.match(/[0-4][.][0-9][0-9]/)\n if gpa == nil\n gpa = t.match(/[0-4][.][0-9]/)\n if gpa == nil\n gpa = resume_as_array[i + 1].match(/[0-4][.][0-9][0-9]/)\n if gpa == nil\n gpa = resume_as_array[i + 1].match(/[0-4][.][0-9]/)\n if gpa == nil\n gpa = resume_as_array[i - 1].match(/[0-4][.][0-9][0-9]/)\n if gpa == nil\n gpa = resume_as_array[i - 1].match(/[0-4][.][0-9]/)\n end\n end\n end\n end\n end\n end\n end\n end\n if gpa != nil\n gpa = gpa[0].to_f\n end\n return gpa\nend", "def compute_average_grade\n total = 0.0\n self.fcqs.compact.each {|x| next if x.avg_grd == nil; total += x.avg_grd}\n count = courses_taught\n if count == 0\n return 1.0 \n else\n return (total.to_f / count.to_f)\n end\n end", "def gen_score\n ## Calculate the score here!\n\n total_score = victories + coins/3 + blues + yellows + purples + leaders + blacks\n ## Greens\n greens = [tablets, compasses, gears]\n total_score += (greens.min*7) + greens[0]**2 + greens[1]**2 + greens[2]**2\n self.score = total_score\n end", "def get_grade(input_array)\n\tsum = 0\n\tinput_array.each do |x|\n\t\tsum += x\n\tend\n\tav_score = sum/input_array.length\n\treturn \"A\" if av_score>=90\n\treturn \"B\" if av_score>=80\n\treturn \"C\" if av_score>=70\n\treturn \"D\" if av_score>=60\n\treturn \"F\" if av_score<60\nend", "def getGPA(reportText)\n gpaSummary = Hash.new()\n # We need to scan this way due to DARS formatting\n gpaArray = Array.new()\n gpaArray = reportText.scan(/(\\d\\.\\d{2}) GPA/)\n if gpaArray == nil\n gpaArray = ['0.00', '0.00']\n elsif gpaArray.length == 1\n gpaArray[1] = '0.00'\n end\n\n gpaSummary[:cumulativeGPA] = gpaArray[0][0]\n gpaSummary[:majorGPA] = gpaArray[1][0]\n return gpaSummary\nend", "def gases_anual()\n gas=0\n aux=@head\n\n loop do\n gas+=(aux.value).gases\n aux=aux.next\n break if aux==nil\n end\n gas=gas*365\n return gas\n end", "def get_gpa(current_qps: , current_gpa_hours:, remaining_grade_distribution:)\n #Add more grades if neccessary\n grade_transitions = {A: 16, Aminus: 14.668, Bplus: 13.332, B: 12}\n remaining_gpa_hours = remaining_grade_distribution.length * 4\n sum_of_new_grades = 0\n remaining_grade_distribution.each {|x| sum_of_new_grades+= grade_transitions[x]}\n\n # \"+ 4\" quality points and \"+1\" gpa hours for eloquent presenter assuming a get an A --> I removed this\n print((current_qps + sum_of_new_grades)/(current_gpa_hours + remaining_gpa_hours))\nend", "def total_score\n\t\t@array = []\n\t\tself.attributes.each do |key, value|\n\t\t\tif key.to_s =~ /^score/\n\t\t\t\t@array << value\n\t\t\tend\n\t\tend\n\t\tunless @array ==[]\n\t\t\treturn @array.reduce(:+)\n\t\telse\n\t\t\treturn 0\n\t\tend\n\tend", "def get_grade(scoreArray)\n\t\t\n\tavg = scoreArray.reduce(:+) / scoreArray.length\n\t\t\n\tcase avg\n\t\twhen 90..100 then 'A'\n\t\twhen 80..89 then 'B'\n\t\twhen 70..79 then 'C'\t\n\t\twhen 60..69 then 'D'\n\t\telse 'F'\t\n\tend\nend", "def quarter_gpa(quarter = nil)\n t = transcripts.find(system_key, quarter.year, quarter.quarter_code_id) rescue nil\n raw_gpa = t.nil? ? nil : (t.qtr_grade_points/t.qtr_graded_attmp) rescue nil\n '%.2f' % raw_gpa rescue \"unknown\" \n end", "def ir_grasa_total \n\t\t@grasa_ir = grasas_totales\n\t\t@ir_grasa_total = (@grasa_ir/70.to_f) * 100\n\t\t@ir_grasa_total.round(1)\n\tend", "def avg_route_difficulty area\n avg = 0.0\n keine_angabe = 0\n area.routes.each { |r| \n keine_angabe += 1 unless uiaa_grades.index(r.grade) > 0\n avg += uiaa_grades.index(r.grade) unless uiaa_grades.index(r.grade) == 0 }\n new_uiaa_index = (avg / (area.routes.length - keine_angabe)).round\n uiaa_grades[new_uiaa_index]\n end", "def average\n return ((@critics_score + @audience_score) / 2.0) #ultimate math skillz.\n end", "def get_extra_grade(score1, score2, score3)\n average = ((score1 + score2 + score3) / 3.0).round(2)\n \n GRADES.each do |grade, range|\n return grade if range.cover?(average)\n end\n\n \"A+\"\nend", "def average_score\n count = 0.0\n avrg = 0.0\n if self.cadets.empty?\n return 0.0\n else\n self.cadets.each do |cdt|\n unless cdt.discharged?\n avrg += cdt.average_score\n count += 1.0\n end\n end\n return count != 0.0 ? (avrg/count).round(1) : 0.0\n end\n end", "def average_score\n grades.average(:score) || 0\n end", "def irgrasas\n vag=(cgrasas * 100) / 70\n vag.round(2)\n end", "def get_grade(avg_score)\n\tif avg_score >= 90\n\t\t\"A\"\n\telsif avg_score >= 80\n\t\t\"B\"\n\telsif avg_score >= 70\n\t\t\"C\"\n\telsif avg_score >= 60\n\t\t\"D\"\n\telse\n\t\t\"F\"\n\tend\nend", "def overall_rating\n\t\ttotal_score = 0\n\t\ttotal_score += self.setting \n\t\ttotal_score += self.hotness\n\t\ttotal_score += self.originality\n\t\ttotal_score += self.style\n\t\ttotal_score += self.attitude\n\t\treturn total_score / 5\n\tend", "def porcentajeGlucidos\r\n total_glucidos = 0.0\r\n la = @listaAlimentos.head\r\n lg = @listaGramos.head\r\n while la != nil do\r\n total_glucidos += (la.value.carbohidratos * lg.value) / 100\r\n la = la.next\r\n lg = lg.next\r\n end\r\n total_gramos = listaGramos.reduce(:+)\r\n porcentajeGlucidos = ((total_glucidos / total_gramos)*100).round(2)\r\n end", "def grade_percentage\n total = 0\n student_tests = BoatingTest.all.select {|test| test.student == self}\n student_tests.each do |test|\n if test.test_status == \"passed\"\n total += 1\n end\n end\n average = total.to_f / student_tests.length\n average * 100\n end", "def calculate_popularity_score\n top_guide = (Guide.order_by(\"impressions_field\" => :asc).last)\n at_most = (top_guide.impressions_field || 0).to_i\n normalized = impressions_field.to_f / at_most\n write_attributes(popularity_score: normalized)\n end", "def gym_average_age\n total_users = self.find_all_gym_users.length\n user_ages = self.gym_user_instances.map{|user| user.age}.sum \n average = user_ages.to_f / total_users.to_f\n average\n end", "def Grass\n \n \tif sexo == \"Hombre\"\n \t\t\n \t\tsexo = 1\n \telse\n \t\n \t\tsexo = 0\n \tend\n\t\n grasas = 1.2 * @imc + 0.23 * edad - 10.8 * sexo - 5.4\n \n if @imc < 18.5 \n puts \"Flaco\"\n else if @imc < 24.9 \n puts \"Aceptable\"\n else \n puts \"Obeso\"\n end \nend \n\n \n return grasas\n \n end", "def get_user_score(user)\n\t\ttotal = 0\n\t\tmy_genres_array = user[:favorite_genres].split(\"|\")\n\n\t\ttotal += self.get_score\n\t\ttotal += self.genre_bonus(my_genres_array)\n\t\ttotal += self.old_movie_bonus(user)\n\t\treturn total\n\tend", "def calculate_final_score\n self.scores.average(:total_score)\n end", "def get_grade(score1, score2, score3)\n\t\n\taverage = (score1 + score2 + score3) / 3\n\n\tcase average\n\t\twhen (90...)\n\t\t\t'A'\n\t\twhen (80..89)\n\t\t\t'B'\n\t\twhen (70..79)\n\t\t\t'C'\n\t\twhen (60..69)\n\t\t\t'D'\n\t\twhen (0..59)\n\t\t\t'F'\n\tend\nend", "def avg_score\n return 0 unless reviews.count.positive?\n reviews.average(:score).round(2).to_f\n end", "def calc_race_gv(course)\n # Rails.logger.info(\"Process course #{course}\")\n total_delta = 0.0\n meet_cnt = 0\n meets = get_meets\n meets.each do |meet|\n delta = process_course(meet,course)\n next if delta == nil\n meet_cnt += 1\n total_delta += delta\n calc_runners_gv(course)\n end\n total_delta / meet_cnt\n end", "def valorgrasassatup\n\t\tvag=(cgrasassa * 70) / 100\n vag.round(2)\n\tend", "def gradeAVG(scores)\n sum = 0\n scores.each do |grade|\n sum += grade\n end\n average = sum / (scores.length)\n return average\nend", "def avg_score\n return 0 unless reviews.size.positive?\n\n reviews.average(:score).to_f.round(2)\n end", "def avg_score\n return 0 unless reviews.count.positive?\n\n reviews.average(:score).round(2).to_f\n end", "def irgrasasp\n vag=(valorgrasassatup * 100) / 70\n vag.round(2)\n end", "def gramos\r\n grams = 0\r\n @lista_alimentos.each do |i|\r\n grams += 100\r\n end\r\n return grams\r\n end", "def recalculate_grade(nowish)\n grade = 0\n \n # all ratings grade (might be negative)\n all_ratings_grade = 0\n ratings = {RatingPlace::LIKED => 0, RatingPlace::DISLIKED => 0}\n tot_ratings = 0\n for link_rating in self.link_ratings()\n if ratings.keys().include?(link_rating.rating) # only count likes and dislikes\n ratings[link_rating.rating] += 1\n tot_ratings += 1\n end\n end\n \n if tot_ratings > 0\n raw_rating = ((ratings[RatingPlace::LIKED] - ratings[RatingPlace::DISLIKED]) / tot_ratings).to_f\n all_ratings_grade = raw_rating * ALL_RATINGS_PROP\n end\n\n self.grade = (get_total_source_grade() * SOURCES_PROP) + all_ratings_grade\n self.grade_recalculated = nowish\n self.save()\n end", "def percentagize_score\n real_percentage = self.score\n return real_percentage.round\n end", "def percentagize_score\n real_percentage = self.score\n return real_percentage.round\n end", "def assignment_average_score(grade_hash, assignment_num)\n marks = assignment_scores(grade_hash, assignment_num)\n marks.sum / marks.length\nend", "def best_score(a_of_g)\n best_score = a_of_g.flatten.return_objects_with(:attempts, 0).max_attribute(:adjusted_goodness)\n end", "def grams\n gram_equivalent / amount\n end", "def average_grade_overall\n return self.data[\"average_grade\"]\n end", "def dieta_gases_anuales(gramos)\n aux = @head\n suma_gases = 0\n i = 0\n while (!aux.nil?)\n suma_gases += aux[:value].auxiliar(gramos[i])\n aux = aux[:next]\n i = i+1\n end\n return suma_gases.round(2)\n\n end", "def avg \n\t\t# prevent divide by zero\n\t\tif (self[:at_bats] != 0)\n\t\t\t(self[:hits].to_i / self[:at_bats].to_f).round(3)\n\t\telse\n\t\t\t0\n\t\tend\n\tend", "def gpa\n '%.2f' % raw_gpa rescue \"unknown\"\n end", "def average\n\t\tif 2 < course.users.length and 0 < grades.length and 0 < worth\n\t\t\taverage = (grades.sum(:grade) / grades.length);\n\t\t\taverage = (average.to_f / worth) * 100;\n\t\t\treturn average\n\t\tend\n\tend", "def gross_amount\n get_awards[:gross_amt]\n end", "def score\n return @score if @score != -1\n prod =\n [p_bases_covered, 0.01].max.to_f * # proportion of bases covered\n [p_not_segmented, 0.01].max.to_f * # prob contig has 0 changepoints\n [p_good, 0.01].max.to_f * # proportion of reads that mapped good\n [p_seq_true, 0.01].max.to_f # scaled 1 - mean per-base edit distance\n @score = [prod, 0.01].max\n end", "def get_grade(test_scores)\n sum = 0.00\n test_scores.each {|score| sum += score}\n avg = sum / test_scores.length\n case avg\n when 90..100\n return \"A\"\n when 80...90\n return \"B\" \n when 70...80\n return \"C\"\n when 60...70\n return \"D\"\n else\n return \"F\"\n end\nend", "def valorgrasasp\n\t\tvag=(cgrasas * 70) / 100\n\t\tvag.round(2)\n\tend", "def batting_avg\r\n at_bats > 0 ? (hits.to_f / at_bats) : 0.0\r\n end", "def get_grade(scores)\n \n sum = scores.reduce(:+)\n \n average = sum.to_f/scores.length\n \n if (average >= 90)\n 'A'\n elsif (average >= 80)\n 'B'\n elsif (average >=70)\n 'C'\n elsif (average >=60)\n 'D'\n else \n 'F'\n end\n \n end", "def grade_average\n @grades.inject(:+) / @grades.size\n end", "def irgrasassaturadas\n vag=(cgrasassa * 100) / 70\n vag.round(2)\n end", "def valormonograsasp\n\t\tvag=(grasasmono * 70) / 100\n vag.round(2)\n\tend", "def get_grade(gr1, gr2, gr3)\n average = (gr1 + gr2 + gr3) / 3\n return \"A\" if average >= 90\n return \"B\" if average >= 80\n return \"C\" if average >= 70\n return \"D\" if average >= 60\n \"F\"\nend", "def g score1, score2\n difference = score_difference(score1, score2)\n case difference\n when 0, 1\n 1\n when 2\n 3/2.0\n else\n (11 + difference) / 8.0\n end\n end", "def get_grade(array)\n\ttotal = 0\n\tarray.each do |x|\n\t\ttotal += x\n\tend\n\taverage = total / array.length\n\tif average >= 90\n\t\treturn \"A\"\n\telsif average >= 80\n\t\treturn \"B\"\n\telsif average >= 70\n\t\treturn \"C\"\n\telsif average >= 60\n\t\treturn \"D\"\n\telse\n\t\treturn \"F\"\n\tend\nend", "def run_aggregation\n GRADES.each_with_index do |grade, idx|\n classifier[grade].each_pair do |metric, values|\n all_values = values\n all_values += classifier[GRADES[idx + 1]][metric] if (idx + 1) < GRADES.count\n\n classifier[grade][metric] =\n if all_values.count <= 2\n values.max || 0\n else\n (all_values.sum / all_values.count).round(2)\n end\n end\n end\n end", "def score\n @scoreTotal = @jogadas[0].down_pin + @jogadas[1].down_pin\n end", "def get_grade(array)\n\tavg = ((array.inject(:+)) / array.length)\n\tcase avg\n\twhen 90..100\n\t\t'A'\n\twhen 80..89\n\t\t'B'\n\twhen 70..79\n\t\t'C'\n\twhen 60..69\n\t\t'D'\n\telse \n\t\t'F'\n\tend\nend", "def average_rating(var)\n rtngs = ratings.select{ |r| r.beer.var == var }\n rtngs.inject(0.0){|sum, r| sum + r.score } / rtngs.count\n end", "def average_of(raitingss)\n raitingss.sum(&:score).to_f / raitingss.count\n end", "def gross_for_director(director_data)\n #pp director_data\n\n result = []\n movie_index = 0\n\n while movie_index < director_data[:movies].length do\n total_gross = director_data[:movies][movie_index][:worldwide_gross]\n result.push(total_gross)\n movie_index += 1\n end\n puts result\n return result.sum\n end", "def get_grade(array)\n\tavg = array.inject(:+) / array.length\n\n\tif avg >= 90\n\t\t\"A\"\n\telsif avg >= 80\n\t\t\"B\"\n\telsif avg >= 70\n\t\t\"C\"\n\telsif avg >=60\n\t\t\"D\"\n\telse\n\t\t\"F\"\n\tend\nend", "def average_age\n sum = 0.0\n count = Bloodoath.all.select do |bloodoath|\n if bloodoath.cult == self\n sum += bloodoath.follower.age\n end\n end\n sum/count.length\n end", "def assignment_average_score(grade_hash, assignment_score)\n sum = 0\n grade_hash.each do |key, value|\n sum += value[assignment_score - 1]\n end\n average = sum / grade_hash.keys.length\n average\nend", "def average_score\n return nil if metrics.empty?\n totals = grades.includes(:subject).group_by(&:subject).map { |_, grades|\n grades.sum(&:weighted_score) }\n return 0 if totals.empty?\n totals.sum.to_f / totals.length\n end", "def avg_owner_familiarity_gap(before = DateTime.new(2050,01,01))\n code_reviews(before).average(:owner_familiarity_gap)\n end", "def get_avggrades(hash)\n sumgrades = 0\n hash[:grades].each do |grade|\n if grade.to_s != 'A'\n sumgrades += grade.to_f\n else\n sumgrades +=1\n end\n end\n sumgrades / hash[:grades].length\nend", "def compute_goggle_cup_score(time_swam)\n # Without a correct time_swam always return 0\n goggle_cup_score = 0.0\n if time_swam && time_swam.to_hundreds > 0\n # Retrieves the time standard\n get_goggle_cup_standard\n if @current_goggle_cup_standard && @current_goggle_cup_standard.get_timing_instance.to_hundreds > 0\n # Calculate the score\n goggle_cup_score = @current_goggle_cup_standard.get_timing_instance.to_hundreds.to_f * @goggle_cup.max_points / time_swam.to_hundreds.to_f\n update_goggle_cup_standard(time_swam) if goggle_cup_score > @goggle_cup.max_points && @goggle_cup.has_to_update_standards\n\n # Check if modifiers should be applied\n modifier = get_swimmer_modifier\n goggle_cup_score += (goggle_cup_score * (modifier / 100)) if modifier != 0.0\n else\n # Without time standard the score is always GoggleCupMaxPoints\n goggle_cup_score = @goggle_cup.max_points\n @current_goggle_cup_standard = new_goggle_cup_standard(time_swam) if @goggle_cup.has_to_create_standards\n end\n end\n\n # The score is always with 2 decimals fixed\n goggle_cup_score.round(2)\n end", "def get_grade(array)\n sum = 0\n array.each do |number|\n sum += number\n end\n avg = sum / array.length\n if (avg >= 90)\n return \"A\"\n elsif (avg >= 80)\n return \"B\"\n elsif (avg >= 70)\n return \"C\"\n elsif (avg >= 60)\n return \"D\"\n else\n return \"F\"\n end\nend", "def grade_percentage\n #Count all tests this student has passed\n tests_passed = BoatingTest.all.select {|test| test.student == self && test.test_status == \"passed\" }.length.to_f\n #Count all tests with this student\n all_tests = BoatingTest.all.select {|test| test.student == self}.length.to_f\n #Calculate percentage as float\n grade_percentage = tests_passed/all_tests\n grade_percentage.round(2)\n end", "def get_grade(score1, score2, score3)\n avg = [score1, score2, score3].sum / 3\n case avg\n when (90..100) then 'A'\n when (80...90) then 'B'\n when (70...80) then 'C'\n when (60...70) then 'D'\n when (0...60) then 'F'\n end\nend", "def assignment_average_score(grade_hash, assignment_num)\n assignment = grade_hash.map {|x| x[1][assignment_num-1]}\n average = assignment.reduce{|x,n| x += n}/assignment.length\nend", "def assignment_average_score(grade_hash, assignment_num)\n a = []\n grade_hash.values.each { |dude| a.push(dude[assignment_num - 1]) }\n sum = a.sum\n average = sum/a.length\nend", "def average_girls_per_family(families)\n num_families = families.count\n num_girls = families.map { |family| family[:num_girls] }.sum\n\n num_girls.to_f / num_families.to_f\n end", "def gases()\n gas=0\n aux=@head\n\n loop do\n gas+=(aux.value).gases\n aux=aux.next\n break if aux==nil\n end\n return gas\n end", "def percent_complete(user)\n\t\tcompletedWorth = 0.0\n\t\ttotalWorth = 0.0\n\t\t\n\t\tself.assignments.each do |assignment|\n\t\t\ttotalWorth += assignment.worth\n\t\t\t\n\t\t\tif assignment.user_grade(user)\n\t\t\t\tcompletedWorth += assignment.worth\n\t\t\tend\n\t\tend\n\t\t\n\t\tif totalWorth != 0\n\t\t\treturn completedWorth / totalWorth\n\t\tend\n\tend", "def gross_for_director(director_data)\n sum = 0\n\t\n\tdirector_data[:movies].each do |movie|\n\t\tsum += movie[:worldwide_gross]\n\tend\n\t\n\treturn sum\nend", "def average_goals_per_game\n total_goals = @teams.map {|team| team.total_goals_scored}.sum\n total_games = @teams.map {|team| team.home_games}.sum\n (total_goals.to_f / total_games.to_f).round(2)\n end", "def results(values, weight)\n gpa = weight.reduce(:+).to_f / values.reduce(:+)\n\n puts $divide\n puts \"\\n#{$first.capitalize} #{$last.capitalize}, your GPA is #{gpa.to_s} \\n\\n\"\nend", "def user_grade(user)\n\t\ttotalGrade = 0\n\t\ttotalWorth = 0\n\t\n\t\tgrades = Grade.joins(:assignment).where('assignments.assignment_type_id' => self.id, :user_id => user)\n\n\t\tif drop_lowest\n\t\t\t# If we are dropping the lowest score, we have to calculate the grades individually\n\t\t\tscores = []\n\t\n\t\t\t# Calculate each score\n\t\t\tgrades.each do |g|\n\t\t\t\tif g.assignment.worth != 0\n\t\t\t\t\tscores.push(g.grade / g.assignment.worth)\n\t\t\t\tend\n\t\t\tend\n\t\t\t\n\t\t\t# Sort and remove lowest score\n\t\t\tscores = scores.sort\n\t\t\tscores.delete_at(0)\n\t\t\n\t\t\t# Calculate grade using remainder\n\t\t\tif scores.length != 0\n\t\t\t\treturn scores.sum / scores.length * 100\n\t\t\tend\n\n\t\telse\n\t\t\t# Calculate the grades in bulk\n\t\t\tgrade = grades.sum(:grade).to_f\n\t\t\tworth = grades.sum(:worth).to_f\n\n\t\t\tif worth != 0\n\t\t\t\treturn (grade / worth) * 100\n\t\t\tend\n\n\t\tend\n\tend", "def irproteinas\n vag=(proteinas * 100) / 50\n vag.round(2)\n end", "def calculate_gross\n items.sum { |item_attributes| calculate_item_gross(item_attributes) }\n end", "def gross_for_director(director_data)\n movie_index = 0\n director_total = 0\n while movie_index < director_data[:movies].length\n director_total += director_data[:movies][movie_index][:worldwide_gross]\n movie_index += 1\n end\n director_total\n\n end", "def avg_score\n reviews.average(:rating).round(2).to_f\n end", "def user_score\n total_score = 0\n score.each do |_phase, categories|\n total_score += categories.reject { |category| category.include? \"oath\" }.count { |category| category[1] >= 80 }\n end\n total_score\n end", "def get_grade(avg)\n\tif avg <= 100 and avg > 89\n\t\treturn \"A\"\n\telsif avg < 90 and avg > 79\n\t\treturn \"B\"\n\telsif avg < 80 and avg > 69\n\t\treturn \"C\"\n\telsif avg < 70 and avg > 59\n\t\treturn \"D\"\n\telse avg < 60 and avg > 0\n\t\treturn \"F\"\n\tend\nend", "def score\n total = 0\n achievements.each do |a|\n total += a.task.score\n end\n total\n end", "def assignment_average_score(grade_hash, assignment_num)\n assignment = grade_hash.map do |key, value|\n value[assignment_num - 1]\n end\n\n sum = assignment.reduce do |sum, x|\n sum += x\n end\n\n sum / assignment.length\nend", "def average_student_gpa\n \"SELECT AVG(gpa) from students;\"\nend", "def avg_rating(attribute)\n\t\tif reviews.none?\n\t\t val = 0\n\t\telse \n\t\t val = reviews.average(attribute)\n\t\tend\n\t\treturn val\n\tend", "def irmonograsas\n vag=(grasasmono * 100) / 70\n vag.round(2)\n end", "def get_grade(score1, score2, score3)\n av = (score1 + score2 + score3) / 3\n case\n when av < 60 then 'F'\n when av < 70 then 'D'\n when av < 80 then 'C'\n when av < 90 then 'B'\n when av >= 90 then 'A'\n end\nend", "def get_average_score()\n if get_maximum_score != 0 then\n ((get_total_score.to_f / get_maximum_score.to_f) * 100).to_i\n else\n 0\n end\n end", "def genre_bonus(user_genre_array)\n\t\t# iterate through each user's genre and see if they match movie\n\t\tuser_genre_array.each do |genre|\n\t\t\tif self.genres.include? genre\n\t\t\t\treturn 3.5\n\t\t\telse\n\t\t\t\treturn 0\n\t\t\tend\n\t\tend\n\tend", "def get_grade(arr)\n\tavg = arr.inject(:+)/arr.length\n \n\tcase avg\n when (90..100) then \"A\"\n when (80..89) then \"B\"\n when (70..79) then \"C\"\n when (60..69) then \"D\"\n else \"F\"\n\tend\nend" ]
[ "0.60018265", "0.5839094", "0.5787341", "0.565506", "0.55642915", "0.55627733", "0.5533933", "0.55288666", "0.55063254", "0.54518044", "0.54405046", "0.54323685", "0.5411593", "0.5410152", "0.53939104", "0.5326942", "0.5324399", "0.53011346", "0.5292673", "0.526699", "0.52649164", "0.5256892", "0.5241025", "0.52228254", "0.5220262", "0.52150196", "0.52127874", "0.5210603", "0.519886", "0.5195242", "0.51892775", "0.5180384", "0.5168752", "0.51676136", "0.51631045", "0.5157601", "0.5139626", "0.5108697", "0.51081467", "0.51081467", "0.5107589", "0.51072776", "0.51020515", "0.50883245", "0.5082188", "0.508102", "0.50767267", "0.50742126", "0.50711966", "0.5066153", "0.5046282", "0.5035701", "0.5032165", "0.5031018", "0.5029358", "0.5029234", "0.50286514", "0.502627", "0.5024269", "0.50238", "0.5023657", "0.5023462", "0.5022713", "0.5016651", "0.50149155", "0.5014167", "0.50139135", "0.49999094", "0.49940577", "0.49914017", "0.49867365", "0.4976623", "0.49750003", "0.49673694", "0.49665284", "0.4962331", "0.49601847", "0.49594116", "0.49586278", "0.4950251", "0.49420556", "0.49395803", "0.4936795", "0.4935218", "0.49340883", "0.49301997", "0.4929086", "0.4924324", "0.4921359", "0.4919357", "0.49172768", "0.49167696", "0.4916445", "0.49163195", "0.49134055", "0.4911991", "0.49116933", "0.49096978", "0.49072573", "0.4904622" ]
0.7091364
0
Calculate the percentage composition of an AA sequence as a Hash object. It return percentage of a given amino acid if aa_code is not nil.
def aa_comp(aa_code=nil) if aa_code.nil? aa_map = {} IUPAC_CODE.keys.each do |k| aa_map[k] = 0.0 end aa_map.update(aa_comp_map){|k,_,v| round(v, 1) } else round(aa_comp_map[aa_code], 1) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def overall_aroma_percentage\n overall_aroma = self.aroma_bundles.inject(0) do |memo, bundle|\n memo += bundle.percent if bundle.percent.is_a?(Integer) || bundle.percent.is_a?(BigDecimal)\n memo\n end\n\n return overall_aroma\n end", "def calculate_percentage_completion\n result = {}\n result[:pc] = ideal_completion[:pc]\n if %w(green amber).include?(status)\n result[:pve] = ideal_completion[:pve]\n # elsif status == \"red\"\n # result[:pve] = 20\n end\n result[:pdl] = ideal_completion[:pdl] if !documents.empty? || !personal_links.empty?\n return result\n end", "def letter_percentages(string)\n chars = string.split('')\n\n hash_of_percentages = { lowercase: 0.0, uppercase: 0.0, neither: 0.0}\n hash_of_percentages = calculate_chars(chars, hash_of_percentages)\n\n total_chars = chars.length\n hash_of_percentages = calculate_percentages(hash_of_percentages, total_chars)\n\n return hash_of_percentages\nend", "def letter_percentages(string)\n letter_case_count = letter_case_count(string)\n result = {}\n letter_case_count.each do |type, num|\n result[type] = (num / letter_case_count.values.sum.to_f * 100).round(1)\n end\n result\nend", "def letter_percentages(str)\n count_lowercase = 0\n count_uppercase = 0\n count_neither = 0\n\n str.each_char do |char|\n if %w(1 2 3 4 5 6 7 8 9 0).include?(char)\n count_neither += 1\n elsif ('A'..'Z').include?(char)\n count_uppercase += 1\n elsif ('a'..'z').include?(char)\n count_lowercase += 1\n else\n count_neither += 1\n end\n\n end\n\n percent_lowercase = (count_lowercase.to_f / str.length) * 100\n percent_uppercase = (count_uppercase.to_f / str.length) * 100\n percent_neither = (count_neither.to_f / str.length) * 100\n\n hsh = {\n lowercase: percent_lowercase,\n uppercase: percent_uppercase,\n neither: percent_neither\n }\nend", "def macro_percentages\n \n if self.total_calories!=nil and self.protein_grams != nil and self.carbohydrate_grams!=nil and self.fat_grams!=nil\n return {:protein=>protein_grams.to_f/total_calories, :carbohydrate => carbohydrate_grams.to_f/total_calories, :fat=> fat_grams.to_f/total_calories}\n end\n\n return nil\n end", "def count_percentage(array,decimal = 2)\n hash1 = Hash.new(0)\n array.each do |element|\n hash1[element] += 1\n end\n total_elements = array.size\n hash2 = Hash.new(0)\n hash1.each do |key,value|\n hash2[key] = (value/total_elements.to_f).round(decimal)\n end\n return hash2\nend", "def basic_count(amino_acid_sequence)\n count = 0\n comp = amino_acid_sequence.composition\n BASIC_AMINO_ACIDS.each do |basic|\n if comp[basic]\n count += comp[basic]\n end\n end\n return count\n end", "def calculate_marks(academic_record)\n marks = Hash.new\n marks[:sub1] = academic_record.sub1_marks.to_i if academic_record.sub1_marks\n marks[:sub2] = academic_record.sub2_marks.to_i if academic_record.sub2_marks\n marks[:sub3] = academic_record.sub3_marks.to_i if academic_record.sub3_marks\n marks[:sub4] = academic_record.sub4_marks.to_i if academic_record.sub4_marks\n marks[:sub5] = academic_record.sub5_marks.to_i if academic_record.sub5_marks\n marks[:sub6] = academic_record.sub6_marks.to_i if academic_record.sub6_marks\n marks[:sub7] = academic_record.sub7_marks.to_i if academic_record.sub7_marks\n marks[:sub8] = academic_record.sub8_marks.to_i if academic_record.sub8_marks\n marks[:sub9] = academic_record.sub9_marks.to_i if academic_record.sub9_marks\n marks[:sub10] = academic_record.sub10_marks.to_i if academic_record.sub10_marks\n\n marks = marks.sort {|x,y| y[1] <=> x[1]}.to_h\n array_marks = marks.values\n best4_marks = array_marks[0].to_i + array_marks[1].to_i + array_marks[2].to_i + array_marks[3].to_i\n\n calculated_marks = 1000000*best4_marks + 10000*academic_record.hs_marks_percent + 100*academic_record.tenth_marks_percent + academic_record.hs_year_pass-2000\n if academic_record.hs_board.downcase.eql?priority_board\n calculated_marks += priority_marks\n end\n calculated_marks\n end", "def final_letter_grades(grade_hash)\n averages = grade_hash.inject({}) { |h, (k,v)| h[k] = letter_grade(v.reduce{|x,n| x += n}/v.length) ; h}\nend", "def profile_completion_score\n attrs = [:name, :bio, :telephone]\n (attrs.reject { |attr| self.send(attr).blank? }.count.to_f / attrs.count) * 100\n end", "def acidic_count(amino_acid_sequence)\n count = 0\n comp = amino_acid_sequence.composition\n ACIDIC_AMINO_ACIDS.each do |acidic|\n if comp[acidic]\n count += comp[acidic]\n end\n end\n return count\n end", "def get_avggrades(hash)\n sumgrades = 0\n hash[:grades].each do |grade|\n if grade.to_s != 'A'\n sumgrades += grade.to_f\n else\n sumgrades +=1\n end\n end\n sumgrades / hash[:grades].length\nend", "def hash_code\n hash_code = {}\n self.seq.each do |letter|\n hash_code.keys.include?(letter) ? hash_code[letter] += 1 : hash_code[letter] = 1\n end\n hash_code\n end", "def averages(grade_hash)\n# a_new_hash = my_hash.inject({}) { |h, (k, v)| h[k] = v.upcase; h }\naverages = grade_hash.inject({}) { |h, (k,v)| h[k] = v.reduce{|x,n| x += n}/v.length ; h}\nend", "def percentage\n if @total > 0\n percent = {}\n @count_per_type.each { |k, v| percent[k] = (v / @total.to_f) * 100.0 }\n {\"percent\" => percent, \"total\" => @total}\n end\n end", "def calculate_percentage(string) #def calculate_percentage(\"Aand\")\n characters = sanitize(string) #characters = sanitize(\"Aand\") --> {\"a\" => 2, \"n\" => 1, \"d\" => 1}\n characters.each do |letter, count| #|a, 2| |n, 1| |d,2|\n characters[letter] = count.to_f/string.length # 2/4 1/4 1/4\n end\nend", "def amino_acid_mass_hash\n {\n \"G\" => 57, \"A\" => 71, \"S\" => 87, \"P\" => 97, \"V\" => 99,\n \"T\" => 101, \"C\" => 103, \"I\" => 113, \"L\" => 113, \"N\" => 114,\n \"D\" => 115, \"K\" => 128, \"Q\" => 128, \"E\" => 129, \"M\" => 131,\n \"H\" => 137, \"F\" => 147, \"R\" => 156, \"Y\" => 163, \"W\" => 186,\n }\n end", "def letter_percentages(str)\n percentages = {}\n str_length = str.length.to_f\n\n percentages[:lowercase] = ((str.count('a-z') / str_length) * 100).round(1)\n percentages[:uppercase] = ((str.count('A-Z') / str_length) * 100).round(1)\n percentages[:neither] = 100 - percentages[:lowercase] - percentages[:uppercase]\n\n percentages\nend", "def achievements_percentage\n @achievements.size.to_f / @schema.achievements.size\n end", "def letter_percentages(string)\n total_count = string.size\n character_hash = {}\n\n character_hash[:lowercase] = (string.count(\"a-z\").to_f / total_count) * 100\n character_hash[:uppercase] = (string.count(\"A-Z\").to_f / total_count) * 100\n character_hash[:neither] = (string.count(\"^a-zA-Z\").to_f / total_count) * 100\n\n character_hash\nend", "def achievements_percentage\n achievements_done.to_f / @achievements.size\n end", "def obtener_promedio(hash)\n hash.values.inject(0) { |sum, n| sum + n }.to_f / hash.length\nend", "def promo_code_percent_total\n applied_codes.select {|h| h[:type] == :percentage}.map {|h| h[:amount]}.flatten.reduce(:+).to_i || 0\n end", "def auction_percentage_hash_help(custom_id, auction_id)\n rtn = {\"\" => \"(空白)\"}\n i = 10\n # get current percentage\n currentCustom = Custom.select(:percentage).where(custom_id: custom_id).where(auction_id: auction_id).first\n currentPercentage = 0\n currentPercentage = currentCustom.percentage unless (currentCustom.nil? || currentCustom.percentage.nil?)\n # caculate percentage\n per = 100 - Custom.where(auction_id: auction_id).sum(:percentage).to_i\n per = per > currentPercentage ? per : currentPercentage if currentPercentage > 0\n while i <= per and i < 100 do\n thash = {i.to_s => percentage_hash_help[i.to_s]}\n rtn.merge! thash\n i += 10\n end\n return rtn\n end", "def linearpeptide_score_with_amino_acids(peptide, spectrum, amh)\n # Given a linear peptide Peptide and a spectrum Spectrum, we define LinearScore(Peptide, Spectrum) \n # as the number of masses shared between Linearspectrum(Peptide) and Spectrum. \n\n # Cyclopeptide Scoring Problem: Compute the score of a cyclic peptide against a spectrum.\n # Input: An amino acid string Peptide and a collection of integers Spectrum. \n # Output: The score of Peptide against Spectrum, Score(Peptide, Spectrum). \n\n theoretical_spectrum = linear_spectrum_with_amino_acids(peptide, amh)\n ts_h = array_to_count_hash(theoretical_spectrum)\n es_h = array_to_count_hash(spectrum)\n\n score = 0\n es_h.keys.each do |mass|\n if ts_h.has_key?(mass)\n # If the experimental spectrum has fewer instances of the same mass than theoritical spectrum use that one\n # to calculate the score but if experimental spectrum has more count of the same mass we should be using\n # the count in the theoritical spectrum\n if es_h[mass] <= ts_h[mass]\n score += es_h[mass]\n else\n score += ts_h[mass]\n end\n end\n end\n return score\n end", "def letter_percentages(str)\n hsh = { lowercase: 0, uppercase: 0, neither: 0 }\n\n str.chars.each do |elem|\n if elem =~ /[a-z]/\n hsh[:lowercase] += 1\n elsif elem =~ /[A-Z]/\n hsh[:uppercase] += 1\n else\n hsh[:neither] += 1\n end\n end\n hsh.transform_values! { |v| format('%.1f', v.fdiv(str.length) * 100).to_f }\nend", "def assignment_average_score(grade_hash, assignment_num)\n sum, n = 0, 0\n grade_hash.each do |k,v|\n n += 1\n sum += v[assignment_num-1]\n end\n return sum/n\nend", "def assignment_average_score(grade_hash, assignment_num)\n marks = assignment_scores(grade_hash, assignment_num)\n marks.sum / marks.length\nend", "def completion_percentage\n fields = %w(first_name last_name address postal_code city country birthday phone_number avatar.present? )\n sum_add = 100.0 / fields.count\n fields.inject(0) { |sum, field| sum + (field.split('.').inject(self) { |us, o| us.send(o) }.blank? ? 0 : sum_add) }.round.to_i\n end", "def letter_percentages(str)\n percentages = {}\n percentages[:lowercase] = (str.count('a-z').to_f / str.size) * 100\n percentages[:uppercase] = (str.count('A-Z').to_f / str.size) * 100\n percentages[:neither] = (str.count('^A-Za-z').to_f / str.size) * 100\n percentages\nend", "def letter_percentages(string)\n\n percent_hash = { lowercase: [], uppercase: [], neither: [] }\n counts = { lowercase: 0, uppercase: 0, neither: 0 }\n characters = string.chars\n\n counts[:lowercase] = characters.count { |ch| ch =~ /[a-z]/ }\n counts[:uppercase] = characters.count { |ch| ch =~ /[A-Z]/ }\n counts[:neither] = characters.count { |ch| ch =~ /[^A-Za-z]/ }\n\n percent_hash[:lowercase] = format(\"%0.2f\", (counts[:lowercase] / string.size.to_f) * 100)\n percent_hash[:uppercase] = format(\"%0.2f\", (counts[:uppercase] / string.size.to_f) * 100)\n percent_hash[:neither] = format(\"%0.2f\", (counts[:neither] / string.size.to_f) * 100)\n percent_hash\nend", "def assignment_average_score(grade_hash, assignment_score)\n sum = 0\n grade_hash.each do |key, value|\n sum += value[assignment_score - 1]\n end\n average = sum / grade_hash.keys.length\n average\nend", "def assignment_average_score(grade_hash, assignment_num)\n assignment_score = grade_hash.map do |key, value|\n value [assignment_num - 1]\n end\n total = assignment_score.reduce do |total, grade|\n total += grade\n end\n total / assignment_score.length\nend", "def letter_percentages(string)\n case_hash = { lowercase: 0, uppercase: 0, neither: 0 }\n\n string.each_char do |char|\n case\n when char =~ /[A-Z]/ then case_hash[:uppercase] += 1\n when char =~ /[a-z]/ then case_hash[:lowercase] += 1\n else case_hash[:neither] += 1\n end\n end\n\n characters = string.length.to_f\n case_hash.keys.each do |key|\n case_hash[key] /= characters\n case_hash[key] *= 100\n end\n\n case_hash\nend", "def percentage_abd\r\n\t\t\t\tall_survivors = Survivor.count()\r\n\t\t\t\tabd_survivors = Survivor.where(abducted: true).count\r\n\t\t\t\tpercentage = (abd_survivors.to_f/all_survivors.to_f) * 100\r\n\t\t\t\trender json: {status: 'SUCCESS', message:'Porcentagem de sobreviventes Abduzidos', percentage:percentage},status: :ok\r\n\t\t\tend", "def peptide_mass_with_amino_acids(peptide, amh)\n mass = 0\n peptide.chars.each do |pep|\n mass += amh[pep]\n end\n return mass\n end", "def progress_percentage\n total_amount = 0\n # proceed_amount = 0\n total_amount = card_sub_tasks.map(&:service_card_count).reduce(:+)\n # card_sub_tasks.each do |card_sub_task|\n # if card_sub_task.proceed == CardSubTask::PROCEED_FINISHED || card_sub_task.proceed == CardSubTask::PROCEED_ERROR\n # proceed_amount += card_sub_task.service_card_count\n # elsif card_sub_task.proceed == CardSubTask::PROCEED_PROCESSING\n # proceed_amount += card_sub_task.service_cards.count\n # end\n # end\n return percentagere = \"#{sprintf(\"%.1f\", proceed_amount.to_i / total_amount.to_f * 100)}%\"\n end", "def letter_percentages(string)\n lowercase = 0.0\n uppercase = 0.0\n neither = 0.0\n string.each_char do |char|\n if char.upcase == char && char.downcase == char\n neither += 1\n elsif char.downcase == char\n lowercase += 1\n else\n uppercase += 1\n end\n end\n\n l_perc = ((lowercase / string.size) * 100).round(2)\n u_perc = ((uppercase / string.size) * 100).round(2)\n n_perc = ((neither / string.size) * 100).round(2)\n\n { lowercase: l_perc, uppercase: u_perc, neither: n_perc }\nend", "def assignment_average_score(grade_hash, assignment_num)\n grade_hash\n .map { |key, value| value[assignment_num -1] }\n .reduce(:+) / grade_hash.length\nend", "def pProteina \n\t\tprot = 0\n\t\ttotal = 0\n\t\t@platos.each do |alimento|\n\t\t\ttotal += (alimento.proteinas + alimento.lipidos + alimento.carbohidratos)\n\t\t\tprot += alimento.proteinas\n\t\tend\n\t\treturn ((prot/total)*100).round\t\n\tend", "def schluessel_pro_wert(a_hash)\n result = {}\n a_hash.each { |key, val|\n val.each { |v| \n result[v] = 0 if !result.has_key?(v)\n result[v] += 1\n }\n }\n result\nend", "def averages(grade_hash)\n grade_hash.transform_values{|v| v.inject(:+)/v.length}\n # hash = {}\n # grade_hash.map do |name, grades|\n # score = 0\n # grades.each do |grade|\n # score += grade\n # end\n # average = score/grades.length\n # hash[name] = average\n # end\n # hash\n # sum = 0\n # grade_hash.each { |x| sum += x }\n # average = sum/grade_hash.length\nend", "def calculate_completeness_score\n total = 0.0\n counted = 0.0\n fields.keys.each do |key|\n total += 1\n if self[key]\n counted += 1\n end\n end\n\n write_attributes(completeness_score: counted / total)\n end", "def estimate_authority_score(guid,authority)\n out_degrees,in_degrees = @driver.degrees\n weight = 1.0\n if @driver.out_link?(guid)\n weight += 1.0/out_degrees\n end\n weight += @driver.directs(guid).to_f/@driver.total_directs\n weight * authority\n end", "def base_composition\n if @base_composition\n return @base_composition\n end\n # else run the C method\n composition(@seq.seq)\n alphabet = ['a', 'c', 'g', 't', 'n']\n @base_composition = {}\n @dibase_composition = {}\n bases = []\n dibases = []\n alphabet.each do |c|\n bases << \"#{c}\".to_sym\n end\n alphabet.each do |c|\n alphabet.each do |d|\n dibases << \"#{c}#{d}\".to_sym\n end\n end\n bases.each_with_index do |a,i|\n @base_composition[a] = base_count(i)\n end\n dibases.each_with_index do |a,i|\n @dibase_composition[a] = dibase_count(i)\n end\n return @base_composition\n end", "def hiv_protease(aa_array,start_aa=1)\n out_hash = {}\n sdrm = {}\n sdrm[23] = ['L',['I']]\n sdrm[24] = ['L',['I']]\n sdrm[30] = ['D',['N']]\n sdrm[32] = ['V',['I']]\n sdrm[46] = ['M',['I','L','V']]\n sdrm[47] = ['I',['V','A']]\n sdrm[48] = ['G',['V','M']]\n sdrm[50] = ['I',['V','L']]\n sdrm[53] = ['F',['L']]\n sdrm[54] = ['I',['V','L','M','T','A','S']]\n sdrm[73] = ['G',['S','T','C','A']]\n sdrm[76] = ['L',['V']]\n sdrm[82] = ['V',['A','T','S','F','L','C','M']]\n sdrm[83] = ['N',['D']]\n sdrm[84] = ['I',['V','A','C']]\n sdrm[85] = ['I',['V']]\n sdrm[88] = ['N',['D','S']]\n sdrm[90] = ['L',['M']]\n aa_length = aa_array.size\n end_aa = start_aa + aa_length - 1\n (start_aa..end_aa).each do |position|\n array_position = position - start_aa\n if sdrm.keys.include?(position)\n wt_aa = sdrm[position][0]\n test_aa = aa_array[array_position]\n if test_aa.size == 1\n unless wt_aa == test_aa\n if sdrm[position][1].include?(test_aa)\n out_hash[position] = [wt_aa,test_aa]\n end\n end\n else\n test_aa_array = test_aa.split(\"/\")\n if (test_aa_array & sdrm[position][1])\n out_hash[position] = [wt_aa,test_aa]\n end\n end\n end\n end\n return out_hash\nend", "def percentage_add(hash_array)\n hash_array.each do |student|\n per = student[:marks]\n p per\n student[:percentage] = (per*100)/100\n end\nend", "def promedio(h)\n suma = h.values.inject(0) {|sum, x| sum + x}\n p suma\n suma / h.count.to_f\nend", "def assignment_average_score(grade_hash, assignment_num)\n grade_hash\n .map {|key, value| value[assignment_num - 1]}\n .reduce(:+) / grade_hash.length\nend", "def assignment_average_score(grade_hash, assignment_num)\n assignment = grade_hash.map do |key, value|\n value[assignment_num - 1]\n end\n\n sum = assignment.reduce do |sum, x|\n sum += x\n end\n\n sum / assignment.length\nend", "def final_letter_grades(grade_hash)\n letter_grade_array = grade_hash.map do |key, value|\n average = value.sum / value.length\n letter_grade = letter_grade(average)\n [key, letter_grade]\n end\n letter_grade_array.to_h\nend", "def competition_result_hash\n (\n person_id.hash ^\n (person_name.hash * 2) ^\n (place.hash * 3) ^\n (points.hash * 5) ^\n (team_id.hash * 7) ^\n (team_name.hash * 11)\n ).hash\n end", "def assignment_average_score(grade_hash, assignment_num)\n sum = 0\n grade_hash.each do |key, value|\n sum += grade_hash[key][assignment_num - 1]\n end\n average = sum / grade_hash.length\nend", "def compute_average_grade\n total = 0.0\n self.fcqs.compact.each {|x| next if x.avg_grd == nil; total += x.avg_grd}\n count = courses_taught\n if count == 0\n return 1.0 \n else\n return (total.to_f / count.to_f)\n end\n end", "def assignment_average_score(grade_hash, assignment_num)\n a = []\n grade_hash.values.each { |dude| a.push(dude[assignment_num - 1]) }\n sum = a.sum\n average = sum/a.length\nend", "def consolidate_age(hash)\n c_10 = 0; c_20 = 0; c_30 = 0\n c_40 = 0; c_50 = 0; c_60 = 0\n c_70 = 0; c_invalid = 0\n hash.each do |k,v|\n case k\n when \"NA\"\n c_invalid+= v\n when 0..30\n c_10 += v\n when 30..50\n c_20 += v\n when 50..70\n c_30 += v\n when 70..200\n c_70 += v\n else\n c_invalid += 1\n end\n end\n {\"Under 30\" => c_10, \"30-49\" => c_20,\"50-69\" => c_30,\"70 and older\" => c_70, \"NA or Invalid\" => c_invalid}\nend", "def percentages\n colors = []\n students.each do |student|\n student.evaluations.each do |evaluation|\n colors << evaluation.color\n end\n end\n\n if !colors.empty?\n {\n green: (colors.count(1) * 100) / colors.size ,\n yellow: (colors.count(2) * 100) / colors.size,\n red: (colors.count(3) * 100) / colors.size\n }\n else\n {}\n end\n end", "def class_average(grade_hash)\n scores = averages(grade_hash)\n result = 0\n scores.each {|k,v| result += v}\n result /= scores.length\nend", "def final_letter_grades(grade_hash)\n letter_grade averages grade_hash\nend", "def class_average(grade_hash)\n sum, n = 0, 0\n grade_hash.each do |k,array|\n array.each do |grade|\n n += 1\n sum += grade\n end\n end\n return sum/n\nend", "def total_score(account,assign)\n total_sum = 0.00\n categories = score_categories(account,assign)\n non_null = 0\n\n p categories\n categories.each do |k,v|\n k == \"skills\" && v != 0 ? total_sum += v[:total_skills] : total_sum += v\n get_assoc(assign,k).size > 0 ? non_null +=1 : non_null = non_null\n end\n return total_sum/non_null\n end", "def total_score_skill(account,assign)\n score_categories = score_skills_assign(account,assign)\n sum = 0.00\n categories = (assign.skills.map{|h| h.category}).uniq\n\n score_categories.each do |k,v|\n sum += v\n end\n\n total = sum / categories.size\n end", "def porcentaje_proteinas\n recorrido = lista_alimentos.head\n acumulador = 0\n porcentaje = 0\n\n while recorrido != nil\n acumulador = acumulador + recorrido.value.proteinas + recorrido.value.carbohidratos + recorrido.value.lipidos\n porcentaje = porcentaje + recorrido.value.proteinas\n\n recorrido = recorrido.next\n end\n\n ((porcentaje * 100)/acumulador).round(2)\n end", "def percentage; end", "def carbsPercent()\n\t\t\t\tplato = @alimentsList.head\n\t\t\t\tgrams = @gramsList.head\n\t\t\t\ttotalEnergy = 0.0\n\t\t\t\ttotalCarbsEnergy = 0.0\n\n\t\t\t\twhile plato != nil\n\t\t\t\t\ttotalEnergy += (plato.value.get_energia * grams.value) / 100\n\t\t\t\t\ttotalCarbsEnergy += (plato.value.get_energia_carbs * grams.value) / 100\n\n\t\t\t\t\tplato = plato.next\n\t\t\t\t\tgrams = grams.next\n\t\t\t\tend\n\n\t\t\t\treturn (totalCarbsEnergy * 100) / totalEnergy\n\t\t\tend", "def total_score_location(account,assign)\n common = (assign.locations & account.locations).size\n total = assign.locations.size\n return (common * 100.00) / total\n end", "def assignment_average_score(grade_hash, assignment_num)\n assignment = grade_hash.map {|x| x[1][assignment_num-1]}\n average = assignment.reduce{|x,n| x += n}/assignment.length\nend", "def proteinsPercent()\n\t\t\t\tplato = @alimentsList.head\n\t\t\t\tgrams = @gramsList.head\n\t\t\t\ttotalEnergy = 0.0\n\t\t\t\ttotalProteinsEnergy = 0.0\n\n\t\t\t\twhile plato != nil\n\t\t\t\t\ttotalEnergy += (plato.value.get_energia * grams.value) / 100\n\t\t\t\t\ttotalProteinsEnergy += (plato.value.get_energia_proteins * grams.value) / 100\n\n\t\t\t\t\tplato = plato.next\n\t\t\t\t\tgrams = grams.next\n\t\t\t\tend\n\n\t\t\t\treturn (totalProteinsEnergy * 100) / totalEnergy\n\t\t\tend", "def commitment_score commitment\n \n commitment_score = {}\n activity_count = commitment.activities.count\n \"-------------- #{activity_count} ---------------\"\n commitment.activities.each do |activity|\n @activity = activity.as_json\n @attendance = get_members_attendance(@activity)\n\n @attendance.each do |member, attendance| \n if commitment_score[member] && attendance == true\n commitment_score[member] += 100\n elsif commitment_score[member] && attendance == false\n commitment_score[member] += 0\n elsif !commitment_score[member] && attendance == false\n commitment_score[member] = 0\n else \n commitment_score[member] = 100\n end\n end\n end\n\n commitment_score.each do |member, attendance|\n commitment_score[member] = attendance / activity_count\n end\n\n return commitment_score\n\n end", "def class_average(grade_hash)\n averages = averages(grade_hash)\n sum = 0\n\n averages.map do |key, value|\n sum += value\n end\n\n sum / averages.length\nend", "def averages(grade_hash)\n grade_hash.transform_values { |marks| marks.inject {|sum, n| sum + n } / marks.length }\nend", "def profile_completeness_percent\n Cache.get(['profile_c', self], nil, true){\n total = completed = 0.0\n self.profile_elements.each do |element, is_completed|\n total += 1.0\n completed += 1.0 if is_completed\n end\n (completed / total).round(2)\n }.to_f\n end", "def percentages\n @_percentages ||= words.each_with_object({}) do |word_count, hash|\n hash[word_count.first] = percentage(word_count.last)\n end\n end", "def grade_percentage\n # This is the total number of tests a student (self) has taken.\n student_tests = BoatingTest.all.select do |test|\n test.student == self\n end\n\n # From the total number of tests taken by that student (self), we just want\n # the one's that have passed.\n passed_test = student_tests.select do |test|\n test.status == \"passed\"\n end\n # From the total number of tests taken by that student (self), we just want\n # the one's that have failed.\n failed_test = student_tests.select do |test|\n test.status == \"failed\"\n end\n\n # Now we need to find the percent of tests that this student (self) has\n # passed compared to the total number of tests they have taken.\n # Multiply by 100 to get a % value instead of decimal.\n # ratio = (passed_test.length.to_f)/(student_tests.length)\n # ratio * 100 SAME AS BELOW\n ratio = \"%.2f\" % (passed_test.length.fdiv(student_tests.length)*100).to_s + \"%\"\n # The \"%.2f\"\n end", "def codon_usage\n rewind\n\n total_usage = {}\n\n each do |e|\n Bio::Sequence::NA.new(e.seq).codon_usage.each do |c, count|\n aa = Bio::Sequence::NA.new(c).translate\n total_usage[aa] ||= {}\n total_usage[aa][c.upcase] ||= 0\n total_usage[aa][c.upcase] += count\n end\n end\n\n rewind\n\n total_usage\n end", "def get_percentage(lines_hit, lines_found, bold=false)\n perc = lines_hit.to_f / lines_found.to_f * 100.0\n color = case when perc >= 90; 32 when perc >= 75; 33 else 31 end\n if bold then color = \"1;#{color}\" end\n perc = perc.finite? ? format('%5.1f%%', perc) : ' ' * 6\n perc = \"\\x1b[#{color}m#{perc}\\x1b[0m\" if @options[:color] and color\n perc\n end", "def calculate_on_base_percentage\n #if (hits.nil? || walks.nil? || hit_by_pitch.nil? || at_bats.nil? || hit_by_pitch.nil? || sacrifice_flies.nil?)\n # pp self.attributes\n #end\n return (self.hits.to_f+self.calculate_bases_on_balls+self.hit_by_pitch.to_f).to_f/(self.at_bats.to_f+self.calculate_bases_on_balls+self.hit_by_pitch.to_f+self.sacrifice_flies.to_f).to_f\n end", "def percentage_grades_array(assignment)\n groupings = assignment.groupings\n .joins(:tas)\n .where(memberships: { user_id: id })\n grades = []\n\n if assignment.assign_graders_to_criteria\n criteria_ids = self.criterion_ta_associations.where(assessment_id: assignment.id).pluck(:criterion_id)\n out_of = criteria_ids.sum do |criterion_id|\n Criterion.find(criterion_id).max_mark\n end\n return [] if out_of.zero?\n\n mark_data = groupings.joins(current_result: :marks)\n .where('marks.criterion_id': criteria_ids)\n .where.not('marks.mark': nil)\n .pluck('results.id', 'marks.mark')\n .group_by { |x| x[0] }\n mark_data.values.each do |marks|\n next if marks.empty?\n\n subtotal = 0\n has_mark = false\n marks.each do |_, mark|\n subtotal += mark\n has_mark = true\n end\n grades << subtotal / out_of * 100 if has_mark\n end\n else\n out_of = assignment.max_mark\n groupings.includes(:current_result).find_each do |grouping|\n result = grouping.current_result\n unless result.nil? || result.total_mark.nil? || result.marking_state != Result::MARKING_STATES[:complete]\n percent = calculate_total_percent(result, out_of)\n unless percent == BLANK_MARK\n grades << percent\n end\n end\n end\n end\n grades\n end", "def calculate_total_percent(result, out_of)\n total = result.total_mark\n\n percent = BLANK_MARK\n\n # Check for NA mark or division by 0\n unless total.nil? || out_of == 0\n percent = (total / out_of) * 100\n end\n percent\n end", "def calculate_total_percent(result, out_of)\n total = result.total_mark\n\n percent = BLANK_MARK\n\n # Check for NA mark or division by 0\n unless total.nil? || out_of == 0\n percent = (total / out_of) * 100\n end\n percent\n end", "def account_percentage_amount( acc_percent = nil )\n tot_cost = 0.0 # init result\n if self.patient.is_a_firm?\n acc_percent ||= AppParameterCustomizations.get_receipt_account_percent()\n tot_cost += self.price * acc_percent.to_f / 100.0\n end\n return tot_cost\n end", "def covered_percent\n return 100.0 if empty? || lines_of_code.zero?\n\n Float(covered_lines * 100.0 / lines_of_code)\n end", "def hcv_ns5a(aa_array,start_aa=1)\n out_hash = {}\n sdrm = {}\n sdrm[28] = ['M',['T']]\n sdrm[30] = ['L',['H','K','R','Q','A','S','D']]\n sdrm[31] = ['L',['M','V','F']]\n sdrm[32] = ['P',['L']]\n sdrm[44] = ['K',['R']]\n sdrm[58] = ['H',['D','P','S']]\n sdrm[64] = ['T',['A','S']]\n sdrm[77] = ['P',['A','S']]\n sdrm[78] = ['R',['K']]\n sdrm[79] = ['T',['A']]\n sdrm[83] = ['T',['M']]\n sdrm[85] = ['S',['N','H','Y']]\n sdrm[92] = ['A',['P','T','K','E']]\n sdrm[93] = ['Y',['C','F','H','N']]\n sdrm[107] = ['K',['T','S']]\n sdrm[121] = ['I',['V']]\n sdrm[135] = ['T',['A']]\n aa_length = aa_array.size\n end_aa = start_aa + aa_length - 1\n (start_aa..end_aa).each do |position|\n array_position = position - start_aa\n if sdrm.keys.include?(position)\n wt_aa = sdrm[position][0]\n test_aa = aa_array[array_position]\n if test_aa.size == 1\n unless wt_aa == test_aa\n if sdrm[position][1].include?(test_aa)\n out_hash[position] = [wt_aa,test_aa]\n end\n end\n else\n test_aa_array = test_aa.split(\"/\")\n if (test_aa_array & sdrm[position][1])\n out_hash[position] = [wt_aa,test_aa]\n end\n end\n end\n end\n return out_hash\nend", "def averages(grade_hash)\n\n averages = grade_hash.map do |key, value|\n total = 1\n sum = grade_hash[key].reduce do |sum, grade|\n total += 1\n sum += grade\n end\n avg = sum / total\n [key, avg]\n end\n\n averages.to_h\nend", "def prop_a\n bases_a / length.to_f\n end", "def letter_percentages(string)\n low, up, non = [0, 0, 0]\n\n string.each_char do |chr|\n case chr\n when /[a-z]/ then low += 1\n when /[A-Z]/ then up += 1\n else non += 1\n end\n end\n\n convert = 100 / string.size.to_f\n low *= convert\n up *= convert\n non *= convert\n\n percentages = { lowercase: low, uppercase: up, neither: non}\nend", "def pick_percentage\n self.score.to_f / Matchup.amount_finished.to_f\n end", "def profile_completion\n percentage = 0\n percentage += 25 if self.full_name.present?\n percentage += 25 if self.has_avatar? and self.city\n percentage += 25 if self.subjects.any?\n percentage += 25 if self.favorites.any?\n percentage\n end", "def prot\n\t\tgrtotal = 0\n\t\tsum = 0\n\t\t#itera en las dos listas a la vez para poder calcular las\n\t\t#proteinas dependiendo de la cantidad y tambien suma\n\t\t#todas las cantidades para poder calcular el porcentaje\n\t\t#despues\n\t\t@lista.zip(@listagr).each do |normal, gr|\n\t\t\tgrtotal += gr\n\t\t\tcant = gr/1000.0\n\t\t\tsum += normal.prot*cant \n\t\tend\n\t\t(sum*100)/grtotal\n\tend", "def assignment_average_score(grade_hash, assignment_num)\n (grade_hash.values.transpose[assignment_num - 1].reduce { |acc, num| acc + num }.to_f / 10).floor\nend", "def convert_fasta_array_to_hash(fasta_array)\n fasta_hash = Hash.new\n\n fasta_array.each do |fasta_sequence|\n query = Bio::FastaFormat.new( fasta_sequence )\n aa_sequence_definition = parse_definition(query.definition)\n fasta_hash[aa_sequence_definition[0].strip] = query.to_seq.seq\n end\n\n return fasta_hash\n end", "def final_letter_grades(grade_hash)\n averages = averages(grade_hash)\n\n final_grades = averages.map do |key, value|\n [key, letter_grade(value)]\n end\n\n final_grades.to_h\nend", "def convert_to_permissions_hash(ace)\n return {} if ace.nil?\n\n sid = ace.sid\n identity = sid_to_name(sid)\n rights = get_ace_rights_from_mask(ace)\n ace_type = get_ace_type(ace)\n child_types = get_ace_child_types(ace)\n affects = get_ace_propagation(ace)\n is_inherited = ace.inherited?\n { 'identity' => identity.to_s, 'id' => sid.to_s, 'rights' => rights,\n 'perm_type' => ace_type, 'child_types' => child_types,\n 'affects' => affects, 'is_inherited' => is_inherited,\n 'mask' => ace.mask.to_s }\n end", "def activity_year_fractions_hash(activity)\n year_fractions = {}\n total_activity_days = activity.endDate - activity.startDate # Cannot be zero, by :validDate\n range_start = activity.startDate\n while range_start.year < activity.endDate.year\n range_end = Date.new(range_start.year + 1)\n year_fractions[range_start.year] = ((range_end - range_start) / total_activity_days)\n range_start = range_end\n end\n year_fractions[range_start.year] = ((activity.endDate - range_start) / total_activity_days)\n year_fractions\n end", "def class_average(grade_hash)\n averages(grade_hash).map{|k, v| v}.inject {|sum, n| sum + n } / grade_hash.length\nend", "def por_proteinas\n\t\taux_proteinas = 0.0\n\t\ti = 0\n\t\twhile i < @lista_alimentos.size do\n\t\t\taux_proteinas += @lista_alimentos[i].proteinas * @lista_cantidades[i]\n\t\t\ti+=1\n\t\tend\n\t\treturn ((aux_proteinas/total_nutrientes)*100.0).round(2) \n\tend", "def get_comps_avg\n # p self.property.zillowId\n comps ||= Rubillow::PropertyDetails.deep_comps( {zpid: self.property.zillowId, count: 3} )\n # p comps.principal.zpid\n # p comps.comparables.size\n comp_list = []\n comps.comparables.each do |c|\n comp_list << (c.last.price.to_f/c.last.finished_square_feet.to_f)\n # p c.last.price\n # p \"-\" + c.last.finished_square_feet\n end unless !comps.success?\n #take the sum of\n self.comp_avg_per_sq_ft = comp_list.inject{ |sum, el| sum + el }.to_f / comp_list.size\n # p self.comp_avg_per_sq_ft.to_f\n end", "def calculate_profile_percentage\n fields = ['gender', 'seeking', 'min_age', 'max_age', 'address_zip', 'address_country',\n 'biography', 'occupation', 'education', 'ethnicity', 'religion', 'likes', 'search_radius',\n 'photos', 'birthday', 'address_state', 'address_city', 'distance_type', 'marital_status', 'outdoor_activities', 'health_fitness',\n 'children', 'drinking', 'eating', 'politics', 'reading', 'nightlife', 'travel', 'career'\n ]\n percent = (filled_in_fields(fields) / fields.size).round(2) * 100\n self.percent_complete = percent.to_i\n end", "def calculate_slugging_percentage\n return (self.bases().to_f)/(at_bats.to_f)\n end" ]
[ "0.57860136", "0.5707039", "0.5654985", "0.5577412", "0.55692405", "0.5556035", "0.5485852", "0.5466409", "0.5452387", "0.54397494", "0.53883076", "0.5377612", "0.5369018", "0.53582907", "0.5344103", "0.5330651", "0.5329907", "0.5329273", "0.5324464", "0.5321181", "0.53096193", "0.5303717", "0.5288017", "0.5278621", "0.52629244", "0.5262242", "0.5231952", "0.52169186", "0.5216043", "0.51789945", "0.5172142", "0.51708615", "0.5169624", "0.514731", "0.51461345", "0.51443046", "0.5141314", "0.51406515", "0.51405364", "0.5127713", "0.5125323", "0.5112341", "0.50857425", "0.50774384", "0.50759923", "0.50753105", "0.506834", "0.5061642", "0.5039725", "0.5024647", "0.5016043", "0.50068456", "0.5005839", "0.50042707", "0.5000645", "0.4995389", "0.49953136", "0.49942112", "0.49858132", "0.4966674", "0.4961442", "0.49487934", "0.4944585", "0.4941225", "0.49401027", "0.49374503", "0.49260947", "0.4923671", "0.49217215", "0.49211687", "0.4908663", "0.4908247", "0.49042243", "0.49012625", "0.48947427", "0.48939058", "0.48922747", "0.48909602", "0.48822543", "0.48713055", "0.48713055", "0.4868658", "0.48681322", "0.4863212", "0.48601732", "0.48577023", "0.48509654", "0.48435506", "0.48431447", "0.48425266", "0.48350638", "0.4833165", "0.4832714", "0.48225522", "0.48127067", "0.48088384", "0.47994712", "0.47987214", "0.47970408", "0.47950265" ]
0.68882215
0
Return proc calculating charge of a residue.
def charge_proc positive, pK, num if positive lambda {|ph| num.to_f / (1.0 + 10.0 ** (ph - pK)) } else lambda {|ph| (-1.0 * num.to_f) / (1.0 + 10.0 ** (pK - ph)) } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def charge\n subtotal * 0\n end", "def charge\n ((sprintf(\"%.1f\", (\n $ioreg_return.split(' = ')[15].strip.split(\"\\n\")[0].to_f / $ioreg_return.split(' = ')[9].strip.split(\"\\n\")[0].to_f )\n )).to_f*100).to_i\n end", "def theoretical_pI\n charges = []\n residue_count().each do |residue|\n charges << charge_proc(residue[:positive],\n residue[:pK],\n residue[:num])\n end\n round(solve_pI(charges), 2)\n end", "def charge_at_pH(pep_charges, pH)\n\tcharge = 0\n\tcharge += -1/(1+10**(pep_charges.c_term-pH))\n\tcharge += -pep_charges.d_num/(1+10**(ResidueTable[:D][2]-pH))\n\tcharge += -pep_charges.e_num/(1+10**(ResidueTable[:E][2]-pH))\n\tcharge += -pep_charges.c_num/(1+10**(ResidueTable[:C][2]-pH))\n\tcharge += -pep_charges.y_num/(1+10**(ResidueTable[:Y][2]-pH))\n\tcharge += 1/(1+10**(pH - pep_charges.n_term))\n\tcharge += pep_charges.h_num/(1+10**(pH-ResidueTable[:H][2]))\n\tcharge += pep_charges.k_num/(1+10**(pH-ResidueTable[:K][2]))\n\tcharge += pep_charges.r_num/(1+10**(pH-ResidueTable[:R][2]))\n\tcharge\nend", "def parent_ion_mass(charge=1)\r\n (mass(nterm) + ladder.last + mass(cterm) + charge * proton_mass)/charge\r\n end", "def get_charge\n @charge\n end", "def formal_charge\r\n\t\tif root?\r\n\t\t\tlewis_electrons = 0\r\n\t\telse #if an element is not the root, it is bonded to another element, thus increase the formal charge count by 1\r\n\t\t\tlewis_electrons = 1\r\n\t\tend\r\n\t\t# if the element has nodes, look at each one\r\n\t\tif nodes?\r\n\t\t\tnodes.each { |node|\r\n\t\t\t\tif node == nil # if the node is unbonded, add 2\r\n\t\t\t\t\tlewis_electrons += 2\r\n\t\t\t\telse # if it is bonded, add 1\r\n\t\t\t\t\tlewis_electrons += 1\r\n\t\t\t\tend\r\n\t\t\t}\r\n\t\tend\r\n\t\t# return the valence count - the lewis count (definition of formal charge)\r\n\t\treturn PeriodicTable.valence(element) - lewis_electrons\r\n\tend", "def car\n\t\tsuma = 0\n\t\tx = 0\n\t\tcantidad = 0\n\n\t\t@alimentos.each do |i|\n\t\t\tcantidad = @gramos[x].valor / (i.proteinas + i.lipidos + i.carbohidratos)\n\t\t\tsuma += i.carbohidratos * cantidad\n\t\t\tx += 1\n\t\tend\t\n\n\t\treturn ((suma * 100) / gramos_total).round(2)\n\tend", "def calculate_charge\n # XXX Need to select correct locations record once we support > 1 location\n # XXX Need to select the correct seat_rate for the location\n (total_time / 60.0) * Location.first.seat_rates.first.dollars_per_minute\n end", "def calMass(mass, charge)\n (mass + (charge.to_f * 1.00727646677)) / charge\n end", "def calMass(mass, charge)\n (mass + (charge.to_f * 1.00727646677)) / charge\n end", "def next_charge\n ( pre_finalised_quote * relative_progress / 100 ) - charged_so_far\n end", "def calcularComprimento(raio)\n return calcularDiametro(raio) * Math::PI\nend", "def energy_pcf\n energy_from_protein +\n energy_from_carbs +\n energy_from_fat\n end", "def perc\n rfd / (rfd + 1)\n end", "def calculoComprimento(raio)\n return calculoDiametro(raio) * Math::PI\nend", "def charge_fee\r\n\t\tif_member = Participant.find_by(participantID: participantID)\r\n\t\tif_course = Course.find_by(courseID: courseID)\r\n\t\t\r\n\t\tif if_course != nil && if_member != nil\r\n\t\t\tearlyBirdTime = if_course.startDate.months_ago(1)\r\n\t\t\tif if_member.expirydate > Date.today\r\n\t\t\t\tif Date.today >= earlyBirdTime && Date.today < if_course.startDate\r\n\t\t\t\t\treturn if_course.earlybirdPrice\r\n\t\t\t\telse\r\n\t\t\t\t\treturn if_course.memberPrice\r\n\t\t\t\tend\r\n\t\t\telse\r\n\t\t\t\treturn if_course.nonmemberPrice\r\n\t\t\tend\r\n\t\tend\r\n\tend", "def charge\n if @charging\n stop_charging\n start_charging\n @charge\n else\n @charge\n end\n end", "def cost\n deductible * RATE\n end", "def cladder_series(charge=1, mod=nil)\r\n get_series(:cladder, charge, mod) do\r\n delta = mass(mod) + mass('H2O') + charge * proton_mass\r\n nterm_series(delta, charge)\r\n end\r\n end", "def charge(company_number, charge_id)\n client.get(\"company/#{company_number}/charges/#{charge_id}/\")\n end", "def new_charge\n end", "def experiMass(mass, charge, diff)\n ((mass + diff) + (charge.to_f * 1.00727646677)) / charge\n end", "def experiMass(mass, charge, diff)\n ((mass + diff) + (charge.to_f * 1.00727646677)) / charge\n end", "def calculate_shipping_charge\n return unless shipping_method = adjustment_source.shipping_method\n shipping_method.calculate_cost(adjustment_source)\n end", "def calculate_shipping_charge\n return unless shipping_method = adjustment_source.shipping_method\n shipping_method.calculate_cost(adjustment_source)\n end", "def charge_credit_card(params = {})\n request = token_request(payment_method: {\n type: 'card', register_card_token: 0\n })\n response = PaybywayConnector.auth_payment(request).parsed_response\n {\n result: response['result'],\n token: response['token'],\n amount: request[:amount],\n currency: request[:currency],\n payment_url: PaybywayConnector.charge_url\n }\n end", "def rule1\n (center_mass - self.position) * PCT_DAMPENER\n end", "def relacion_cc\n\t\t(ccintura / ccadera).round(2)\n\tend", "def calc_perc_carbohydrates\r\n alimentos = @food.collect { |x| x.carbohydrates }\r\n gramos = @quantities.collect { |x| x/100.0 }\r\n result = 0.0\r\n\r\n for i in 0...alimentos.size\r\n result += (gramos[i] * alimentos[i]) * 4\r\n end\r\n result /= @vct\r\n end", "def gc\n s = codons.map { |c| c.nuc_codon[2] }.join\n ((s.count('G')+s.count('C')).to_f/codons.count).round(4)\n end", "def charge_type\n if is_tax\n return 10\n elsif description.include?('Refund for')\n return 5\n elsif description.include?('Cancellation fee')\n return 11\n end\n case charge.charge_type\n when 'booking'\n 3\n when 'fuel'\n 6\n when 'cleaning'\n 7\n when 'damage'\n 8\n when 'other'\n 9\n when 'security_deposit'\n 2\n when 'membership'\n 1\n when 'lesson'\n 4\n end\n end", "def fpc(sam,pop)\n Math::sqrt((pop-sam).quo(pop-1))\n end", "def sum_charges\n return (self.sum_produits_used)\n end", "def fixed_charges\n 20.0\n end", "def cost(certificate)\n company = certificate.company\n company.face_value || get_par_price(company) * certificate.num_shares\n end", "def fuel_cost\n ((amount * 100) / (mileage - predecessor.mileage)).round(1) if predecessor\n end", "def cost_of_cable(length)\n\t\tmeter = length * 0.01\n\t\tdollar = [meter * 0.4079 + 0.5771, meter * 0.0919 + 7.2745].min * BANDWIDTH\n\t\t(dollar * 100).round.to_f / 100\n\tend", "def mass\n @ob.get_exact_mass - (@ob.get_total_charge * Rubabel::MASS_E)\n end", "def charge_customer()\n array = find_films()\n # charge = ticket_cost\n for film in array\n result = @funds - film.price\n @funds = result\n end\n update\n end", "def por_carbo\n\t\t\t(@carbohidratos/suma_gramos)*100\n\t\tend", "def area_circ(rad) # Declaring the area_circ method (area_circ is a local variable) and let it accept a local variable rad\n return $Pie*rad**2 # Returning a calculated value using a global variable and a local Variable\nend", "def calculate_cbm\n @cbm = @bab + @str_modifier + @unarmed_prof\n @cbm_def = 10 + @bab + @str_modifier + @dex_modifier + @unarmed_prof\n end", "def ctof (degres)\n return ((degres * 1.8) + 32)\nend", "def reciprocal\nFraccionario.new(@den, @num)\nend", "def ctof(cel)\n cel * 9.0 / 5.0 + 32\nend", "def univ_fee_amount_to_charge()\n raise \"not a university\" if ! university\n payments.select(&:good?).empty? ? payments.first.amount : university.subscription_charge_for_n(univ_dvd_rate)\n end", "def rcc(c_cintura,c_cadera)\n\t\t@rcc = (c_cintura/c_cadera)\t\n\tend", "def get_cout_total\n if (self.comptable_null?)\n return (0)\n elsif (self.comptable_diff?)\n return (self.cout - self.sum_charges)\n elsif (self.comptable_total?)\n return (self.cout)\n end\n end", "def deduction(price, copoun_obj) \n if copoun_obj.deduction_type == \"percentage\"\n total_price = price * (copoun_obj.deduction_percentage / 100)\n else\n total_price = price - copoun_obj.deduction_amount\n end\n end", "def fuel_needed(mass)\n return (mass / 3) - 2\nend", "def deca\n big_self * DECA\n end", "def cac2\n 0\n end", "def ccf\n end", "def calculate_with_fuel\n s = 0\n res = calculate\n until res.zero?\n s += res\n @mass = res\n res = calculate\n end\n s\n end", "def cf\n\t\tself.buy ? (-self.amount-self.fee) : (self.amount - self.fee)\n\tend", "def sum_of_charges\n Transaction.where(card_id: self.id).sum(:amount)\n end", "def simplificar (fraccion)\n mcd = gcd(fraccion.numerador, fraccion.denominador)\n Fraccion.new( fraccion.numerador/mcd , fraccion.denominador/mcd)\n \n \n end", "def cost\n\t\treturn @extra_cost + @real_donation.cost\n\tend", "def ctof(cel)\n (cel * 9.0) / 5.0 + 32\nend", "def chip_cd_for_income\n return nil unless product_eligibility_determination\n product_eligibility_determination.chip_cd_for_income\n end", "def position_cost\n return 0 if self.is_close?\n value = self.traded_price * self.open_volume\n value * instrument_multiplier * instrument_currency_exchange_rate\n end", "def vct\n\t\tsuma = 0\n\t\t\n\t\tsuma += prot * gramos_total * 4 / 100\n\t\tsuma += car * gramos_total * 4 / 100\n\t\tsuma += lip * gramos_total * 9 / 100\n\t\t\n\t\treturn suma.round(2)\n\tend", "def recip\n\t\tg, s, t = @residue.ext_gcd(@modulus)\n\t\tif !g.one?\n\t\t\traise \"F2_poly_mod.recip: division by zero.\"\n\t\tend\n\t\treturn F2_poly_mod.new(s, @modulus)\n\tend", "def converted_minimal_charge(exr)\n b = read_attribute(:minimal_charge)\n b.to_d * exr.to_d\n end", "def prop_c\n bases_c / length.to_f\n end", "def proton_mass\r\n mass(HYDROGEN) - mass(ELECTRON)\r\n end", "def arccot(x, unity)\n xpow = unity / x\n n = 1\n sign = 1\n sum = 0\n loop do\n term = xpow / n\n break if term == 0\n sum += sign * (xpow/n)\n xpow /= x*x\n n += 2\n sign = -sign\n end\n sum\n end", "def por_prote\n\t\t\t(@proteinas/suma_gramos)*100\n\t\tend", "def product_rate_plan_charge\n Zapi::Models::ProductRatePlanCharge.new\n end", "def add_charge(desc, bond)\n self[:charges] << {\n :desc => desc.to_s.strip,\n :bond => bond.to_s.gsub('$', '').strip.to_i\n \t}\n Log.d(\"Adding charge: #{self[:charges].last[:desc]}, #{self[:charges].last[:bond]}\")\n end", "def freq_vco(synth)\n f_pfd = freq_pfd(synth)\n int = Valon.get_field(registers(synth), :int)\n frac = Valon.get_field(registers(synth), :frac)\n mod = Valon.get_field(registers(synth), :mod)\n mod = 1 if mod == 0\n f_vco = f_pfd * (int + Rational(frac,mod))\n f_vco.denominator == 1 ? f_vco.to_i : f_vco.denominator\n end", "def cost \n return @extra_cost + @basic_prescription.cost\n end", "def total\n charges.map { |x| x.total_cost.to_f }.inject(:+)\n end", "def potenciaC(n)\n\t\tif n.class != Float && n.class != Fixnum && n.class != Bignum && (n.floor != n || n < 0)\n\t\t\treturn \"No es una potencia valida\"\n\t\t\texit\n\t\telsif n == 0\n\t\t\treturn NumCom.new(1,0)\n\t\telsif n == 1\n\t\t\treturn self\n\t\telsif n > 1\n\t\t\taux = self\n\t\t\tfor i in (1..n-1)\n\t\t\t\taux = aux.multDeComplejos(self)\n\t\t\tend\n\t\t\treturn aux\n\t\tend\n\tend", "def charge!\n unless charged || canceled\n return true unless order.price.cents > 50\n begin\n result = Stripe::Charge.create(\n customer: billing.customer_id,\n amount: order.price.cents,\n currency: order.price.currency\n )\n\n update charged: true, trans_id: result.id\n rescue Stripe::CardError => e\n e.message\n end\n end\n end", "def reciprocal ()\n\tFraccion.new(@denominador,@numerador)\n end", "def calculate_roc(buffer, pos, roc_period)\n\troc_period_key = roc_period.to_s\n\n\tbuffer[pos].rocs[roc_period_key] = (buffer[pos].close_bid - buffer[pos - roc_period].close_bid) / buffer[pos - roc_period].close_bid\nend", "def ctof celcius\n\tcelcius.to_f*(9.0/5.0)+32\nend", "def demand\n direction = @config.direction\n base_amount = @source.query.public_send(@config.attribute)\n\n if direction.nil?\n base_amount * @config.conversion_of(nil)\n else\n @config.conversion.sum do |carrier, conv_config|\n slot = conversion_slot(direction, carrier)\n factor = conversion_factor(slot)\n\n if factor.nil?\n raise 'Expected a numeric conversion but got nil when calculating a molecule ' \\\n \"connection with #{carrier} #{conv_config.inspect} using #{@source.key}\"\n end\n\n base_amount * slot.conversion * factor\n end\n end\n end", "def corr\n raise NotImplementedError, \"Does not work for complex dtypes\" if complex_dtype?\n standard_deviation = std\n cov / (standard_deviation.transpose.dot(standard_deviation))\n end", "def ctof(ctemp)\n32.0+(ctemp*9.0/5.0)\nend", "def proc\n return $PROC\n end", "def shipping_charge\n if empty? || subtotal >= 100\n return 0\n else\n return 10\n end\n end", "def charge\n order = current_order || raise(ActiveRecord::RecordNotFound)\n payment_method = Spree::PaymentMethod.where(type: \"Spree::Gateway::MidtransGateway\").find(params[:payment_method_id])\n charge = payment_method.charge(order)\n\n order.next\n\n if charge.success? && order.complete?\n redirect_to charge.redirect_url\n else\n flash[:error] = charge.data[:message]\n redirect_to checkout_state_path(:payment)\n end\n end", "def reciprocal\n if coeffs.first.zero?\n ContinuedFraction.new(coeffs.suffix(1))\n else\n ContinuedFraction.new(coeffs.prepend(0))\n end\n end", "def CPI\n if self.spent_hours>0 and self.estimated_hours>0\n earned_value= (self.completed_percent * self.estimated_hours)/100\n actual_cost=self.spent_hours\n return (earned_value/actual_cost)\n else\n return 0\n end\n\n rescue\n return 0\n end", "def charge(attrs = {})\n post :charges, {}, attrs.to_xml(:root => :charge)\n end", "def perimeter radius\n puts radius * radius * PI\n end", "def charge_to_s # :nodoc:\r\n charge == nil ? \"\" : \"#{charge.abs}#{charge > 0 ? '+' : '-'}\"\r\n end", "def totalPrazo(cp,quant)\n\t\treg = cp.size - 1\n\t\tret = 0\n\t\tfor ct in (0..reg)\n\t\t\tret = ret + (desconto(Produt.find(cp[ct]).prazo, Produt.find(cp[ct]).id) * quant[ct])\n\t\tend\n\t\treturn ret\n\tend", "def abs ()\n\tFraccion.new(@numerador.abs,@denominador.abs)\n end", "def calculCouleur(cellule,clique)\n #Gestion du clique gauche\n if clique == CLIQUEGAUCHE\n couleur = cellule.clicGauche\n #Gestion duclique droit\n elsif clique == CLIQUEDROIT\n couleur = cellule.clicDroit\n #Aucune gestion pour tout les autres boutons de la souris\n else\n couleur = nil\n puts \"Aucun evenement lié au bouton\"+clique.to_s\n end\n return couleur\n end", "def calculate_value_of_specific_commission_(type)\n (@cancellation_factor * @sale_amount_factor * @hash[type][0].from_german_to_f).to_german_s\n end", "def draw_charge(x, y, dx, dy, pulse)\n draw_x = dx*@cell_size + x*$node_size + $node_size/2.0\n draw_y = dy*@cell_size + y*$node_size + $node_size/2.0\n Charge.create({:x => draw_x, :y => draw_y, :factor_x => @size, :factor_y => @size}, pulse)\n end", "def consignment_fee\n hash[\"ConsignmentFee\"]\n end", "def cost\n 0.89\n end", "def proteinas\n\t\treturn @proteinas*@cantidad\n\tend", "def charge\n authorize!\n set_players\n reset_actions\n\n system_messages = []\n player_messages = []\n opponent_messages = []\n\n hand_card_selected = @game.cards_selected(@player, AREA_LIST[:HAND])[0]\n\n if (hand_card_selected.present?)\n # 6-2-6. A checkpoint occurs. When all necessary processing is carried out for this checkpoint, proceed to the Main Phase.\n card_info = @game.get_card_info(hand_card_selected)\n\n @game.remove_card_from_hand(@player, hand_card_selected)\n @game.add_card_to_energy_area(@player, hand_card_selected)\n @game.set_cards_playable_from_hand(@player)\n\n player_messages << {body: \"You charged #{card_info[\"title\"]}.\"}\n opponent_messages << {body: \"#{@player} charged #{card_info[\"title\"]}.\"}\n else\n player_messages << {body: \"You did not charge a card.\"}\n opponent_messages << {body: \"#{@player} did not charge a card.\"}\n end\n\n @game.clear_all_cards_selected(@player)\n @game.clear_cards_selectable(@player)\n @game.auto_action = \"start_main_phase\"\n\n broadcast_state({\n system_messages: system_messages,\n player_messages: player_messages,\n opponent_messages: opponent_messages\n })\n end", "def ctof(c)\n c * 9.0/5.0 + 32.0\nend" ]
[ "0.6225294", "0.5906098", "0.5820925", "0.5817745", "0.57494015", "0.5707212", "0.5559077", "0.54159015", "0.5376804", "0.53589404", "0.53589404", "0.53448075", "0.53445965", "0.52909523", "0.5265159", "0.524935", "0.5217298", "0.5191494", "0.5138116", "0.5102817", "0.50868833", "0.50661016", "0.5062941", "0.5062941", "0.5058351", "0.5058351", "0.50499415", "0.50295633", "0.5029209", "0.50171375", "0.50029886", "0.49930003", "0.49798235", "0.49750313", "0.49501434", "0.49458563", "0.49414364", "0.4938348", "0.49311098", "0.49287027", "0.49083033", "0.49066558", "0.49053055", "0.49014813", "0.48990187", "0.48876128", "0.48805693", "0.4873878", "0.48682928", "0.48674297", "0.48649162", "0.48455474", "0.48449677", "0.48362297", "0.4811881", "0.48078582", "0.48068345", "0.47857976", "0.47856215", "0.4775868", "0.47723547", "0.4765111", "0.4762149", "0.4759818", "0.47499824", "0.47496265", "0.47495145", "0.47488528", "0.4741734", "0.4734873", "0.4727137", "0.47234336", "0.47206712", "0.47144288", "0.471335", "0.47127447", "0.4706861", "0.47048992", "0.47026065", "0.46966296", "0.4695807", "0.469161", "0.46844792", "0.46815315", "0.46760246", "0.46697566", "0.46623218", "0.46531442", "0.46515226", "0.46513245", "0.46416086", "0.4636844", "0.46357954", "0.4635463", "0.46277967", "0.46247655", "0.46240887", "0.46123677", "0.46119526", "0.46108764" ]
0.65045726
0
Transform AA sequence into residue count
def residue_count counted = [] # N-terminal n_term = @seq[0].chr if PK[:nterm].key? n_term.to_sym counted << { :num => 1, :residue => n_term.to_sym, :pK => PK[:nterm][n_term.to_sym], :positive => positive?(n_term) } elsif PK[:normal].key? n_term.to_sym counted << { :num => 1, :residue => n_term.to_sym, :pK => PK[:normal][n_term.to_sym], :positive => positive?(n_term) } end # Internal tmp_internal = {} @seq[1,(@seq.length-2)].each_byte do |x| aa = x.chr.to_sym if PK[:internal].key? aa if tmp_internal.key? aa tmp_internal[aa][:num] += 1 else tmp_internal[aa] = { :num => 1, :residue => aa, :pK => PK[:internal][aa], :positive => positive?(aa.to_s) } end end end tmp_internal.each do |aa, val| counted << val end # C-terminal c_term = @seq[-1].chr if PK[:cterm].key? c_term.to_sym counted << { :num => 1, :residue => c_term.to_sym, :pK => PK[:cterm][c_term.to_sym], :positive => positive?(c_term) } end counted end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def acidic_count(amino_acid_sequence)\n count = 0\n comp = amino_acid_sequence.composition\n ACIDIC_AMINO_ACIDS.each do |acidic|\n if comp[acidic]\n count += comp[acidic]\n end\n end\n return count\n end", "def basic_count(amino_acid_sequence)\n count = 0\n comp = amino_acid_sequence.composition\n BASIC_AMINO_ACIDS.each do |basic|\n if comp[basic]\n count += comp[basic]\n end\n end\n return count\n end", "def countAtoms(seq)\n\t\t\t\to = 0\n\t\t\t\tn = 0\n\t\t\t\tc = 0\n\t\t\t\th = 0\n\t\t\t\ts = 0\n\t\t\t\tp = 0\n\t\t\t\tse = 0\n\t\t\t\tseq.each_char do |aa|\n\t\t\t\t\to = o + MS::Feature::AA::ATOM_COUNTS[aa][:o]\n\t\t\t\t\tn = n + MS::Feature::AA::ATOM_COUNTS[aa][:n]\n\t\t\t\t\tc = c + MS::Feature::AA::ATOM_COUNTS[aa][:c]\n\t\t\t\t\th = h + MS::Feature::AA::ATOM_COUNTS[aa][:h]\n\t\t\t\t\ts = s + MS::Feature::AA::ATOM_COUNTS[aa][:s]\n\t\t\t\t\tp = p + MS::Feature::AA::ATOM_COUNTS[aa][:p]\n\t\t\t\t\tse = se + MS::Feature::AA::ATOM_COUNTS[aa][:se]\n\t\t\t\tend\n\t\t\t\treturn o,n,c,h,s,p,se\n\t\t\tend", "def amino_acid_number\n @seq.length\n end", "def dnaSequence s\n hash, diff = Hash.new(0), Hash.new(0)\n diff[[0, 0, 0]] = 1\n\n sum = 0\n s.chars.each { |c|\n hash[c] += 1\n res = [hash['A'] - hash['C'], hash['C'] - hash['G'], hash['G'] - hash['T']]\n sum += diff[res]\n diff[res] += 1\n }\n sum\nend", "def occ(seq, b)\n # löchen alles anstatt was in b drin ist\n return seq.gsub(/^#{b}/, \"\").length\n end", "def count_dna dna\n DNA.keys.map { |nt| dna.count nt }\n end", "def count_nucleotides(data)\n ['A', 'C', 'G', 'T'].map {|nucleotid| data.count(nucleotid)} * ' '\nend", "def count_and_say(sequence)\n\treturn 0 if sequence == nil\n\tsequence = sequence.to_s\n\tn = sequence.to_s.size\n result = ''\n\ti = 1\n\trepeat = sequence[0]\n\ttimes = 1\n\twhile (i<=n) do\n\t\tif sequence[i] == repeat\n\t\t\ttimes += 1\n else\n \tresult += times.to_s + repeat.to_s\n \ttimes = 1\n repeat \t= sequence[i].to_i\n end\n i+=1\n end \n\treturn result \nend", "def read_sequence (seq)\n g = 0\n a = 0\n t = 0\n c = 0\n # testen, ob uebergebenes Objekt einzelne Zeichen zurueckgeben kann\n if not seq.respond_to?(\"each_char\")\n return nil\n end\n # iteration ueber alle Symbole (in Großschreibweise) und Ermittlung\n # der absoluten Haeufigkeit der Basen\n seq.each_char do |base|\n base.upcase!\n if base == \"G\"\n g += 1\n elsif base == \"A\"\n a += 1\n elsif base == \"T\"\n t += 1\n elsif base == \"C\"\n c += 1\n else\n return nil\n end\n end\n return g,a,t,c\nend", "def num_decodings(s)\n i1, i2 = 1\n count = 0\n (1..s.size).each do |i|\n# s[i-1, 1] i- 1 is position & 1 is how many ele's you want \n count = s[i-1,1] != '0' ? i1 : 0 # if previous was not 0 set to i1\n count += i2 if s[i - 2, 2].between?('10', '26') && i > 1\n i2 = i1\n i1 = count\n end\n count\nend", "def generate_aasequences\n (0..self.sequence.length-1).each do |i|\n AAsequence.create(:seq_id=> self.seq_id,\n :amino_acid=>self.sequence[i],\n :original_position=>i)\n end\n end", "def get_aa_array(initial_position = 0)\n @aa_array = []\n require_sequence = @dna_sequence[initial_position..-1].tr('-','N')\n base_array = []\n require_sequence.each_char {|base| base_array << base}\n while (base_array.length>=3) do\n base_3= \"\"\n 3.times{base_3 += base_array.shift}\n @aa_array<< amino_acid_2(base_3)\n end\n end", "def rna_to_amino_acid(rna)\n # Protein Translation Problem: Translate an RNA string into an amino acid string.\n # Input: An RNA string Pattern and the array GeneticCode.\n # Output: The translation of Pattern into an amino acid string Peptide. \n\n r_to_c_h = rna_to_codon_hash\n # puts r_to_c_h\n i = 0\n codon_length = 3\n amino_acid = \"\"\n while (codon = rna.slice(i, codon_length)) do\n # puts codon\n # puts r_to_c_h[codon.to_sym]\n break if codon.empty?\n amino_acid += r_to_c_h[codon.to_sym].to_s\n i += codon_length\n end\n return amino_acid\n end", "def counts\n {\n \"A\" => 0,\n \"G\" => 0,\n \"C\" => 0,\n \"T\" => 0\n }\n end", "def ae_count(str)\n ae_counter = Hash.new(0)\n my_hash = {}\n str.each_char do |char|\n if char == 'a' || char == 'e'\n ae_counter[char] += 1\n end\n end\n sorted = ae_counter.sort_by {|key, val| key}\n my_hash[sorted[0][0]] = sorted[0][1]\n my_hash[sorted[1][0]] = sorted[1][1]\n return my_hash\nend", "def count_code(str)\n count_coe = 0\n (str.size - 3).times do |i|\n slice = str[i..(i+1)] + str[(i+3)]\n if slice == \"coe\"\n count_coe += 1\n end\n end\n return count_coe\nend", "def hash_code\n hash_code = {}\n self.seq.each do |letter|\n hash_code.keys.include?(letter) ? hash_code[letter] += 1 : hash_code[letter] = 1\n end\n hash_code\n end", "def isDNA?(fasta)\n seq = File.read(fasta, 10000).split(\"\\n\").grep(/^[^>]/).join\n seq.upcase.count(\"ACTGNU\").to_f / seq.upcase.count(\"ACDEFGHIKLMNPQRSTVWYZ\") > 0.90\nend", "def num_decodings(s)\n\n decode = ('A'..'Z').to_a\n number_of_prev_ended_singly = 1\n\n ways_count = 1\n number_of_prev_ended_singly = 1\n\n s.chars[1..-1].each_with_index do |ch, idx|\n if s[idx - 1].to_i == 1 ||\n s[idx - 1] == 2.to_i && ch.to_i.between?(1,6)\n\n numbers_added_this_time = ways_count - number_of_prev_ended_singly\n ways_count += numbers_added_this_time\n number_of_prev_ended_singly = numbers_added_this_time\n else\n number_of_prev_ended_singly = 0\n end\n end\n\n ways_count\n\nend", "def run\n # Digits 1,4,7,8 have 2,4,3,7 segments respectively\n @list.map{|line| line[1]}.flatten.map(&:length).filter{|len| [2, 4, 3, 7].include?(len)}.count\n end", "def creation_counter(sequencetext)\n @sequencetext = sequencetext\n\t@creations = creation_searcher(@sequencetext)\n\tif (@creations === [\"no letters remain after processing\"])\n\t @creations_count = 0\n else\n @creations_count = @creations.count.to_s\n end\n end", "def count_nucleotides( input )\n\n bases = {\n \"A\" => 0,\n \"C\" => 0,\n \"G\" => 0,\n \"T\" => 0,\n }\n\n dna = [ ]\n\n input.upcase.chars.each do | letter |\n if bases.key? letter\n bases[ letter ] +=1 # if letter matches than start the counter\n else\n dna.push \"#{ letter } is not a nucleotide.\" # if letter is not a match then saves letter and states that in output\n end\n\n\n end #input.chars\n\n bases.each do | key, value |\n dna.push \"#{ key }, #{ value }\"\n end\n\n puts dna\n # puts bases\n end", "def count_nucleotides string\n nucleotides = {\n 'A' => 0,\n 'C' => 0,\n 'G' => 0,\n 'T' => 0,\n 'Error' => 0\n }\n\n string.split(//).map do |item|\n if nucleotides[item.capitalize]\n nucleotides[item.capitalize] += 1\n else\n nucleotides['Error'] += 1\n end\n end\n\n nucleotides.map {|k, v| puts \"#{k}: #{v}\"}\nend", "def part1()\n @seats = @input.map(&:dup)\n until rules_part1() == 0\n end\n count = 0\n @seats.each { |row| count += row.count('#') }\n count\nend", "def count_nucleotides dna\n bases_count = {\n 'A' => 0,\n 'C' => 0, \n 'T' => 0,\n 'G' => 0,\n }\n \n \n #\n dna.each_char do |x|\n if bases_count.key? base\n bases_count[ base ] += 1\n else \n puts \"#{base} not a valid nucleotide\"\n end # if\n end # DNA.each_char end\n\n bases_count.each do |key, val|\n puts \"#{key} : #{val}\"\n end #bases_count.each end\n \n\nend", "def encode(bv)\n code = []\n last = bv[0]\n code.push last\n count = 0\n\n bv.split(\"\").each do |c|\n if c != last \n code.push count\n count = 1 \n else \n count += 1\n end\n last = c\n end\n code.push count\n code.join\nend", "def number_counting_seq(n)\n return \"\" if n == 0\n a = \"11\"\n return a[0...n] if n <= 2\n\n res = \"11\"\n (n-2).times do\n new_piece = res.split(\"\").chunk_while { |a, b| a == b }.to_a if res.length > 1\n res = \"\"\n new_piece.each { |chunk| res += \"#{chunk.length}#{chunk[0]}\" }\n end\n res\nend", "def lexigram_counter(sequencetext)\n @sequencetext = sequencetext\n\t@lexigrams = lexigram_searcher(@sequencetext)\n\tif (@lexigrams === [\"no letters remain after processing\"])\n\t @lexigrams_count = 0\n else\n @lexigrams_count = @lexigrams.count.to_s\n end\n end", "def amino_acid_2 (bases)\n bases_to_aa = []\n aa_list = []\n base1 = bases[0].to_list\n base2 = bases[1].to_list\n base3 = bases[2].to_list\n l1 = base1.size - 1\n l2 = base2.size - 1\n l3 = base3.size - 1\n (0..l1).each do |n1|\n b1 = base1[n1]\n (0..l2).each do |n2|\n b2 = base2[n2]\n (0..l3).each do |n3|\n b3 = base3[n3]\n bases_all = b1 + b2 + b3\n bases_to_aa << bases_all\n end\n end\n end\n\n bases_to_aa.each do |base|\n case base\n when /^TT[TCY]$/\n aa = \"F\"\n when /^TT[AGR]$/\n aa = \"L\"\n when /^CT.$/\n aa = \"L\"\n when /^AT[TCAHYWM]$/\n aa = \"I\"\n when \"ATG\"\n aa = \"M\"\n when /^GT.$/\n aa = \"V\"\n when /^TC.$/\n aa = \"S\"\n when /^CC.$/\n aa = \"P\"\n when /^AC.$/\n aa = \"T\"\n when /^GC.$/\n aa = \"A\"\n when /^TA[TCY]$/\n aa = \"Y\"\n when /^TA[AGR]$/\n aa = \"*\"\n when /^T[GR]A$/\n aa = \"*\"\n when /^CA[TCY]$/\n aa = \"H\"\n when /^CA[AGR]$/\n aa = \"Q\"\n when /^AA[TCY]$/\n aa = \"N\"\n when /^AA[AGR]$/\n aa = \"K\"\n when /^GA[TCY]$/\n aa = \"D\"\n when /^GA[AGR]$/\n aa = \"E\"\n when /^TG[TCY]$/\n aa = \"C\"\n when \"TGG\"\n aa = \"W\"\n when /^CG.$/\n aa = \"R\"\n when /^AG[TCY]$/\n aa = \"S\"\n when /^[AM]G[AGR]$/\n aa = \"R\"\n when /^GG.$/\n aa = \"G\"\n when /^[ATW][CGS][CTY]$/\n aa = \"S\"\n when /^[TCY]T[AGR]$/\n aa = \"L\"\n else\n aa = \"-\"\n end\n aa_list << aa\n end\n aa_out = aa_list.uniq.join\n return aa_out\n end", "def countNumIntran(res)\n\t\tiCount = 0\n\n\t\tif res == nil || res.length == 0\n\t\t\treturn iCount\n\t\tend\n\n\t\tres.each do |constituent|\n\t\t\t# verify Intransitive Verb Phrase\n\t\t\tif(constituent.pos == @vp)\n\t\t\t\t# (or no immediate children at all)\n\t\t\t\tif(constituent.children == nil || !constituent.has_children?)\n\t\t\t\t\tiCount = iCount + 1\n\t\t\t\telse\n\t\t\t\t\t# whose immediate (top-level) constituents include no NPs\n\t\t\t\t\t# containsNps = false\n\t\t\t\t\t# constituent.children.each do |child|\n\t\t\t\t\t# \tif(child.pos == @np)\n\t\t\t\t\t# \t\tcontainsNps = true\n\t\t\t\t\t# \t\tbreak\n\t\t\t\t\t# \tend\n\t\t\t\t\t# end\n\n\t\t\t\t\t# # no top-level constituents found\n\t\t\t\t\t# if(!containsNps)\n\t\t\t\t\t# \tiCount = iCount + 1\n\t\t\t\t\t# end\n\t\t\t\tend\n\t\t\tend\n\n\t\t\tiCount = iCount + countNumIntran(constituent.children)\n\t\tend\n\t\treturn iCount\n\tend", "def nucleotide_counts\n hash = {}\n @valid_inputs.each do |i|\n hash[i] = @dna.count i\n end\n hash\n end", "def schluessel_pro_wert(a_hash)\n result = {}\n a_hash.each { |key, val|\n val.each { |v| \n result[v] = 0 if !result.has_key?(v)\n result[v] += 1\n }\n }\n result\nend", "def reorganize_string(a)\np a\n a = get_frequencies(a)\n\n count = count_char_numbers(a)\n\n return \"\" unless can_reorganize?(count)\n\n build_new_string(a, count)\nend", "def fasta_with_lengths(fasta_fn)\n tmp_file = register_new_tempfile('positive_peaks_formatted.fa')\n File.open(fasta_fn){|f|\n f.each_line.slice_before(/^>/).each{|hdr, *lines|\n seq = lines.map(&:strip).join\n tmp_file.puts \"#{hdr.strip}:#{seq.size}\"\n tmp_file.puts seq\n }\n }\n tmp_file.close\n tmp_file.path\nend", "def isDNA?(fasta)\n seq = File.read(fasta, 10000).split(\"\\n\").grep(/^[^>]/).join\n seq.upcase.count(\"ACTGNU\").to_f / seq.upcase.count(\"ACDEFGHIKLMNPQRSTVWYZ\") > 0.90\nend", "def countingValleys(n, s)\n valleys = 0\n pre = 0\n ac = 0\n for i in 0..n\n pre = ac\n ac += val(s[i]) \n valleys +=1 if pre == -1 && ac == 0\n end\n return valleys\nend", "def solution(s)\n return 0 if s.empty?\n t = 0\n ('A'..'Z').to_a.each do |c|\n t += s.count(c)\n end\n t + 1\nend", "def lucas_sequence(len)\nend", "def possibilities(arrx) #convert shortened array into characters\n\ty= File.select!{|valcount| valcount =~ arry} #break down array into strings of specified length\n\n\t#need to count every letter from each string and match with positions and count the occurence of said letters\n\nend", "def countSubst(path)\n count = 0\n path.each do | atom |\n if @atoms[atom].size > 2 then\n count += (@atoms[atom].size - 2)\n end\n end\n count\n end", "def valleyCounter(n,s)\n currentAltitude = 0\n lastAltitude = 0\n index = 0\n numberOfValleys = 0\n s.each_char do |char|\n if char == \"U\"\n currentAltitude += 1\n lastAltitude = currentAltitude - 1\n else\n currentAltitude -= 1\n lastAltitude = currentAltitude + 1\n end\n if currentAltitude == 0 && lastAltitude < 0\n numberOfValleys += 1\n end\n end\n puts numberOfValleys\nend", "def ae_count(str)\n count = {\"a\"=>0, \"e\"=>0}\n\n str.each_char do |char|\n if (char == \"a\" || char == \"e\")\n count[char] += 1\n end\n end\n\n return count\nend", "def number_counting_seq(n)\r\n\r\nend", "def solution(a)\n h = {}\n a.each do |num|\n h[num] ? h[num] += 1 : h[num] = 1\n end\n h.keys.count\nend", "def run_encode(text)\n text.scan(/(.)(\\1*)/).reduce([]) {|arr,match| arr << [ match[1].length + 1, match[0] ]}\nend", "def to_int_array(seq)\n raise ArgumentError, 'seq must be a string' unless seq.is_a? String\n\n seq.each_char.map do |base|\n DNA2INT[base] || DNA2INT['N']\n end\n end", "def ae_count(string)\n hash = Hash.new(0)\n string.each_char do |char|\n if char == 'a' || char == 'e'\n hash[char] += 1 \n end\n end\n\n hash\nend", "def number_counting_seq(n)\n count = 0\n result = ''\n while count < n\n if count == 0\n result = '1'\n else\n result = translate(result)\n end\n count += 1\n end\n result\nend", "def homocount(str)\n\ts = str.size\n lasts = ''\n homo = {}\n st = 0\n flag = 0\n 0.upto(s-1) do |i|\n cur = str[i,1].upcase\n if cur == lasts\n if flag == 0 # this is the second \n homo[i-1] = 2\n st = i - 1\n else # this is the third or more\n homo[st] += 1\n end\n flag = 1\n else\n flag = 0\n end\n lasts = cur\n end\n if homo.size > 0\n top = homo.keys.sort {|a,b| homo[b] <=> homo[a]}[0]\n xx = homo[top]\n else\n xx = 0\n end\n return xx\nend", "def countingValleys(n, s)\n valleysNum = 0\n level = 0\n s.each_char do | step |\n step == \"D\" ? level -= 1 : level += 1\n valleysNum += 1 if (level == 0 && step == \"U\")\n end\n p valleysNum\nend", "def count_chars a\n\tc = 0\n\ta.each do |s|\n\t\tc += s.length\t\t#this returns c\n\tend\t\t\t\t\t\t#but this returns a\n\tc \t\t\t\t\t\t#so this returns c (again)\nend", "def count_code(str)\n times = 0\n str.size.times do |n|\n if n != (str.size - 1) && n != (str.size - 2) && n != (str.size - 3) && str[n] == \"c\" && str[n + 1] == \"o\" && str[n + 3] == \"e\"\n times += 1\n end\n end\n return times\nend", "def part1 groups\n return groups.map { | g |\n g.gsub(/[^a-z]/,\"\").chars.uniq.length\n }.reduce(0){ |m,v|\n m+v\n }\nend", "def count ( nucleotide, strand )\n\tstrand.upcase.count( nucleotide )\nend", "def countA(string)\n counter = 0\n string.each_char do |char|\n if char == \"a\"\n counter +=1\n end\n end\n return counter\nend", "def discover_input_sequence_type(sequence)\n # Index of the first newline char.\n start = sequence.index(/\\n/)\n # Remove the sequence FASTA header.\n seq = sequence.slice(start..-1).gsub!(/\\n/, '')\n\n if seq =~ /[EQILFPeqilfp]+/\n type = \"amino_acid\"\n else\n # Length of the sequence minus the FASTA header.\n len = seq.length.to_f\n\n na_percent = 15.0\n counts = []\n\n counts << (seq.count(\"Aa\").to_f / len) * 100\n counts << (seq.count(\"Tt\").to_f / len) * 100\n counts << (seq.count(\"Uu\").to_f / len) * 100\n\n counts << (seq.count(\"Gg\").to_f / len) * 100\n counts << (seq.count(\"Cc\").to_f / len) * 100\n\n counts << (seq.count(\"Nn\").to_f / len) * 100\n\n counts.reject! { |c| c < na_percent }\n if (!counts.empty?)\n type = \"nucleic_acid\"\n else\n type = \"amino_acid\"\n end\n end\n type\n end", "def title_to_number(s)\n i = - 1\n s.chars.reverse.inject(0) { |agg, c|\n i += 1\n agg + 26 ** i * (c.ord - 'A'.ord + 1)\n } \nend", "def homocount(str)\n s = str.size\n lasts = ''\n homo = {}\n st = 0\n flag = 0\n 0.upto(s-1) do |i|\n cur = str[i,1].upcase\n if cur == lasts\n if flag == 0 # this is the second \n homo[i-1] = 2\n st = i - 1\n else # this is the third or more\n homo[st] += 1\n end\n flag = 1\n else\n flag = 0\n end\n lasts = cur\n end\n if homo.size > 0\n top = homo.keys.sort {|a,b| homo[b] <=> homo[a]}[0]\n xx = homo[top]\n else\n xx = 1\n end\n return xx\nend", "def homocount(str)\n s = str.size\n lasts = ''\n homo = {}\n st = 0\n flag = 0\n 0.upto(s-1) do |i|\n cur = str[i,1].upcase\n if cur == lasts\n if flag == 0 # this is the second \n homo[i-1] = 2\n st = i - 1\n else # this is the third or more\n homo[st] += 1\n end\n flag = 1\n else\n flag = 0\n end\n lasts = cur\n end\n if homo.size > 0\n top = homo.keys.sort {|a,b| homo[b] <=> homo[a]}[0]\n xx = homo[top]\n else\n xx = 1\n end\n return xx\nend", "def calcuate_frequencies(sequences)\n freq_array = Array.new(4) {|i|Array.new(10){|i| 0}} #2-dimensional array, second dimension initialised to 0's\n sequences.each do |seq|\n for position in 0..3\n freq_array[position][seq[position].to_i] += 1 #increment frequency value by 1\n end\n end\n freq_array\nend", "def count_a(word)\n\tcounter = 0\n \ti = 0\n \twhile i < word.length\n if word[i] == \"a\" || word[i] == \"A\"\n counter += 1\n end\n i += 1\n end\n return counter\nend", "def count_nucleotides(input)\n\n bases = {\n \"A\" => 0,\n \"C\" => 0,\n \"G\" => 0,\n \"T\" => 0\n }\n\n dna = []\n\n input.upcase.chars.each do |letter|\n # puts \"#{letter}\"\n\n #version 1\n # is_nucleotides = false\n #\n # bases.each do |key, value|\n # # puts \"#{key}, #{value}\"\n #\n # if letter == key\n # bases[key] += 1\n # is_nucleotides = true\n # end\n # end #bases.each\n #\n # if is_nucleotides == false\n # dna.push \"#{letter} is not a nucleotide.\"\n # end #if\n\n #version 2\n if bases.key? letter\n bases[letter] +=1\n else\n dna.push \"#{letter} is not a nucleotide.\"\n end\n\n end #input.chars\n\n bases.each do |key, value|\n dna.push \"#{key}, #{value}\"\n end\n\n # puts bases\n puts dna\n\nend", "def title_to_number(s)\n s.split(\"\").map {|ch| ch.ord - 'A'.ord + 1}.reduce(:+)\nend", "def analysis\n hash = {}\n @array.each do |item|\n chars = item.chars.to_a - @used_chars\n\n chars.each do |char|\n if hash[char] == nil\n hash[char] = 1\n else\n hash[char] += 1\n end\n end\n end\n\n hash.sort_by { |_, v| -v }\n end", "def count_arara(num)\n\tnum_adak = (num/2).floor\n\tnum_anane = num%2\n\tphrase = \"adak \"*num_adak + \"anane\"*num_anane\n\tphrase = phrase.sub(/[\" \"]\\Z/, \"\")\n\tphrase\nend", "def count_code(string)\n count = 0\n empty = []\n (string.size - 3).times do |i|\n slice = string[i..(i + 3)]\n if slice == \"code\" \n count += 1\n end\n end\n return count \nend", "def distinct_subseq_ii(s)\n alphabets = ('a'..'z').to_a\n dict = Array.new(27, 0)\n mod = 10 ** 9 + 7\n total = 1\n s.chars.each do |char|\n index = alphabets.index(char) + 1\n combo = total * 2 - dict[index]\n dict[index] = total # if 'c' ever appears again, it will clash with the current combos.\n total = combo < 0 ? 0 + mod : combo % mod\n end\n total - 1 # subtract empty string\nend", "def alphabet_frequency string, letter\n decode_attempt = c_decode string, letter\n frequency_total_array = []\n $frequencies.each do |key, array|\n frequency_total_array.push((frequency_value(decode_attempt.split(\"\"), key) - $frequencies[key]).abs)\nend\nfrequency_total_array.inject(0, :+)\nend", "def getCount(inputStr)\n #your code here\n count = 0\n inputStr.chars {|x| x.match(/[aeiou]/) ? count += 1 : count += 0 }\n count\nend", "def cnts a\n r = []\n found = false\n a.each do |x|\n r.each do |y|\n if y[0] === x\n y[1] += 1\n found = true\n break\n end\n end\n if !found\n r.push([x, 1])\n else\n found = false\n end\n end\n r\nend", "def count_a(word)\n count = 0\n \n i = 0 \n while i < word.length\n char = word[i]\n \n if char == \"a\"\n count += 1\n \n elsif char == \"A\"\n count += 1\n end\n \n i += 1\n end\n \n return count\nend", "def solve(array)\n alphabet = ('a'..'z').to_a.join\n results = []\n \n array.each do |string|\n count = 0\n string.downcase!\n string.chars.each_with_index do |char, index|\n count += 1 if string[index] == alphabet[index]\n end\n results << count\n end\n results \nend", "def count(line)\n\t\tpos = 0\n\t\twhile (pos < line.length)\n\t\t\t# if marker, decompress and count length\n\t\t\t# else add 1 to length, for normal character\n\t\t\tif line[pos] == \"(\"\n\t\t\t\t# substring containing only the marker\n\t\t\t\tmarker = line[pos, line[pos, line.length - pos].index(\")\") + 1]\n\t\t\t\tlen = marker[/(?<=\\()\\d+/].to_i\n\t\t\t\trepeat = marker[/\\d+\\)$/].to_i\n\t\t\t\t@length += repeat * len\n\n\t\t\t\t# move pos onto next piece of data\n\t\t\t\tpos += marker.length + len\n\t\t\telse\n\t\t\t\t@length += 1\n\t\t\t\tpos += 1\n\t\t\tend\n\t\tend\n\tend", "def codon_usage\n rewind\n\n total_usage = {}\n\n each do |e|\n Bio::Sequence::NA.new(e.seq).codon_usage.each do |c, count|\n aa = Bio::Sequence::NA.new(c).translate\n total_usage[aa] ||= {}\n total_usage[aa][c.upcase] ||= 0\n total_usage[aa][c.upcase] += count\n end\n end\n\n rewind\n\n total_usage\n end", "def count_signs\n # suskaiciuojami visi zenklai\n temp = 0\n @signs.size.times do |i|\n temp += 1 if @signs[i] != 0\n end\n temp\n end", "def solve(array)\n aplhabet = ('a'..'z').to_a\n array.map do |string|\n count = 0\n string.chars.each_with_index do |char, idx|\n count += 1 if char.downcase == aplhabet[idx]\n end\n count\n end\nend", "def count_nucleotides(input)\n dna = []\n\n bases = {\n \"A\" => 0,\n \"C\" => 0,\n \"T\" => 0,\n \"G\" => 0,\n }\n\n input.upcase.chars.each do |letter|\n # puts \"Checking for letter: #{letter}\"\n\n is_nucleotides = false\n\n bases.each do |key, value|\n # puts \"The key: #{key} add the value: #{value}.\"\n\n if letter == key\n bases[key] += 1\n is_nucleotides = true\n end\n end #bases.each\n\n if is_nucleotides == false\n dna.push \"#{letter} is not a nucleotide.\"\n end\n\n end #input.chars\n\n bases.each do |key, value|\n dna.push \"#{key}, #{value}\"\n end\n\n puts dna.uniq\n # puts bases\nend", "def base_composition\n if @base_composition\n return @base_composition\n end\n # else run the C method\n composition(@seq.seq)\n alphabet = ['a', 'c', 'g', 't', 'n']\n @base_composition = {}\n @dibase_composition = {}\n bases = []\n dibases = []\n alphabet.each do |c|\n bases << \"#{c}\".to_sym\n end\n alphabet.each do |c|\n alphabet.each do |d|\n dibases << \"#{c}#{d}\".to_sym\n end\n end\n bases.each_with_index do |a,i|\n @base_composition[a] = base_count(i)\n end\n dibases.each_with_index do |a,i|\n @dibase_composition[a] = dibase_count(i)\n end\n return @base_composition\n end", "def ae_count(str)\n # Write your code here\n arr=str.scan(/./)\n my_list = Hash.new(0)\n num = 1\n # puts \";Hey #{sentence}\"\n\n arr.each do |chr|\n if chr == 'e' || chr == 'a'\n my_list[chr] += num\n end\n end\n Hash[my_list.sort]\nend", "def count_SE_groups(a)\n return 1 if a.length == 1\n record = Hash.new\n len_elem = a[0].length\n if len_elem > 1\n a.length.times do |i|\n atemp = Array.new(2,\"\")\n len_elem.times do |j|\n atemp[j % 2] += a[i][j]\n end\n atemp = atemp[0].chars.sort!*\"\" + atemp[1].chars.sort!*\"\"\n a[i] = atemp\n end\n end\n p a.sort!\n count_of_groups = 0\n a.length.times do |i|\n count_of_groups += 1 if a[i + 1] != a[i]\n end\n count_of_groups\nend", "def count_index(to_count)\n\tmy_hash = Hash.new{|hash, key| hash[key] = []}\n\tcount = 0\n\tto_count.split('').each do |letter|\n\t\tcount += 1\n\t\tmy_hash[letter].push(count)\n\tend\n\tmy_hash\t\nend", "def ab_counts(experiment, alternative)\n record = VanityExperiment.retrieve(experiment)\n participants = VanityParticipant.where(experiment_id: experiment.to_s, seen: alternative).count\n converted = VanityParticipant.where(experiment_id: experiment.to_s, converted: alternative).count\n conversions = record.vanity_conversions.where(alternative: alternative).sum(:conversions)\n\n {\n participants: participants,\n converted: converted,\n conversions: conversions,\n }\n end", "def count_a(word)\n counter = 0\n i = 0\n while i < word.length\n if word[i] == 'a' || word[i] == 'A'\n counter += 1\n end\n i += 1\n end\n return counter\nend", "def count_as(string)\n string_array = string.split(\"\")\n count = 0\n\n string_array.each do |letter|\n if letter == \"a\"\n count += 1\n end\n end\n\n count\nend", "def frequency_distribution (sequence, length_pattern)\n assert(length_pattern > 0, \"The pattern length must be grater than 0\")\n frequency = Hash.new\n index = 0\n while index < sequence.length do\n codon = sequence[index .. index + length_pattern - 1]\n frequency[codon] == nil ? frequency[codon] = 1 : frequency[codon] += 1\n index += length_pattern\n end\n frequency\nend", "def count_code(str)\n count = 0\n (str.size - 2).times do |i|\n slice = str[i..(i + 3)]\n if slice[0] == \"c\" && slice[1] == \"o\" && slice[3] == \"e\"\n count += 1\n end\n end\n\n return count\n\nend", "def subjects_count\n subject_count = 0\n self.slots.each do |slot|\n subject_count += slot.subjects.count unless slot.cancelled?\n end\n return subject_count\n end", "def countingValleys(n, s)\n vcount = 0\n level = 0\n n.times do |i|\n if s[i] == \"U\"\n level +=1\n vcount +=1 if level == 0\n elsif s[i] == \"D\"\n level -=1\n end\n end\n return vcount \nend", "def ae_count(str)\n count = {\"a\"=> 0, \"e\" => 0}\n puts count\n str.each_char do |char|\n if (char == \"a\" || char == \"e\")\n count[char] += 1\n end \n end\n return count\nend", "def count_a(word)\n i = 0\n count = 0\n while( i < word.length)\n if(word[i] == \"a\" or word[i] == \"A\")\n count += 1\n end\n i+=1\n end\n return count\n\nend", "def main\n\n while line = ARGF.gets do \n next if line.match(\"^#\")\n \n cols = line.chomp.split(/\\s+/)\n \n allelec = [0,0,0,0]\n pos = cols[1] \n cols[3..-1].each do |gt|\n a = gt.split(';')\n 1.upto(4) do |i|\n n = a[i].to_i\n# a[1..-1].each do |n|\n if n > 0\n allelec[i-1] += 1\n end\n # allelec += n.to_i\n end\n end\n \n ga = allelec.select {|g| g > 0}\n if ga.size > 1\n puts line\n# if pos == \"121320556\"\n # $stderr.puts ga.join(\"\\t\")\n # end\n end\n end\nend", "def encode_num_subs(strn)\n strn = strn.downcase\n alphabets = \"abcdefghijklmnopqrstuvwxyz\".split(\"\")\n out = {\" \" => \" \"}\n alphabets.each do |alphabet|\n out[alphabet] = (alphabets.index(alphabet) + 1).to_s\n \n end\n out_list = []\n strn.split(\"\").each do |el|\n out_list << out[el]\n out_list << \"-\"\n end\n out_list = out_list[0...out_list.length-1]\n #puts out_list\n\n out_list.join(\"\")\nend", "def asignador\n alum = []\n line = read_alumnos\n line.each do |alumno|\n contador = 0\n arr = alumno.split(' ')\n arr.each do |x|\n contador += 1 if x == 'A'\n end\n alum << Alumnos.new(arr[0], arr[1], arr[2], arr[3], contador)\n end\n alum\nend", "def sequence_number; end", "def calculate_total(cards)\r\n\ttotal = 0\r\n\tarr = cards.map {|e| e[1]}\r\n\tarr.each do |val|\r\n\t\tif val == 'A'\r\n\t\t\ttotal += 11\r\n\t\telsif val.to_i == 0 # J,Q,K\r\n\t\t\ttotal += 10\r\n\t\telse \r\n\t\t\ttotal += val.to_i\r\n\t\tend\r\n\tend\r\n\r\n\t#correct for aces\r\n\tarr.select {|e| e=='A'}.count.times do\r\n\t\ttotal -= 10 if total > 21\r\n\tend\r\n\r\n\ttotal\r\nend", "def count_a(word)\n count = 0\n \n i = 0\n while i < word.length\n char = word[i]\n \n if char == \"a\" || char == \"A\"\n count += 1\n end\n \n i += 1\n end \n \n return count\nend", "def synthesize(protein)\n adn = ''\n for a in (0..protein.length-1)\n aminoacido = protein[a,1]\n entropy = rand(100-10) + 10\n \n \n if (@aminoacidos.include?(aminoacido))\n \n adn = adn + @codons[aminoacido][entropy % (@codons[aminoacido].length)]\n end\n \n end\n @synthesize = adn\n end", "def roman_to_int(s)\n # Declare a variable with converting info from roman to integer\n roman = {\n \"I\" => 1,\n \"V\" => 5,\n \"X\" => 10,\n \"L\" => 50,\n \"C\" => 100,\n \"D\" => 500,\n \"M\" => 1000\n }\n # Declare a count variable for adding up numbers\n counts = 0\n # Iterate each letters in the array\n (0...s.length-1).each do |idx|\n # If the next number is small than the current one, add the number to the counts\n if roman[s[idx]] < roman[s[idx+1]]\n counts -= roman[s[idx]]\n else\n counts += roman[s[idx]] \n # else minus the number from the counts\n end\n # return the counts\n end\n counts += roman[s[-1]]\n\nend", "def solution(a)\n # write your code in Ruby 2.2\n counts = {}\n missing = -1\n\n a.each do |a_i|\n counts[a_i] = counts[a_i].to_i + 1\n end\n\n (1..a.length).each do |i|\n if(counts[i].nil?)\n missing = i\n break\n end\n end\n\n if(missing == -1)\n missing = a.length + 1\n end\n\n missing\nend" ]
[ "0.7141778", "0.70089996", "0.68835706", "0.6433953", "0.5985886", "0.5922526", "0.5756015", "0.57402045", "0.56796736", "0.5613895", "0.5606639", "0.5547495", "0.55425197", "0.5510146", "0.54603595", "0.54540306", "0.5436752", "0.5427353", "0.5423404", "0.54028624", "0.5394869", "0.5380639", "0.5377433", "0.5372348", "0.535426", "0.53507066", "0.5347709", "0.5335564", "0.5324431", "0.5312259", "0.53033155", "0.52955556", "0.5287804", "0.5252632", "0.52471066", "0.5228238", "0.5218153", "0.5207079", "0.5206491", "0.51889", "0.5188484", "0.5181994", "0.5181546", "0.5179514", "0.51715887", "0.5171273", "0.5170811", "0.51695615", "0.51685184", "0.51658595", "0.51346684", "0.51324385", "0.5121434", "0.5116778", "0.51113164", "0.5110845", "0.5105271", "0.50906104", "0.50885296", "0.50885296", "0.50860935", "0.5080651", "0.50679827", "0.50603724", "0.50565785", "0.5054874", "0.5053938", "0.50530666", "0.5049914", "0.5045621", "0.50272375", "0.5018058", "0.5016278", "0.50158334", "0.5011875", "0.5009819", "0.50067866", "0.50045365", "0.50018334", "0.50002456", "0.4993483", "0.4992108", "0.49897465", "0.49871072", "0.49858886", "0.49838686", "0.49769408", "0.49687037", "0.49634546", "0.49563158", "0.4947677", "0.49444002", "0.49427602", "0.493982", "0.493884", "0.49297276", "0.49228734", "0.4922744", "0.49121547", "0.4905489" ]
0.7270198
0
Solving pI value with bisect algorithm.
def solve_pI charges state = { :ph => 0.0, :charges => charges, :pI => nil, :ph_prev => 0.0, :ph_next => 14.0, :net_charge => 0.0 } error = false # epsilon means precision [pI = pH +_ E] epsilon = 0.001 loop do # Reset net charge state[:net_charge] = 0.0 # Calculate net charge state[:charges].each do |charge_proc| state[:net_charge] += charge_proc.call state[:ph] end # Something is wrong - pH is higher than 14 if state[:ph] >= 14.0 error = true break end # Making decision temp_ph = 0.0 if state[:net_charge] <= 0.0 temp_ph = state[:ph] state[:ph] = state[:ph] - ((state[:ph] - state[:ph_prev]) / 2.0) state[:ph_next] = temp_ph else temp_ph = state[:ph] state[:ph] = state[:ph] + ((state[:ph_next] - state[:ph]) / 2.0) state[:ph_prev] = temp_ph end if (state[:ph] - state[:ph_prev] < epsilon) && (state[:ph_next] - state[:ph] < epsilon) state[:pI] = state[:ph] break end end if !state[:pI].nil? && !error state[:pI] else raise "Failed to Calc pI: pH is higher than 14" end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def p_value(p, a, b, rmin = 0, rmax = 1)\n fail 'a <= 0' if a <= 0\n fail 'b <= 0' if b <= 0\n fail 'rmin == rmax' if rmin == rmax\n fail 'p <= 0' if p <= 0\n fail 'p > 1' if p > 1\n\n precision = 8.88e-016\n max_iterations = 256\n\n ga = 0\n gb = 2\n\n i = 1\n while ((gb - ga) > precision) && (i < max_iterations)\n guess = (ga + gb) / 2.0\n result = cdf(guess, a, b)\n\n if (result == p) || (result == 0)\n gb = ga\n elsif result > p\n gb = guess\n else\n ga = guess\n end\n\n fail 'No value' if i == max_iterations\n\n i += 1\n end\n\n rmin + guess * (rmax - rmin)\n end", "def interpolation_search_internal(value)\n return [false, 0] if @inner.size == 0\n left = 0\n right = @inner.size - 1\n return [false, 0] if value < @inner[left]\n return [false, right + 1] if value > @inner[right]\n while left <= right\n if left == right\n candidate = left\n else\n candidate = (left + (right - left) * (value - @inner[left]) / (@inner[right] - @inner[left]).to_f).round\n end\n return [false, left] if candidate < left\n return [false, right + 1] if candidate > right\n if @inner[candidate] == value\n return [true, candidate]\n elsif value < @inner[candidate]\n right = candidate - 1\n else\n left = candidate + 1\n end\n end\n return [false, left]\n end", "def solution(x, y, d)\r\n # write your code in Ruby 2.2\r\n i=1\r\n loop do\r\n s=x+i*d\r\n \r\n break if(s>=y)\r\n \r\n i+=1\r\n end \r\n i\r\nend", "def p(i, j, k)\n n = neighbours(i, k)\n if n.include?(j) then\n this_move_value = 0.0\n other_possible_moves_summed_value = 0.0\n @state.transaction do\n this_move_value = @state[:trails][[i, j]]\n other_possible_moves_summed_value = n.inject(0){|sum, n| sum + (@state[:trails][[i, n]]**@alpha)*(heuristic_value(i, n)**@beta)}\n end\n probability = (this_move_value**@alpha)*(heuristic_value(i, j)**@beta)/ (other_possible_moves_summed_value)\n return probability\n else\n return 0.0\n end\n end", "def native_kendalTauish_cost( pi )\n EpsSrraNative::rank_aggergate_upperW(@n){ |u,v| pi.pref(u,v) == @w[u][v] ? 0 : 1 } \n end", "def p_value(pr,k)\n GSL::Cdf.tdist_Pinv(pr,k)\n end", "def bsearch(trueside,falseside,tol=10**(-9))\r\n ok,ng=trueside,falseside\r\n div=tol.is_a?(Integer) ? 2 : 2.0\r\n while((ok-ng).abs>tol) do\r\n mid=(ng+ok)/div\r\n if(yield(mid))\r\n ok=mid\r\n else\r\n ng=mid\r\n end\r\n end\r\n return ok\r\nend", "def solve(l,p,c)\n\tif( l*c >= p )\n\t\treturn 0\n\telse \n\t\t#the optimal strategy is to pick the\n\t\t#geometric mean and not the average\n\t\tmean = Math.sqrt(l*p)\n\t\t# pick a = c * l :\n\t\tval1 = solve(mean,p,c)\n\t\t# pick a = p / c :\n\t\tval2 = solve(l,mean,c)\n\t\t\n\t\treturn 1 + [val1,val2].max\n\tend\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 enter_infertility\n @infertility = @p_o_i\n end", "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 bisect\n n = self.size\n l = n / 2\n [self[0...l], self[l...n]]\n end", "def search(a_sign:, b_sign:)\n if a_sign == \"positive\"\n a_bound = 1000\n step = 1\n end\n if a_sign == \"negative\"\n a_bound = -1000\n step = -1\n end\n\n test_a = 0\n test_b = 0\n max_primes = 0\n\n 0.step(a_bound, step) do |a| # Search for the 'a' coefficient, while a < 1000. Use a block-local variable a.\n Prime.each(1000) do |b| # Search for the 'b' coefficient, while b < 1000.\n b = -(b) if b_sign == \"negative\" # Flip the sign of the prime if we wanted to search for b in [-1000, 0]\n p = 0 # How many primes 'expression' produces.\n 0.step do |n| # The loop for checking if the expression does indeed produce\n # consecutive primes starting at 0.\n expression = n ** 2 + a*n + b\n break unless expression.prime?\n p += 1 # another prime was found\n end # end step loop\n\n if p > max_primes\n max_primes = p\n test_a = a\n test_b = b\n end\n\n end # end prime loop; b\n end # end 'a' loop\n # Returns a hash with keys :a, :b, and max_primes with their values respectively.\n {:a => test_a, :b => test_b, :primes => max_primes}\n end", "def solution(a, b, k)\n # write your code in Ruby 2.2\n e = b / k\n s = (a-1) / k\n\n e - s\nend", "def get_icdf(prob)\n if prob.class == Array\n inv_vals = []\n for i in (0 ...prob.length)\n check_range(prob[i])\n inv_vals[i] = (find_root(prob[i], @n/2, 0.0, @n)).floor\n end\n return inv_vals\n else\n check_range(prob)\n return (find_root(prob, @n/2, 0.0, @n)).floor\n end\n end", "def solution(a, b, k)\n return (b / k) - ((a - 1) / k)\nend", "def condition(i, j)\n # first solved the two equations for just i and j\n 500_000 - 1000*i - 1000*j + i*j == 0\nend", "def bp(k,u,v)\n @pis[k][u][v][1]\n end", "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(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 solve\n a = Time.new\n for i in 0..@itemsSize - 1\n @table[0][i] = 0\n end\n \n for i in 1..@itemsSize - 1\n price = @problem.prices[i-1]\n weight = @problem.weights[i-1]\n for w in 1..@weights - 1\n if weight <= w\n if (price + @table[w - weight][i - 1]) > @table[w][i -1]\n @table [w][i]= price + @table[w - weight][i - 1]\n else\n @table[w][i] = @table[w][i - 1]\n end\n else\n @table[w][i] = @table[w][i - 1]\n end\n end\n end\n \n \n prev_item = 0\n for i in 1..@itemsSize - 1\n curr_item = @table[@weights - 1][i]\n if prev_item < curr_item\n @best_configuration.push(1)\n else\n @best_configuration.push(0)\n end\n prev_item = curr_item\n end\n \n @best_fitness = @table[@weights - 1][@itemsSize - 1]\n \n b = Time.new\n @time = b-a\n end", "def interpolation_search(value)\n search_result = interpolation_search_internal(value)\n return search_result[0] ? search_result[1] : -1\n end", "def h_value(current, goal)\n [(goal.i - current.i).abs, (goal.j - current.j).abs].max\n end", "def h_value(current, goal)\n [(goal.i - current.i).abs, (goal.j - current.j).abs].max\n end", "def minimumBribes(q)\n sum = 0\n q.each_with_index do |v,i|\n if v-(1+i) > 2\n puts \"Too chaotic\"\n return\n end\n bound = [v-2,0].max\n (bound..i-1).each do |j|\n sum+=1 if q[j] > v\n end\n end\n puts sum\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 get_icdf(p)\n check_range(p)\n return @lower + p.to_f * (@upper - @lower)\n end", "def b_s(sorted_arr, value)\n left = 0\n right = sorted_arr.length - 1\n\n while left <= right\n #specify the middle of the array, if you get a decimal, it is automatically rounded down\n mid = (left+right)/2\n\n # So now we are saying that we have:\n # beginning of array\n # end of the array,\n # middle of the array\n # value to check between either the right or left side\n\n #compare the value of the position is currently at with the supplied value\n\n #return the position that the value is at if the evaluation of mid in the array is equal\n if sorted_arr[mid] == value\n #return the position of value\n return mid\n end\n # if the evalution turns out to be less than the value...\n if sorted_arr[mid] < value\n # since we know the evaluation on the left side is less than the value,\n # set left to current mid plus one to converge towards the right\n # do this so that you are pinching the value you are looking for.\n # think of it as pinching the array.\n # as a result of this analogy, I came up with this other strange analogy:\n # or think of it as your brain implementing an algorithm in spacetime where you\n # you are pinching in spacetime for an object, where once you have grasp, the message is\n # returned back to your brain telling you the value in space time was found and you calculate further.\n left = mid + 1\n\n # notice how we don't even have to set the conditional of arr[mid] > value...we can just:\n else\n # since the last element (right) is less than the evalution of arr[mid],\n # we readjust the right to be less\n right = mid - 1\n end\n end\n return nil\nend", "def binsearch(ary, x)\n left = 0\n right = ary.length - 1\n while left < right\n middle = (left + right) / 2\n Tanj.array :ary, index: [:left..:right, :middle]\n if ary[middle] == x\n Tanj.message \"found it!\"\n return middle\n elsif ary[middle] < x\n Tanj.message \"too small\"\n left = middle + 1\n elsif ary[middle] > x\n Tanj.message \"too large\"\n right = middle - 1\n else\n Tanj.message \"this should be unreachable!\"\n end\n end\n Tanj.message \"didn't find it\"\n return nil\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 binsearch arr, target\n return if arr.blank?\n low = 0\n high = arr.count\n loop do\n choice = (low + high) / 2\n bin_lower = arr[choice]\n bin_lower = yield(bin_lower) if block_given?\n bin_upper = arr[choice + 1]\n bin_upper = yield(bin_upper) if bin_upper and block_given?\n if target >= bin_lower\n return choice if !bin_upper || (bin_upper > target)\n # puts \"Rejected #{arr[choice]}->#{arr[choice+1]}: too low\"\n low = choice + 1\n else\n # puts \"Rejected #{arr[choice]}->#{arr[choice+1]}: too high\"\n return nil if high == choice\n high = choice\n end\n end\nend", "def solution_proximity_heuristic(amount,comb,coins)\n (amount-comb.sum)*min_size_heuristic(amount,comb,coins)\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 adjust_prob(hash, position)\n hash.each_key do | pos |\n diff = (pos - position).abs\n # 1 Mb is the cut off on either side\n cutoff = 1000000\n if diff < cutoff\n adj = hash[pos] * (diff/cutoff)\n hash[pos] = adj.to_i\n end\n end\n hash\nend", "def solve(nums)\n nums.each_with_index do |n, i|\n if nums[i] == i\n return i\n end\n end\n return -1\nend", "def solve_identity(d, e, f)\n # First we solve Bezout's identity by using the extended gcd algorithm.\n # See the wikipedia entry in detail.\n g = d.gcd(e)\n return if f % g != 0 # No solution\n d, e, f = d / g, e / g, f / g\n a, b = d, -e\n x0, x1 = 1, 0\n y0, y1 = 0, 1\n while b != 0\n q = a / b\n a, b = b, a % b\n x0, x1 = x1, x0 - x1 * q\n y0, y1 = y1, y0 - y1 * q\n end\n\n # Now we have solution candidates.\n # x = -f * x0 - e * t\n # y = -f * y0 - d * t\n # where t is a free parameter.\n # Then, we consider another constraint: x and y is both printable.\n\n # We must satisfy: 35 <= x <= 126\n # -> ceil((35+f*x0) / e) <= -t <= floor((126+f*x0) / e)\n # -> ceil((35+f*x0) / e) * d - f*y0 <= y <= floor((126+f*x0) / e) * d - f*y0\n ymin = ( 35+f*x0+e+1) / e * d - f*y0\n ymax = (126+f*x0 ) / e * d - f*y0\n\n return if ymax < ymin || ymax < 33 || ymin > 126 # No solution.\n\n ((ymax + f*y0) / -d).upto((ymin + f*y0) / -d) do |t|\n x = -f * x0 - e * t\n y = -f * y0 - d * t\n return [x, y] if printable?(x) && printable?(y) # Solution found.\n end\n\n return # No solution.\nend", "def theoretical_pI\n charges = []\n residue_count().each do |residue|\n charges << charge_proc(residue[:positive],\n residue[:pK],\n residue[:num])\n end\n round(solve_pI(charges), 2)\n end", "def fixed_point(array)\n @start_index = 0\n @end_index = array.length - 1\n @result = -1\n while @start_index <= @end_index\n @mid_index = @start_index + (@end_index - @start_index) / 2\n if @mid_index == array[@mid_index]\n @result = @mid_index\n @end_index = @mid_index - 1\n elsif @mid_index < array[@mid_index]\n @end_index = @mid_index - 1\n else\n @start_index = @mid_index + 1\n end\n end\n @result\nend", "def findValue(value)\n if ! @sorted\n @map.sort{ |a,b| a[0] <=> b[0] }\n @sorted = true\n end\n \n @map.binsearch{|x| x[0] >= value}[1]\n end", "def find_optimal(rootCode,goalCode)\n\tfindHops(rootCode, goalCode, \n\t\tlambda{|flight,oldweight| \n\t\t\toldweight + (flight.date.date.to_i + (flight.flightDuration).seconds - @date.date.to_i)/1200 + 100 + flight.seatprice/5 \n\t\t\t# oldweight + (number of hours between arrival and departure + 100 (per hop))*3 + seatprice/5 (~25-250)\n\t\t\t})\nend", "def binary_search_iterative(array, target)\n# declare variables for low and high positions\nlow_index = 0\nhigh_index = array.length - 1\nmid_index = (high_index + low_index) / 2\n\n# while the low is less than the high\nwhile low_index <= high_index do\n\n return mid_index if target == array[mid_index]\n\n puts \"#{low_index} #{mid_index} #{high_index}\"\n\n if low_index == mid_index\n return high_index\n elsif target > array[mid_index]\n # move lower bound up to mid, recalculate new mid\n low_index = mid_index\n # set the high halfway between\n mid_index = (low_index + high_index) / 2\n elsif target < array[mid_index]\n # move upper bound to mid, recalculate new mid\n high_index = mid_index\n mid_index = (low_index + high_index) / 2\n end\n end\nend", "def interp ( ya, yb, xa, xb, x )\n# return ya if x == xa\n factor = (x - xa) / (xb - xa )\n return ya + factor * ( yb - ya )\nend", "def 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 solution(a)\n return 0 if a.count <= 1\n \n max_profit = 0\n min_price = a.first\n a[1..-1].each { |price|\n max_profit = [max_profit, price - min_price].max\n min_price = [min_price, price].min\n }\n max_profit\nend", "def solve\n s = Hash[(1...1000).map { |i| [i, i * i] }]\n (1...1000).each do |c|\n (1...c).each do |b|\n (1..b).each do |a|\n return a * b * c if (a + b + c) == 1000 && (s[a] + s[b]) == s[c]\n end\n end\n end\nend", "def angle_bisect(angle1, angle2)\n \t bisector = (2 * Math::PI + angle1 + angle2).abs / 2.0\n \t if angle_delta(bisector, angle1) >= (Math::PI / 2.0)\n \t bisector = (angle1 + angle2).abs / 2.0\n \t end\n \t return bisector\n \tend", "def icubert(n)\n x = n\n loop do\n y = ((2*x + n/(x**2))/3)\n if y < x\n x = y\n else\n return x\n end\n end\nend", "def minimumBribes(q)\n q.each_with_index.inject(0) do |bribes, (actual, index)|\n return bribes if q[index + 1].nil?\n\n index_diff = actual - index - 1\n maximun_distance = actual - 2\n distance = if index_diff <= 0 && maximun_distance >= 0 then\n q[maximun_distance...index].all? { |x| x > actual } ? 1 : 0\n else\n [index_diff, 0].max\n end\n\n debug(actual, distance, index_diff, bribes)\n\n if distance > 2\n return \"Too chaotic\"\n break\n end\n bribes + distance\n end\nend", "def solution(n)\n lowest_p = nil\n a = 1\n\n while a * a <= n\n if n % a == 0\n b = n / a\n current_p = 2 * (a + b)\n\n if !lowest_p || current_p < lowest_p\n lowest_p = current_p\n end\n end\n\n a += 1\n end\n\n lowest_p\nend", "def ri(p,i,n,a,s)\n j = 0\n v = nil\n h = nil\n k = nil\n while i > 0\n k = n-j-1\n h = b(k)\n v = b(j) * h\n i -= v\n j += 1\n end\n i += v\n j -= 1\n p[a-1] = j + 1 + s\n y = (i-1-((i-1)/h)*h) + 1\n w = (i-y) / h + 1\n\n if j > 1\n ri(p,w,j,a+1,s) \n elsif j == 1\n p[a] = s+1\n end\n\n if k > 1\n ri(p,y,k,a+j+1,s+j+1)\n elsif k==1\n p[a+j] = s+j+2\n end\n end", "def binary_search_integers(sorted_array, value)\n low = 0\n high = sorted_array.length - 1\n\n while low <= high\n mid = (low + high)/2\n guess = sorted_array[mid]\n\n if guess == value\n return mid\n end\n\n if guess > value\n high = mid - 1\n else\n low = mid + 1\n end\n end\n return nil\nend", "def setup_pps_by_pii_value(pii_value, pps_currency, pps_threshold, pps_threshold_type, pps_status, pps_value_type, pps_notify=nil, logtag=nil)\n pii = Pii.find_by_pii_value(pii_value)\n setup_pps_by_pii(pii, pps_currency, pps_threshold, pps_threshold_type, pps_status, pps_value_type, pps_notify, logtag)\n pii\n end", "def key_for_min_value(ha)\nans = 999999999\n ha.each do |hash, key|\n if key < ans\n ans = key\n end\n end\n \n ha.each do |hash1, key1|\n if key1===ans\n return hash1\n end\n end\n puts ans\n\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 solve112(target_proportion)\n bouncy_proportion = 0\n total_bouncy = 0\n num = 0\n while bouncy_proportion < target_proportion\n num += 1\n if bouncy?(num)\n total_bouncy += 1\n bouncy_proportion = 1.0*total_bouncy/num\n end\n end\n puts target_proportion, num\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 getPrimeById i\n\n if i < 1\n raise 'Input must be positive integer greater than zero'\n end\n\n initial = @@listOfPrimes[i]\n \n if initial != nil\n return initial\n else\n # calculate\n secondary = @@listOfPrimes[i - 1]\n \n if secondary != nil\n p = getNextPrime secondary\n @@listOfPrimes[i] = p\n return p\n else\n raise \"Something isn't set up right\"\n end\n end\n \nend", "def solve(a, b, c)\n v = b ** 2 - 4 * a * c\n if v < 0: raise RangeError end\n s0 = ((-1)*b - Math.sqrt(v))/(2*a)\n s1 = ((-1)*b + Math.sqrt(v))/(2*a)\n return s0, s1\nend", "def solution(value)\n # enter your solution here\n value.round(2)\nend", "def phil_search(haystack, needle)\n size = haystack.size\n midpoint = (size / 2.0).round\n value = haystack[midpoint]\n if value > needle\n linear_search(haystack[0...midpoint], needle)\n elsif value < needle\n linear_search(haystack[midpoint...size], needle)\n else\n value\n end\nend", "def solve\n return ((1..40).inject(:*) / ((1..20).inject(:*) ** 2))\nend", "def b_find_number(n, number_to_find)\n n.bsearch {|x| puts x }\nend", "def simple_linear_search(array, value)\n array.each do |element|\n return value if element == value\n break \"Not in array\" if element > value\n end\n \"Not in array\"\nend", "def solve (input)\n output = 0\n mult_five = 5\n curr_val = 3\n\n while curr_val < input\n if curr_val > mult_five\n output += mult_five\n mult_five += 5\n elsif curr_val == mult_five\n mult_five += 5\n end\n\n output += curr_val\n curr_val += 3\n end\n\n return output\nend", "def nearest_fibonacci_level(val)\n if val < self.begin\n raise FibonacciRangeUtils::ValueOutOfRangeError, \"Must pass a value within the range.\" unless val > self.end\n elsif val > self.begin\n raise FibonacciRangeUtils::ValueOutOfRangeError, \"Must pass a value within the range.\" unless val < self.end\n end\n \n span = (self.end - self.begin).abs\n move = (val - self.begin).abs\n\n current_level = move/span\n nearest_key_level = KEY_FIB_LEVELS.sort_by { |level| (level-current_level).abs }.first\n\n if self.begin < self.end\n nearest_fib_value = self.begin + span*nearest_key_level\n else\n nearest_fib_value = self.begin - span*nearest_key_level\n end\n [nearest_fib_value.round(3), nearest_key_level]\n end", "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 solution(value)\n value.round(2)\nend", "def optimize_kevin_bacon_search\n\t\t# winning_attempts = []\n\t\t# find_kevin_bacon_2(winning_attempts)\n\t\t# if winning_attempts.count > 0\n\t\t\t# winning_attempts.each do |attempt|\n\t\t\t\t# compare with a neighbor, shorter one wins\n\t\t\t\t# there will be lots of ties we skip over\n\t\t# else\n\t\t\t# returns nil\n\t\t# end\n\t\twinning_attempts = []\n\t\tfind_save_kevin_bacon(start_node, winning_attempts)\n\t\twinning_attempts.compact!\n\t\tif winning_attempts.count == 0\n\t\t\tputs 'no bacon :('\n\t\telse\n\t\t\twinning_attempts.index do |i|\n\t\t\t\tif i != 0\n\t\t\t\t\tif winning_attempts[i - 1] < winning_attempts[i]\n\t\t\t\t\t\twinning_attempts.delete_at(i)\n\t\t\t\t\telse\n\t\t\t\t\t\twinning_attempts.delete_at(i - 1)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\twinning_attempts\n\tend", "def solve\n @solving = Thread.new do\n (@lo..@hi).each do |i|\n if i % 50000 == 0\n sleep(0.001)\n end\n if @stop\n Thread.stop\n end\n @iteration = i\n if @prime % i == 0\n # print \"Already here\\n\"\n Thread.current[:proof] = i\n Debugger.debug_print(1, \"signaling solver with #{i}\")\n self.signal(i)\n break\n end\n end\n Debugger.debug_print(1, \"signaling solver with false\")\n self.signal(false)\n end\n end", "def solution(a)\n min_val = 10_000\n min_pos = 0\n \n sums = [0]\n for i in (0..a.count - 1) \n sums << sums.last + a[i] \n end\n for p in (0..a.count - 2)\n for q in (p + 1..[p + 2, a.count - 1].min)\n s = (sums[q + 1] - sums[p]).to_f / (q - p + 1)\n if s < min_val\n min_val = s\n min_pos = p\n end\n end\n end\n min_pos\nend", "def price_is_right(bids, actual_retail_price)\n diff = actual_retail_price\n best_bid = nil\n bids.each do |bid|\n\n highest = actual_retail_price - bid\n\n if highest > 0 && highest <= diff\n diff, best_bid = highest, bid\n end\n end\n\n best_bid\nend", "def solveProblem lst\n big = -1\n numbers = {}\n half = lst.length / 2\n lst.each do |i|\n if numbers.has_key?(i) then\n numbers[i] += 1\n else\n numbers[i] = 1\n end\n if numbers[i] > half then return i end\n end\n return big\nend", "def test_find\n @search.adjacent_points_function = ->(current) {[-0.1, 0.1].map {|x| current + x}}\n @search.cost_function = ->(x){x - 0.1}\n assert_in_delta 0.1, @search.find\n end", "def ukp4(ukpi)\n n = ukpi[:n]\n c = ukpi[:c]\n items = ukpi[:items].clone\n\n g = Array.new(c+1, 0)\n sort_items_by_profitability!(items)\n\n items.each do | item |\n pi = item[:p]\n wi = item[:w]\n max_xi = Rational(c, wi).floor\n z = pi\n y = wi\n max_xi.times do\n if g[y] == 0 then\n g[y] = z\n else\n z = g[y]\n end\n z += pi\n y += wi\n end\n\n break if g[c] != 0\n end\n\n g\nend", "def solution(x, b)\n puts x\nputs b\nend", "def solution(k, m, a)\n from = a.max\n to = a.inject(:+)\n min = from\n while from <= to\n mid = (from + to) / 2\n if check(mid, k, m, a)\n min = mid\n to = mid - 1\n else\n from = mid + 1\n end\n end\n min\nend", "def solve(input, testing: false)\n paths = input.map do |wire|\n build_path([[0,0]], wire)\n end\n x_at = (paths[0] & paths[1] - [[0, 0]])\n x_at.map { |c| c[0].abs + c[1].abs }.min\n end", "def solution(a, b)\n # write your code in Ruby 1.9.3\n a = 0 if a < 0\n return 0 if b<0\n return Math.sqrt(b).floor - Math.sqrt(a).ceil + 1\nend", "def solution(x, y, d)\n (y - x).fdiv(d).ceil\nend", "def binary_search(value)\n search_result = binary_search_internal(value)\n return search_result[0] ? search_result[1] : -1\n end", "def solve( n = 100_000_000 )\n # Observe that:\n # 1. n must be 1 or even\n # 2. n + 1 must be prime\n # 3. n/2 + 2 must be prime\n # 4. (n - 2) % 4 = 0 for n > 1, so (n + 1) % 4 = 3 for n > 1\n p = {}\n n.prime_sieve.each {|i| p[i] = 1}\n\n # From observation 2, we can work backward to compute candidate values of\n # n from known primes.\n primes = p.keys.select do |i|\n # Skip primes that don't satisfy observation 4. \n next if 3 != i % 4\n\n # Test every divisor up to the square root of each candidate.\n cand, d = i - 1, 1 \n begin\n d += 1\n q, r = cand / d, cand % d\n\n match = p.has_key?( d+q ) if 0 == r\n end while match && d < q\n\n match\n end\n\n # Add one since it isn't included in the primes array. Adjust down to\n # account for each n = p-1.\n 1 + primes.reduce( :+ ) - primes.length\n end", "def binary_search(array, value)\n \n # First, we establish the lower and upper bounds of where the value we are\n # searching for can be. At the beginning, the lower bound is the first value\n # of the array and the upper bound is the last value of the array.\n lower_bound = 0\n upper_bound = array.length - 1\n\n # Now we start searching for the value inside the array between the lower and upper bounds.\n # In each iteration of the loop, we check the middle value between the lower and upper bounds\n # against the value we are searching for. If the middle value matches the value we are searching\n # for then we stop, otherwise we update the lower and upper bounds of our search accordingly(Should\n # we search to the right or the left of the mid point in the next iteration to find the value we are\n # looking for).\n #\n # If the value at the mid point matches with the value we are looking for, we are done and we return\n # the mid point(index of the value we are looking for).\n #\n # If the value is lower than the value at the mid point, we should to search to the left side of the mid point\n # in the next iteration. So we set the upper bound to the left of mid point.\n #\n # If the value is higher than the value at the mid point, we should to search to the right side of the mid point\n # in the next iteration. So we set the lower bound to the right of mid point.\n\n while lower_bound <= upper_bound\n\n # Find the mid point between the upper and lower bounds\n mid_point = (lower_bound + upper_bound) / 2\n\n # Look up the value at the mid point\n value_at_mid_point = array[mid_point]\n\n # Check the value at the mid point against the value we are looking for:\n\n if value == value_at_mid_point\n return mid_point\n elsif value < value_at_mid_point\n upper_bound = mid_point - 1\n elsif value > value_at_mid_point\n lower_bound = mid_point + 1\n end\n end\n\n # If the value is not found, return nil indicating the value we are searching for\n # doesn't exist inside the array.\n return nil\nend", "def irenergeticoKJp\n vag=(valorenergeticoKJp() * 100) / 8400\n vag.round(2)\n end", "def next_value(value, array)\n i = value > 0 ? 0 : 1\n index = value == -1 ? 1 : false\n sum = 0\n while i < 100\n if array[i].abs <= value.abs\n sum += array[i].abs\n i += 2\n index = i\n next\n end\n method = sum >= value.abs ? :sum : :cut\n return [index, method]\n end\n method = sum >= value.abs ? :sum : :cut\n return [index, method]\nend", "def solution(x)\n x.abs.to_s.reverse.to_i * (x < 0 ? -1 : 1)\nend", "def search\n prepare_search\n catch :success do\n # Main iteration loop\n @max_iterations.times do |iteration|\n begin # RuntimeError rescue block\n # At the start of each iteration\n prepare_each_run\n if @banned_points.has_key?(path.last) && path.size == 1\n throw :success\n end\n debug_each_iteration iteration\n going = catch :keep_going do\n message = catch :jump_back do\n # cost_vector is a list of all adjacent points with their \n # respective costs\n candidate_list = get_candidate_list\n begin # IndexError rescue block\n # If we've run out of all possible points, step back and keep \n # trying. Only works when candidate_list#size is the largest\n # dimension, i.e., for a normal Array of NArrays. For NArray, \n # #size gives the total number of elements.\n if @interval_index >= candidate_list.size \n throw :jump_back, \"index #{@interval_index} is out of range\"\n end\n # Load up the candidate from the cost_vector\n candidate = candidate_list[@interval_index]\n candidate_cost = get_cost candidate\n # Skip all candidates that are banned, are already in the path, \n # or don't get us any closer.\n while (@banned_points.has_key? candidate.hash) || (@path.include? candidate) || (candidate_cost >= @current_cost)\n @interval_index += 1\n # If we've exhausted all possible intervals, jump back\n if @interval_index >= candidate_list.size\n @banned_points[candidate.hash] = 1\n throw :jump_back, \"index #{@interval_index} is out of range\"\n end\n # Get the movement that is at the current index\n candidate = candidate_list[@interval_index]\n candidate_cost = get_cost candidate\n end\n # Add it to the path!\n @path << candidate\n @current_cost = candidate_cost\n rescue IndexError => er\n puts \"\\nIndexError: #{er.message}\"\n print er.backtrace.join(\"\\n\")\n throw :jump_back\n rescue RangeError => er\n # If handle_range_error has not been defined in a subclass, any \n # call will just re-raise the exception\n handle_range_error er\n end\n # Judge success\n if @current_cost < @epsilon\n @current_point = @path.last\n prepare_result\n throw :success\n else\n @initial_run = true\n throw :keep_going, true\n end\n end # catch :jump_back\n if @debug_level > 1\n puts message\n end\n jump_back\n end # catch :keep_going\n if going\n keep_going\n going = false\n end\n rescue RuntimeError => er\n puts \"\\n#{er.message}\"\n print er.backtrace.join(\"\\n\")\n print \"\\n\\nPath: #{@path.to_a}\\n\"\n break\n end #RuntimeError block\n end # main iteration loop\n end # catch :success\n debug_final_report\n prepare_data\n @data\n end", "def solution(a, b, k)\n first_dividend = a\n remainder = first_dividend%k\n\n while remainder != 0 && first_dividend <= b do\n first_dividend += 1\n remainder = first_dividend%k\n end\n\n remainder == 0 ? (b - first_dividend) / k + 1 : 0\nend", "def solve(a, b, c)\n par = (b * b - 4 * a * c).sqrt\n [(-b + par) / (2 * a), (-b - par) / (2 * a)]\n end", "def nearest_larger(arr, i) # array = [2,3,4,8], indec [i=1]= 3\n d = 1\n while true\n l = i - d\n r = i + d\n\n if (l >= 0) && (arr[l] > arr[i])\n return l\n elsif (r < arr.length) && (arr[r] > arr[i])\n return r\n elsif (l < 0 ) && (r >= arr.length)\n return nil\n end\n d += 1\n end\nend", "def solve(f,l,h)\n\n while true\n \n\t# calculate the mid point. \n m = (l + h) / 2\n\t\n\t# solve f at two points.\n\tx = f(l)\t\n\ty = f(m)\n\t\t\n\t# check for tolerance and f(m)=0\n\tif y==0 or (h-l)/2 < $TOL\n\t return m\n\tend\n\t\t\n\t# if the signs of 'x' and 'y' match then the zero is not in that interval.\n\t# else it is.\n if x * y > 0\n l = m\n else\n h = m\n end\n \n end\n\t\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 educated_search(array, val)\n # Make sure the value is in the bounds of the array\n return nil if not (val >= array[0] and val <= array[-1]) \n\n # Generate a guess index\n i = ((val.to_f - array[0])/(array[-1]-array[0])*array.count).to_i\n\n # If the index is larger than possible, reduce it,\n # then see if we found it.\n i = array.count-1 if i > array.count-1\n return i if array[i] == val\n\n # If we're below the desired value, loop up\n # Otherwise loop down\n if array[i] < val\n while array[i] < val and i < array.count-1\n i += 1\n return i if array[i] == val\n end\n else\n while array[i] > val and i > 0\n i -= 1\n return i if array[i] == val\n end\n end\n\n # If not found, return nil\n return nil\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 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(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 calc_imc(a, p)\n\taqd = (a * a) / 10000\n\timc = p / aqd\n\tr_imc(imc)\nend", "def btc_profit\n break_even.abs\n end", "def solve2\n input = Utils.input_read(13)\n busses = input[1].split(',').each_with_index.map { |b, i| { buss: b.to_i, offset: i } }.filter { |b| b[:buss] != 0 }\n\n biggest_bus = busses.max { |b| b[:buss] }\n # puts biggest_bus\n sequence = Enumerator.new do |yielder|\n number = 0\n loop do\n number += biggest_bus[:buss]\n yielder.yield number\n end\n end\n\n t = sequence.find do |i|\n busses.all? { |b| (i + b[:offset] - biggest_bus[:offset]) % b[:buss] == 0 }\n end\n puts t\nend", "def binary_search_internal(value)\n return [false, 0] if @inner.size == 0\n left = 0\n right = @inner.size - 1\n return [false, 0] if value < @inner[left]\n return [false, right + 1] if value > @inner[right]\n while left <= right\n middle = (left + right) / 2\n if @inner[middle] == value\n return [true, middle]\n elsif value < @inner[middle]\n right = middle - 1\n else\n left = middle + 1\n end\n end\n return [false, left]\n end", "def right_hand_solve\n until @buckets[1] == @target\n fill_right\n until @buckets[1].zero?\n right_to_left\n break if @buckets.include?(@target)\n empty_left\n break if @buckets.include?(@target)\n right_to_left\n break if @buckets.include?(@target)\n end\n end\n end" ]
[ "0.614283", "0.5933399", "0.56879985", "0.56388", "0.5591578", "0.5515401", "0.545671", "0.5451235", "0.5417222", "0.53818583", "0.53731453", "0.5349993", "0.5303633", "0.52670103", "0.5259487", "0.5258435", "0.52548975", "0.524092", "0.52062017", "0.51943946", "0.5193879", "0.5183659", "0.51703954", "0.51703954", "0.51619947", "0.51425123", "0.51413655", "0.5130353", "0.5120814", "0.51192975", "0.5116317", "0.5113792", "0.5104591", "0.5094906", "0.5076973", "0.50752634", "0.5074294", "0.50691515", "0.5066573", "0.5053049", "0.5043878", "0.504302", "0.504249", "0.5037944", "0.5031973", "0.50289124", "0.50282896", "0.5019797", "0.5013936", "0.5012255", "0.50079554", "0.5005794", "0.49926704", "0.49897122", "0.49883", "0.4985618", "0.4985401", "0.49818873", "0.49783665", "0.49731973", "0.4971561", "0.4967684", "0.4962501", "0.49558222", "0.49552268", "0.4951698", "0.4949852", "0.4942085", "0.49395043", "0.49367496", "0.49334288", "0.49295944", "0.49293023", "0.49228868", "0.49225804", "0.49224532", "0.49219447", "0.49169075", "0.49143204", "0.4906187", "0.49045435", "0.49020457", "0.4901616", "0.4898572", "0.48982382", "0.48979667", "0.48953083", "0.48885927", "0.4885453", "0.48840854", "0.4877582", "0.48766378", "0.48761868", "0.48748028", "0.48742384", "0.48734453", "0.48728967", "0.48717442", "0.48691356", "0.48667306" ]
0.61282843
1
file. As a deterrent against cheating, when the game loads a save file it performs a simple check against the file's modification time. If it differs from the timestamp recorded inside the file, the game refuses to load the save file. The save_game method is responsible for recording the timestamp:
def save_game(file) score = 1000 open(file, "w") do |f| f.puts(score) f.puts(Time.new.to_i) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def save_game\n\t\t# If current game was previously saved, delete the old version of current game...\n\t\tif @running_saved_game != nil\n\t\t\tover_write_data\n\t\tend\n\t\t# And add new version of current game to saved data\n\t\tFile.open(@path, 'a+') do |f|\n\t\t\t\tf.puts \"#{@word.join},#{@guess},#{@wrong_letters},#{@turn}\"\n\t\tend\n\tend", "def load_game(file) \n raise \"I suspect you of cheating.\" if File.mtime(file) != Time.at(File.readlines(file).last.to_i)\nend", "def save_game\n\t\tputs \"Type a name for your saved game\"\n\t\tgame_name = gets.chomp\n\t\tfilename = \"#{game_name}.txt\"\n\n\t\t ex_file = File.expand_path(\"./saved_games/#{filename}\")\n\t\t \n\t\tif File.exists?(ex_file)\n\t puts \"#{filename} exists\" #overwrite method?\n\t \n\t self.save_game\n\t else\n\t\t\tFile.open(ex_file, \"w\") do |f|\n\n\t\t\t\tf.puts YAML::dump(game_state)\n\n\t\t\t\tputs \"Your game was saved as #{filename}\" \n\t\t\tend\n\t\tend\n\tend", "def record_save\n # Load mapinfo for map name\n mapinfos = load_data(\"Data/MapInfos.rxdata\")\n # Make the filename\n if Wep::Random_file_name and Wep::Modify_game_system\n filename = Wep::Game_version+\"-\"+$game_system.random_filename+\"-\"+Wep::Save_record_name\n else\n filename = Wep::Game_version+\"-\"+Wep::Save_record_name\n end\n estado = open(filename, \"a\")\n estado.write(\"------------------------------------------\\n\")\n estado.write(\"||||\"+Wep::Save_name+\" \"+($game_system.save_count+1).to_s+\"||||\")\n estado.write(\"\\n------------------------------------------\\n\") \n # Write time\n @total_sec = Graphics.frame_count / Graphics.frame_rate\n hour = @total_sec / 60 / 60\n min = @total_sec / 60 % 60\n sec = @total_sec % 60\n text = sprintf(\"%02d:%02d:%02d\", hour, min, sec)\n tiempo = \"\\nPlaytime: \"\n tiempo+= text\n estado.write(tiempo)\n # Write money\n money = \". Money: \"\n money += $game_party.gold.to_s\n estado.write(money)\n # Write actual map(and name)\n estado.write(\". Map: \"+$game_map.map_id.to_s+\" (\"+mapinfos[$game_map.map_id].name+\")\\n\")\n if Wep::Record_saves_actors\n if Wep::Record_saves_all_actors == false\n for actor in $game_party.actors\n estado.write(\"\\n\"+actor.name+\" (\"+$data_classes[actor.class_id].name+\") Nv\"+actor.level.to_s+\"\\n\")\n end\n else\n \n for i in 1...$data_actors.size\n estado.write(\"\\n\"+$game_actors[i].name+\" (\"+$data_classes[$game_actors[i].class_id].name+\") Nv\"+$game_actors[i].level.to_s+\"\\n\")\n end\n \n end\n end\n estado.write (\"\\n\")\n estado.close\n end", "def save_game\n\t\tputs \"Type a name for your saved game\"\n\t\tgame_name = gets.chomp\t\n\t\tfilename = \"#{game_name}.yml\"\n\n\t\t ex_file = File.expand_path(\"./saved_games/#{filename}\")\n\t\t \n\t\tif File.exists?(ex_file)\n\t puts \"#{filename} exists\" #overwrite method?\n\t \n\t self.save_game\n\t else\n\t\t\tFile.open(ex_file, \"w\") do |f|\n\t\t\t\tgame_state = YAML::dump(self)\n\t\t\t\tf.puts game_state\n\t\t\t\tputs \"Your game was saved as #{filename}\" \n\t\t\tend\n\t\tend\n\tend", "def save_curr_game(fname)\n @log.debug \"Don't save the network game\"\n end", "def new_game(saver)\n File.open(\"#{saver}\",\"a\") do |line|\n write_to = open(Player.my_name, 'w')\n write_to.write(Player.my_name)\n write_to.write(\"\\n\")\n write_to.write(Player.type)\n write_to.write(\"\\n\")\n write_to.write(Player.location)\n write_to.write(\"\\n\")\n write_to.write(Player.x_pos)\n write_to.write(\"\\n\")\n write_to.write(Player.y_pos)\n write_to.write(\"\\n\")\n write_to.write(Player.exp_to_next_lvl)\n write_to.write(\"\\n\")\n write_to.write(Player.cur_exp)\n write_to.write(\"\\n\")\n write_to.write(Player.fatigue)\n write_to.write(\"\\n\")\n write_to.write(Player.stats.agility)\n write_to.write(\"\\n\")\n write_to.write(Player.stats.attack)\n write_to.write(\"\\n\")\n write_to.write(Player.stats.defense)\n write_to.write(\"\\n\")\n write_to.write(Player.stats.health_cur)\n write_to.write(\"\\n\")\n write_to.write(Player.stats.health_max)\n write_to.write(\"\\n\")\n write_to.write(Player.stats.vitality)\n write_to.write(\"\\n\")\n write_to.write(Player.inventory.name)\n write_to.write(\"\\n\")\n write_to.write(Player.level)\n write_to.write(\"\\n\")\n end\nend", "def save_game\n file_name = input_save_name\n begin\n Dir.mkdir('saves') unless Dir.exist?('saves')\n save_file = File.new(file_name, 'w')\n save_file.puts generate_save\n save_file.close\n puts 'Game saved!'\n rescue IOError\n puts 'Save failed'\n end\n end", "def save_game\n Dir.mkdir(\"../saves\") unless Dir.exists?(\"../saves\")\n @@save_count += 1\n binding.pry\n log_saves\n savefile = \"../saves/save_#{@@save_count}.yml\"\n File.open(savefile, 'w') do | file |\n file.write(self.to_yaml)\n end\n end", "def save\n file_name = ask_save_file\n save_file = File.open(file_name, 'w')\n save_file.puts(serialize)\n save_file.close\n puts \"Game has been saved to Save File #{file_name[-5]}!\"\n puts \"\\n\\n\"\n end", "def save_game\n puts \"=================================================\"\n puts \"\\nSaving game...\"\n filename = \"../saved_games/hangman_save.json\"\n File.open(filename, \"w\") { |file| file.puts self.serialize }\n puts \"Game Saved.\"\n puts \"\\n=================================================\"\n end", "def save_game\n\t\tall_saved_games = yaml_load(SAVED_FILENAME)\n\t\tgame_name = get_save_name(all_saved_games)\n\t\treturn if game_name.nil?\n\n\t\tgame_string = self.to_yaml \n\t\tall_saved_games[game_name] = game_string\n\t\tyaml_save(SAVED_FILENAME, all_saved_games)\n\t\tmessage_then_enter \"'#{ game_name }' successfully saved.\"\n\tend", "def save_game\n store = YAML.dump(self)\n File.open('lib/saved_game.yml', 'w') do |file|\n file.puts(store)\n end\n puts 'your game has been saved!'\n end", "def save_game\n @drawing= false\n puts \"Save game...\"\n db = Db.new\n score = @window.level.mouse.score\n lvl = @window.level.num\n name = Time.now.strftime(\"%d/%m/%Y %H:%M\")\n db.save_game name, score, lvl\n end", "def load_gamedata\n @time_stamp = Time.at(0)\n @file_exist = FileTest.exist?(@filename)\n if @file_exist\n file = File.open(@filename, \"r\")\n @time_stamp = file.mtime\n begin\n @characters = Marshal.load(file)\n @frame_count = Marshal.load(file)\n @last_bgm = Marshal.load(file)\n @last_bgs = Marshal.load(file)\n @game_system = Marshal.load(file)\n @game_message = Marshal.load(file)\n @game_switches = Marshal.load(file)\n @game_variables = Marshal.load(file)\n @total_sec = @frame_count / Graphics.frame_rate\n rescue\n @file_exist = false\n ensure\n file.close\n end\n end\n end", "def save_status(file_path)\n begin\n Pathname.new(file_path).open('wb') do |f|\n @saved_at = Fluent::Engine.now\n @saved_duration = @saved_at - @last_checked\n Marshal.dump({\n :counts => @counts,\n :matches => @matches,\n :saved_at => @saved_at,\n :saved_duration => @saved_duration,\n :regexp => @regexp,\n :exclude => @exclude,\n :input_key => @input_key,\n }, f)\n end\n rescue => e\n log.warn \"out_grepcounter: Can't write store_file #{e.class} #{e.message}\"\n end\n end", "def save_game\n #yaml = YAML::dump(self)\n puts \"Please enter a filename for the saved game.\"\n save_file_name = gets.chomp.downcase\n save_file = File.write(\"saved_games/#{save_file_name}.yaml\", self.to_yaml)\n #save_file.write(yaml)\n puts \"Your game has been saved!\"\n puts \"Goodbye!\"\n end", "def save(game)\n\t\tprint \"Name the save: \"\n\t\tsave_name = gets.chomp.downcase\n\t\tDir.mkdir \"saves\" unless Dir.exists? \"saves\"\n\t\tfile_path = File.join(\"saves\", \"#{save_name}\")\n\t\tFile.open(file_path, \"w\") { |f|\n\t\t\tf.write(YAML.dump(game))\n\t\t}\n\t\tputs \"The game has been saved!\"\n\tend", "def save_game\n\t\tsaves = []\n\t\tsaves << @board\n\t\tsaves << @current_player\n\t\tsave_yaml = YAML.dump(saves)\n\n\t\tFile.open('saved_game.yaml', 'w') do |file|\n\t\t\tfile.puts save_yaml\n\t\tend\n\t\tputs \"Your game has been saved.\"\n\t\tputs \"Closing the game...\"\n\t\texit\n\tend", "def save_status(file_path)\n begin\n Pathname.new(file_path).open('wb') do |f|\n @saved_at = Fluent::Engine.now\n @saved_duration = @saved_at - @last_checked\n Marshal.dump({\n :counts => @counts,\n :saved_at => @saved_at,\n :saved_duration => @saved_duration,\n :aggregate => @aggregate,\n :count_key => @count_key,\n :patterns => @patterns,\n }, f)\n end\n rescue => e\n log.warn \"out_datacounter: Can't write store_file #{e.class} #{e.message}\"\n end\n end", "def save_file\r\n @saved = true\r\n saving\r\n Dir.mkdir(\"saves\") unless Dir.exists? \"saves\"\r\n File.open(\"my_save.yaml\", \"w\") {|f| f.puts YAML::dump(self) }\r\n end", "def save_game\n\t\tDir.mkdir('saved_games') unless Dir.exist? 'saved_games'\n\t\tDir.chdir(\"saved_games\")\n\t\tdata = save\n\t\tFile.open(\"save.yaml\", \"w\") do |file|\n\t\t\tsaved_games = YAML::dump(data)\n\t\t\tfile.write(saved_games)\n\t\tend\n\t\tputs \"Games Saved!!\"\n\t\tabort\n\tend", "def save_game(player)\n player_data = YAML::dump(player)\n File.open(\"player.yaml\", \"w\") do |file|\n file.puts player_data\n end\n print \"Successfully saved the game!\\n\\n\"\n return\nend", "def save_game\n Dir.mkdir 'save_files' unless Dir.exists?(\"save_files\")\n\n filename = \"save#{Dir[\"save_files/**/*\"].length}.json\"\n\n save_data = {\n code_word: @code_word,\n good_guesses: @good_guesses,\n bad_guesses: @bad_guesses,\n tries: @tries\n }\n\n File.write(\"save_files/#{filename}\", JSON.dump(save_data))\n end", "def save_game \n File.open('hangman_save.yml', 'w') { |f| YAML.dump(self,f)}\n exit\n end", "def save_turn_without_rescue\n File.open(SAVE_FILE, \"wb\") do |file|\n Marshal.dump($game_variables[VAR], file)\n Marshal.dump($game_variables[VAR2], file)\n end\n return true\n end", "def save_game\n game = {\n :word => @word,\n :max_turn => @max_turn,\n :current_turn => @current_turn,\n :display_word => @display_word,\n :current_guess => @current_guess\n }\n File.open(\"hangman.yaml\", 'w') { |f| f.write(game.to_yaml)}\n print \"Game is saved!\\n\"\n end", "def write_pos_file()\r\n last_update = File.exist?(@pos.pos_file) ? File.mtime(@pos.pos_file) : Time.at(0)\r\n for state in @watched_files.values\r\n if last_update < state.last_emit\r\n @pos.write_to_file()\r\n break\r\n end\r\n end\r\n end", "def save_tracker_cache\n # These values should only be written if the audit has been successful!!\n # Best to write it back to a new file - then move the new file to the\n # original location (overwriting the original)\n return if @parent.ret_val == 3\n tracker_file = get_tracker_filename\n File.open(tracker_file + \".temp\", 'w') { |f|\n # First, save the initial timestamp and the current SOA serial\n f.puts(@initial_timestamp.to_s)\n f.puts(@last_soa_serial.to_s)\n # Now save the cache!!\n Status.strings.each {|s|\n status = s.downcase\n eval \"@cache.#{status}.each {|key, time|\n write_key_to_file(f, key.to_s, status, time[0], time[1])\n }\".untaint\n }\n\n }\n # Now move the .temp file over the original\n File.delete(tracker_file)\n File.rename(tracker_file+\".temp\", tracker_file)\n end", "def save_file\n\t\t\tfile_hash = Digest::MD5.hexdigest(File.read(@file))\n\t\t\tif file = @db.find_html_file(@filename)\n\t\t\t\t@file_changed = @db.check_or_update_if_file_changed(file, @filename, file_hash)\n\t\t\telse\n\t\t\t\t@db.create_html_file(@filename, file_hash)\n\t\t\tend\n\t\tend", "def file_save file\n\t\tfields \t\t\t\t= {}\n \t\tfields[:uid] \t\t= file_uid\n\t\tfields[:fnum] \t\t= file_num_generate\n\t\tfields[:name] \t\t= file[:filename].split('.').first\n\t\tfields[:created]\t= Time.now\n\t\tfields[:type]\t\t= file[:type]\n \t\tfields[:path] \t\t= \"#{file_uid}-#{fields[:created].to_i}#{_random(3)}\"\n\n\t\t# allow these file type to save\n\t\tunless _var(:file_type).include? file[:type]\n\t\t\t_throw Sl[:'the file type isn`t allowed to save']\n\t\tend\n\n\t\t# allow the scope of file size\n\t\tfile_content = file[:tempfile].read\n\t\tif (fields[:size] = file_content.size) > _var(:file_size).to_i\n\t\t\t_throw Sl[:'the file size is too big']\n\t\tend\n\n\t\t# save the info of file\n\t\tSdb[:file_info].insert(fields)\n\n\t\t# save the body of file\n\t\tpath = Spath[:upload_dir] + fields[:path]\n\t\tSimrb.path_write path, file_content\n\t\t_msg :file_save, Sl['saved file successfully']\n\n# \t\t\tFile.open(Spath[:upload_dir] + fields[:path], 'w+') do | f |\n# \t\t\t\tf.write file_content\n# \t\t\tend\n\n# \n# \t\t# return the value\n# \t\tunless reval == nil\n# \t\t\tSdb[:file_info].filter(fields).get(reval)\n# \t\tend\n\tend", "def save\n create_file\n true\n end", "def save_game(game_state)\n save_file = File.open('save_game.yml', 'w')\n YAML.dump(game_state, save_file)\n save_file.close\n exit\n end", "def save\n now = Time.now\n\n data = {\n :id => @id,\n :desc => @desc,\n :ctime => Timestamp.dump(@ctime) || Timestamp.dump(now),\n :mtime => Timestamp.dump(now),\n :ppg_filename => @ppg_filename,\n }\n jobinfo.write(YAML.dump(data))\n end", "def load_game_from_save\n #TODO implement game state saving and loading\n end", "def save_game\n save_data = YAML::dump(self)\n puts \"Please enter a name for your save game:\"\n prompt\n @filename = gets.chomp\n File.open(\"./saved/#{@filename}\", \"w\") { |file| file.write(save_data)}\n puts \"Saved\"\n get_input\n end", "def save # :nodoc:\n if @file\n File.open(SAVE_FILE, 'w') do |f|\n Marshal.dump(file, f)\n end\n else\n forget\n end\n end", "def save # :nodoc:\n if @file\n File.open(SAVE_FILE, 'w') do |f|\n Marshal.dump(file, f)\n end\n else\n forget\n end\n end", "def load_game\n print_saves\n begin\n read_save\n rescue IOError, SystemCallError\n puts 'File not found'\n load_game\n end\n end", "def store_activity_end_time\n File.open(MAIN_DIR + \"prev_end_time\", \"w\") do |timeFile|\n timeFile.syswrite(current_time)\n end\nend", "def determine_savefile\n if @saving\n if FileTest.exist?(make_filename(@last_slot_index))\n Sound.play_decision\n @confirm_window.show()\n @window_slotlist.active=false\n else\n Sound.play_save\n do_save()\n end\n else\n if FileTest.exist?(make_filename(@last_slot_index))\n Sound.play_load\n do_load()\n else\n Sound.play_buzzer\n end\n end\n end", "def dump\n File.open(\"saved_games.yaml\", \"a\") do |out|\n YAML::dump(self, out)\n end\n end", "def save_game\n File.open(@save_file, 'w') do |f|\n Marshal.dump(@hero, f)\n end\n @cmd_window.setpos(0,0)\n @cmd_window << \"Game saved!\".rjust(CMD_WIDTH)\n end", "def save!(file=nil)\n file = file || @file || self.class.default_filename\n file = @root + file if String === file\n now! # update date\n File.open(file, 'w'){ |f| f << yaml }\n end", "def load_game\n file = File.open(\"../saves/log.yml\", \"r\")\n s_log = file.read.to_i\n file.close\n if s_log == 0\n puts \"No save data.\"\n else\n puts \"Select a save file (1 to #{s_log}).\"\n s_choice = gets.chomp.to_i\n if s_choice <= s_log\n puts \"Loading save game # #{s_choice}...\"\n game_state = YAML.load(File.read(\"../saves/save_#{s_choice}.yml\"))\n game_state.play\n else\n puts \"Selected save file does not exist.\"\n end\n end\n end", "def test_filetime\n\t\t# for saving, we can use Date, Time, or DateTime.\n\t\tassert_equal \"\\000\\000\\260\\3077-\\307\\001\", FileTime.dump(Time.gm(2007, 1, 1))\n\t\ttime = FileTime.load \"\\000\\000\\260\\3077-\\307\\001\"\n\t\tassert_equal FileTime, time.class\n\t\tassert_equal '2007-01-01T00:00:00+00:00', time.to_s\n\t\t# note that if we'd used Time.local, instead of gm, we'd get a different value. eg\n\t\tassert_equal \"\\000\\370\\331\\336\\r-\\307\\001\", FileTime.dump(DateTime.parse('2007-01-01 00:00 +0500'))\n\t\t# note that it still loads up as GMT, because there's no associated time zone.\n\t\t# essentially, i'm storing and loading times as GMT. maybe i should add in conversion to local time\n\t\t# zone when loading\n\t\tassert_equal '2006-12-31T19:00:00+00:00', FileTime.load(\"\\000\\370\\331\\336\\r-\\307\\001\").to_s\n\t\t# test loading a bogus time\n\t\tassert_equal nil, FileTime.load(0.chr * 8)\n\t\t# this used to be counted as an \"unlikely time\", and discarded. that has been removed\n\t\tassert_equal '1700-01-01T00:00:00+00:00', FileTime.load(FileTime.dump(Date.new(1700, 1, 1))).to_s\n\t\tassert_equal '#<Ole::Types::FileTime 2006-12-31T19:00:00+00:00>', FileTime.load(\"\\000\\370\\331\\336\\r-\\307\\001\").inspect\n\tend", "def save!\n if save\n self\n else\n raise FileNotSaved\n end\n end", "def recordAnalysis(filename)\n\t\t\tfile = File.open(filename, \"a\")\n timenow = Time.now.asctime\n # file.puts @resulta\n file.puts @score\n file.puts @table\n file.puts @turn\n file.puts @turnsleft\n file.puts secret\n file.close \n \n end", "def save\n ensure_file_open!\n @file.commit\n true\n end", "def saved?\n return !@realfile.nil?\n end", "def log_saves \n s_log = File.open(\"../saves/log.yml\", \"w\")\n s_log.puts @@save_count\n s_log.close\n end", "def save_game\n\t\tputs \"To save game please provide a game name. Please only use letters, numbers and underscores\"\n\t\tinput = gets.chomp.downcase\n\t\tvalid = input.index(/[^\\d,\\w,_]/)\n\t\tuntil !valid\n\t\t\tputs \"Please enter a valid name\"\n\t\t\tinput = gets.chomp.downcase\t\n\t\t\tvalid = input.index(/[^\\d+,\\w+, _+]/)\t\t\t\n\t\tend\n\t\tputs \"Saving #{input}\"\n\t\tyaml = YAML::dump(self)\n\t\tif !Dir.exists?(\"saved\")\n\t\t\tDir.mkdir(\"saved\") \n\t\tend\n\t\tsave_file = File.open(\"saved/#{input}.yaml\", 'w')\n\t\tsave_file.write(yaml)\n\t\tsave_file.close\n\t\tputs \"Game Saved!\"\n\t\texit\n\tend", "def save_data(obj, filename) \r\n File.open(File.join(Yrgss.game.getPath.getAbsolutePath,filename), \"wb\") { |f|\r\n Marshal.dump(obj, f)\r\n }\r\nend", "def save\n unless @filespec.nil?\n yaml_filespec = @filespec.ext('.yaml')\n if !File.exist?(yaml_filespec) || (File.mtime(@filespec) > File.mtime(yaml_filespec))\n @logger.info { \"saving: #{yaml_filespec}\" }\n File.open(yaml_filespec, \"w\") do |f|\n YAML.dump(\n {\n :title_isbn_hash => @title_isbn_hash,\n :isbn_title_hash => @isbn_title_hash,\n :isbn_dvd_hash => @isbn_dvd_hash,\n }, f)\n end\n else\n @logger.info { \"not saving, yaml file is newer than xml file\" }\n end\n else\n @logger.error { \"can not save, the filespec is nil\" }\n end\n end", "def scoreSave()\n\t\tscoreFile = File.new(\"save_files/save_score.yml\", \"w\") \n\t\n\t\tif(!scoreFile.closed?)\n\t\t\tprint \"Sauvegarde du tableau de score...\\n\"\n\t\tend\n\n\t\t#for cpt in 0...10\n\t\t#\tscoreFile.write (self.score_tableau[cpt].getNom()+\":\"+self.score_tableau[cpt].getScore().to_s()+\"\\n\")\n\t\t#end\t\t\n\t\t@score_tableau.sort\n\t\tscoreFile.puts YAML::dump(@score_tableau)\n\t\tscoreFile.close()\n\n\t\tif(scoreFile.closed?)\n\t\t\tprint \"Sauvegarde du tableau de score terminée !\\n\"\n\t\tend\n\n\tend", "def write_timestamp\n filepath = \"#{Dir.tmpdir}/govpay_request_refund_service_last_run_time\"\n # FileUtils.touch seems unreliable in VM so need to write/read the actual time\n File.write(filepath, Time.zone.now)\n end", "def save_data?\n return safeExists?(RTP.getSaveFileName(\"Game.rxdata\"))\n end", "def load_game\n save_file = YAML.load(File.read('save_game.yml'))\n @guess = save_file['guess']\n @secret_word = save_file['secret_word']\n @word_teaser = save_file['word_teaser']\n @lives = save_file['lives']\n round_start\n end", "def init_gamedata\r\n file = File.open(@filename, \"r\")\r\n @time_stamp = file.mtime\r\n @characters = Marshal.load(file)\r\n @frame_count = Marshal.load(file)\r\n @game_system = Marshal.load(file)\r\n @game_switches = Marshal.load(file)\r\n @game_variables = Marshal.load(file)\r\n @total_sec = @frame_count / Graphics.frame_rate\r\n file.close\r\n end", "def mod_time\n File.mtime(@filepath)\n end", "def modified?\n return File.mtime(@filename).to_i > @load_time\n end", "def save( )\n\t\t\tdestDir = nil\t\t\n\t\t\tadd = false\n\t\t\tif not @filename\n\t\t\t\tcreated = Digest::MD5::hexdigest(\"#{@data.created}-#{@data.name}\")\n\t\t\t\tcreated = created[ 0, 8 ]\n\t\t\t\tname = @data.name.gsub( /[\\/\\\\\\ :\\?]/, '_')\n\t\t\t\tDir.mkdir( @options.tickets_directory ) if not File.directory?( @options.tickets_directory )\n\t\t\t\tdestDir = File.join( @options.tickets_directory, \"#{created}-#{name}.ticket\")\n\t\t\t\tif not File.directory?( destDir )\n\t\t\t\t\tDir.mkdir( destDir )\n\t\t\t\t\tadd = true\n\t\t\t\tend\n\t\t\t\t@data.updated=DateTime.now()\n\t\t\t\t@idstring = File.basename( destDir )[0..7]\n\t\t\t\t@filename = File.join( destDir, \"ticket.yaml\")\n\t\t\tend\n\t\n\t\t\t\n\t\t\tFile.open( @filename, File::WRONLY|File::TRUNC|File::CREAT) do |f|\n\t\t\t\tf.write YAML.unescape( YAML.dump( @data ) )\n\t\t\tend\n\t\n\t\t\tloadComments if @comments.length == 0\n\t\t\tcommentsFile = File.join( File.dirname(@filename) , \"comments.yaml\" ) \n\t\t\tFile.open( commentsFile, File::WRONLY|File::TRUNC|File::CREAT) do |f|\n\t\t\t\tf.write YAML.unescape( YAML.dump( @comments ) )\n\t\t\tend\n\t\t\t\n\t\t\tloadAttachments if @attachments.length == 0\n\t\t\tattachmentsFile = File.join( File.dirname(@filename) , \"attachments.yaml\" ) \n\t\t\tFile.open( attachmentsFile, File::WRONLY|File::TRUNC|File::CREAT) do |f|\n\t\t\t\tf.write YAML.unescape( YAML.dump( @attachments ) )\n\t\t\tend\n\t\t\t\n\t\t\tif add\n\t\t\t\tcmd = @options.after_add_ticket\n\t\t\t\tif cmd and not cmd.empty?\n\t\t\t\t\tsystem( \"#{cmd} \\\"#{destDir}\\\"\" )\n\t\t\t\tend\n\t\t\tend\n\t\t\tputs \"Ticket #{@idstring} saved.\"\n\t\tend", "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 createFile(file,time)\n\t\tFile.open(file, \"w+\") do |f|\n\t\t\tf.print time\n\t\tend\n\tend", "def create_timestamp_file\n timestamp = Time.now.utc\n timestamp_file = File.new(report_timing_file, 'w')\n timestamp_file.puts(timestamp)\n timestamp_file.close\n end", "def modified_at(file, timestamp = nil)\n require 'date'\n time = timestamp ? DateTime.parse(\"#{timestamp}\") : DateTime.now\n timestamp = time.strftime('%Y%m%d%H%M')\n execute(\"/bin/touch -mt #{timestamp} #{file}\")\n end", "def save_game(game)\n print \"Enter a new filename to save game in: \"\n filename = gets.chomp\n File.open(filename, \"w\") {|f| f.puts game.to_yaml}\nend", "def save\n\n playerset('')\n $savefile = File.new(\"../Resources/Saves/save.txt\", \"w\")\n $savefile.puts(@@hand, @@ehand)\n cputs(\"saved\", \"green\")\n\nend", "def save!(file_path)\n File.open(file_path, \"w\") do |f|\n f.write(YAML.dump(@log))\n end\n end", "def save!\n File.open(@config[\"lock_file\"], File::RDWR | File::CREAT, 0o600) do |fl|\n # take the lock in non-blocking mode. if this process doesn't get the lock\n # then another will be run from cron shortly. this prevents a whole bunch\n # of processes queueing on the lock and causing weirdness if/when they\n # get woken up in a random order.\n got_lock = fl.flock(File::LOCK_EX | File::LOCK_NB)\n break unless got_lock\n\n # try and write the files to tmp locations and then\n # move them into place later, to avoid in-progress\n # clashes, or people seeing incomplete files.\n begin\n changesets = open_changesets\n @state[\"sequence\"] = sequence\n @state[\"last_run\"] = @now\n\n write_tmp_files!(changesets)\n\n move_tmp_files_into_place!\n\n fl.flock(File::LOCK_UN)\n rescue StandardError\n warn \"Error! Couldn't update state.\"\n fl.flock(File::LOCK_UN)\n raise\n end\n end\n end", "def timestamp\n @file_mtime ||\n if _exist?(name)\n @file_mtime = _mtime(name.to_s)\n else\n Rake::LATE\n end\n end", "def save(overwrite=true)\n write_file(overwrite, @filename)\n end", "def save!; File.write @path, @data end", "def save_game\n\tresponse\n\tif settings.game_data\n\t\tsettings.game_data.save\n\t\tresponse = \"Game saved.\"\n\telse\n\t\tresponse = \"No game loaded yet, so no game saved.\"\n\tend\n\treturn response\nend", "def save\n # first, get a lock for this process\n db = File.open(@fume_db, \"r+\")\n db.flock(File::LOCK_EX)\n\n # now make sure this thread is also locked\n @thread_lock.synchronize do \n \n # then, check if any changes occurred and merge them if necessary\n modified = modified?\n\n if modified\n old_entries = @entries\n \n # reload to minimize chance of overwriting anything\n load_files\n\n # add changes; additions are accepted, but conflicts have to be resolved manually\n @entries.merge! old_entries do |id, old_e, new_e|\n old_e.merge(new_e) do |attr, old_v, new_v|\n if old_v != new_v\n error_db = \"fume_db_error_#{Time.now.strftime(\"%s\")}.yaml\"\n File.open(File.join(Fume::Config[\"fume_dir\"], error_db), \"w\") do |f|\n YAML.dump(old_entries, f)\n end\n raise \"conflict for #{id}: #{attr} '#{old_v}' != '#{new_v}'\"\n else\n new_v\n end\n end\n end\n end\n\n # write entries to file\n YAML.dump(@entries, db)\n end\n\n # minimize the necessity of reloads\n @last_modified = File.ctime(@fume_db)\n\n # let go of lock\n db.flock(File::LOCK_UN)\n \n # update caches again (always necessary)\n update_caches\n end", "def load\n file_name = ask_save_file\n save_file = File.open(file_name, 'r')\n save_file.pos = 0\n contents = unserialize(save_file.read)\n @name = contents['name']\n @guess = contents['guess']\n @word = contents['word']\n @bank = contents['bank']\n @lives = contents['lives']\n @letter = contents['letter']\n puts \"Game has been loaded from Save File #{file_name[-5]}!\"\n puts \"\\n\\n\"\n end", "def save\r\n if valid?\r\n begin\r\n File.open(@filename, 'w') { |f| YAML.dump(@hash, f) }\r\n rescue StandardError => e\r\n Rails.logger.error(e)\r\n end\r\n \r\n # in production environment, there may be several threads of the application that are being cached, which will contain old\r\n # values for these settings; to workaround this, tell Passenger to restart after saving. This will cause the server to restart\r\n # on the next request (there is a separate server process that checks this file).\r\n FileUtils.touch(File.join(Rails.root, 'tmp', 'restart.txt')) if Rails.env.production?\r\n \r\n true\r\n else\r\n false\r\n end\r\n end", "def generate_timestamp_file(filename)\n now = Time.now.to_i\n output_path = \"#{@archive_root}/#{filename}\"\n File.write(output_path, now)\n end", "def save_file\n if self.file then\n self.file.save\n end\n end", "def save\n MiGA.DEBUG \"Metadata.save #{path}\"\n self[:updated] = Time.now.to_s\n json = JSON.pretty_generate(data)\n sleeper = 0.0\n while File.exist?(lock_file)\n sleeper += 0.1 if sleeper <= 10.0\n sleep(sleeper.to_i)\n end\n FileUtils.touch lock_file\n ofh = File.open(\"#{path}.tmp\", \"w\")\n ofh.puts json\n ofh.close\n raise \"Lock-racing detected for #{path}.\" unless\n File.exist?(\"#{path}.tmp\") and File.exist?(lock_file)\n File.rename(\"#{path}.tmp\", path)\n File.unlink(lock_file)\n end", "def save_cache!(config_file = File.expand_path(Assh::CONFIG_CACHE),\n timestamp_file = File.expand_path(Assh::CONFIG_CACHE_AT))\n cache = {\n hosts: @hosts,\n groups: @groups\n }\n File.open(config_file, 'w') { |f| f << cache.to_yaml }\n File.open(timestamp_file, 'w') { |f| f << current_time }\n\n end", "def test_serialize\n first=[[0,0,0],[0,0,0],[0,0,0]]\n f1='test_first.sav'\n\n second=[[0,1,0],[1,0,1],[0,1,0]]\n f2='test_second.sav'\n\n @game.state=first\n @game.save f1\n @game.state=second\n @game.save f2\n\n @game.load f1\n assert_equal first,@game.state\n\n @game.load f2\n assert_equal second,@game.state\n\n File.delete('test_first.sav')\n File.delete('test_second.sav')\n end", "def setTime\n if self.exists && File.writable?(\".\")\n nFile = File.new(\"timed_#{@filename}\", \"w+\")\n \n self.play\n \n puts \"Press enter every time the next lyric should show up!\\n\"\n \n @file.each {\n |line|\n charPrint(line)\n getTime(line, nFile)\n }\n\n nFile.close\n @file.rewind\n end\n end", "def save_moves\n\t\tFile.open(@filename, 'w') {|f| f.write(@past_moves.to_yaml)}\n\tend", "def endgame()\n\t\t@database = Database.new\n\t\t@database.save_files(@players)\n\t\t@database.load_files\n\tend", "def record_access_timestamp(path, timestamp)\n # Hook method: Already stored with File.utime\n end", "def save_game(game_id)\n db = Database.new\n user2 = @game_list[game_id].user2\n if user2.nil?\n user2 = ''\n end\n db.save_game(game_id, @game_list[game_id].user1, user2, game_state(game_id))\n db.close\n ''\n end", "def save!\n File.open(@config[\"state_file\"], \"r\") do |fl|\n fl.flock(File::LOCK_EX)\n\n sequence = (@state.key?(\"sequence\") ? @state[\"sequence\"] + 1 : 0)\n data_file = @config[\"data_dir\"] + format(\"/%03d/%03d/%03d.osm.gz\", sequence / 1000000, (sequence / 1000) % 1000, (sequence % 1000))\n tmp_state = @config[\"state_file\"] + \".tmp\"\n tmp_data = \"/tmp/changeset_data.osm.tmp\"\n # try and write the files to tmp locations and then\n # move them into place later, to avoid in-progress\n # clashes, or people seeing incomplete files.\n begin\n FileUtils.mkdir_p(File.dirname(data_file))\n Zlib::GzipWriter.open(tmp_data) do |fh|\n fh.write(changeset_dump(open_changesets))\n end\n @state[\"sequence\"] = sequence\n File.open(tmp_state, \"w\") do |fh|\n fh.write(YAML.dump(@state))\n end\n\n # sanity check: the files we're moving into place\n # should be non-empty.\n raise \"Temporary gzip file should exist, but doesn't.\" unless File.exist?(tmp_data)\n raise \"Temporary state file should exist, but doesn't.\" unless File.exist?(tmp_state)\n raise \"Temporary gzip file should be non-empty, but isn't.\" if File.zero?(tmp_data)\n raise \"Temporary state file should be non-empty, but isn't.\" if File.zero?(tmp_state)\n\n FileUtils.mv(tmp_data, data_file)\n FileUtils.mv(tmp_state, @config[\"state_file\"])\n fl.flock(File::LOCK_UN)\n\n rescue\n STDERR.puts(\"Error! Couldn't update state.\")\n fl.flock(File::LOCK_UN)\n raise\n end\n end\n end", "def now!\r\n @last_build_file.modification_time = @time = Time.now\r\n end", "def write()\n\t\tdata = {\"rows\"=>@rows, \"cols\"=>@cols , \"moves\"=>@moves , \"time\"=> @time, \"nbGames\" => @nbGames}\n\t\tFile.open(@path, \"w\") {|out| out.puts data.to_yaml }\n\t\treturn self\n\tend", "def save\n if !persisted? \n if @contents\n gps = EXIFR::JPEG.new(@contents).gps\n @location = Point.new(:lng => gps.longitude, :lat => gps.latitude)\n \n @contents.rewind # Reposition read location to beggining of file\n \n grid_file = Mongo::Grid::File.new(@contents.read, get_description) # Unsaved gridfs file\n\n # Store file to mongo db\n id = self.class.mongo_client.database.fs.insert_one(grid_file)\n\n @id = id.to_s\n end\n else\n file = self.class.mongo_client.database.fs.find(_id: BSON::ObjectId.from_string(@id))\n file.update_one(get_description)\n end\n end", "def save\n return if !self.valid?\n\n File.open(@file, \"w\") do |f|\n NWN::Gff.write(f, :gff, @obj)\n end\n end", "def write_last_measurement(line, filename = '/tmp/currentcost')\n File.open(filename, \"w\") do |file|\n file.puts Time.now,(line)\n end\nend", "def save\n file_path = self.class.file_path(@save_id)\n File.open(file_path, 'w') { |file| \n bytes = file.write @items.inspect\n if bytes > 0\n puts \"saved to #{file_path}\"\n else\n puts \"save to #{file_path} failed\"\n end\n }\n end", "def create(filename)\n time = Time.now\n @files[filename] = time # Updates the \"files\" hash with the timestamp for when the file was created\n puts \"The file #{filename} was created at #{time}\"\n end", "def last_write\n @file\n end", "def save_match_to_file(fname)\r\n #fname_old_loc = File.expand_path(File.join( File.dirname(__FILE__) + \"/../..\",fname))\r\n fname_old_loc = fname\r\n File.open( fname_old_loc, 'w' ) do |out|\r\n YAML.dump( @info_match, out )\r\n end\r\n end", "def save_history(file=DEF_HISTORY_FILE)\n begin\n f = File.new(file, File::CREAT|File::TRUNC|File::RDWR, 0644)\n f.puts(@rundate)\n @currprocstat.each do |username,time|\n f.puts(\"#{username} #{time} #{@currprociowait[username]}\")\n end\n f.close\n rescue => e\n puts \"Cannot save history data: #{e}\"\n end\n end", "def save\n ::File.open(@file, \"w\") { |file| file << self.to_hash.to_yaml }\n end", "def load_game(i)\n sys('load')\n File.open(filename(i), \"rb\") do |file|\n Marshal.load(file)\n extract_save_contents(Marshal.load(file))\n $game.reload\n @index = i\n end\n return true\n end" ]
[ "0.73074615", "0.72911596", "0.69355166", "0.68088514", "0.67271143", "0.66961", "0.6551119", "0.65485656", "0.65349394", "0.6527913", "0.6441509", "0.64391744", "0.6438206", "0.63551563", "0.6337121", "0.6307436", "0.6300116", "0.6267606", "0.62563145", "0.622857", "0.61912745", "0.6190341", "0.6189307", "0.6175752", "0.6100857", "0.606057", "0.6038944", "0.60354835", "0.602443", "0.60017264", "0.599491", "0.59645563", "0.5960892", "0.5958032", "0.59442276", "0.59325385", "0.5926035", "0.5926035", "0.5923088", "0.59178877", "0.59167546", "0.59014124", "0.5888235", "0.5882411", "0.5870759", "0.58642656", "0.5850723", "0.5843902", "0.58400774", "0.5797111", "0.579254", "0.57855374", "0.57816225", "0.576883", "0.57538366", "0.57440555", "0.5743699", "0.5727623", "0.5714236", "0.5700274", "0.5686277", "0.56769943", "0.5661824", "0.56541353", "0.56527513", "0.56490403", "0.5643642", "0.5627457", "0.56272435", "0.56245136", "0.5622429", "0.5621587", "0.56058955", "0.56057966", "0.5603368", "0.55846256", "0.5571214", "0.55645996", "0.5564454", "0.55509907", "0.55507505", "0.55439466", "0.55333525", "0.552584", "0.55135375", "0.55052274", "0.5502805", "0.54868317", "0.54808617", "0.5474669", "0.5474618", "0.5472018", "0.5470209", "0.5468258", "0.5460384", "0.54587835", "0.54556435", "0.543862", "0.54238683", "0.54185295" ]
0.6833198
3
The load_game method is responsible for comparing the timestamp within the file to the time the filesystem has associated with the file. Write the load_game(file) method.
def load_game(file) raise "I suspect you of cheating." if File.mtime(file) != Time.at(File.readlines(file).last.to_i) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load_gamedata\n @time_stamp = Time.at(0)\n @file_exist = FileTest.exist?(@filename)\n if @file_exist\n file = File.open(@filename, \"r\")\n @time_stamp = file.mtime\n begin\n @characters = Marshal.load(file)\n @frame_count = Marshal.load(file)\n @last_bgm = Marshal.load(file)\n @last_bgs = Marshal.load(file)\n @game_system = Marshal.load(file)\n @game_message = Marshal.load(file)\n @game_switches = Marshal.load(file)\n @game_variables = Marshal.load(file)\n @total_sec = @frame_count / Graphics.frame_rate\n rescue\n @file_exist = false\n ensure\n file.close\n end\n end\n end", "def load_game\n print_saves\n begin\n read_save\n rescue IOError, SystemCallError\n puts 'File not found'\n load_game\n end\n end", "def load_game\n save_file = YAML.load(File.read('save_game.yml'))\n @guess = save_file['guess']\n @secret_word = save_file['secret_word']\n @word_teaser = save_file['word_teaser']\n @lives = save_file['lives']\n round_start\n end", "def load_game\n\t\tall_saved_games = yaml_load(SAVED_FILENAME)\n\t\tgame_name = get_game_name(all_saved_games, \"load\")\n\t\treturn if game_name.nil?\n\n\t\tsaved_game = YAML::load(all_saved_games[game_name])\n\t\tmessage_then_enter \"'#{ game_name }' successfully loaded.\"\n\t\tsaved_game.play_game\n\tend", "def load_game(i)\n sys('load')\n File.open(filename(i), \"rb\") do |file|\n Marshal.load(file)\n extract_save_contents(Marshal.load(file))\n $game.reload\n @index = i\n end\n return true\n end", "def load_game\n file = File.open(\"../saves/log.yml\", \"r\")\n s_log = file.read.to_i\n file.close\n if s_log == 0\n puts \"No save data.\"\n else\n puts \"Select a save file (1 to #{s_log}).\"\n s_choice = gets.chomp.to_i\n if s_choice <= s_log\n puts \"Loading save game # #{s_choice}...\"\n game_state = YAML.load(File.read(\"../saves/save_#{s_choice}.yml\"))\n game_state.play\n else\n puts \"Selected save file does not exist.\"\n end\n end\n end", "def load()\n code = File.open(@filename) {|file| file.read}\n dup = @players.last.dup\n begin\n dup.reset\n dup.instance_eval(code)\n @players.push(dup)\n rescue\n puts \"LOAD ERROR #{$!}\"\n end\n @load_time = Time.now.to_i\n end", "def load_game\n\t\tload_gameplay = YAML.load(File.read 'saved_game.yaml')\n\t\t@board = load_gameplay[0]\n\t\t@current_player = load_gameplay[1]\n\t\tshow_board\n\t\tinput_validation\n\tend", "def init_gamedata\r\n file = File.open(@filename, \"r\")\r\n @time_stamp = file.mtime\r\n @characters = Marshal.load(file)\r\n @frame_count = Marshal.load(file)\r\n @game_system = Marshal.load(file)\r\n @game_switches = Marshal.load(file)\r\n @game_variables = Marshal.load(file)\r\n @total_sec = @frame_count / Graphics.frame_rate\r\n file.close\r\n end", "def load_game_from_save\n #TODO implement game state saving and loading\n end", "def load_game\n if File.exists?(@save_file)\n File.open(@save_file, 'r') do |f|\n @hero = Marshal.load(f)\n end\n @cmd_window.setpos(0,0)\n @cmd_window << \"Game loaded!\".rjust(CMD_WIDTH)\n else\n @cmd_window.setpos(0,0)\n @cmd_window << \"No save file found!\".rjust(CMD_WIDTH)\n end\n end", "def load\n file_name = ask_save_file\n save_file = File.open(file_name, 'r')\n save_file.pos = 0\n contents = unserialize(save_file.read)\n @name = contents['name']\n @guess = contents['guess']\n @word = contents['word']\n @bank = contents['bank']\n @lives = contents['lives']\n @letter = contents['letter']\n puts \"Game has been loaded from Save File #{file_name[-5]}!\"\n puts \"\\n\\n\"\n end", "def load #TODO: validation\n \tputs \"What game do you want to load?\"\n \tsaved_game = gets.chomp.gsub(' ', '_')\n \tsaved_game = \"#{saved_game}.yaml\"\n \tload_game(saved_game)\n end", "def load_state\n begin\n save_file = File.read(\"saved_state.json\")\n rescue\n return \"No saved game found\"\n end\n json_hash = JSON.parse(save_file)\n json_hash[\"json_board\"].each do |key, value|\n value == nil ? @board[key] = nil : \n @board[key] = Chess.const_get(value[\"class\"]).new(value[\"team\"])\n end\n @current_player = json_hash[\"current_player\"]\n return \"Game loaded\"\n end", "def initialize(file, game)\n @file = file\n @game = game\n end", "def load \n \tputs \"Type 'load' to load an existing game, or press Enter to continue.\"\n \tanswer = gets.chomp.downcase\n \tif answer == 'load'\n data = YAML.load_file('store.yml')\n @turns = data.turns\n @lives = data.lives\n @wrong = data.wrong\n @right = data.right\n @word= data.word\n puts \"Loading...\"\n sleep(2)\n end\n\n end", "def get_game\n\t\tif @file_exists == 1\n\t\t\t# If the file exists, but there are no rows in it, there are no saved games\n\t\t\tif @data.length == 0\n\t\t\t\tputs \"Oops, you have no saved games.\"\n\t\t\t\tputs \"Here, start a new one!\"\n\t\t\t\tputs\n\t\t\t\tnew_game\n\t\t\telse\n\t\t\t\tputs \"Which game?\"\n\t\t\t\t# Display each partially guessed word like: \"1. _ e _ _ t\"\n\t\t\t\t@data.each_with_index { |row, i| puts \"#{i+1}. #{row[1].split(\"\").join(\" \")}\" }\n\t\t\t\t# Get user's choice\n\t\t\t\tgame = gets.chomp.to_i\n\t\t\t\t# If the user entered a number that appears on the board...\n\t\t\t\tif game.between?(1,@data.length)\n\t\t\t\t\t# Get all info out of chosen row\n\t\t\t\t\t@word = @data[game-1][0].split(\"\").to_a\n\t\t\t\t\t@guess = @data[game-1][1]\n\t\t\t\t\t@wrong_letters = @data[game-1][2]\n\t\t\t\t\t@turn = @data[game-1][3].to_i\n\t\t\t\t\t@running_saved_game = (game - 1)\n\t\t\t\t\t# Get the next guess\n\t\t\t\t\tget_guess\n\t\t\t\telse\n\t\t\t\t\tputs \"Not a valid choice! Pick again\"\n\t\t\t\t\tget_game\n\t\t\t\tend\n\t\t\tend\n\t\telse\n\t\t\tputs \"Oops, you have no saved games.\"\n\t\t\tputs \"Here, start a new one!\"\n\t\t\tputs\n\t\t\tnew_game\n\t\tend\n\tend", "def load_hero_file\n clear_message_box\n #ask for file\n @ui.set_colour(DungeonOfDoom::C_BLACK_ON_YELLOW)\n @ui.place_text('USE CHARACTER FILE?'.ljust(20),1,2)\n @ui.place_text('>'.ljust(20),1,3)\n file_name=nil\n #loop until file is good\n while file_name.nil?\n @ui.place_text(' '*19,2,3)\n file_name = @ui.get_string(2,3)\n #check and try to open file\n if file_name.split('.').last != 'yaml' #needs yaml extention\n @ui.place_text('!REQUIRES YAML EXT'.ljust(20),1,4)\n file_name=nil\n elsif !File.exists?(file_name) #file must exist\n @ui.place_text('!FILE NOT FOUND'.ljust(20),1,4)\n file_name=nil\n else\n hero_data = YAML.load(File.open(file_name))\n if hero_data.is_a? Hash #file must be in a valid yaml format\n #load stats\n hero_data[:stats].each do |stat|\n @stats[stat[0].downcase.to_sym] = stat[1]\n end\n @orig_stats.merge!(@stats) #make a copy\n #load objects\n @objects = hero_data[:objects]\n #load remaining gold (used for final score)\n @gold_count += hero_data[:gold]\n #display heros name\n @ui.place_text(hero_data[:name].center(20), 1, 1, DungeonOfDoom::C_BLACK_ON_WHITE)\n #set magic spell count based on 2 x power of NECRONOMICON and SCROLLS\n book = @objects.find { |object| object[:name]=='NECRONOMICON' }\n if book\n power = book[:power]\n [:super_zap, :santuary, :teleport].each do |spell|\n @spells[spell] = power\n end\n end\n scroll = @objects.find { |object| object[:name]=='SCROLLS' }\n if scroll\n power = scroll[:power]\n [:powersurge, :metamorphosis, :healing].each do |spell|\n @spells[spell] = power\n end\n end\n #set torch power\n torch = @objects.find { |object| object[:name]=='TORCH' }\n @torch_power = torch[:power] if torch\n #find initial potion count\n potion = @objects.find { |object| object[:name]=='POTION' }\n @potions += potion[:count] if potion\n #find initial attack power\n ['2 HAND SWORD','BROADSWORD','SHORTSWORD','AXE','MACE','FLAIL','DAGGER','GAUNTLET'].each do |item|\n object = @objects.find { |object| object[:name]==item }\n @attack += object[:power] if object\n end\n @attack += @stats[:strength]\n #find initial defence power\n ['HEAVY ARMOUR','CHAIN ARMOUR','LEATHER SKINS','HEAVY ROBE','GOLD HELMET','HEADPIECE','SHIELD'].each do |item|\n object = @objects.find { |object| object[:name]==item }\n @defence += object[:power] if object\n end\n else #all okay!\n @ui.place_text('!FILE BAD FORMAT'.ljust(20),1,4)\n file_name=nil\n end\n end\n end\n end", "def load_game\n begin\n player = YAML.load_file(\"player.yaml\")\n return player\n rescue\n return nil\n end\nend", "def load_game\n $pokemon_party = @all_window[@index].data\n $pokemon_party.expand_global_var\n $pokemon_party.load_parameters\n $game_system.se_play($data_system.cursor_se)\n $game_map.setup($game_map.map_id)\n $game_player.moveto($game_player.x, $game_player.y) # center\n $game_party.refresh\n $game_system.bgm_play($game_system.playing_bgm)\n $game_system.bgs_play($game_system.playing_bgs)\n $game_map.update\n $game_temp.message_window_showing = false\n $trainer.load_time\n Pathfinding.load\n end", "def load_file(filename)\n file = File.open(filename, \"r\")\n grid = JSON.parse(file.read)\n file.close\n return Game.new(grid.length, grid[0].length, grid)\nend", "def load_file(file)\n klasses = ObjectSpace.classes.dup\n load file\n LOADED_CLASSES[file] = ObjectSpace.classes - klasses\n MTIMES[file] = File.mtime(file)\n end", "def load_game\nputs \"Please choose one of the below saved profiles:\"\nsystem (\"ls *.ca\")\nprint \":\"\n$name = gets.chomp\n$file_name = $name + \".ca\"\nwhile(!system(\"test -e '#{$file_name}'\")) do\nputs \"Such profile does not exits, please choose a valid one.\"\nsystem (\"ls *.ca\")\nprint \":\"\n$name = gets.chomp\n$file_name = $name + \".ca\"\nend\ninfo = IO.readlines(\"#{$file_name}\") # info is a array and each index value is the info of a line info[3] = info that is on line number three.\n# now info is acctualy being loaded intro the system variables\n$name = info[0]\n$lvl = info[1]\n$gold = info[2]\nfor i in 3..((info.length)-1) do\n$inventory[$inventory.length] = info[i] # with $inventory.length start from 0 becuse it's initial null it will automaticaly grow\nend\nputs \"Loading please wait...\"\nsleep(2)\nprint \"............\"\nsleep(1)\nputs \"............\"\nputs $name\nputs $gold\nputs $lvl\nputs $inventory\n####call the level method\nend", "def loadGame()\n\nend", "def load(game)\n\t\t@moves.replay(game)\n\t\treturn self\n\tend", "def initialize(slot_name, filename)\n @slot_name = slot_name\n if FileTest.exist?(filename)\n @used = true\n # Start load data\n file = File.open(filename, \"r\")\n @time = file.mtime\n @characters = Marshal.load(file)\n @frame_count = Marshal.load(file)\n @last_bgm = Marshal.load(file)\n @last_bgs = Marshal.load(file)\n @game_sys = Marshal.load(file)\n @game_mes = Marshal.load(file)\n @game_swi = Marshal.load(file)\n @game_var = Marshal.load(file)\n @game_self_swi = Marshal.load(file)\n @game_act = Marshal.load(file)\n @game_par = Marshal.load(file)\n @game_tro = Marshal.load(file)\n @game_map = Marshal.load(file)\n @game_pla = Marshal.load(file)\n @screenshot_stream = Marshal.load(file)\n file.close\n else\n @used = false\n end\n end", "def load_menu\n\t\ti = 1\n File.new(\"saved_games.yaml\",\"w\") unless File.exist?(\"saved_games.yaml\")\n if File.read(\"saved_games.yaml\").empty?\n puts \"There are no saved games, yet.\"\n initialize\n else\n YAML.load_stream(File.open(\"saved_games.yaml\")) do |saved_game|\n puts \"#{i}: \" + saved_game[-1].strftime(\"%m/%d/%Y %I:%M%P\")\n i += 1\n end\n puts \"\"\n puts \"Choose a game to load or \\\"exit\\\" to menu:\"\n game_index = gets.chomp.strip.downcase\n if game_index == \"exit\"\n initialize\n elsif game_index.to_i <= i && game_index.to_i >= 1\n game_index = game_index.to_i\n i = 1\n File.new(\"temp.yaml\",\"w\")\n puts \"\"\n YAML.load_stream(File.open(\"saved_games.yaml\")) do |game|\n if i == game_index\n \t@gameboard = game[0]\n @pieces = game[1]\n @player_color = game[2]\n else\n File.open(\"temp.yaml\",\"a\") do |out|\n YAML::dump(game,out)\n end\n end\n i += 1\n end\n File.delete(\"saved_games.yaml\")\n File.rename(\"temp.yaml\",\"saved_games.yaml\")\n Chess.new(@gameboard,@pieces,@player_color)\n else\n puts \"Invalid input. Try again...\"\n puts \"\"\n load_menu\n end\n end\n\tend", "def load_game\n\t\tprint \"Load game (y/n): \"\n\t\tload = gets.chomp.downcase[0]\n\t\treturn false if load == 'n'\n\t\treturn loader if load == 'y'\n\t\tload_game if (load != 'n' || load != 'y')\n\tend", "def load_game\n\tsettings.game_data = Ben::Game.load\n\tgame_json\nend", "def load_level(file_name)\n @enemies = []\n @candies = []\n @tiles = []\n\n # a grid representing the tiles of the level\n # . = empty background\n # - = platform\n line_no = 0\n File.readlines(file_name).each do |line|\n if line_no == 0\n x, y = line.split(/\\s/)\n @start_x = x.to_i\n @start_y = y.to_i\n elsif line_no == 1\n x, y = line.split(/\\s/)\n @door = Door.new(@window, x.to_i, y.to_i)\n elsif line_no == 2\n # load the tiles (platforms, background, empty space)\n @tiles = line.split(/\\s/)\n\n @tile_types = {\n \".\" => :background,\n \",\" => :background2,\n \"-\" => :platform,\n \"x\" => :none,\n }\n\n # change from small single-character representations of tiles\n # to full name representations\n @tiles.collect! { |t| @tile_types[t] }\n elsif line_no > 1\n # load the enemies and candies\n x, y, type = line.split(/\\s/)\n class_type = Object.const_get(type)\n class_name_plural = class_type.superclass.to_s.downcase\n class_name_plural[-1] = \"ies\"\n # grab the correct array\n array = instance_eval(\"@\" + class_name_plural)\n # place a new object of type 'type' with the given parameters\n array.push(class_type.new(@window, x.to_i, y.to_i))\n end\n line_no += 1\n end\n @platforms = []\n @ledges = []\n\n # add all the platform rectangles to check for collision\n 0.upto(WIDTH - 1) do |x|\n 0.upto(HEIGHT - 1) do |y|\n if @tiles[x + y * WIDTH] == :platform && (y == 0 || @tiles[x + (y - 1) * WIDTH] != :platform)\n @ledges.push(Rectangle.new(x * TILE_WIDTH, y * TILE_HEIGHT - Y_OFFSET, TILE_WIDTH, TILE_HEIGHT + Y_OFFSET))\n end\n @platforms.push(Rectangle.new(x * TILE_WIDTH, y * TILE_HEIGHT - Y_OFFSET, TILE_WIDTH, TILE_HEIGHT + Y_OFFSET)) if @tiles[x + y * WIDTH] == :platform\n end\n end\n end", "def load_moves\n\t\tif File.exists?(@filename)\n\t\t\t@past_moves = YAML.load_file(@filename)\n\t\telse\n\t\t\t@past_moves = []\n\t\tend\n\tend", "def load(fname)\n @score.clear\n File.foreach(fname) do |line|\n who, score, time = line.chomp.split(/\\s+/)\n @score[who] = [score.to_i, time]\n end\n end", "def load_game\n require './game/setup.rb'\n end", "def load_dungeon_file(level)\n clear_message_box\n #ask for file if necessary\n @ui.set_colour(DungeonOfDoom::C_BLACK_ON_YELLOW)\n unless @dungeon_file\n @ui.place_text('USE DUNGEON FILE?'.ljust(20),1,2)\n @ui.place_text('>'.ljust(20),1,3)\n #loop until file is good\n while @dungeon_file.nil?\n @ui.place_text(' '*19,2,3)\n @dungeon_file = @ui.get_string(2,3)\n #check to see if file exists\n unless File.exists?(@dungeon_file) #file must exist\n @ui.place_text('!FILE NOT FOUND'.ljust(20), 1, 4)\n @dungeon_file=nil\n end\n end\n end\n #check if here has enough experience to enter level\n if LEVEL_EXPERIENCE_CHECK && level > @stats[:experience]\n @ui.place_text(MSG_EXP.ljust(20),1,4)\n else\n #all okay, load level and start location\n levels = IO.readlines(@dungeon_file)\n new_level = levels.find do |data|\n #level data should be at position (15x15)+4=229\n data[229..230].to_i == level\n end\n if new_level\n #okay level found\n data = new_level.chars.to_a #make and array of characters\n (0..14).each do |row|\n (0..14).each do |col|\n @room[row][col] = data[(15*row)+col]\n end\n end\n @ui.draw_box(15,15,2,6,DungeonOfDoom::C_WHITE_ON_BLACK)\n @cur_x = (data[225]+data[226]).to_i\n @cur_y = (data[227]+data[228]).to_i\n @current_level = level\n @monster_detected = false\n else\n @ui.place_text(\"!LEVEL #{level} NOT FOUND\".ljust(20),1,4)\n @ui.place_text('!BAD DUNGEON FILE'.ljust(20),1,5)\n end\n end\n end", "def dynamic_load(file) # FilePair\n\t\tbegin\n\t\t\t# NOTE: file timestamps only have 1 sec resolution, so there may be a slight delay when attempting to reload more than once per second.\n\t\t\tif file.changed?\n\t\t\t\tfile.update_time\n\t\t\t\t# NOTE: Timestamps updated whenever load is *attempted*\n\t\t\t\t\t# This is actually what you want.\n\t\t\t\t\t# If you don't do it this way, then when there is a load error,\n\t\t\t\t\t# the system will try and fail to reload the file every tick\n\t\t\t\t\t# of the main loop.\n\t\t\t\t\t# This will generate a lot of useless noise in the log.\n\t\t\t\t\t# However, once the file is updated, you expect the system to\n\t\t\t\t\t# attempt a reload at least once.\n\t\t\t\t\n\t\t\t\tputs \"live loading #{file}\"\n\t\t\t\tload file.to_s\n\t\t\t\tself.successful_reload()\n\t\t\tend\n\t\trescue SyntaxError, ScriptError, NameError => e\n\t\t\t# This block triggers if there is some sort of\n\t\t\t# syntax error or similar - something that is\n\t\t\t# caught on load, rather than on run.\n\t\t\t\n\t\t\t# ----\n\t\t\t\n\t\t\t# NameError is a specific subclass of StandardError\n\t\t\t# other forms of StandardError should not happen on load.\n\t\t\t# \n\t\t\t# If they are happening, something weird and unexpected has happened, and the program should fail spectacularly, as expected.\n\t\t\t\n\t\t\tputs \"FAILURE TO LOAD: #{file}\"\n\t\t\t\n\t\t\tprint_wrapped_error(e)\n\t\t\t\n\t\t\tself.runtime_error()\n\t\tensure\n\t\t\t\n\t\tend\n\tend", "def load_or_new_game\n puts \"Welcome to Hangman!\"\n if File.exist?(\"savefile.txt\")\n puts \"Would you like to (1) load your saved game or (2) start a new game? Please enter 1 or 2.\"\n answer = gets.chomp\n if answer == \"1\"\n save_state = File.read(\"savefile.txt\")\n status = YAML.load(save_state)\n File.delete(\"savefile.txt\")\n else\n status = start_game\n end\n else \n status = start_game\n end\n show_board(status)\n return status\n end", "def initialize(path)\n File.open(path, 'rb') do |file|\n num_players = file.size / PLAYER_LENGTH\n @players = Buffer2d.new(num_players, PLAYER_LENGTH, nil)\n num_players.times do |x|\n player = file.read(PLAYER_LENGTH).chars\n @players.write_vert(x, 0, player)\n end\n\n puts \"Players file contains #{num_players} players.\"\n\n # modify_attribute(4, ATTRIBUTE_INFO[:name], 'sheeit')\n # modify_attribute(4, ATTRIBUTE_INFO[:exp], 100000)\n\n modify_attribute(4, ATTRIBUTE_INFO[:hp], 13200)\n\n modify_attribute(4, ATTRIBUTE_INFO[:level], 25)\n\n modify_attribute(4, ATTRIBUTE_INFO[:shield], 72)\n modify_attribute(4, ATTRIBUTE_INFO[:cloak], 72)\n modify_attribute(4, ATTRIBUTE_INFO[:boots], 72)\n modify_attribute(4, ATTRIBUTE_INFO[:ring], 72)\n modify_attribute(4, ATTRIBUTE_INFO[:weapon], 72)\n modify_attribute(4, ATTRIBUTE_INFO[:armor], 72)\n\n modify_attribute(4, ATTRIBUTE_INFO[:str], 32)\n modify_attribute(4, ATTRIBUTE_INFO[:int], 32)\n modify_attribute(4, ATTRIBUTE_INFO[:wis], 32)\n modify_attribute(4, ATTRIBUTE_INFO[:con], 32)\n modify_attribute(4, ATTRIBUTE_INFO[:dex], 32)\n modify_attribute(4, ATTRIBUTE_INFO[:cha], 32)\n\n compare\n print_by_attribute\n\n save_players\n end\n end", "def save_game\n\t\t# If current game was previously saved, delete the old version of current game...\n\t\tif @running_saved_game != nil\n\t\t\tover_write_data\n\t\tend\n\t\t# And add new version of current game to saved data\n\t\tFile.open(@path, 'a+') do |f|\n\t\t\t\tf.puts \"#{@word.join},#{@guess},#{@wrong_letters},#{@turn}\"\n\t\tend\n\tend", "def load_battle_test_database\n en_et_dm_lbd\n if FileTest.directory?(\"Data/Text/#{SES::ExternalText::Languages[0]}\")\n create_text\n end\n $game_text = load_data(\"Data/#{check_language}.rvdata2\")\n end", "def load_game_from_map(map_path)\n $LOGGER.info \"Loading map from file. Path: '#{map_path}'\"\n begin\n game_state = Game::GameState.new [Map::GameMap.new(Map.load_map(map_path))], Character::Character.new\n $LOGGER.info \"Map with id: '#{game_state.current_map}' loaded successful.\"\n return game_state\n rescue Map::MapParseException, NoMethodError => e\n $LOGGER.error \"Errors occured while map loading:\"\n $LOGGER.error e.message\n fail e\n end\n end", "def load\n yaml_filespec = @filespec.ext('.yaml')\n if File.exist?(yaml_filespec) && (File.mtime(yaml_filespec) > File.mtime(@filespec))\n load_from_yaml(yaml_filespec)\n else\n load_from_xml(@filespec)\n end\n end", "def load_game\n puts \"Would you like to load a saved game?\"\n puts \"Enter \\\"y\\\" or \\\"n\\\":\"\n input = gets.chomp\n if input != \"\" && input[0].downcase == \"y\"\n game = YAML.load(File.read(\"hangman.yaml\"))\n @word = game[:word]\n @max_turn = game[:max_turn]\n @current_turn = game[:current_turn]\n @display_word = game[:display_word]\n @current_guess = game[:current_turn]\n end\n puts \"Game is loaded!\"\n end", "def load\n puts \"Would you like to load your previous game? (y/n)\"\n puts \"\"\n response = gets.strip.downcase\n puts \"\"\n if response == \"y\" && File.exist?(\"saves.yaml\")\n save = File.read(\"saves.yaml\")\n @computer = YAML::load(save)\n puts \"Your game has been loaded!\"\n puts \"\"\n else\n puts \"New game created!\"\n puts \"\"\n end\n end", "def load(filename)\n @filename = filename\n @mtime = File::mtime(@filename)\n\n File.open(filename) { |f| parse(f) }\n end", "def load_file(file); end", "def load_file(filename); end", "def load_file(filename); end", "def load_supported_games\n @supported_game_map = InfoAvilGames.info_supported_games(@log)\n #@supported_game_map.each{|k,v| p k}\n #p @supported_game_map\n # execute require 'mygame'\n @all_games_bots.each do |botgame|\n infogame = @supported_game_map[botgame[:key]]\n if infogame != nil and infogame[:enabled] == true\n botgame[:name] = infogame[:name]\n botgame[:opt] = infogame[:opt]\n else\n @log.warn(\"Game bot key #{botgame[:key]} not enabled in game_info\")\n end\n end\n #p @all_games_bots\n end", "def initialize(file = \"\")\n @file = file\n @replays = []\n\n load if File.exist?(file)\n end", "def load_game\n @game = Game.find_by_id(params[:id])\n unless @game\n render( :status => :not_found, :text => \"Game not found.\")\n return false\n end\n return true\n end", "def load(filename)\n\t\tend", "def load_file(file)\n return if @loaded.include? file\n\n # We have to specify Kernel.load, because we have a load method.\n begin\n # Store the file path so we don't try to reload it\n @loaded << file\n Kernel.load(file)\n rescue ScriptError => detail\n # Don't store the path if the file can't be loaded\n # in case it's loadable later on.\n @loaded.delete(file)\n Facter.warn \"Error loading fact #{file} #{detail}\"\n end\n end", "def load(file); end", "def load_startup_time(delete_file = false)\n t = nil\n if File.exist?( $PROJECT_DIR + '/' + $TIME_LOG_FILE )\n File.open( $PROJECT_DIR + '/' + $TIME_LOG_FILE, \"r+\" ) do |infile|\n t = Marshal.load( infile )\n end\n if delete_file then File.delete( $PROJECT_DIR + '/' + $TIME_LOG_FILE ) end\n end\n t\nend", "def load!(file=nil)\n return if @loaded\n\n file ||= latest_binary_file\n\n unless file && File.readable?(file)\n if ENV['SWISSMATCH_DATA']\n raise LoadError.new(\"File #{file.inspect} not found or not readable (used SWISSMATCH_DATA, data_directory=#{@data_directory}) - see https://github.com/apeiros/swissmatch-location#installation\", nil)\n else\n raise LoadError.new(\"File #{file.inspect} not found or not readable (used ~/.swissmatch, data_directory=#{@data_directory}) - see https://github.com/apeiros/swissmatch-location#installation\", nil)\n end\n end\n\n data = File.read(file, encoding: Encoding::BINARY)\n date, random_code, zip1_count, zip2_count, com1_count, com2_count, district_count = *data[0,18].unpack(\"NNn*\")\n int1_size, int2_size, int4_size, text_size = *data[18,16].unpack(\"N*\")\n\n offset = 34\n int1_cols = data[offset, int1_size].unpack(\"C*\")\n int2_cols = data[offset+=int1_size, int2_size].unpack(\"n*\")\n int4_cols = data[offset+=int2_size, int4_size].unpack(\"N*\")\n text_cols = data[offset+=int4_size, text_size].force_encoding(Encoding::UTF_8).split(\"\\x1f\")\n\n offset = 0\n zip1_type = int1_cols[offset, zip1_count]\n zip1_addon = int1_cols[offset += zip1_count, zip1_count]\n zip1_language = int1_cols[offset += zip1_count, zip1_count]\n zip1_language_alternative = int1_cols[offset += zip1_count, zip1_count]\n zip2_region = int1_cols[offset += zip1_count, zip2_count]\n zip2_type = int1_cols[offset += zip2_count, zip2_count]\n zip2_lang = int1_cols[offset += zip2_count, zip2_count]\n com2_PLZZ = int1_cols[offset += zip2_count, com2_count]\n\n offset = 0\n zip1_onrp = int2_cols[offset, zip1_count]\n zip1_code = int2_cols[offset += zip1_count, zip1_count]\n zip1_delivery_by = int2_cols[offset += zip1_count, zip1_count]\n zip1_largest_community_number = int2_cols[offset += zip1_count, zip1_count]\n zip2_onrp = int2_cols[offset += zip1_count, zip2_count]\n com1_bfsnr = int2_cols[offset += zip2_count, com1_count]\n com1_agglomeration = int2_cols[offset += com1_count, com1_count]\n com2_GDENR = int2_cols[offset += com1_count, com2_count]\n com2_PLZ4 = int2_cols[offset += com2_count, com2_count]\n district_GDEBZNR = int2_cols[offset += com2_count, district_count]\n\n zip1_valid_from = int4_cols\n\n offset = 0\n zip1_name_short = text_cols[offset, zip1_count]\n zip1_name = text_cols[offset += zip1_count, zip1_count]\n zip1_canton = text_cols[offset += zip1_count, zip1_count]\n zip2_short = text_cols[offset += zip1_count, zip2_count]\n zip2_name = text_cols[offset += zip2_count, zip2_count]\n com1_name = text_cols[offset += zip2_count, com1_count]\n com1_canton = text_cols[offset += com1_count, com1_count]\n district_GDEKT = text_cols[offset += com1_count, district_count]\n district_GDEBZNA = text_cols[offset += district_count, district_count]\n\n zip1 = [\n zip1_onrp, zip1_type, zip1_canton, zip1_code, zip1_addon,\n zip1_delivery_by, zip1_language, zip1_language_alternative,\n zip1_name_short, zip1_name, zip1_largest_community_number,\n zip1_valid_from\n ].transpose\n zip2 = [zip2_onrp, zip2_region, zip2_type, zip2_lang, zip2_short, zip2_name].transpose\n com1 = [com1_bfsnr, com1_name, com1_canton, com1_agglomeration].transpose\n com2 = [com2_PLZ4, com2_PLZZ, com2_GDENR].transpose\n district = [district_GDEKT, district_GDEBZNR, district_GDEBZNA].transpose\n\n @date = Date.jd(date)\n @random_code = random_code\n @cantons = AllCantons\n @districts = load_districts(district)\n @communities = load_communities(com1)\n @zip_codes = load_zipcodes(zip1, zip2, com2)\n\n self\n end", "def load(filename)\n end", "def load_game\n @game = Game.find params[:id]\n head :unprocessable_entity unless @game\n end", "def endgame()\n\t\t@database = Database.new\n\t\t@database.save_files(@players)\n\t\t@database.load_files\n\tend", "def loadGame \n \"loadGame\" \n end", "def mark_loaded(name, file)\n name = cleanpath(name).chomp('.rb')\n file = File.expand_path(file)\n $LOADED_FEATURES << file unless $LOADED_FEATURES.include?(file)\n loaded[name] = [file, File.mtime(file)]\n end", "def parse_file(filename: \"\", type: \"level\")\n !filename.empty? ? file = File.binread(filename) : return\n case type\n when \"level\"\n mode = file[12].reverse.hd # game mode: 0 = solo, 1 = coop, 2 = race, 4 = unset\n title = file[38..165].split(//).delete_if{ |b| b == \"\\x00\" }.join\n author = \"\"\n map = parse_map(data: file[184..-1], type: \"new\")\n when \"attract\"\n map_length = file[0..3].reverse.hd\n demo_length = file[4..7].reverse.hd\n map_data = file[8 .. 8 + map_length - 1]\n demo_data = file[8 + map_length .. 8 + map_length + demo_length - 1]\n\n level_id = map_data[0..3].reverse.hd\n title = map_data[30..157].split(//).delete_if{ |b| b == \"\\x00\" }.join\n index = map_data[159..-1].split(//).find_index(\"\\x00\") + 158\n author = map_data[159..index]\n map = parse_map(data: map_data[index + 2..-1], type: \"new\")\n # demo = parse_demo(data: demo_data, attract: true) # no se si el attract hace falta, comparar esto con una replay normal\n when \"old\"\n title = file.split('#')[0][1..-1]\n author = \"Metanet Software\"\n map = parse_map(data: file.split(\"#\")[1], type: \"old\")\n else\n print(\"ERROR: Incorrect type (level, attract, old).\")\n return 0\n end\n {title: title, author: author, tiles: map[:tiles], objects: map[:objects]}\nend", "def save_game\n\t\tputs \"Type a name for your saved game\"\n\t\tgame_name = gets.chomp\n\t\tfilename = \"#{game_name}.txt\"\n\n\t\t ex_file = File.expand_path(\"./saved_games/#{filename}\")\n\t\t \n\t\tif File.exists?(ex_file)\n\t puts \"#{filename} exists\" #overwrite method?\n\t \n\t self.save_game\n\t else\n\t\t\tFile.open(ex_file, \"w\") do |f|\n\n\t\t\t\tf.puts YAML::dump(game_state)\n\n\t\t\t\tputs \"Your game was saved as #{filename}\" \n\t\t\tend\n\t\tend\n\tend", "def save_game\n\t\tall_saved_games = yaml_load(SAVED_FILENAME)\n\t\tgame_name = get_save_name(all_saved_games)\n\t\treturn if game_name.nil?\n\n\t\tgame_string = self.to_yaml \n\t\tall_saved_games[game_name] = game_string\n\t\tyaml_save(SAVED_FILENAME, all_saved_games)\n\t\tmessage_then_enter \"'#{ game_name }' successfully saved.\"\n\tend", "def save_game\n\t\tputs \"Type a name for your saved game\"\n\t\tgame_name = gets.chomp\t\n\t\tfilename = \"#{game_name}.yml\"\n\n\t\t ex_file = File.expand_path(\"./saved_games/#{filename}\")\n\t\t \n\t\tif File.exists?(ex_file)\n\t puts \"#{filename} exists\" #overwrite method?\n\t \n\t self.save_game\n\t else\n\t\t\tFile.open(ex_file, \"w\") do |f|\n\t\t\t\tgame_state = YAML::dump(self)\n\t\t\t\tf.puts game_state\n\t\t\t\tputs \"Your game was saved as #{filename}\" \n\t\t\tend\n\t\tend\n\tend", "def play\n frames = {}\n\n # Keep track of the last player\n last_player = nil\n\n # Iterate each line from the file\n File.open(@filename).each do |line|\n # Assign new player\n player = Player.new(line.split(' ').first)\n\n # Assign empty array if player frame is nil\n frames[player] = [] if frames[player].nil?\n\n # Get score\n score = line.split(' ').last\n\n # Verify whether last player is not equal to current player\n unless last_player.eql? player\n # Assign the last frame number to each player\n frames[player] << Frame.new(frames[player].last.number || 0) unless frames[player].last.nil?\n\n # Assign frame 0 if player has no frame\n frames[player] << Frame.new(0) if frames[player].last.nil?\n end\n\n # Add score to player frame\n frames[player].last.add(score)\n\n # Assign last player to current player\n last_player = player\n end\n\n # Return hash of frames\n frames\n end", "def test_filetime\n\t\t# for saving, we can use Date, Time, or DateTime.\n\t\tassert_equal \"\\000\\000\\260\\3077-\\307\\001\", FileTime.dump(Time.gm(2007, 1, 1))\n\t\ttime = FileTime.load \"\\000\\000\\260\\3077-\\307\\001\"\n\t\tassert_equal FileTime, time.class\n\t\tassert_equal '2007-01-01T00:00:00+00:00', time.to_s\n\t\t# note that if we'd used Time.local, instead of gm, we'd get a different value. eg\n\t\tassert_equal \"\\000\\370\\331\\336\\r-\\307\\001\", FileTime.dump(DateTime.parse('2007-01-01 00:00 +0500'))\n\t\t# note that it still loads up as GMT, because there's no associated time zone.\n\t\t# essentially, i'm storing and loading times as GMT. maybe i should add in conversion to local time\n\t\t# zone when loading\n\t\tassert_equal '2006-12-31T19:00:00+00:00', FileTime.load(\"\\000\\370\\331\\336\\r-\\307\\001\").to_s\n\t\t# test loading a bogus time\n\t\tassert_equal nil, FileTime.load(0.chr * 8)\n\t\t# this used to be counted as an \"unlikely time\", and discarded. that has been removed\n\t\tassert_equal '1700-01-01T00:00:00+00:00', FileTime.load(FileTime.dump(Date.new(1700, 1, 1))).to_s\n\t\tassert_equal '#<Ole::Types::FileTime 2006-12-31T19:00:00+00:00>', FileTime.load(\"\\000\\370\\331\\336\\r-\\307\\001\").inspect\n\tend", "def load\n if File.exist?(@file_path)\n\n @_cache = JSON File.open(@file_path, &:read).strip\n else\n $stderr.puts \"#{@file_path} does not exist\"\n end\n end", "def load_supported_games\r\n @supported_game_map = InfoAvailableGames.info_supported_games(@log)\r\n #p @supported_game_map\r\n SETTINGS_DEFAULT_APPGUI[:games_opt] = {}\r\n @supported_game_map.each do |k, game_item|\r\n if game_item[:enabled] == true\r\n require game_item[:file_req]\r\n @log.debug(\"Game #{game_item[:name]} is enabled\")\r\n SETTINGS_DEFAULT_APPGUI[:games_opt][k] = game_item[:opt]\r\n end\r\n end\r\n end", "def fgame\n if @full_game == nil\n @full_game = Game.from_game_string(self.game)\n end\n @full_game\n end", "def yaml_load\n if File.exist?(yaml_file) && !File.zero?(yaml_file)\n YAML.load_file(yaml_file).sort_by!(&:time).reverse!\n else\n []\n end\n end", "def load(file_path); end", "def load(file_path); end", "def load(file = @monster.filename, dir = @monster.work_dir, *_args)\n path = get_path(file, dir)\n a = split_canvas(ChunkyPNG::Canvas.from_file(path))\n h = { rom: @rom, index: @index }\n\n normal_rgb = a[0].to_rgb_stream + a[2].to_rgb_stream\n shiny_rgb = a[1].to_rgb_stream + a[3].to_rgb_stream\n\n @palettes = Palette.create_synced_palettes(\n normal_rgb,\n shiny_rgb,\n h.merge(table: :palette_table),\n h.merge(table: :shinypal_table)\n )\n\n frames = @rom.special_frames.fetch(@index, @rom.frames)\n front = crop_canvas(a[0], frames.first * 64)\n back = crop_canvas(a[2], frames.last * 64)\n\n @sprites = [\n Sprite.from_canvas(\n front,\n @palettes.first,\n h.merge(table: :front_table)\n ),\n Sprite.from_canvas(\n back,\n @palettes.first,\n h.merge(table: :back_table)\n )\n ]\n\n justify\n self\n end", "def load(folder_path)\n players = []\n @errors = []\n \n Dir[\"#{folder_path}/*.rb\"].each do |player_file| \n require_player_file player_file\n end\n \n Module.constants.select do |constant_name|\n constant = eval constant_name.to_s\n if not constant.nil? and constant.is_a? Class and constant_name.to_s.end_with? \"Player\"\n if check_method(constant, constant_name, 'name') && check_method(constant, constant_name, 'new_game') && check_method(constant, constant_name, 'take_turn') \n players << constant\n end\n end\n end\n \n return players\n end", "def has_valid_game_path?\n return File.exists?(game_path)\n end", "def load_game?\n\t\tputs \"Would you like to load a previously saved game\"\n\t\tputs \"(yes or no)\"\n\t\tanswer = gets.chomp.downcase\n\t\tif answer == \"yes\"\n\t\t\tload\n\t\telsif answer == \"no\"\n\t\t\treturn\n\t\telse\n\t\t\tputs \"I did not understand that answer, try again\"\n\t\t\tload_game?\n\t\tend\n\tend", "def data_load\r\n unless $data_actors\r\n $data_actors = _clean_name_utf8(load_data(\"Data/Actors.rxdata\"))\r\n $data_classes = _clean_name_utf8(load_data(\"Data/Classes.rxdata\"))\r\n $data_enemies = _clean_name_utf8(load_data(\"Data/Enemies.rxdata\"))\r\n $data_troops = _clean_name_utf8(load_data(\"Data/Troops.rxdata\"))\r\n $data_tilesets = _clean_name_utf8(load_data(\"Data/Tilesets.rxdata\"))\r\n $data_common_events = _clean_name_utf8(load_data(\"Data/CommonEvents.rxdata\"))\r\n $data_system = load_data_utf8(\"Data/System.rxdata\")\r\n end\r\n $game_system = Game_System.new\r\n $game_temp = Game_Temp.new\r\n end", "def gamedate_check(game)\n if @schedule.size > 0\n games_this_date = Game.on_that_date(@schedule, @cur_date)\n\n if Game.any_team_play?(games_this_date, game.team_a, game.team_b)\n @cur_rule_index = (@cur_rule_index < @rules.size - 1) ? @cur_rule_index + 1 : 0\n @cur_rule = @rules[@cur_rule_index]\n reset_resource_availability\n @cur_game_time = get_best_game_time(game)\n @cur_ps = get_best_field(game, @cur_game_time)\n @cur_date = next_game_date(@cur_date += 1, @cur_rule.wday)\n end\n end\n end", "def battler(filename, _hue = 0)\n load_image(@battler_cache, filename, Battlers_Path, @battler_data)\n end", "def modified?\n return File.mtime(@filename).to_i > @load_time\n end", "def handle_loading\n check_watched_files\n reload! if !loaded? && load_cooldown_expired?\n end", "def dump\n File.open(\"saved_games.yaml\", \"a\") do |out|\n YAML::dump(self, out)\n end\n end", "def gamedate_check(game)\n return unless @schedule.size.positive?\n\n games_this_date = Game.on_that_date(@schedule, @cur_date)\n\n return unless Game.any_team_play?(games_this_date, game.team_a, game.team_b)\n\n @cur_rule_index = @cur_rule_index < @rules.size - 1 ? @cur_rule_index + 1 : 0\n @cur_rule = @rules[@cur_rule_index]\n reset_resource_availability\n @cur_game_time = get_best_game_time(game)\n @cur_ps = get_best_field(game, @cur_game_time)\n @cur_date = next_game_date(@cur_date += 1, @cur_rule.wday)\n end", "def load(filename)\n Format.load(filename)\n end", "def load_file(filename)\n full_file = File.expand_path(filename, @dispatch.save_dir)\n save_dir(full_file)\n begin\n File.new(full_file, 'r').each do |line|\n break unless load(full_file, $., line)\n end\n rescue\n puts \"Error loading file #{full_file}\"\n end\n restore_dir\n end", "def anaylze(load_file)\n generate_all(load_file)\n=begin\n get_win_rates(load_file)\n get_win_turn(load_file)\n get_win_damage(load_file)\n=end\n end", "def safe_load(file, options={})\n began_at = Time.now\n file = figure_path(file)\n return unless options[:force] || file_changed?(file)\n return require(file) if feature_excluded?(file)\n\n Storage.prepare(file) # might call #safe_load recursively\n logger.devel(file_new?(file) ? :loading : :reload, began_at, file)\n begin\n with_silence{ require(file) }\n Storage.commit(file)\n update_modification_time(file)\n rescue Exception => exception\n unless options[:cyclic]\n logger.exception exception, :short\n logger.error \"Failed to load #{file}; removing partially defined constants\"\n end\n Storage.rollback(file)\n raise\n end\n end", "def run_app\n games = []\n @standings = []\n\n # load file from cli arg and parse teams and games\n # NOTE: for this exercise, if CLI argument is omitted, \n # it will load the sample file by default\n load_file.each do |line|\n game = []\n\n # get game's teams, fetch scores, and ensure team is listed in standings\n teams = line.chomp.split(\", \")\n\n teams.each do |team|\n team_stats = parse_game(team)\n add_team_to_standings(team_stats[:name])\n\n game << team_stats\n end\n\n games << game\n end\n\n # determine if tie game\n games.each do |game|\n if game.first[:score] == game.last[:score]\n its_a_tie(game)\n else\n determine_winner(game)\n end\n end\n\n # return and print winners by placement\n output_placements\nend", "def load file='GOL.sav'\n self.state=File.open(file,'r') do |f|\n Marshal.load(f)\n end\n end", "def load\n statefile_filename = state_filename\n if File.exist?(statefile_filename) &&\n File.file?(statefile_filename) &&\n File.readable?(statefile_filename)\n $log.debug \"Loading state from #{statefile_filename}\"\n @state = YAML.load_file(statefile_filename)\n else\n $log.debug 'No statefile found.'\n clean\n end\n @changed = false\n end", "def load_game(chosen_word,word_guess,dead_man)\n @chosen_word = chosen_word\n @word_guess = word_guess\n @dead_man = dead_man\n\n @word_guess.display(@dead_man)\n round\n end", "def load\n flush\n replay\n end", "def save_curr_game(fname)\n @log.debug \"Don't save the network game\"\n end", "def tick args\n if !args.state.loaded && !respond_to?(:game) # if game is not loaded and not responding to game symbol's method\n args.labels << [640, 370, 'Hey there! Welcome to Four Decisions.', 0, 1] # a welcome label is shown\n args.labels << [640, 340, 'Go to the file called decision.rb and tell me your story.', 0, 1]\n elsif respond_to?(:game) # otherwise, if responds to game\n args.state.loaded = true\n tick_game args # calls tick_game method, runs game\n end\n\n if args.state.tick_count.mod_zero? 60 # update every 60 frames\n t = args.gtk.ffi_file.mtime GAME_FILE # mtime returns modification time for named file\n if t != args.state.mtime\n args.state.mtime = t\n require GAME_FILE # require used to load file\n args.state.game_definition = nil # game definition and decision are empty\n args.state.decision_id = nil\n end\n end\nend", "def load!(file_path)\n if File.exist? file_path\n @log = YAML.load(File.read(file_path))\n else\n @log = {}\n end\n end", "def load_twlfile(file)\n tm_assert{ file.is_a? Pathname }\n tm_assert{ file.exist? }\n ThinWestLake::Project.last_instance = nil\n load file.to_s\n tm_assert{ ThinWestLake::Project.last_instance }\n ThinWestLake::Project.last_instance.twlpath file.parent\n ThinWestLake::Project.last_instance\n end", "def reload\n load @filename\n end", "def load\n if File.exists? @file\n @main = YAML::load_file @file\n else\n self.load_defaults\n end\n end", "def checkWall\n path = $path + \"/themes/\" + loadconf + '/'\n t = Time.now\n # convert timestring to int such that the highest 4 digit number is 2359\n # now it it easy to check instead of checking hours and minutes seperately\n @timenow = (t.strftime('%H') + t.strftime('%M')).to_i\n @theme = YAML.load_file(path + loadconf + \".yaml\")\n k = @theme.keys\n @wp = path + @theme[k[0]]\n\n k.each do |item|\n timeparse item\n puts @time\n puts @timenow\n if @timenow >= @time\n @wp = path + @theme[item]\n #puts @wp\n end\n end\n setwall @wp\n end", "def load_normal_database\n en_et_dm_lnd\n if FileTest.directory?(\"Data/Text/#{SES::ExternalText::Languages[0]}\")\n create_text\n end\n $game_text = load_data(\"Data/#{check_language}.rvdata2\")\n end" ]
[ "0.77167517", "0.727479", "0.72611916", "0.7061204", "0.6986792", "0.69377977", "0.685706", "0.6831958", "0.6797869", "0.67838186", "0.664105", "0.6372434", "0.63679725", "0.6291665", "0.6234307", "0.6166935", "0.6145533", "0.6017127", "0.60056835", "0.59807503", "0.5978757", "0.59684265", "0.5966986", "0.5877333", "0.58486265", "0.58264995", "0.58010924", "0.5787201", "0.57596076", "0.57593596", "0.5742311", "0.57370514", "0.5709436", "0.5703127", "0.5688371", "0.567732", "0.5676825", "0.566809", "0.5643144", "0.5634448", "0.56096107", "0.5603935", "0.560137", "0.55513126", "0.55497634", "0.55466104", "0.55466104", "0.55463505", "0.55219007", "0.54983914", "0.5494309", "0.54816025", "0.5480751", "0.54703087", "0.546096", "0.54568213", "0.5456601", "0.54071826", "0.53695846", "0.5354193", "0.5326955", "0.5315445", "0.5315176", "0.5294539", "0.5289492", "0.5268082", "0.52397543", "0.5236283", "0.5231985", "0.5228775", "0.5218705", "0.5218705", "0.5209568", "0.52034277", "0.5193916", "0.51876414", "0.51847774", "0.5184163", "0.51769966", "0.5159039", "0.51587135", "0.51489925", "0.5145246", "0.51412773", "0.51406264", "0.5140449", "0.51385957", "0.5137518", "0.5131504", "0.51285046", "0.5126333", "0.51215833", "0.51211256", "0.5120189", "0.51187617", "0.5116778", "0.5112565", "0.5109548", "0.5105394", "0.5104468" ]
0.80305064
0
Oauth specfic login method
def auth request.env['omniauth.auth'] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def oauth\n login_at(auth_params[:provider])\n end", "def oauth\n login_at(auth_params[:provider])\n end", "def oauth_authentication; end", "def http_auth_login\n # FIXME: Implement\n end", "def oauth_login oauth\n method = ::AuthMethod.by_provider_data oauth.provider_data\n\n if !method\n user = find_by_email(oauth.email) || create_from_oauth(oauth)\n\n if user.respond_to? :add_auth_method\n method = user.add_auth_method oauth.provider_data\n else\n method = user.auth_methods.create! oauth.provider_data\n end\n end\n\n method.create_token access_token: oauth.access_token\n end", "def login_by_token\n\n end", "def signin\n oauth_authorize\n end", "def oauth\n session[:return_to_url] = params[:redirect_after_login] if params[:redirect_after_login]\n login_at(auth_params[:provider])\n end", "def login; end", "def auth\r\n OAuth2\r\n end", "def login\n params = {\n :head => { 'authorization' => [@username, @password] },\n :body => {}\n }\n params[:body]['client_id'] = @client_id if @client_id\n params[:body]['client_secret'] = @client_secret if @client_secret\n http = EM::HttpRequest.new(API_OAUTH_URL).post(params)\n\n http.errback do |http|\n fail(http.error, *@deferrable_args)\n end\n\n http.callback do |http|\n if http.response_header.status != 200\n fail(http.response, *@deferrable_args)\n next\n end\n\n @access_token = http.response\n if @access_token.nil?\n fail('OAuth request did not return an access token', *@deferrable_args)\n next\n else\n yield if block_given?\n end\n end\n end", "def login\n oauth_callback = url_for(:action => :authorize)\n request_token = @consumer.get_request_token(:oauth_callback => oauth_callback)\n session[:request_token] = request_token\n redirect_to request_token.authorize_url\n end", "def oauth\n Auth.new(params[:uid], params[:oauth_token], action_name)\n end", "def oauth_login\n @login_handler =\n ProviderLogin.from_provider(\n params[:provider], params[:auth_token], params[:auth_token_secret]\n )\n\n if @login_handler.save\n expose @login_handler.user, serializer: CompactUserSerializer\n else\n error! :invalid_resource, @login_handler.user.errors,\n metadata: {\n error_description: \"An error occured when creating a user.\"\n }\n end\n end", "def login\n\n end", "def login\n\n end", "def capable_login_auth?; end", "def login\n end", "def login\n end", "def login\n end", "def login\n end", "def login\n end", "def login\n end", "def login\n end", "def login\n end", "def login\n end", "def auth\n end", "def auth\n end", "def login\n end", "def auth\n ::Deepblue::LoggingHelper.bold_debug [ ::Deepblue::LoggingHelper.here,\n ::Deepblue::LoggingHelper.called_from,\n \"params=#{params}\",\n \"\" ] if browse_everything_controller_debug_verbose\n # params contains the access code with with the key :code\n provider_session.token = provider.connect(params, provider_session.data, connector_response_url_options)\n ::Deepblue::LoggingHelper.bold_debug [ ::Deepblue::LoggingHelper.here,\n ::Deepblue::LoggingHelper.called_from,\n \"provider_session.token=#{provider_session.token}\",\n \"\" ] if browse_everything_controller_debug_verbose\n provider_session.token\n end", "def login\n \tauthenticate(params)\n end", "def login\n state_json = {\n redirect_url: params[:redirect_url],\n access_token: params[:access_token],\n ip: request.remote_ip\n }\n\n unless params[:mixpanel_id].blank?\n state_json.merge!(mp_id: params[:mixpanel_id])\n end\n\n encoded_state = LinkedAccount::Base.encode_state(state_json)\n\n case params[:provider]\n when 'github'\n redirect_to LinkedAccount::Github::User.oauth_url(scope: params[:scope], state: encoded_state)\n\n when 'facebook'\n redirect_to LinkedAccount::Facebook.oauth_url(scope: params[:scope], state: encoded_state)\n\n when 'twitter'\n redirect_to LinkedAccount::Twitter.oauth_url(scope: params[:scope], state: encoded_state)\n\n else render json: { error: 'Unsupported provider' }, status: :bad_request\n end\n end", "def login_from_param\n return true unless params[:auth_provider]\n return true unless request.get?\n if logged_in?\n uri_pieces = request.fullpath.split('?')\n param_pieces = uri_pieces[1].split('&')\n param_pieces.delete_if {|p| p =~ /^auth_provider/}\n redirect_to [uri_pieces[0], param_pieces.join('&')].join('?')\n return true\n end\n provider, url = ProviderAuthorization::AUTH_URLS.detect do |provider, url| \n provider.downcase == params[:auth_provider].to_s.downcase\n end\n if url\n return redirect_to oauth_bounce_url( provider: provider )\n end\n true\n end", "def login\n client.login(\n params[:user],\n params[:password],\n authParams: {\n scope: 'openid name email'\n },\n connection: 'Username-Password-Authentication'\n )\n end", "def login_0\n\n #definde needed header\n headers = {'Authorization' => \"Basic \" + @base_user_string}\n\n #Login\n response = request({:method => \"POST\", :url => @host + \"login\", :headers => headers})\n\n #Get organisation link\n @org_link = parse_content(response.body, '//Org')[0].attribute('href').to_s\n\n #Get authentication header key\n @auth_key = response.headers[:x_vcloud_authorization]\n\n end", "def authenticate\n # if valid_access_token?\n # fetch_access_token\n # else\n get_new_access_token\n # end\n end", "def login\n mandatory_keys = [:app_id, :user_name, :password, :sign]\n if params.slice(*mandatory_keys).values.any?(&:nil?)\n render json: to_response('Some params are lost') and return\n elsif @service_provider.nil?\n render json: to_response('ServiceProvider error') and return\n elsif not CommonUtils.valid_sign?(params[:app_id], params[:user_name], params[:password], @service_provider.credential, params[:sign])\n render json: to_response('Invalid request: parameter error') and return\n end\n\n user = User.find_by_user_name(params[:user_name])\n if user && user.authenticate(params[:password])\n render json: (user.invalid_role? ? to_response('User needs to be activated') : to_response('success', user))\n elsif user.nil?\n render to_response \"User not exist:#{params[:user_name]}\"\n else\n render to_response 'Password error'\n end\n end", "def login\n @request_token = twitter_api.connection.consumer.get_request_token(oauth_callback: callback_url)\n session[:request_token] = @request_token\n redirect_to @request_token.authorize_url\n end", "def token_auth(*args, &block); end", "def userauth_request(username, next_service, auth_method, *others); end", "def auth_http(info = @config[\"login/\"])\n # parse parameters\n case info\n when String\n # If the parameter is given by a string,\n # It is treated as the user name\n user = info\n reload = false\n browser = false\n when Hash\n user = info.fetch(:user, @config[\"login/\"])\n reload = info.fetch(:reload, false)\n browser = info.fetch(:browser, false)\n else\n errmsg = \"A String (user name) or Hash (parameters) is required as the argument (#{info.class} given)\"\n if info == nil\n errmsg << \"\\n* Perhaps you have not finished authentication. Try '#{$0} init' to register the default user.\"\n end\n raise ArgumentError, errmsg\n end\n \n # creates an instance of AccessToken\n user_key = \"users/#{user}\"\n @config[user_key] ||= {}\n \n if reload || !(user_registered?(user))\n # if token is not stored, or the library user choosed not to use stored token,\n # retrieves it with xAuth or browser\n if browser\n # with browser\n access_token = TwBot.access_token_via_browser(user)\n else\n # with xAuth\n # \n # Note:\n # TwBot is not allowed to use xAuth for now.\n # \"TwBot.access_token_via_xauth\" will always return HTTP 401 error.\n # (2010-04-30)\n unless @config[user_key][\"password\"]\n if user == @config[\"login/\"]\n @config[user_key][\"password\"] = @config[\"password/\"]\n else\n raise IncompleteConfigError, \"Password for user \\\"#{user}\\\" is not specified.\"\n end\n end\n \n access_token = TwBot.access_token_via_xauth(user, @config[user_key][\"password\"])\n end\n \n return nil if access_token == nil\n \n # Store the result to @config\n @config[user_key][\"token\"] = access_token.token\n @config[user_key][\"secret\"] = access_token.secret\n \n # return the access token\n access_token\n else\n # if token is stored, creates access token with it\n OAuth::AccessToken.new(@@consumer, @config[user_key][\"token\"], @config[user_key][\"secret\"])\n end\n end", "def login_required\n if session[:user_id]\n @user ||= User.find(session[:user_id])\n @access_token ||= OAuth::AccessToken.new(get_consumer, @user.oauth_token, @user.oauth_secret)\n else\n redirect_to :controller => 'session', :action => 'new'\n end\n end", "def http_auth?; end", "def login_at(provider, args = {})\n @provider = Config.send(provider)\n if @provider.has_callback?\n redirect_to @provider.login_url(params,session)\n else\n #@provider.login(args)\n end\n end", "def login\n make_login_call\n end", "def login\n\tend", "def authenticate!\n redirect \"https://github.com/login/oauth/authorize?scope=user:email,read:org&client_id=#{CLIENT_ID}\"\nend", "def require_login\n end", "def authenticate_signin\n\t Client.authenticate(params[:email], params[:password]) || render_unauthorized\n\t end", "def login!(passwd = nil)\n self.password = passwd || self.password\n response = client.login(username.to_s, password.to_s)\n apply_attributes! response.result\n self.session_token.present?\n end", "def oauth_login_path name = nil\n oauth_instance(name).login_path\n end", "def authorize\n oauth_verifier = params[:oauth_verifier]\n request_token = session[:request_token]\n access_token = request_token.get_access_token(:oauth_verifier => oauth_verifier)\n \n user = User.login(access_token)\n session[:user] = user.id unless user.nil?\n redirect_to :controller => :home\n end", "def sign_in\n login = params['login']\n password = params['password']\n type = (params['type'] || 'standard').to_sym\n\n if login.nil? || password.nil?\n render :json => {error:'please enter params'}\n return\n end\n\n if type == :standard\n user = User.where(login:login,password:password,user_type:type).first\n if user.nil?\n render :json => { login:false , error: 'Invalid credentials' }\n return\n else\n raw_token = {login: user.login , password: password , type:user.user_type }\n token = JsonWebToken.encode(raw_token)\n render :json => { login:true , token: token , admin:user.admin , user: {login:user.login, type:user.user_type, id: user.id} }\n return\n end\n end\n if type == :ldap\n sing_in_ldap({login:login, password:password})\n\n end\n end", "def request_login\n _store_request_information 'login'\n\n redirect_to user_omniauth_authorize_path(params[:provider])\n end", "def oauth\n request_token = @oauth_consumer.get_request_token\n authorize_url = request_token.authorize_url(:oauth_consumer_key => \n Netflix::Client.consumer_key)\n Launchy.open(authorize_url)\n puts \"Go to browser, a page has been opened to establish oauth\"\n printf \"Pin from Netflix:\"\n pin = gets.chomp\n access_token = request_token.get_access_token(:oauth_verifier => pin)\n end", "def oauth\n if params[:code]\n token_response = get_user_tokens(params[:code])\n signup_or_login(token_response)\n end\n\n render json: params\n end", "def login_url(params,session)\n req_token = self.get_request_token\n session[:request_token] = req_token.token\n session[:request_token_secret] = req_token.secret\n self.authorize_url({:request_token => req_token.token, :request_token_secret => req_token.secret})\n end", "def facebook\n handle_oauth\n end", "def login(*credentials)\n basic_authorize(*credentials)\n end", "def login_url(params,session)\n self.authorize_url({:authorize_url => @auth_path})\n end", "def auth_param; end", "def login\n #localhost:3000/api/login -u 'admin:password'\n authenticate_or_request_with_http_basic do |username, password|\n if username.include? '%40'\n email = username.gsub('%40','@');\n @user = User.find_by_email(email.downcase)\n else\n @user = User.find_by_username(username.downcase)\n end\n\n if @user && @user.authenticate(password)\n remember_token = RememberToken.create(token: User.encrypt(User.new_remember_token), user_id: @user.id, accessed_at: Time.now)\n respond_to do |format|\n format.json { render :json => remember_token }\n end\n end\n end\n end", "def auth(value); end", "def login\n if current_user and params[:return_to]\n # Already logged in; just need to send a token to the requesting\n # API client.\n #\n # FIXME: if current_user has never authorized this app before,\n # ask for confirmation here!\n\n send_api_token_to(params[:return_to], current_user)\n elsif params[:return_to]\n redirect_to \"/auth/joshid?return_to=#{CGI.escape(params[:return_to])}\"\n else\n redirect_to \"/auth/joshid\"\n end\n end", "def authentication\n login_required and \n (params[\"commit\"] == \"Login\" or verify_authenticity_token) \n end", "def action_login!()\n @action = TAC_PLUS_AUTHEN_LOGIN\n\n end", "def login_api\n @user = User.find_for_database_authentication({:username => params[:username].downcase})\n\n if (!@user.nil?)\n if (!@user.valid_password?(params[:password]))\n @user = nil\n end\n end\n\n if (@user.nil?)\n @user = User.find_by_auth_token(params[:auth_token]) unless params[:auth_token].nil?\n else\n @user.generate_auth_token\n end\n\n if @user.nil?\n # Do nothing\n error \"Your username or password was incorrect.\"\n else\n render json: @user\n end\n end", "def login_api\n @user = User.find_for_database_authentication({:username => params[:username].downcase})\n\n if (!@user.nil?)\n if (!@user.valid_password?(params[:password]))\n @user = nil\n end\n end\n\n if (@user.nil?)\n @user = User.find_by_auth_token(params[:auth_token]) unless params[:auth_token].nil?\n else\n @user.generate_auth_token\n end\n\n if @user.nil?\n # Do nothing\n error \"Your username or password was incorrect.\"\n else\n render json: @user\n end\n end", "def api_login\n creator = Creator.find_by(name: request.headers['name'])\n if creator && creator.authenticate(request.headers['password'])\n encode = encodeJWT(creator)\n selected_format({jwt: encode,creator_id: creator.id,name: creator.name,submits:creator.submits},:ok)\n else\n selected_format({ error: 'Invalid username or password' },:unauthorized)\n end\n end", "def oauth\n puts '*'*50\n puts session[:category]\n session[:category] = nil\n session[:category] = params[:category]\n puts '*'*50\n puts session[:category]\n login_at(auth_params[:provider])\n end", "def login_with(provider)\n post \"/auth/#{provider}/callback\", params: OmniAuth.config.mock_auth[provider.to_sym]\n end", "def login_with(provider)\n post \"/auth/#{provider}/callback\", params: OmniAuth.config.mock_auth[provider.to_sym]\n end", "def use_oauth\n\t\t\t\n\t\tend", "def login_from_client\n return nil unless params[:auth_client] && \n params[:auth_client] == \"iphone\" &&\n params[:auth_id] &&\n params[:auth_secret] \n\n auth_secret_index = request.url =~ /&auth_secret/\n signature = Digest::MD5.hexdigest \"--#{CONFIG[:iphone_salt]}\"\\\n \"--#{request.url.slice(0,auth_secret_index)}\"\n\n return nil unless signature == params[:auth_secret].downcase || /\\/auth/ === request.url\n\n User.find Cryptography.deobfuscate(params[:auth_id])\n rescue\n nil\n end", "def oauth_login_path name = nil\n oauth_instance(name).login_path\n end", "def oauth_login?\n github_id.present? || facebook_id.present?\n end", "def authenticate_by_login_or_key(options = {})\n if api_request?\n self.current_account = site_account_by_provider_key\n else\n login_required\n end\n end", "def auth\n\t\tclient = TwitterOAuth::Client.new(\n\t\t :consumer_key => CONSUMER_KEY,\n\t\t :consumer_secret => CONSUMER_SECRET\n\t\t)\n\t\taccess_token = client.authorize(\n\t\t\tsession[:request_token],\n\t\t\tsession[:request_token_key],\n\t\t\t:oauth_verifier => params[:oauth_verifier]\n\t\t)\n\t\tif client.authorized?\n\t\t\tsession[:access_token] = access_token.token\n\t\t\tsession[:access_token_secret] = access_token.secret\n\t\t\tsession[:user_name] = client.info['name']\n\t\tend\n\t\tredirect_to root_url\n\tend", "def login\n @login ||= begin\n client.user.login\n rescue Octokit::Unauthorized, Faraday::ConnectionFailed\n nil\n end\n end", "def login_from_params\n authenticate(params[:password])\n end", "def user_authentication!\n if params[:auth_token].present? or params[:token_authentication]== \"true\"\n #this is for api authentication and access\n authenticate_user_from_token!\n else\n #normal devise authentication\n authenticate_user!\n end\n end", "def authenticate_or_token\n @@host = request.host_with_port\n return if params[:action].index('login') || params[:controller] == 'accesses'\n authenticate_user! if params[:controller].index('api').nil?\n @current_user = current_user if @current_user.nil?\n end", "def user_authentication\n end", "def login\n\n=begin\n :: Expected Params ::\n\n Constants::REQUEST_PARAM_USERNAME => Username\n Constants::REQUEST_PARAM_USERPASSWORD => UserPassword\n\n=end\n\n # Look up for User in database\n find_user\n\n if @user\n @user.signin!(request)\n\n render json: {status: status_code(:ok), message: '', data: @user.as_signin_json}\n \n end\n\n end", "def auth(controller)\n #controller.reset_session\n token = controller.params[:access_token]\n user = User.where(:access_token => token).first\n if user\n controller.sign_in(user)\n\n ## TODO: We should change the token here.\n\n data = \"<login\"\n data += \" name='#{user.name}'\"\n data += \" email='#{user.email}'\"\n data += \" roles='#{user.role_symbols.join(\",\")}'\"\n data += \" authToken='#{token}'\"\n data += \"/>\"\n controller.render :xml => data, :status => 200\n else\n controller.render :xml => \"<NoWay/>\", :status => 404\n end\n end", "def auth_methods; end", "def authorize(auth = {})\n auth[:login] = auth[:login] || auth[:username]\n raise TaskMapper::Exception.new('Please provide at least a username') if auth[:login].blank?\n provider.login = auth[:login]\n provider.user_token = auth[:password] || auth[:oauth_token]\n provider.api = new_github_client auth\n end", "def login_from_access_token(provider)\n @provider = Config.send(provider)\n args = {}\n args.merge!({:oauth_verifier => params[:oauth_verifier], :request_token => session[:request_token]}) if @provider.respond_to?(:get_request_token)\n args.merge!({:code => params[:code]}) if params[:code]\n @access_token = @provider.get_access_token(args)\n @user_hash = @provider.get_user_hash(@access_token)\n if user = Config.user_class.load_from_provider(provider,@user_hash[:uid])\n reset_session\n login_user(user)\n user\n end\n end", "def default_login\n login(\"rohitsjce@gmail.com\",\"codetheoryio\")\n end", "def auth_oauth\n @attributes[:auth_oauth]\n end", "def login\n\n if params[:username] && params[:token]\n @user = token_based_login\n end\n\n if @user\n set_session_headers\n render json: { username: @user.username, auth_token: get_md5_digest(params[:username]), logged_in: true }\n else\n render json: { logged_in: false }, status: 401\n end\n end", "def login_url(params,session)\n self.authorize_url\n end", "def login(do_update_config=true)\n if needs_api_key?\n get_api_key\n end\n\n if needs_auth_token?\n pin = get_oauth_verifier\n return false if pin.nil?\n\n\n begin\n # this will throw an error that we can try and catch\n @access_token = request_token.get_access_token(:oauth_verifier => pin.chomp)\n get_screen_name\n\n self.config[:access_token] = @access_token.token\n self.config[:access_token_secret] = @access_token.secret\n\n #update_config unless ! do_update_config\n reset_client\n\n rescue OAuth::Unauthorized => e\n display_oauth_error\n warn e.inspect\n return false\n end\n end\n\n return true\n end", "def login\n @client = Octokit::Client.new(login: username, oauth_token: token)\n end", "def authenticating_with_oauth?\n correct_request_class? && using_oauth?\n end", "def find_oauth_access_token\n end", "def login_url(_params, _session)\n authorize_url\n end", "def authenticate(request, realm, &password_procedure); end", "def authentication_type; end", "def auth_scheme; end", "def authenticate\n authenticate_or_request_with_http_basic(\"myTaskboard Login\") do |email, password|\n user = User.where(email: email, password: password).first rescue nil\n redirect_to controller: :login, action: :index, status: 403 and return if user.nil?\n\n session[:current_user_id] = user.id #rescue nil\n end\n end" ]
[ "0.8281184", "0.8281184", "0.81554186", "0.77170265", "0.7650618", "0.7426348", "0.7329483", "0.72815555", "0.72606593", "0.715163", "0.71176964", "0.7108532", "0.7086213", "0.7080806", "0.7065281", "0.7065281", "0.70414764", "0.70107776", "0.70107776", "0.70107776", "0.70107776", "0.70107776", "0.70107776", "0.70107776", "0.70107776", "0.70107776", "0.69947416", "0.69947416", "0.69740367", "0.6963314", "0.6959311", "0.694517", "0.6935373", "0.6934112", "0.68177277", "0.6791978", "0.6791281", "0.6783296", "0.676593", "0.6761706", "0.6729306", "0.6724239", "0.6720763", "0.67199534", "0.6705799", "0.6692878", "0.66866267", "0.6669505", "0.6664936", "0.66644585", "0.66573936", "0.6651642", "0.6633384", "0.66101354", "0.66100353", "0.6605774", "0.65844315", "0.65726537", "0.6561933", "0.6559497", "0.6546524", "0.6538145", "0.6528802", "0.6526313", "0.6521912", "0.6516744", "0.6516628", "0.6516628", "0.65096545", "0.6505391", "0.65047646", "0.65047646", "0.65043616", "0.648329", "0.64819676", "0.64815074", "0.6477834", "0.646941", "0.64678234", "0.6458582", "0.6454687", "0.6453261", "0.6448665", "0.6445446", "0.64423203", "0.6438695", "0.64214194", "0.6415639", "0.6410929", "0.64097136", "0.64057434", "0.64055705", "0.6402002", "0.6395684", "0.6392138", "0.6391592", "0.63908875", "0.6387697", "0.6387321", "0.63860136", "0.6380236" ]
0.0
-1
Extra credit: write a function to calculate some other formula
def calculate_area_of_trapezoid(h,b1,b2) puts "Calculating the area of a trapezoid with height #{h}, top #{b1}, bottom #{b2}" multiply(divide(h, 2), add(b1, b2)) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def formula() @ob.get_formula end", "def inverse_formula (a, b)\n return 2 * (a + 5 * b)\nend", "def calculation\n end", "def calc_t1(price, tip, tax)\n tax_amount = price * tax\n tip_amount = price * tip\n price + tip_amount + tax_amount\nend", "def calculated; end", "def calc_equation(x, y)\n return (1000 * x) + (1000 * y) - (x * y) == 500000\nend", "def bmi_formula (kg, m)\n result = kg / (m ** 2)\nend", "def secret_formula( started ) # Here first parameter 'started' will be referenced to the start_point which equals 10000\n jelly_beans = started * 500 # the variable 'jelly_beans' is equal to 10000 x 500 = 5,000,000\n jars = jelly_beans / 1000 # the variable 'jars' is equal to the value of jelly_beans (5,000,000) / 1,000 = 5,000\n crates = jars / 100 # the variable 'crates' is equal to the value of jars (5,000) / 100 = 50\n return jelly_beans, jars, crates # returns all the expressed values for the three variables to be used outside the method\nend", "def numerator() end", "def calculate\n (2 + 2) * 2\nend", "def calculate(x, operator, y)\n\t# lots of ways to do the below part ...\n\t# if/elsif would have worked,\n\t# as would a case statement\n\treturn x + y if operator == '+'\n\treturn x - y if operator == '-'\n\treturn x * y if operator == '*'\n\treturn x / y if operator == '/'\nend", "def secret_formula(started)\n\tjelly_beans = started * 500 #assign the producto of the parameter and 500 to the variable jely_beans\n\tjars = jelly_beans / 1000 #assign the division of the variable jelly_beans and 1000 to the variable jars\n\tcrates = jars / 100 #crates is equal to the division of jars and 100\n\t#return jelly_beans, jars, crates #return the value of jelly_beans, jars and crates\nend", "def operation(x)\n Math.sqrt(x.abs) + 5 * x ** 3\nend", "def square_of_sum\n end", "def secret_formula(started)\n# Assigns variables, each building on the other.\n jelly_beans = started * 500\n jars = jelly_beans / 1000\n crates = jars / 100\n# Returns a value that is associated with each variable\n return jelly_beans, jars, crates\nend", "def cal()\n @v = 0.0;\n @n.times {|i|\n @v += @wn[i] * @xn[i];\n }\n nil;\n end", "def calculate(a,b,c)\n s = a * b* c \n end", "def calcTaxes price\r\n taxrate = 0.95\r\n return taxrate * price\r\nend", "def calculate( a, operator, c )\n\tif operator == \"+\"\n\t\ta + c\n\telsif operator == \"-\"\n\t\ta - c\n\telsif operator == \"*\"\n\t\ta * c\n\telsif operator == \"/\"\n\t\ta/c\n\t\t\n\tend\n\t\nend", "def equationValue(a, b, c, d, x)\n\t\tf = ((a+x)/(b+x))**(b + x)\n\t\tf = f - (c/d)\n\t\treturn f\n\tend", "def calc(expr)\n expr.split.each_with_object([]) { |e, a|\n if e.match(/\\d+/)\n a << e.to_f\n else\n y, x = a.pop, a.pop\n a << x.send(e, y)\n end\n }.last || 0\nend", "def calculate(op, x, y)\n case op\n when 'plus'\n x.to_f + y.to_f\n when 'minus'\n x.to_f - y.to_f\n when 'divide'\n x.to_f / y.to_f\n when 'multiple'\n x.to_f * y.to_f\n end\nend", "def ctof(ctemp)\n32.0+(ctemp*9.0/5.0)\nend", "def linear_equation(equation)\n #TODO:: calculate\n end", "def uberX_fare_calculator\nend", "def calculate( op, a1, a2 = nil )\n case op\n when :abs; a2\n when :rel; a2\n when :mul; a1 * a2\n when :add; a1 + a2\n when :sub; a1 - a2\n when :inv; a1 * -1\n else 0\n end\n end", "def recalculate\n end", "def return\n earning/(@amount*@term)\n end", "def get_formula_base_cost\n price = 0.0\n self.ingredients.each do |ingredient|\n price += ingredient.getPrice * ingredient.quantity\n end\n return price\n end", "def calculate!\n calculate_amount\n calculate_fee\n calculate_insurance\n calculate_deposit\n end", "def recalculate\n\tend", "def amount_calc\n quantity * price\n end", "def mathoper4argum(n, y, a, b)\n\n\tn + y - a / b\n\nend", "def elegant_calc(expr)\n expr.split.each_with_object([]) { |e, a|\n if e.match(/\\d+/)\n a << e.to_f\n else\n y, x = a.pop, a.pop\n a << x.send(e, y)\n end\n }.last || 0\nend", "def arithmetic1 (n)\nn*5-20\nend", "def calculate_pymnt(amt, j, n)\n x = amt.to_f * (j.to_f / (1 - (1 + j.to_f)**-n.to_f))\n round_money(x)\nend", "def squared_sum(a, b)\n # Q1 CODE HERE\n return (a + b) ** 2\nend", "def arithmetic1(n)\r\r\n n * 5 - 20\r\r\nend", "def calculate(starting_value, operations)\n sum = starting_value\n operations.each do |ops|\n operator = ops[0]\n operand = ops[1]\n \n case operator\n when '+'\n sum += operand \n when '-'\n sum -= operand\n when '*'\n sum *= operand\n when '/'\n sum /=operand\n else \n end\n end \n sum \nend", "def getExp ( x , y )\n\texp = x ** y\n\treturn exp\nend", "def calculate_total_2(info) # info is a hash with expected arguments\n taxAmt = info[:price] * info[:tax]\n tipAmt = info[:price] * info[:tip]\n info[:price] + tipAmt + taxAmt\nend", "def compute_es(_T)\n #equation 11\n #t units are celsius, es units are kPa\n es = 0.6108 * Math.exp((17.27 * _T) / (_T + 237.3))\nend", "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 gear_inches\n # ... a few lines of scary math\n foo = some_intermediate_result * wheel.diameter\n # ... more lines of scary math\nend", "def calc_tip(bill, tip)\n (bill * (tip / 100))\nend", "def function(x)\n 3.70 + -0.048 * x\nend", "def sum_difference_product\n # your code goes here\nend", "def calculate_formula(record)\n formula = record.measure.formula\n unless formula.blank?\n parser = FormulaParser.new\n p = parser.parse(formula.gsub(/ /,\"\"))\n p.measure_id = measure.id\n p.period = period\n record.achieved = eval(p.code_value)\n end\n end", "def value\n (\n 0.7 * (annual_income / average_income) +\n 0.3 * (base_manpower / avearge_manpower)\n ).round(6)\n end", "def calculate\n product.taxes&.map { |tax| tax_portion(tax) }.sum.to_f || 0\n end", "def gear_inches\n #... a few lines of scary math\n foo = some_intermediate_result * diameter\n #... more lines of scary math\nend", "def gear_inches\n #... a few lines of scary math\n foo = some_intermediate_result * diameter\n #... more lines of scary math\nend", "def calc_total\n (@total_after_tax * @gratuity) + @total_after_tax\n end", "def calculation(duration, loan, apr)\n loan * (apr / (1 - (1 + apr)**(-duration)))\nend", "def solve(meal_cost, tip_percent, tax_percent)\n\n result = meal_cost * (1 + tip_percent.to_f / 100 + tax_percent.to_f / 100)\n puts result.round()\n \nend", "def calculate(height, weight)\n bmi = (weight / height) / height.to_f;\nend", "def secret_formula(started)\n jelly_beans = started * 500\n jars = jelly_beans / 1000\n crates = jars / 100\n return jelly_beans, jars , crates\nend", "def Calculate(x,y) do\n\n#to mam nam zwrocic dwa stringi latexowe, tablica whatever gotowe do druku\nend", "def propagation_fn(x) 1/(1+Math.exp(-x)) end", "def bmi_calc height, weight\n return (weight / height**2).to_i\nend", "def transmogrifier(num1, num2, num3)\n return (num1*num2)**num3\nend", "def calculate_bonus(salary, bonus)\n bonus ? (salary / 2) : 0\nend", "def calculate_bonus(salary, bonus)\n bonus ? (salary / 2) : 0\nend", "def calculate_bonus(salary, bonus)\n bonus ? (salary / 2) : 0\nend", "def calculate_bonus(salary, bonus)\n bonus ? (salary / 2) : 0\nend", "def calculate_bonus(salary, bonus)\n bonus ? (salary / 2) : 0\nend", "def transmorgifier (num1,num2,num3)\n (num1*num2).pow(num3)\nend", "def apply_math(fn, a, b)\n a.send(fn, b)\nend", "def calculate_product(a,b)\n a*b\nend", "def trapecios(a, b, n, &f)\n h = (b - a).fdiv(n)\n ai0 = f.call(a) + f.call(b)\n ai = 0\n\n (1..n - 1).each do |k|\n x = a + k * h\n ai += f.call(x)\n end\n\n ai = (ai0 + 2 * ai) * h.fdiv(2)\n\n puts \"Un valor aproximado de la integral para #{n} subintervalos es #{ai}.\"\n return ai\nend", "def calculate_bonus(salary, bonus)\n bonus ? (salary / 2) : 0 \nend", "def calcuate_tax\n @price * 0.12\n end", "def numerology(num1)\n\t# Calculate answer \n\t(((((num1 + 5) * 2) - 4) / 2) - num1)\nend", "def obvious_total(subtotal:, tax:, discount:)\r\n subtotal + tax - discount\r\nend", "def calculate_bonus(salary, bonus)\n bonus ? salary / 2.0 : 0\nend", "def compute_Delta(_T)\n #equation 13\n #kPa/C\n _Delta = 4098.0 * (0.6108 * Math.exp(17.27 * _T / (_T + 237.3))) / (_T + 237.3) ** 2\nend", "def transmogrifier (num1,num2,num3)\n (num1 * num2)**num3\nend", "def rec_exp_1(base, power)\nend", "def ctof(temp)\n temp * (9.0 / 5.0) + 32\nend", "def calc_return(total, pool, commission)\n if pool == 0\n return 0\n elsif total == 0\n return ( pool - (pool*commission) ) \n else\n return ( pool - (pool*commission) ) / total.to_f\n end\n end", "def secret_formula(started)\r\n\tjelly_beans = started * 500\r\n\tjars = jelly_beans / 1000\r\n\tcrates = jars / 100\r\n\treturn jelly_beans, jars, crates\r\nend", "def calculate_bonus(num,pay)\n if pay; return num /2 else return 0 end\nend", "def calc_contribution(f)\n each_class do |k|\n a, b, c, d = get_A(f, k), get_B(f, k), get_C(f, k), get_D(f, k)\n \n s = 0.0\n x, y = b+d, a+c\n \n s = (d/x)**(@k) - (c/y)**(@k) if not x.zero? and not y.zero?\n \n set_feature_score(f, k, s)\n end\n end", "def mathy(n1, n2, operation)\n answer = n1.send(operation, n2).round(4)\n return answer\nend", "def sustitucion_regresiva(n, a, b)\n n = n - 1\n\n x = Array.new(n + 1)\n x[n] = b[n].fdiv(a[n][n])\n\n (0..n - 1).reverse_each do |i|\n sumatoria = (i + 1..n).inject(0) { |sum, k| sum + a[i][k] * x[k] }\n x[i] = (b[i] - sumatoria).fdiv(a[i][i])\n end\n\n puts \"Una solucion aproximada del sistema es X = #{x}\"\n return x\nend", "def calculate(operation, n1, n2)\n if operation == \"add\" || operation == \"+\"\n return \"#{n1} + #{n2} = #{n1+n2}\"\n elsif operation == \"subtract\" || operation == \"-\"\n return \"#{n1} - #{n2} = #{n1-n2}\"\n elsif operation == \"multiply\" || operation == \"*\"\n return \"#{n1} * #{n2} = #{n1*n2}\"\n elsif operation == \"divide\" || operation == \"/\"\n if n2 == 0\n return \"undefined\"\n else\n return \"#{n1} / #{n2} = #{n1/n2}\"\n end\n elsif operation == \"exponent\" || operation == \"^\"\n return \"#{n1} ^ #{n2} = #{n1**n2}\"\n elsif operation == \"modulo\" || operation == \"%\"\n return \"#{n1} % #{n2} = #{n1%n2}\"\n end\nend", "def celcius_calculation(fahrenheit_input) #Celcius calculation\n ((fahrenheit_input.to_f - 32) * 5) / 9\nend", "def compute_fuel(element)\n (element/3).floor - 2\n end", "def ctof temp2\n (temp2*1.8) + 32\nend", "def calculate_bonus(salary, bonus)\n bonus ? salary / 2 : 0\nend", "def calculate_bonus(salary, bonus)\n bonus ? salary / 2 : 0\nend", "def calculate_bonus(salary, bonus)\n bonus ? salary / 2 : 0\nend", "def tax_calc\n tax = @quantity * @price * @taxe\n end", "def calculate_discount(inLX,inLXZero)\n Float(inLX) / Float(inLXZero)\n end", "def math(l, w)\n (l * w).round(2)\nend", "def income_tax(income=0,inc_tax_rate=0.1)\n income*inc_tax_rate\nend", "def income_tax(income=0,inc_tax_rate=0.1)\n income*inc_tax_rate\nend", "def restaurant_bill(meal_cost, tax, tips)\n tax_amount = meal_cost * tax\n tip_amount = meal_cost * tips\n meal_cost + tax_amount + tip_amount\nend", "def gear_inches\n #... some complex code\n foo = some_intermediate_result * ratio * wheel.diameter\n # ...some complex code\n end", "def evaluar_funcion(x)\n ecuacion = \"\"\n\n for i in (0...@ecuacion.length) do\n ecuacion += @ecuacion[i] >= 0 ? \"+#{@ecuacion[i]}*x^#{@grado - i}\" : \"#{@ecuacion[i]}*x^#{@grado - i}\"\n end\n\n if @ecuacion[0] >= 0\n ecuacion = ecuacion[1, ecuacion.length]\n end\n\n return DK.evaluate(ecuacion, x: x)\n end", "def compute_actual\n line[1] = @ho_form.line['sqft']\n line[2] = @ho_form.line['total_sqft']\n line[3] = (line[1] * 100.0 / line[2]).round(2)\n\n line['4/gross_inc'] = gross_income\n\n # We make a simplifying assumption that (1) every Home Office Expense\n # applies to every Home Office form, and (2) all expenses are indirect.\n categorize_records('Home Office Expense')\n #\n # We assume that the home office using the actual method is being rented and\n # thus there are no mortgage payments or such on it.\n #\n #fill_for_categories(self, '5b', 'Casualty_Losses')\n #fill_for_categories(self, '6b', 'Mortgage_Interest')\n #fill_for_categories(self, '7b', 'Real_Estate_Taxes')\n\n line['8b'] = sum_lines('5b', '6b', '7b')\n line[9] = (line['8b'] * line[3] / 100.0).round\n line[10] = line[9]\n\n line[11] = other_business_expenses\n\n line[12] = sum_lines(10, 11)\n line['13/ho_max_ded'] = line[4] - line[12]\n\n fill_for_categories(self, '16b', 'Insurance')\n fill_for_categories(self, '17b', 'Rent')\n fill_for_categories(self, '18b', 'Repairs')\n fill_for_categories(self, '19b', 'Utilities')\n fill_other_categories(\n self, '20b', continuation: 'Other Home Office Expenses'\n )\n line['21b'] = sum_lines(*%w(14b 15b 16b 17b 18b 19b 20b))\n line[22] = (line['21b'] * line[3] / 100.0).round\n\n # Assume no carryover for line 23\n line['24/ho_ded'] = sum_lines('21a', 22, 23)\n line[25] = [ line[13], line[24] ].min\n line[26] = line[13] - line[25]\n\n # Assume no casualty losses or depreciation for lines 27-29 and 33\n line[30] = sum_lines(27, 28, 29)\n line[31] = [ line[26], line[30] ].min\n line[32] = sum_lines(10, 25, 31)\n\n line[33] = BlankZero\n line['34/ho_expenses'] = line[32] - line[33]\n\n end" ]
[ "0.71227455", "0.6990211", "0.6879419", "0.68395585", "0.6785403", "0.6698989", "0.66834563", "0.66183764", "0.65040666", "0.64839524", "0.64831805", "0.6469795", "0.64187896", "0.64091796", "0.6404391", "0.6380907", "0.63642734", "0.6345924", "0.6339137", "0.63385624", "0.6324466", "0.6324198", "0.6319556", "0.6305566", "0.63014823", "0.628837", "0.62845755", "0.62811327", "0.62744194", "0.62737286", "0.6272341", "0.6263618", "0.625718", "0.62433684", "0.6234118", "0.62315863", "0.6218348", "0.621669", "0.62133795", "0.6198046", "0.61844", "0.6160937", "0.61585516", "0.6143116", "0.61418974", "0.6130465", "0.6126339", "0.612627", "0.61212593", "0.61164546", "0.6116405", "0.6116405", "0.6113669", "0.6112225", "0.6110474", "0.61072195", "0.61021614", "0.60941327", "0.60853904", "0.6076261", "0.60651267", "0.606101", "0.606101", "0.606101", "0.606101", "0.606101", "0.60595536", "0.6049885", "0.6048093", "0.6046815", "0.60437953", "0.6030198", "0.60292906", "0.6027196", "0.60265195", "0.601441", "0.60143983", "0.60120237", "0.5999581", "0.59940904", "0.59937227", "0.5990784", "0.5989113", "0.5988703", "0.5987027", "0.5979078", "0.5976786", "0.59766227", "0.59753", "0.5973784", "0.5973784", "0.5973784", "0.59704196", "0.5969552", "0.59661776", "0.5965276", "0.5965276", "0.596443", "0.59633243", "0.59626395", "0.5951621" ]
0.0
-1
initializer that will parse the configuration file that was passed in and makes it available via the instance variables
def initialize(configuration_file_location) @rules_location = "" file = File.new( configuration_file_location ) doc = REXML::Document.new file @rules_location = doc.elements["snortRulesAnalysisEngineConfiguration/rulesLocation"].text end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def initialize\n @config = config_from_file || empty_config\n end", "def initialize\n\n # Set some defaults\n self.auth_location = 'usa'\n self.use_service_net = 'false'\n self.retention_days = 7\n\n config_file = find_config_file\n raise \"Unable to find configuration file\" if config_file.nil?\n\n File.open(config_file, 'r') do |file|\n while (line = file.gets)\n key, value = line.strip.split('=', 2)\n send(:\"#{key}=\", value)\n end\n end\n\n end", "def initialize(config_file=nil)\n @config_file = config_file\n @params = {}\n @groups = []\n \n if(self.config_file)\n self.validate_config()\n self.import_config()\n end\n end", "def initialize()\n @config = YAML.load_file('config.yaml')\n @puppetdb = @config['puppetdb']\n @servicenow = @config['servicenoe']\n @syslog = @config['syslog']\n end", "def initialize \n @Attributes = Hash.new \n @ConfigurationFilename = \"configuration.txt\" \n load_attributes \n end", "def initialize(config_file)\n @config_file = config_file\n raise Errno::EACCES, \"#{self.config_file} is not readable\" unless File.readable?(self.config_file)\n open(self.config_file).each { |line| \n line.chomp\n unless (/^\\#/.match(line))\n if(/\\s*=\\s*/.match(line))\n param, value = line.split(/\\s*=\\s*/, 2) \n var_name = \"#{param}\".chomp.strip\n value = value.chomp.strip\n new_value = ''\n if (value)\n if value =~ /^['\"](.*)['\"]$/\n new_value = $1\n else\n new_value = value\n end\n else\n new_value = ''\n end \n self.instance_variable_set(\"@#{var_name}\", new_value)\n end\n end\n } \n end", "def initialize\n @tree = YAML::parse(File.open(CONFIG_FILE))\n end", "def initialize\n create_config unless File.exists?(config_file)\n load_settings\n set_domain\n end", "def initialize(config_file='../config_parser/example_config.conf', comments=%w{# ;})\n @config_file = config_file\n @params = {}\n @splitRegex = '\\s*=\\s*'\n @comments = comments\n\n # validate the file and extract the content\n self.validate_file\n self.import_config_content_from_file\n end", "def initialize\n options = parse_options\n CONFIG[:user] = options[:user]\n $config = CONFIG.merge(YAML.load_file(\"#{options[:prefix]}/#{options[:'config-dir']}/config.yml\").rekey) rescue CONFIG.clone\n $config.merge!(options)\n [:'config-dir', :'pid-file', :'log-file', :'spool-dir'].each {|item| $config[item] = \"#{$config[:prefix]}/#{$config[item]}\".sub(/\\/\\//, '/') }\n $messages = MESSAGES.merge(YAML.load_file(\"#{$config[:'config-dir']}/messages.yml\").rekey) rescue MESSAGES.clone\n $recipients = YAML.load_file(\"#{$config[:'config-dir']}/recipients.yml\") rescue {}\n end", "def initialize\n @path = File.join(File.expand_path('.'), FILE_NAME)\n unless File.exist?(@path)\n @path = (ENV['ASPELLBEE_CONFIG_PATH'] || File.join(File.expand_path('~'), FILE_NAME))\n end\n @data = load_config_file\n end", "def initialize\n message.info \"Loading configuration...\"\n @config ||= validate(config_file)\n aws_config\n end", "def initialize\n define_os\n define_path\n read_settings\n end", "def initialize\n @path = '/tmp/gordon/config.yaml'\n @file = inspec.file(@path)\n return skip_resource \"Can't find file \\\"#{@path}\\\"\" if !@file.file?\n\n # Protect from invalid YAML content\n begin\n @params = YAML.load(@file.content)\n rescue Exception\n return skip_resource \"#{@file}: #{$!}\"\n end\n add_some_extra_params\n end", "def initialize()\n @config_file=\"projects.yml\"\n @config = YAML.load_file(@config_file)\n end", "def load config_file\n YAML.load_file(config_file).each do |parameter,value|\n instance_variable_set( \"@#{parameter}\", value )\n end\n end", "def initialize(configuration_file_location)\t\t\r\n\t\tfile = File.new( configuration_file_location )\r\n\t\tdoc = REXML::Document.new file\r\n\t\t\r\n\t\t@visitor = doc.elements[\"honeyCConfiguration/visitor\"].text\r\n\t\t@queuer = doc.elements[\"honeyCConfiguration/queuer\"].text\r\n\t\t@analysis_engine = doc.elements[\"honeyCConfiguration/analysisEngine\"].text\r\n\tend", "def parse(file_name)\n raise Mongify::ConfigurationFileNotFound, \"File #{file_name} is missing\" unless File.exists?(file_name)\n config = self.new\n config.instance_eval(File.read(file_name))\n config\n end", "def initialize(config)\n raise TypeError, \"'config' needs to be a string\" unless config.is_a?(String)\n raise TypeError, \"Configuration file '#{config}' cannot be found\" unless File.exist? config\n\n begin\n # open base config\n @config = load(config)\n # set default value if key? does not exist\n @config.default = nil\n @@config = config\n rescue StandardError => e\n print_error \"Fatal Error: cannot load configuration file '#{config}' : #{e.message}\"\n print_more e.backtrace\n exit(1)\n end\n\n @@instance = self\n end", "def parse_config \n path = \"#{Rails.root}/config/mebla.yml\"\n return unless File.exists?(path)\n \n conf = YAML::load(ERB.new(IO.read(path)).result)[Rails.env]\n \n conf.each do |key,value|\n self.send(\"#{key}=\", value) if self.respond_to?(\"#{key}=\")\n end unless conf.nil?\n end", "def initialize\n set_config\n end", "def initialize (file=DEFAULTS['cf'])\n @everything = YAML.load(ERB.new(IO.read(file)).result)\n raise \"malformed ferret server config\" unless @everything.is_a?(Hash)\n @config = DEFAULTS.merge(@everything[RAILS_ENV] || {})\n if @everything[RAILS_ENV]\n @config['uri'] = socket.nil? ? \"druby://#{host}:#{port}\" : \"drbunix:#{socket}\"\n end\n end", "def initialize(file = DEFAULTS['cfg'])\n @everything = YAML.load(ERB.new(IO.read(file)).result)\n raise \"malformed yarb config\" unless @everything.is_a?(Hash)\n @config = DEFAULTS.merge(@everything[RAILS_ENV] || {})\n rescue\n puts \"error reading config file: #{$!}, using defaults\"\n @config = DEFAULTS\n end", "def initialize(config, facility, location, zip_file_name, inbound_file_information = nil)\n @config_yml = YAML::load(File.open(config))\n @facility = facility\n @location = location\n @zip_file_name = zip_file_name\n @inbound_file_information = inbound_file_information\n end", "def read_config_file; end", "def initialize\n configure_via_yaml\n configure_via_env\n end", "def initialize(file_path, log, debug=false)\n @config_file = file_path\n @parsed_hash = {}\n @log = log\n @debug = debug\n @errors_count = 0\n end", "def initialize(config_file = nil, meta_tree = nil)\n @meta = meta_tree || { :dir => true }\n begin\n if config_file: load(config_file)\n else @cfg = {} end\n rescue StandardError => e\n $log.puts \"Exception loading ConfigSpace: #{e.inspect}\"\n raise e\n end\n end", "def initialize\n @params = {}\n @path = \"/tmp/example/config.yaml\"\n @file = inspec.file(@path)\n\n unless @file.file?\n raise Inspec::Exceptions::ResourceSkipped, \"Can't find file `#{@path}`\"\n end\n\n # Protect from invalid YAML content\n begin\n @params = YAML.load(@file.content)\n # Add two extra matchers\n @params[\"file_size\"] = @file.size\n @params[\"file_path\"] = @path\n @params[\"ruby\"] = \"RUBY IS HERE TO HELP ME!\"\n rescue StandardError => e\n raise Inspec::Exceptions::ResourceSkipped, \"#{@file}: #{e.message}\"\n end\n end", "def initialize(config_file = nil)\n if config_file.nil?\n @mail = @password = ''\n return\n end\n\n config = load_yaml_file(config_file)\n unless config.has_key?('mail') && config.has_key?('password')\n raise ConfigurationError, \"#{config_file}: Invalid configuration file\"\n end\n\n @mail = config['mail']\n @password = config['password']\n end", "def initialize(file_name, config = Crossref::Config)\n @file_name = file_name\n @config = config.load_config\n end", "def parse_config_file(path)\n return unless File.exists?(path)\n \n conf = YAML::load(ERB.new(IO.read(path)).result)[Rails.env]\n \n conf.each do |key,value|\n self.send(\"#{key}=\", value) if self.respond_to?(\"#{key}=\")\n end unless conf.nil?\n end", "def initialize(arg='/etc/dansguardian/dansguardian.conf')\n h = {}\n if arg.respond_to? :[]\n h = arg\n else # String-like assumed\n h = {:mainfile => arg}\n end\n @mainfile = h[:mainfile] \n @mainconfig = nil\n @filtergroups = []\n end", "def config_load(config); end", "def initialize(file)\n @file = File.expand_path(file)\n fail \"Can't find file #{@file}\" unless File.exist?(@file)\n @dir = File.dirname(@file)\n IO.readlines(@file).each { |line| initialize_data line }\n @configuration = Configuration.new(self)\n @semver = Versioning.find(@dir)\n end", "def config(value)\n # require value if File.exists?(value)\n if File.exists?(value)\n fc = File.read(value)\n self.instance_eval(fc)\n end\n end", "def initialize(conf)\n self.linked_data_url = conf[\"linked_data_url\"]\n self.namespaces = conf[\"namespaces\"]\n self.search = conf[\"search\"]\n self.pretty_name = conf[\"prettyNames\"]\n self.stylesheet_portal = conf[\"stylesheet_portal\"]\n end", "def initialize(filename = \"#{File.dirname(__FILE__)}/../conf/config.json\")\n if filename.instance_of?(Hash)\n @filename = nil\n @pjson = filename\n else\n @filename = filename\n json = File.read(filename)\n @pjson = JSON.parse(json)\n end\n end", "def initialize_config(file_path = nil)\n @config = read_config_file(file_path)\n alias_server_attributes\n\n @https ||= {}\n end", "def initialize(base_dir)\r\n read_config(base_dir)\r\n end", "def initialize(config_yml_file, facility, location, zip_file_name,inbound_file_information)\n @config_yml = config_yml_file\n @facility = facility\n @parser = @facility.index_file_parser_type.to_s.downcase.split('_')[0]\n @sitecode = @facility.sitecode.to_s.strip.upcase\n @location = location\n @zip_file_name = zip_file_name\n @client = facility.client\n @@batch_date = Date.today if !defined?(@@batch_date)\n @hash_envelop_images = {}\n @hash_envelop_value = 0\n @inbound_file_information = inbound_file_information \n end", "def initialize(config_path = nil)\n @config = Configuration.new(config_path)\n @errors = {}\n end", "def initialize(path)\n @f = nil\n @path = path\n open_config()\n @bot = []\n parse_config(false)\n end", "def initialize(config=nil)\n super()\n read_config(config) if !config.nil?\n end", "def initialize(config=nil)\n super()\n read_config(config) if !config.nil?\n end", "def initialize( custom_config = {} )\n config = config_file.merge custom_config\n config = symbolize_keys config\n\n config[:username] = config[:api_key] if config[:api_key]\n config[:headers] ||= {}\n config[:request] ||= {}\n config[:response] ||= {}\n\n config[:headers][:accept] ||= \"application/hal+json\"\n\n # Copy the config into this Configuration instance.\n config.each { |k, v| self[k] = v }\n\n super()\n\n configure_user_agent\n configure_cache\n\n validate\n end", "def conf\n begin\n @conf ||= JSON.parse(File.read(config_file))\n rescue\n @conf ||= {}\n end\n end", "def conf\n begin\n @conf ||= JSON.parse(File.read(config_file))\n rescue\n @conf ||= {}\n end\n end", "def initialize(configFileName, configSelect=nil)\r\n \r\n configFile = File.expand_path(configFileName + \".yaml\")\r\n basePath = File.dirname(configFile)\r\n config = YAML.load(File.new(configFile))\r\n \r\n #activeConfigs=config.select{|x| [x[:name]] & ConfigSelet}\r\n\r\n selectedConfig=config.first\r\n #TODO: check the config file\r\n @input = selectedConfig[:input].map{|file| File.expand_path(\"#{basePath}/#{file}\")}\r\n @outdir = File.expand_path(\"#{basePath}/#{selectedConfig[:outdir]}\")\r\n @outname = selectedConfig[:outname]\r\n @format = selectedConfig[:format]\r\n @traceSortOrder = selectedConfig[:traceSortOrder]\r\n @vars = selectedConfig[:vars] || {}\r\n @editions = selectedConfig[:editions] || nil\r\n\r\n @downstream_tracefile = selectedConfig[:downstream_tracefile] || nil \r\n\r\n @reqtracefile_base = selectedConfig[:reqtracefile_base] #todo expand path\r\n\r\n @upstream_tracefiles = selectedConfig[:upstream_tracefiles] || nil\r\n @upstream_tracefiles = @upstream_tracefiles.map{|file| File.expand_path(\"#{basePath}/#{file}\")} unless @upstream_tracefiles.nil?\r\n snippets = selectedConfig[:snippets]\r\n if snippets.nil?\r\n @snippets = nil \r\n else\r\n @snippets = snippets.map{|file| File.expand_path(\"#{basePath}/#{file}\")}\r\n end\r\n end", "def parse_config(config); end", "def initialize attributes={}\n self.config = attributes[:config]\n end", "def from_config(file = nil)\n config_file = config_file(file)\n\n init(config_file.config[:uri], config_file.config[:prefix])\n end", "def load\n configuration # Need to call this to make sure it's populated\n self.instance_eval(IO.read(path), path, 1) if path && File.exists?(path)\n self\n end", "def initialize(arg = nil)\n parse_arg arg if arg\n parse_config\n end", "def params\n begin\n YAML::load(File.open(@config))\n rescue\n {}\n end\n end", "def conf\n unless @conf\n if @db_url || @db # skip loading config if db set explicitly\n @conf = {}\n else\n parse_command_line unless @args\n\n raise \"No configuration file defined (-c <config>).\" if @args[\"config\"].nil?\n raise \"Couldn't read #{@args[\"config\"]} file.\" unless @args['config'] && @conf = YAML::load(File.new(@args[\"config\"]).read)\n # setting default options that should be written along with all the records to process_items\n if @conf['default_options']\n @conf['default_options'].each do |k,v|\n default_options.send(\"#{k}=\", v)\n end\n end\n\n if @args['params']\n @args['params'].each do |k, v|\n default_options.send(\"#{k}=\", v)\n end\n end\n end\n end\n @conf\n end", "def parse!(configuration_file)\n instance_eval(File.read(configuration_file))\n\n ##\n # If no configuration is found by environment then\n # it will re-parse it in a forced manner, meaning it won't\n # care about the environment and it will just parse everything it finds.\n # This is done because we can then extract all set \"modules\" from the configuration\n # file and display them in the \"Help\" screen so users can look up information/examples on them.\n #\n # This will only occur if no environment is found/specified. So when doing anything\n # environment specific, it will never force the parsing.\n if not found? and environment.nil?\n @force_parse = true\n instance_eval(File.read(configuration_file))\n @additional_modules.uniq!\n end\n\n if not found? and not environment.nil?\n GitPusshuTen::Log.error \"Could not find any configuration for #{environment.to_s.color(:yellow)}.\"\n exit\n end\n\n ##\n # Default to port 22 if no port is specified\n @port ||= '22'\n\n self\n end", "def from_config\n config ||= YAML::load(File.open((File.join(File.dirname(__FILE__), 'config.yml'))))\nend", "def initialize(filename, environment = nil)\n raise \"Config #{filename} not found\" unless File.exist? filename\n @filename = filename\n @environment = environment || current_environment\n end", "def initialize\n @configuration = Configuration.new\n end", "def config\n @config ||= YAML.load File.read(@config_file)\n end", "def as_config\n Configureasy::Config.new self.parse\n end", "def config\n @config ||= YAML.load_file @options[:config_file]\n end", "def initialize(configuration = {}, file=nil)\n @configuration = configuration\n @explanation = {}\n self.file = file\n end", "def parse\n checkArguments\n configContent = File.read(ARGV[0])\n @config = JSON.parse(configContent)\n checkConfig\n end", "def configure_from_options\n if @options[:config]\n config = Configuration.new(@path, @options[:config])\n config.from_options\n end\n end", "def initialize(hash_or_file = self.class.source, section = nil)\n #puts \"new! #{hash_or_file}\"\n case hash_or_file\n when nil\n raise Errno::ENOENT, \"No file specified as Settingslogic source\"\n when Hash\n self.replace hash_or_file\n else\n file_contents = open(hash_or_file).read\n hash = file_contents.empty? ? {} : YAML.load(ERB.new(file_contents).result).to_hash\n if self.class.namespace\n hash = hash[self.class.namespace] or return missing_key(\"Missing setting '#{self.class.namespace}' in #{hash_or_file}\")\n end\n self.replace hash\n end\n @section = section || self.class.source # so end of error says \"in application.yml\"\n create_accessors!\n end", "def initialize(defaults,cmd_opts)\n @fields = defaults\n if !cmd_opts[:config_file].nil?\n path = cmd_opts[:config_file]\n else\n path = defaults[:config_file]\n end\n data = YAML.load_file(path)\n # Now combine data:\n # defaults, config file, command line (low->high priority)\n data.each do |k,v|\n if EXPECTED.include? k.to_sym\n @fields[k.to_sym] = v\n else\n STDERR.puts \"Warning: unknown section '#{k}' in config file\"\n end\n end\n cmd_opts.each do |k,v|\n @fields[k] = v\n end\n end", "def initialize\n @configurations = {}\n end", "def initialize(options)\n options.each { |k, v| self.send :\"#{k}=\", v }\n self.file = File.expand_path file\n end", "def configuration\n\t\t\t\tconfiguration = Configuration.new\n\t\t\t\t\n\t\t\t\tself.resolved_paths.each do |path|\n\t\t\t\t\tpath = File.expand_path(path)\n\t\t\t\t\t\n\t\t\t\t\tconfiguration.load_file(path)\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\treturn configuration\n\t\t\tend", "def initialize\n credentials = self.rails_credentials\n\n CONFIG_PARAMS.each do |param, config|\n value = (\n config[:sources]&.map { |s| credentials[s] }&.compact&.first ||\n config[:env_vars]&.map { |v| ENV[v] }&.compact&.first\n )\n\n if (value)\n if (config[:parse])\n instance_variable_set(config[:ivar], config[:parse].call(value))\n else\n instance_variable_set(config[:ivar], value)\n end\n else\n case (config[:default])\n when Proc\n instance_variable_set(config[:ivar], config[:default].call)\n else\n instance_variable_set(config[:ivar], config[:default])\n end\n end\n end\n end", "def initialize(settings_file)\n @settings_file = JSON.parse(settings_file)\n end", "def process_configuration\n self.configuration = YAML::load(File.read('.codecom.yml'))\n end", "def initialize\n @options = {}\n # Populate the @options hash, if and only if\n # hadooken started directly by its own command.\n # The reason is, ARGV can be populated by puma\n # or rspec configuration options and this options\n # can be unrecognized by Hadooken and will lead\n # an exception in OptionParser.\n parser.parse! if Kernel.const_defined?(:HADOOKEN)\n @options[:config_file] ||= DEFAULT_CONFIG_FILE if File.exist?(DEFAULT_CONFIG_FILE)\n parse_config_file if @options[:config_file]\n end", "def load_config\n # Nothing in base class. This should be used to load the configuration from\n # disk if saved to a file.\n configuration || {}\n end", "def config\n @config_file\n end", "def initialize(params = {})\n params = { config: params } if params.is_a? String\n load_config(params[:config])\n @helpers = []\n load_helpers(params[:helpers])\n @parser = HSS::Parser.new(@config)\n end", "def initialize(config_str=nil)\n\n if config_str\n\n # We have been passed a config file as a string.\n #\n config_files = [ config_str ]\n config_class = StringIO\n\n else\n\n # Perform the usual search for the system and user config files.\n #\n config_files = [ File.join( '', 'etc', 'amazonrc' ) ]\n\n # Figure out where home is. The locations after HOME are for Windows.\n # [ruby-core:12347]\n #\n home = ENV['AMAZONRCDIR'] ||\n ENV['HOME'] || ENV['HOMEDRIVE'] + ENV['HOMEPATH'] ||\n ENV['USERPROFILE']\n user_rcfile = ENV['AMAZONRCFILE'] || '.amazonrc'\n\n if home\n config_files << File.expand_path( File.join( home, user_rcfile ) )\n end\n\n config_class = File\n end\n\n config_files.each do |cf|\n\n if config_class == StringIO\n readable = true\n else\n # We must determine whether the file is readable.\n #\n readable = File.exists?( cf ) && File.readable?( cf )\n end\n\n if readable\n\n Amazon.dprintf( 'Opening %s ...', cf ) if config_class == File\n \n config_class.open( cf ) { |f| lines = f.readlines }.each do |line|\n line.chomp!\n \n # Skip comments and blank lines.\n #\n next if line =~ /^(#|$)/\n \n Amazon.dprintf( 'Read: %s', line )\n \n # Store these, because we'll probably find a use for these later.\n #\n begin\n match = line.match( /^\\s*(\\S+)\\s*=\\s*(['\"]?)([^'\"]+)(['\"]?)/ )\n key, begin_quote, val, end_quote = match[1, 4]\n raise ConfigError if begin_quote != end_quote\n\n rescue NoMethodError, ConfigError\n raise ConfigError, \"bad config line: #{line}\"\n end\n \n self[key] = val\n \n end\n end\n\n end\n\n end", "def initialize()\n @ip = Settings.get[\"cpe\"][\"ip\"]\n @port = Settings.get[\"cpe\"][\"port\"]\n @path = Settings.get[\"cpe\"][\"path\"]\n @username = Settings.get[\"cpe\"][\"username\"]\n @password = Settings.get[\"cpe\"][\"password\"]\n @file_root = Settings.get[\"cpe\"][\"file_root\"]\n @firmware = Settings.get[\"cpe\"][\"firmware\"]\n @config = Settings.get[\"cpe\"][\"config\"]\n @log = Settings.get[\"cpe\"][\"log\"]\n end", "def load_config\n @config = YAML.safe_load(ERB.new(File.read(config_path)).result)\n @queue_ahead = @config[\"queue_ahead\"] || Task::DEFAULT_QUEUE_AHEAD_MINUTES\n @queue_name = @config[\"queue_name\"] || \"default\"\n @time_zone = @config[\"tz\"] || Time.zone.tzinfo.name\n @config.delete(\"queue_ahead\")\n @config.delete(\"queue_name\")\n @config.delete(\"tz\")\n end", "def initialize(config={})\n @configuration = config\n end", "def initialize(*args)\n initialize_config unless instance_variable_defined?(:@config)\n super\n end", "def initialize\n @conf = Hash.new\n @conf[:verbose] = 0\n @conf[:banner] = \"Usage: #{File.basename($0)} [options]\"\n @conf[:config_name] = Meta::NAME + '.yaml'\n @conf[:config_env] = Meta::NAME.upcase + '_CONF'\n @conf[:config_dirs] = DIR_CONFIG\n end", "def initialize\n @main = {}\n @config_directory = File.expand_path \"~/.config/next_background\"\n @file = \"#{@config_directory}/config.yaml\"\n self.load\n end", "def read_config_file(file); end", "def initialize(file,settings={})\n\t\t@file = file\n\t\t@settings = settings\n\tend", "def initialize(*paths)\n @configuration = {}\n paths.each { |f| load f }\n end", "def init\n # Guard against doing this more than once.\n unless @config.nil?\n return\n end\n\n if Config.config_files.nil?\n raise \"No configuration file provided, set LapisLazuli::WorldModule::Config.config_files\"\n end\n\n load_config(Config.config_files)\n # In case there was no config file found an empty @config needs to be set to prevent infinite looping.\n if @config.nil?\n warn 'Unable to find a configuration file, defaulting to empty config.yml.'\n @config = {}\n end\n\n @metadata = Runtime.instance.set_if(self, :metadata) do\n log.debug \"Creating metadata storage\"\n Storage.new(\"metadata\")\n end\n end", "def initialize(file)\n \n @file = File.expand_path(file)\n File.open(file, \"r\") do |f|\n @item = YAML.load_file(f)\n end\n \n # Is there a trailer to configure?\n @trailer = @item.key?(\"trailer\")\n \n # Get the required season episode number from the config\n if @item['content'].key?(\"episode\")\n number = @item['content']['episode']['number']\n season, episode = number.match(/^S(\\d+)E(\\d+)/i).captures\n @item['content']['episode']['season'] = season\n @item['content']['episode']['episode_number'] = episode\n end\n\n # Ensure that the price field is always set\n @item['offer']['price'] = \"0.00\" if !@item['offer'].has_key?('price')\n\n # Set the base operation modes \n @media_operation = :nop\n @offer_operation = :nop\n @trailer_operation = :nop\n end", "def initialize(project_root, file_path, profile, autoscaling_force_size)\n Config.project_root = project_root;\n Config.json = JSON.parse(File.read(absolute_path(file_path)))\n @profile = profile\n @colors_enabled = conf \"colors-enabled\"\n @region = conf \"region\"\n @iam = IamConfig.new\n @autoscaling = AutoScalingConfig.new(autoscaling_force_size)\n @route53 = Route53Config.new\n @security = SecurityConfig.new\n @cloudfront = CloudFrontConfig.new\n @s3 = S3Config.new\n @elb = ELBConfig.new\n @vpc = VpcConfig.new\n @kinesis = KinesisConfig.new\n @sqs = SQSConfig.new\n @ec2 = EC2Config.new\n end", "def config\n @config ||= YAML.load_file(@config_file_path)\n end", "def initialize(arg=nil)\n set_from_config!(arg) if arg\n end", "def initialize\n yield self\n Config.apply(self)\n end", "def initialize(config)\n end", "def initialize(config)\n end", "def initialize(...)\n super()\n configure(...)\n end", "def load_vars\n config = YAML.load_file(@config_file)\n @dev_port = config[\"development\"][\"port\"] ||= @default_dev_port\n @dev_pid = config[\"development\"][\"pid\"] ||= @default_dev_pid\n @dev_log = config[\"development\"][\"log\"] ||= @default_dev_log\n @prod_port = config[\"production\"][\"port\"] ||= @default_prod_port\n @prod_pid = config[\"production\"][\"pid\"] ||= @default_prod_pid\n @prod_log = config[\"production\"][\"log\"] ||= @default_prod_log\nend", "def load(fn)\n if File.file?(fn)\n begin\n File.open(fn).each do |line|\n #peel off terminators/leading spaces, etc.\n line.strip!\n\n #ignore comment lines...\n if (line[0..0]!=\"#\")\n keyval = line.split(\"=\") # split on equal sign\n\n #ignore blank lines\n if keyval.size>0\n key = keyval[0].strip\n value = keyval[1].strip\n self[key] = value\n end\n end\n end\n rescue\n raise \"Error: trouble loading data from file: #{fn}.\\nDetails: #{$!}\"\n end\n else\n raise \"Error: cannot find configuration file: #{fn}.\\nDetails: File not found.\"\n end\n end", "def config=(_arg0); end" ]
[ "0.8030183", "0.7928831", "0.7583291", "0.75449616", "0.74726194", "0.7442349", "0.74075323", "0.7381535", "0.73444533", "0.7335179", "0.7221417", "0.71948636", "0.7142813", "0.71253437", "0.7106711", "0.70752573", "0.7075207", "0.70208704", "0.7018089", "0.7011479", "0.70073295", "0.6984714", "0.6980663", "0.6967595", "0.6966257", "0.6956967", "0.69310814", "0.6925894", "0.68996", "0.68540317", "0.68525314", "0.6851505", "0.6850307", "0.6842367", "0.6840146", "0.68207747", "0.6811734", "0.68034726", "0.68031263", "0.68009543", "0.68001443", "0.67970335", "0.6789415", "0.6775058", "0.6775058", "0.67678744", "0.676173", "0.676173", "0.67597336", "0.6757815", "0.6753404", "0.67504144", "0.6738242", "0.6711774", "0.6710724", "0.67070353", "0.6703805", "0.6684506", "0.66810834", "0.6679049", "0.6676173", "0.6673307", "0.66730285", "0.6666876", "0.66620773", "0.66553444", "0.6652327", "0.66518575", "0.66517884", "0.6636907", "0.6609746", "0.6604885", "0.6602953", "0.6602205", "0.65982044", "0.6588877", "0.6585583", "0.65770763", "0.657521", "0.6574079", "0.6562799", "0.6560861", "0.6547791", "0.65459245", "0.65414935", "0.6514069", "0.65081", "0.6502792", "0.6498611", "0.64981395", "0.6490998", "0.64750254", "0.6474734", "0.6456769", "0.64368147", "0.64368147", "0.64367855", "0.6430388", "0.64265996", "0.64259434" ]
0.674817
52
find note and parent picture, destroy then redirect back to artwork
def destroy @note = Note.find(params[:id]) @picture = @note.picture @artwork = @picture.artwork @note.destroy redirect_to @artwork end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def destroy\n @picture = Picture.find(params[:id])\n @picture.destroy\n\n #need a redirect here\n redirect_back(fallback_location: root_path)\n #if artwork is no longer present fallback to the root\n end", "def destroy\n if @note\n @parent = @note.get_parent if @note\n @note.destroy\n redirect_to :url => \"/\" if !@parent\n redirect_to :url => @parent.relative_url if @parent\n end\n end", "def destroy\n @photograph.destroy\n redirect_back(fallback_location: mygallery_path)\n end", "def destroy\n noteId = @note.id\n @note_images = NoteImage.where(note_id: noteId)\n first_image = @note_images.first\n @note_images.each do |note_image|\n @comments = Comment.where(note_image_id: first_image)\n if @comments != nil?\n @comments.each do |comment|\n comment.destroy\n end\n note_image.destroy\n end\n end\n @note.destroy\n\n respond_to do |format|\n format.html { redirect_to notes_url, notice: 'Note was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n\n if @note.about_person\n @aboutPerson = @note.about_person\n @aboutPerson.destroy\n end\n\n if @note.about_event\n @about_event = @note.about_event\n @about_event.destroy\n end\n\n\n @rn = RemovedNote.new(:sequence_number => @note.id, :person_id => @note.person_id)\n @rn.save\n\n @note.destroy\n\n respond_to do |format|\n format.html { redirect_to notes_url }\n format.json { head :no_content }\n end\n end", "def picture_delete\n @memorial = Memorial.find(params[:id])\n p = Picture.find(params[:picture])\n p.destroy\n redirect_to :action => \"show\", :id => @memorial\n end", "def destroy\n @title = 'Photos'\n @painting = Painting.find(params[:id])\n @painting.destroy\n redirect_to @painting.gallery\n end", "def destroy_note\n @note = Note.find(params[:id])\n\t\t@owner = Track.find(params[:track_id])\n\t\t@owner_id = @owner.id\n\t\t\n @note.destroy\n\t\t# refresh\n\t\t@destroy_url = \"/albums/#{@owner.id}/notes/\"\n\t\t@owner_notes = @owner.notes\n\t\t\n\t\trespond_to do |format|\n\t\t\t\n\t\t\tformat.html { redirect_to :back }\n\t\t\tformat.js\n\t\tend\n \n end", "def removeImage\n @groof = Greenroof.find(params[:id])\n if not (@groof.images.first.nil?)\n\n\n directory = \"/public/greenroofs/photos/\" + params[:id]\n photoFilename = @groof.images.first.photo\n thumbFilename = @groof.images.first.thumb\n photoPath = Dir.pwd + directory + \"/\" + photoFilename\n thumbPath = Dir.pwd + directory + \"/\" + thumbFilename\n File.delete(photoPath)\n File.delete(thumbPath)\n @groof.images.first.delete\n end\n redirect_to greenroof_path(@groof)\n end", "def destroy\n @photo.destroy\n render root_path\n end", "def destroy\n @image_to_part.destroy\n respond_to do |format|\n format.html { redirect_to image_to_parts_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @photo = Photo.find(params[:id])\n @photo.destroy\n\n respond_to do |format|\n format.html { redirect_to(:back) }\n end\n end", "def destroy\n @ministry_picture_child = MinistryPictureChild.find(params[:id])\n redirect_id = @ministry_picture_child.ministry_id\n @ministry_picture_child.destroy\n\n \n respond_to do |format|\n format.html { redirect_to ministry_child_path(redirect_id), notice: 'The picture has been removed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @pin.galleries.each do |f|\n f.photo = nil\n end\n @pin.destroy\n respond_to do |format|\n format.html { redirect_to my_cars_path, notice: 'Destruido correctamente' }\n format.json { head :no_content }\n end\n end", "def destroy\n @documentary.remove_thumbnail = true\n @documentary.save!\n head :no_content\n end", "def destroy\n @note = Note.find(params[:id])\n @note.destroy\n\n respond_to do |format|\n format.html { redirect_to house_path(@note.house_id) }\n format.json { head :no_content }\n end\n end", "def destroy_photo\n @establishment = Establishment.find(params[:id])\n\n # If photo to destory belongs to this establishment\n if @establishment.photos.any? { |p| p.id == params[:photo_id] }\n # Nullify image so we can send correct version of establishment\n # back to frontend\n image = Image.find(params[:photo_id])\n image.imageable_type = nil\n image.imageable_id = nil\n image.save\n\n @establishment.reload\n\n # Now remove image\n image.enqueue_removal\n respond_to do |format|\n format.json { render :show }\n end\n end\n\n end", "def destroy\n @artwork = Artwork.find_by(id: params[:id])\n @artwork.destroy\n redirect_to @current_user\n end", "def destroy\n @photo = LandPhoto.find(params[:id])\n @photo.destroy\n\n redirect_to(bbs_cpanel_photos_url)\n end", "def destroy\n @article.remove_thumbnail = true\n @article.save!\n head :no_content\n end", "def destroy\n artwork_destroy=Artwork.find_by(id:params[:id])\n artwork_destroy.destroy \n head:no_content\n end", "def destroy\n @raw_image.destroy\n redirect_to admin_raw_images_path\n end", "def destroy\n #@picture = Picture.find(params[:id])\n @picture = @museum.pictures.find(params[:id])\n directory = \"public/data\"\n path = File.join(directory, @picture.name)\n if File.exist?(path)\n File.delete(path) \n end\n @picture.destroy\n\n respond_to do |format|\n #format.html { redirect_to pictures_url }\n format.html { redirect_to museum_pictures_path(@museum) }\n format.json { head :no_content }\n end\n end", "def destroy\n @picture.destroy\n\n head :no_content\n end", "def destroy\n @locweb_thepic.destroy\n respond_to do |format|\n format.html { redirect_to locweb_thepics_url }\n format.json { head :no_content }\n end\n end", "def unlink_from_work\n work = parent_for(file_set: file_set)\n return unless work && (work.thumbnail_id == file_set.id || work.representative_id == file_set.id || work.rendering_ids.include?(file_set.id))\n work.thumbnail = nil if work.thumbnail_id == file_set.id\n work.representative = nil if work.representative_id == file_set.id\n work.rendering_ids -= [file_set.id]\n work.save!\n end", "def destroy\n #remove main photo if necessary\n post = Post.where(main_photo: @photo.id).first\n if (post.present?)\n first_photo = Photo.sort_photos_asc.from_post(post.id).first\n if (first_photo.present?)\n post.main_photo = firstPhoto.id\n post.save\n end\n end\n\n @photo.destroy\n\n respond_to do |format|\n format.html { redirect_to photos_url, notice: 'Photo was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @related_content = RelatedContent.find(params[:id])\n @related_content.destroy\n dirname = \"#{RelatedContent::UPLOAD_DIR}/#{@related_content.id}\"\n FileUtils.rm_rf dirname\t\n redirect_to @related_content.node\t \n\nend", "def destroy\n @photo = Photo.find(params[:id])\n @photo.destroy\n redirect_to edit_dashboard_sunjust_product_path(@photo.product.id)\n end", "def destroy\n unless session[:codes].include?(SUPER_SECRET_CODE) || session[:codes].include?(@collection.code)\n redirect_to root_path \n else\n @photo = Photo.find(params[:id])\n @photo.destroy\n\n respond_to do |format|\n format.html { redirect_to photos_url }\n format.json { head :no_content }\n end\n end\n end", "def destroy\n #@document = current_user.documents.find(params[:document_id])\n @document_photo = @document.document_photos.find(params[:id])\n if @document_photo\n \n @document_photo.destroy\n\n respond_to do |format|\n format.html { redirect_to document_itemimages_url(@document) }\n format.json { head :no_content }\n end\n end\n end", "def destroy\n @photo.destroy\n respond_to do |format|\n format.html { redirect_to @photo.item }\n format.json { head :no_content }\n end\n end", "def destroy\n\n destroyable = true\n\n gallery = Gallery.find(params[:id])\n parent_object = gallery.get_parent_object\n\n\n if(gallery.pictures.size>0)\n destroyable = false\n end\n\n if gallery.comments.size>0\n destroyable = false\n end\n\n\n\n if destroyable\n gallery.destroy\n else\n gallery.pictures.each do |picture|\n picture.suspend!\n end\n gallery.suspend!\n end\n\n respond_to do |format|\n flash[:notice] = I18n.t('galleries.controller.Successfully_destroyed')\n format.html { redirect_to(url_for_even_polymorphic(parent_object)) }\n format.xml { head :ok }\n end\n end", "def destroy\n @exercise_image = case @exercise.blank?\n when true\n ExerciseMediumImage.where(token: params[:exercise_medium_id], id: params[:id])\n when false\n @exercise.exercise_images.find(params[:id])\n end\n \n @exercise_image.destroy\n head :no_content\n end", "def destroy\n @photo = @surrounding.photos.find(params[:id])\n @photo.destroy\n respond_to do |format|\n format.html { redirect_to '/surroundings/1/' }\n format.json { head :no_content }\n end\n end", "def destroy\n @plate_photo = PlatePhoto.find(params[:id])\n @plate_photo.destroy\n\n respond_to do |format|\n format.html { redirect_to plate_photos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @pict = Picture.find(params[:id])\n @pict.destroy if @pict\n\n respond_to do |format|\n format.html { redirect_to pictures_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @asset = Asset.find(params[:id])\n @asset.photo.destroy\n @asset.save\n redirect_to :back\n end", "def destroy\n\t@artwork = Artwork.find(params[:id])\n\t@artwork.destroy\n\tredirect_to category_artworks_path(1)\nend", "def destroy\n @article = Article.get(params[:id])\n \n # 업로드된 이미지 파일 삭제 =========================================================================\n file_name = @article.image_filename\n if File.exist?(IMAGE_PATH + file_name)\n \tFile.delete(IMAGE_PATH + file_name) #original image file\n \tFile.delete(IMAGE_PATH + \"t_\" + file_name) #thumbnail file\n end\n # 업로드된 이미지 파일 삭제 =========================================================================\n @article.destroy\n\n respond_to do |format|\n format.html { redirect_to(articles_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @photo.destroy\n\n head :no_content\n end", "def destroy\n # @photo is pulling Photo's information \n @photo = Photo.find(params[:id])\n # @photo_id is keeping the photos id\n @photo_id = @photo.id\n # Is destroying the photo\n @photo.destroy\n # @photo = current_user.photos.find_by(id: params[:id])\n # redirect_to root_url if @photo.nil?\n # redirect_to photos_path\n end", "def destroy\n @item_photos = ItemPhoto.find(params[:id])\n @item_photos.destroy\n\n respond_to do |format|\n format.html { redirect_to :controller => 'items', :action => 'show', :id => @item_photos.item_id }\n end\n end", "def remove_image\n \t@person = Person.find(params[:id])\n \t@person.image = nil\n \t@person.save!\n \tredirect_to @person\n end", "def destroy\n \t@photo = Photo.find(params[:id])\n \t@photo.destroy\n \tredirect_to photos_path, notice: \"The photo #{@photo.name} has been deleted.\"\n end", "def destroy\n @tea_picture = TeaPicture.find(params[:id])\n @tea = @tea_picture.tea\n if @tea_picture.user == current_user ||\n @tea_picture.tea.user == current_user\n\n @tea_picture.destroy\n respond_to do |format|\n format.html { redirect_to @tea }\n format.json { head :no_content }\n end\n else\n respond_to do |format|\n format.html { redirect_to @tea, :warning => \"You can not deattach this picture\"}\n format.json { head :no_content }\n end\n end\n end", "def destroy\n id = @rent_image.rent_id\n @rent_image.destroy\n respond_to do |format|\n format.html { redirect_to \"/rents/gallery/\"+id.to_s, notice: 'Rent image was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @picture = @album.pictures.find(params[:id])\n @picture.destroy\n flash[:notice] = 'Picture was successfully removed.'\n redirect_to(album_pictures_path(@album)) \n end", "def unlink_from_work\n work = parent_for(file_set: file_set)\n return unless work && (work.thumbnail_id == file_set.id || work.representative_id == file_set.id || work.rendering_ids.include?(file_set.id))\n work.thumbnail = nil if work.thumbnail_id == file_set.id\n work.representative = nil if work.representative_id == file_set.id\n work.rendering_ids -= [file_set.id]\n work.save!\n end", "def destroy\n @pic.destroy\n\n notifications = Notification.find(:all, :conditions => ['notification_type = ? and object_id = ?', \"comment\", @pic.id])\n notifications.each do |n|\n n.destroy\n end\n respond_to do |format|\n format.html { redirect_to(root_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @recipe_photo.destroy\n respond_to do |format|\n format.html { redirect_to recipe_photos_url, notice: 'Recipe photo was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete\r\n #KS- don't do anything unless the request was a POST\r\n if @request.method == :post\r\n picture = Picture.find(params['id'])\r\n \r\n #KS- destroy the thumbnail and original image\r\n Picture.delete_image_set(picture.id, current_user)\r\n \r\n #KS- need to force a reload of current_user to get the proper pictures array\r\n pics = current_user.pictures(true)\r\n \r\n #KS- if there are any pics left, set the primary pic for the user to one of those\r\n if !pics.nil? && pics.length > 0\r\n current_user.make_primary(pics[0])\r\n end\r\n end\r\n \r\n redirect_to :action => 'add_picture'\r\n end", "def destroy\n @workshop_images = WorkshopImage.find(params[:id])\n @workshop_images.destroy\n #back to previouse page with the same parameter\n redirect_to :back\n end", "def remove\n\t\t#Clean up unused rtwork\n\t\tif Artwork.find_by_majorpost_uuid(params[:majorpost_uuid])\n\t\t\tResque.enqueue(Image::ArtworkCleanup, params[:majorpost_uuid])\n\t\tend\n\tend", "def destroy\n @photo = Photo.find(params[:id])\n @photo.destroy\n\n head :no_content\n end", "def delete_photo\n@photo = Photo.find(params[:id])\n@photoset = @photo.photoset\n\n\nif !@photo.blank? \n if @photo.photoset.coverimage_id == @photo.id \n coverphoto = Photo.find(:first, :conditions => [\"photoset_id LIKE ? and id != ?\",@photo.photoset_id,@photo.id],:select => [\"id\"])\n if !coverphoto.blank?\n @photo.photoset.coverimage_id = coverphoto.id\n else \n @photo.photoset.coverimage_id =\"\" \n end\n @photo.photoset.update_attributes(params[:photoset]) \n end \n \n \n for story in @photo.photoset.user.stories\n if !story.added_images.blank? \n if story.added_images.include?(\"#{@photo.id}\")\n story.update_attributes(:added_images => story.added_images.delete(\"#{@photo.id}\"))\n end \n end \n end \n \n @photo.destroy\n flash[:notice] = \"Photo(s) successfully deleted\"\n redirect_to :action => 'edit', :id => @photoset.permalink and return \nelse \n flash[:notice] = \"Unable to delete photo from photoset\" \n redirect_to :action => 'edit', :id => @photoset.permalink\nend\n\nend", "def destroy\n @photo = Photo.find(params[:id])\n @photo.destroy\n\n respond_to do |format|\n format.html { redirect_to(photos_path.add_param(:blurb_image => @blurb_image)) }\n format.xml { head :ok }\n end\n end", "def destroy\n @image.inTrash = true\n @image.save\n respond_to do |format|\n format.html { redirect_to @gallery, notice: 'Image is in Trash Folder' }\n format.json { head :no_content }\n end\n end", "def destroy\n attachable = @picture_file.picture_attachable\n @picture_file.destroy\n\n respond_to do |format|\n flash[:notice] = t('controller.successfully_deleted', model: t('activerecord.models.picture_file'))\n format.html {\n case attachable.class.name\n when 'Manifestation'\n redirect_to picture_files_url(manifestation_id: attachable.id)\n when 'Agent'\n redirect_to picture_files_url(agent_id: attachable.id)\n when 'Shelf'\n redirect_to picture_files_url(shelf_id: attachable.id)\n else\n if defined?(EnjuEvent)\n if attachable.class.name == 'Event'\n redirect_to picture_files_url(event_id: attachable.id)\n else\n redirect_to picture_files_url\n end\n else\n redirect_to picture_files_url\n end\n end\n }\n format.json { head :no_content }\n end\n end", "def destroy\n if @article.img_path != ''\n File.delete('app/assets/images/' + @article.img_path) if File.exist?('app/assets/images/' + @article.img_path)\n end\n @article.destroy\n respond_to do |format|\n format.html { redirect_to articles_url, notice: 'Article was successfully destroyed.' }\n format.json { head :no_content }\n end\n\n\n end", "def destroy\r\n @note = Note.find(params[:id])\r\n @note.destroy\r\n\r\n redirect_to @note\r\n end", "def destroy\n @photo = Photo.find(params[:id])\n @photo.destroy\n\n respond_to do |format|\n format.html { redirect_to @photo.photoable }\n format.json { head :no_content }\n end\n end", "def destroy\n @artifact_note = ArtifactNote.find(params[:id])\n @artifact_note.destroy\n\n respond_to do |format|\n format.html { redirect_to(artifact_notes_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n\t @question = Question.find(params[:id])\n\t @question.deleteImgFile\n\t @question.destroy\n\t redirect_to :action => \"listByCourse\" , :course_id => @question.course_id\n\tend", "def destroy \n @note.delete_from_user(current_user)\n Tag.delete_tags_from_parent(@note)\n\n respond_to do |format|\n format.html { redirect_to(user_notes_path(:username => current_user.username)) }\n format.json { head :ok }\n end\n end", "def destroy\n @pic_story = current_user.pic_stories.find(params[:id])\n @pic_story.destroy\n\n respond_to do |format|\n format.html { redirect_to pic_stories_url }\n format.json { head :no_content }\n end\n end", "def destroy\n path = 'public/uploads/batale/text/image/' + @batale_text.id\n FileUtils.remove_dir(path) unless Dir.glob(path).empty? # Remove imagem associada ao texto, caso exista\n @batale_text.destroy\n respond_to do |format|\n format.html { redirect_to batale_texts_url, notice: 'Texto deletado com sucesso.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @picture = Picture.find(params[:id])\n @picture.image.purge\n @picture.destroy\n\n respond_to do |wants|\n #wants.html { redirect_to(:controller=>'welcome',:action =>:index) }\n wants.html {redirect_to pictures_url, alert: \"Product was successfully destroyed.\"}\n wants.xml { head :ok }\n end\n end", "def destroy\n @photo = Photo.find(params[:id])\n @photo.destroy\n\n respond_to do |format|\n format.html { redirect_to request.env[\"HTTP_REFERER\"] || @photo.photoable, notice: 'Photo removed!' }\n format.json { head :no_content }\n end\n end", "def destroy\n @note.destroy\n render('destroy')\n end", "def destroy\n \n @photo = Photo.find(params[:id])\n if @photo.user_id == current_user.id then\n @photo.destroy\n @comments = Comment.where(:photo_id => params[:id])\n end\n\t\n respond_to do |format|\n format.html { redirect_to(photos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @photo = Photo.find(params[:photo_id])\n @comment = @photo.comments.find(params[:id])\n @comment.destroy\n render :nothing => true\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 destroy\n @pic.destroy\n respond_to do |format|\n format.html { redirect_to pics_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @picture = @album.pictures.find(params[:id]) #JRD111115\n @picture.destroy\n respond_to do |format|\n format.html { redirect_to album_pictures_url(@album), notice: 'Picture was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy \n @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 destroy\n @picture.destroy\n redirect_to pictures_path, notice: 'Picture was successfully destroyed'\n end", "def destroy\n @post_pic.destroy\n respond_to do |format|\n format.html { redirect_to post_pics_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @patient_photo = PatientPhoto.find(params[:id])\n @patient_photo.destroy\n\n respond_to do |format|\n format.html { redirect_to(patient_photos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @cat = Cat.find(params[:id])\n #TODO @pictures = Picture.where(\"title LIKE '\"+@cat.id.to_s+\"'\")\n #TODO: call @picture.destroy for each @pictures..\n @cat.destroy\n\n redirect_to cats_path\n end", "def destroy\n @pictures_of_cat = PicturesOfCat.find(params[:id])\n @pictures_of_cat.destroy\n\n respond_to do |format|\n format.html { redirect_to pictures_of_cats_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @picture = Picture.find(params[:id])\n @picture.destroy\n\n respond_to do |format|\n format.html { redirect_to(pictures_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @picture = Picture.find(params[:id])\n @picture.destroy\n\n respond_to do |format|\n format.html { redirect_to(pictures_url) }\n format.xml { head :ok }\n end\n end", "def photo__after_destroy_trigger\r\n\r\nDir[File.join(FILES_DEST_PHOTO, \"#{self.id}_*\")].each{|f| File.delete(f)}\r\nDir[File.join(FILES_DEST_PHOTO__THUMBS, \"#{self.id}_*\")].each{|f| File.delete(f)}\r\nend", "def destroy\n @img = Img.find(params[:id])\n @img.destroy\n\n respond_to do |format|\n format.html { redirect_to(imgs_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @photo = Photo.find(params[:id])\n File.delete(Rails.root.join(\"app\",'assets','images',@photo.path))\n @photo.destroy\n\n respond_to do |format|\n format.html { redirect_to photos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @image = Image.find(params[:id])\n @image.destroy\n\n\n redirect_to new_flat_image_path(@image.flat)\n\n end", "def destroy\n redirect_to game_pictures_url, notice: 'This Picture has been used in Game play. so cannot be deleted' and return if @game_picture.is_used?\n @game_picture.destroy\n respond_to do |format|\n format.html { redirect_to game_pictures_url, notice: 'Game picture was successfully destroyed.' }\n end\n end", "def destroy\n @album = Album.find(params[:album_id])\n @photo = Photo.find(params[:id])\n @goto_page = @photo.pageForDelete(:id, 5)\n if @goto_page < 1\n @goto_page = 1\n end\n \t\n @photo.destroy\n respond_to do |format|\n\t format.html { redirect_to(album_photos_path(@album, :page => @goto_page), :notice => 'Photo was successfully deleted.') }\n end\n end", "def destroy\n @interviewer = Interviewer.find(params[:id])\n if File.exists?(\"#{RAILS_ROOT}/public/images/#{@interviewer.image_name}\")\n File.delete(\"#{RAILS_ROOT}/public/images/#{@interviewer.image_name}\")\n end\n AdminLog.create(:admin_id=>session[:admin_id], :log=>\"Removed a interviewer -> \"+@interviewer.id.to_s)\n @interviewer.destroy\n\n respond_to do |format|\n format.html { redirect_to(interviewers_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @story_image.destroy\n respond_to do |format|\n format.html { redirect_to story_images_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @article.images.purge if @article.images.attached?\n @article.destroy\n respond_to do |format|\n format.html { redirect_to articles_url, notice: '記事を削除しました。' }\n format.json { head :no_content }\n end\n end", "def destroy\n @work = Work.find(params[:id])\n @work.work_thumbnail.destroy\n @work.destroy\n\n respond_to do |format|\n format.html { redirect_to(works_url) }\n format.xml { head :ok }\n end\n end", "def destroy \n @photo = @pictureable.photos.find(params[:id])\n @photo.destroy\n\n respond_to do |format|\n format.html { redirect_to_pictureable_path }\n format.js\n end\n\n rescue ActiveRecord::RecordNotFound\n render :nothing => true, :status => :not_found\n end", "def destroy\n @picture_comment.destroy\n redirect_to picture_path(@picture_comment.picture)\n # respond_to do |format|\n # format.html { redirect_to picture_comments_url, notice: 'Picture comment was successfully destroyed.' }\n # format.json { head :no_content }\n # end\n end", "def destroy\n @notepicture.destroy\n respond_to do |format|\n format.html { redirect_to notepictures_url, notice: 'Notepicture was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @exercise_illustration = case @exercise.blank?\n when true\n ExerciseIllustration.where(token: params[:exercise_id], id: params[:id])\n when false\n @exercise.exercise_illustrations.find(params[:id])\n end\n \n @exercise_illustration.destroy\n head :no_content\n end", "def destroy\n @photo.photo.destroy\n @photo.destroy\n respond_to do |format|\n format.html { redirect_to photos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n\t\timage = Image.find(params[:id])\n\t\timage.destroy\n\t\tredirect_to :back\n\tend", "def destroy\n gallery = load_personal_gallery_from_url\n gallery.destroy\n\n redirect_to \"/\"\n end" ]
[ "0.73953956", "0.71886754", "0.66464704", "0.64856774", "0.6481065", "0.6458882", "0.6432985", "0.6409424", "0.6349936", "0.6347975", "0.6316039", "0.63066953", "0.62736166", "0.6269202", "0.6267368", "0.6244086", "0.6211219", "0.62053996", "0.6203089", "0.619996", "0.6199286", "0.61833656", "0.6179215", "0.617684", "0.61726147", "0.6169812", "0.6164403", "0.61619925", "0.6157067", "0.61413693", "0.6128575", "0.61146337", "0.6114426", "0.6112423", "0.6105784", "0.6089451", "0.6087922", "0.60656416", "0.6042297", "0.60393584", "0.60326976", "0.60311425", "0.6030157", "0.6026952", "0.6022519", "0.6019226", "0.60188067", "0.6008602", "0.6007301", "0.5997956", "0.5997224", "0.5995119", "0.59942764", "0.5993488", "0.5988612", "0.5987741", "0.598027", "0.5979081", "0.5974793", "0.59710014", "0.59683985", "0.5956119", "0.5952275", "0.594986", "0.5948136", "0.59478337", "0.5947097", "0.5944505", "0.59431124", "0.5940391", "0.5931504", "0.59295577", "0.59241784", "0.59236205", "0.59163696", "0.59160167", "0.5904684", "0.5903991", "0.5902272", "0.58936346", "0.58932203", "0.5892565", "0.5892565", "0.5892147", "0.58914244", "0.58912545", "0.5890292", "0.58878124", "0.58835876", "0.58827716", "0.5882384", "0.5881436", "0.5878238", "0.58733207", "0.5869562", "0.5868466", "0.586684", "0.5862415", "0.5861035", "0.58605987" ]
0.75453204
0
defined strong params for notes
def note_params params.require(:note).permit(:content, :noteImgData, :noteImg) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def note_params\n\t\tparams.require(:note).permit(:text, :author_id, :student_id)\n\tend", "def note_params\n\t\tparams.require(:note).permit(:text, :author_id, :student_id)\n\tend", "def notes_params\n params.require(:note).permit(:title, :author, :body)\n end", "def note_params\n params.require(:note).permit!\n end", "def note_params\n params.require(:notes).permit(:title, :body)\n end", "def note_params\n params.require(:note).permit(:title, :content, :cover, :shared, :user_id )\n end", "def note_params\n params.require(:note).permit(:title, :note)\n end", "def note_params\n params.require(:note).permit(:title, :body)\n end", "def note_params\n params.require(:note).permit(:title, :body)\n end", "def note_params\n params.require(:note).permit(:text, :note_object_id, :note_object_type, :note_object_attribute, :created_by_id, :updated_by_id, :project_id)\n end", "def note_params\n params.require(:note).permit(:note)\n end", "def note_params\n params.require(:note).permit(:content, :notable_id, :notable_type, :user_id)\n end", "def note_params\n params.require(:note).permit(:notes_data_type, :notes_data_id, :notes_text, :employee_id, :status)\n end", "def note_params\n params.require(:note).permit(:user_id, :noteSubject, :noteContent, :isPublic)\n end", "def note_params\n params.require(:note).permit(:title, :body, :course_id, :user_id, :lecture_id)\n end", "def note_params\n params.require(:note).permit(:title, :body, :category_id) if params[:note]\n end", "def note_params\n params.require(:note).permit(:title, :subtitle, :body)\n end", "def note_params\n params.require(:note).permit(:name, :content, :game_id, :user_id, :privacy)\n end", "def note_params\n params.require(:note).permit(:title, :text, :date)\n end", "def note_params\n params.require(:note).permit(:title, :content, :user_id)\n end", "def note_params\n params.require(:note).permit(:title, :content, :user_id)\n end", "def note_params\n params.require(:note).permit(:title, :description)\n end", "def note_params\n params.require(:note).permit(:title, :user_id ,:content)\n end", "def note_params\n params.require(:note).permit(\n :title,\n :description,\n :user_id,\n :tag_list,\n :important\n )\n end", "def note_params\n params.require(:note).permit(:prospect_id, :body, :user_id)\n end", "def note_params\n params.require(:note).permit(:title, :body, :user_id)\n end", "def note_params\n params.require(:note).permit(:title, :description, :tag_list, :important)\n end", "def note_params\n params.fetch(:note, {}).permit(:content)\n end", "def note_params\n params.require(:note).permit(:title, :body, :tags)\n end", "def note_params\n params.require(:note).permit(:description)\n end", "def note_params\n params.require(:note).permit(:comment, :user_id)\n end", "def note_params\n params.require(:note).permit(:comment, :user_id)\n end", "def note_params\n params.require(:note).permit(:note, :case_id, :user_id, :note_type, :created_at, :updated_at, :author)\n end", "def note_params\n params.require(:note).permit(:note_id, :body, :last_seen, :all_tags, :prime)\n end", "def note_params\n params.require(:note).permit(:book_id, :title, :content)\n end", "def note_params\n params.require(:note).permit(:title, :content, :address)\n end", "def note_params\n params.require(:note).permit(:reminder_date, :description, :user_id)\n end", "def note_params\n params.permit(:title, :starred, :text)\n end", "def note_params\n params.require(:note).permit(:title, :body, :job_site_id)\n end", "def note_params\n params.require(:note).permit(:description,:instance_id)\n end", "def note_params\n get_user_from_session()\n params.require(:note).permit(:participant_id, :note_text, :important, :notify_on, :updated_by, :notify, :isDone, :isPinned)\n end", "def note_params\n params.require(:note).permit(:showing_id, :description)\n end", "def notes_params\n params.require(:note).permit(:content, :visible_to)\n end", "def note_params\n params.require(:note).permit(:msg, :url)\n end", "def note_params\n params.require(:note).permit(:note_text, :team_player_id)\n end", "def note_params\n params.require(:note).permit(:id, :title, :noteText, :coordinates, :picture, :user_id)\n end", "def note_params\n params.require(:note).permit(:title, :body, :position)\n end", "def note_params\n params.require(:note).permit(:content, :date)\n end", "def note_params\n params[:note]\n end", "def note_params\n params.require(:note).permit(:title, :content, :notebook_id)\n end", "def note_params\n params[:note]\n end", "def api_note_params\n params.fetch(:note).permit(:name, :description)\n end", "def note_params\n params.require(:note).permit(:body,:device_device_id,:user_id,:room_id,:id)\n end", "def note_params\n params.require(:note).permit(:title, :text, :image)\n end", "def note_params\n params.require(:note).permit(:message, :created_at, :sent_at)\n end", "def admin_note_params\n params.fetch(:note).permit!\n end", "def note_params\n params.require(:note).permit(:body, :tag, :second)\n end", "def note_params\n # params.require(:note).permit(:title, :tag, :overview, :detail, user_notes_attributes: [:id,:user_id, :note_id], note_categories_attributes: [:id, :note_id,:category_id])\n end", "def note_params\n params.require(:note).permit(:planting_id, :user_id, :note, :hard_delete)\n end", "def note_params\r\n params.require(:note).permit(:content, :recipe_id, :id)\r\n end", "def note_params\n params.require(:note).permit(:title, :tag, :overview, :detail, user_notes_attributes: [:id,:user_id, :note_id], note_categories_attributes: [:id, :note_id,:category_id])\n end", "def note_params\n params.require(:note).permit(:content, :visible_to)\n end", "def notes_list_params\n params.require(:notes_list).permit(:txtTitle, :txt, :codeTitle, :code, :embedTitle, :embed, :noteStatus)\n end", "def ticketnote_params\n params.require(:ticketnote).permit(:notes, :troubleticket_id, :admin)\n end", "def note_params\n params.permit(:content, :domain, :url)\n end", "def note_create_params\n params.require(:note).permit(:project_id, :id, :title, :type, :description, :show)\n end", "def note_params\n params.require(:note).permit(:user_id, :week_id, :body)\n end", "def sr_note_params\n params.require(:sr_note).permit(:note, :user)\n end", "def case_note_params\n\t\t# Permitting the case note parameters to the particular case\n\t\tparams.require(:case_note).permit(:note)\n\tend", "def note_params\n params.require(:note).permit(:index, :new, :create, :show, :update, :delete)\n end", "def note_params\n params.permit(:id, :title, :note, :audio_path, :latitude, :longitude, :sender, :recipient, :visible_range)\n end", "def case_note_params\n\t\t# Permitting the case note parameters to the particular case\n\t\tparams.require(:case_note).permit(:note,:case_id,:owner_id)\n\tend", "def textnote_params\n params.require(:textnote).permit(:content, :usuario_id)\n end", "def note_params\r\n params.require(:note).permit(:title, :description, :image)\r\n end", "def note_params\n params.require(:note).permit(:title, :description, :subject, :teacher, :rating, :user_id, :create_note, :image, image_attributes: [:id])\n end", "def private_note_params\n params.require(:private_note).permit(:user_id, :link_id, :body, :title)\n end", "def interview_note_params\n params.require(:interview_note).permit(:app_form_id, :user_id, :text)\n end", "def remember_note_params\n params.require(:remember_note).permit(:title, :description)\n end", "def note_params\n params.require(:note).permit(:file, :topic_id, :subject_id)\n end", "def sticky_note_params\n params.require(:sticky_note).permit(:content)\n end", "def order_note_params\n params.require(:order_note).permit(:information, :order_id)\n end", "def property_note_params\n params.require(:property_note).permit(:user_id, :property_id, :text)\n end", "def notegood_params\n params.require(:notegood).permit(:user_id, :note_id)\n end", "def pnote_params\n params.require(:pnote).permit(:para1, :para2, :para3, :patient_id)\n end", "def note_book_params\n params.require(:note_book).permit(:title, :about)\n end", "def note_params\n params.require(:note).permit(:title, :description, attachments_attributes: [:file, :file_cache])\n end", "def note_reply_params\n params.permit(:text, :note_id, :user_id)\n end", "def note1_params\n params.require(:note1).permit(:name, :age)\n end", "def note_params\n params.require(:note).permit(:note, :artboard_id, :user_id, rect: [:x, :y, :width, :height])\n end", "def formula_note_params\n params.require(:formula_note).permit(:formula_id, :note)\n end", "def to_do_note_params\n params.require(:to_do_note).permit(:title, :notes, :user_id, :done)\n end", "def note_title_params\n params.require(:note_title).permit(:title)\n end", "def note_params\n type = if params[:checklist_note]\n :checklist_note\n elsif params[:survey_note]\n :survey_note\n elsif params[:case_note]\n :case_note\n elsif params[:task_note]\n :task_note\n else\n :note\n end\n params.require(type).permit(Note.safe_attributes)\n end", "def note_collection_params\n params.require(:note_collection).permit(:name, :user_id, :note_id)\n end", "def event_note_params\n params.require(:event_note).permit(:title, :content, :admin_id, :event_id)\n end", "def product_note_params\n params.require(:product_note).permit(:product_id, :note)\n end", "def project_note_params\n params.require(:project_note).permit(:project_id, :project_notes, :project_note_date, :project_note_owner)\n end", "def user_has_note_params\n params.require(:user_has_note).permit(:user_id, :note_id)\n end", "def release_note_params\n params.require(:release_note).permit(:sistema_id, :path_deploy, :contexto, :motivacao, :instrucao_uso, :monitoramento)\n end", "def credit_note_params\n params.require(:credit_note).permit(:creation_date, :informed_gross_amount, :sii_status, :receipt_id)\n end" ]
[ "0.8095777", "0.8095777", "0.8080339", "0.8072689", "0.80465996", "0.8020872", "0.79912484", "0.7966443", "0.7966443", "0.79652786", "0.7953361", "0.7946721", "0.7938833", "0.7935312", "0.7931431", "0.7913021", "0.79067695", "0.79060334", "0.790305", "0.7878012", "0.7878012", "0.78743184", "0.78720164", "0.78617805", "0.7860734", "0.7854281", "0.7848418", "0.78388554", "0.78369224", "0.7830612", "0.78251064", "0.78251064", "0.7821976", "0.7817835", "0.7798952", "0.7777483", "0.7773638", "0.7772069", "0.7731584", "0.7726318", "0.77245235", "0.7724482", "0.765697", "0.76366127", "0.76336086", "0.763292", "0.7626062", "0.76210976", "0.76198137", "0.7616731", "0.7616261", "0.76029426", "0.7600345", "0.75651425", "0.75519526", "0.75477445", "0.75449544", "0.7542346", "0.7536329", "0.752858", "0.7515579", "0.75102943", "0.74748516", "0.7469157", "0.746001", "0.7457592", "0.74566144", "0.7410106", "0.7393113", "0.738373", "0.736979", "0.7366885", "0.7361892", "0.73485094", "0.73331577", "0.7332426", "0.7314184", "0.73043144", "0.7300311", "0.72978467", "0.72877645", "0.72564644", "0.7247495", "0.7244759", "0.7243009", "0.72316366", "0.72306985", "0.72086614", "0.720134", "0.71996206", "0.7198681", "0.7124309", "0.7109751", "0.7097928", "0.70896304", "0.7087282", "0.70758593", "0.7066561", "0.7064712", "0.70207876" ]
0.7565081
54
For a recurrent network, this resets hidden states back to zero
def reset if config.isRecurrent @nn.resetRecurrentStates else puts "Warning not a recurrent network. This does nothing" end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def reset_state\n @hidden.data = @hidden.data.fill(0) if @hidden.data\n end", "def reset\n clear\n CONNECTION_TYPES.map { |ct| connections.send(ct) }.each do |conn_group|\n conn_group.each_value { |conn| conn.weight = rand * 0.2 - 0.1 }\n end\n\n @bias = rand * 0.2 - 0.1\n @old = @state = @activation = 0\n end", "def reset_state\n @state = nil\n end", "def reset_all_nodes\n nodes.where(net_id: id).each do |node|\n node.output = 0\n node.total_input = 0\n node.save\n end\n end", "def reset\r\n @v_n_1 = @v_n_2 = 0\r\n end", "def reset\n @current = 0\n @state = :stopped\n end", "def wipe_state\r\n @modes = nil\r\n @online = false\r\n end", "def reset\n @grid.reset_pulses\n end", "def internal_reset(initial_value); end", "def resets; end", "def state_no_network\n @log.debug(\"Net_state: change to state state_no_network\")\n @network_state = :state_no_network\n make_state_change_ntfy(:ntfy_state_no_network)\n end", "def reset \n init_fann\n end", "def clearState()\n\t\t\t@_previous_state = @_state\n\t\t\t@_state = nil\n\t\tend", "def resetStates()\r\n @players.each do |player|\r\n if(player.money > 0)\r\n player.state = \"fine\"\r\n else\r\n player.state = \"broke\"\r\n end\r\n end\r\n end", "def clear_state\n @state.clear\n self\n end", "def do_reset\n\t\t\n\t\t\t# Mark state as reset\n\t\t\t@reset = true\n\t\t\t\n\t\t\t# Revert text and palette\n\t\t\tself.text = nil \n\t\t\tself.palette = @palette_normal\t\t\t\n\t\tend", "def reset\n\t\t@r = 0\n\t\t@p = 0\n\t\t@t = 0\n\t\t@l = 0\n\t\t@s = 0\n\tend", "def reset()\n \n end", "def reset_transition_flags\n @trans_flag = BACKDROP_TRANS_DEFAULT[BACKDROP_SWITCH]\n @transition = BACKDROP_TRANS_DEFAULT[BACKDROP_NAME]\n @duration = BACKDROP_TRANS_DEFAULT[BACKDROP_DURATION]\n @trans_vague = BACKDROP_TRANS_DEFAULT[BACKDROP_VAGUE]\n end", "def reset\n @fann = RubyFann::Standard.new fann_opts\n if algo && algo != :rwg\n fann.set_training_algorithm(algo)\n end\n if actfn\n fann.set_activation_function_hidden(actfn)\n fann.set_activation_function_output(actfn)\n end\n if init_weights_range\n fann.randomize_weights(*init_weights_range.map(&method(:Float)))\n end\n end", "def reset()\n @x\n \n end", "def reset\n @round = 0\n @turn = 0 \n assign_player_colors\n seat_players\n seed_player_funds\n reset_state_bins\n add_home_state_picks\n pick_who_goes_first\n start_at_first_day\n end", "def reset() end", "def hide_frame_state(graph)\n graph.nodes.each_value do |node|\n if FRAME_STATE_NODES.include?(node.props.dig(:node_class, :node_class))\n node.props[:hidden] = true\n end\n end\n end", "def reset()\n\n\t\t@aChecksum = [ 0xFF, 0xFF ];\n\n\tend", "def private_reset!\n @balance = 0\n end", "def reset\n\t\tdo_send('ARST 2')\n\tend", "def reset\n @state = :waiting\n @man_days_done = 0\n end", "def clear\n current_state.clear\n end", "def setup_rem_state\n return TSBS.error(@acts[0], 1, @used_sequence) if @acts.size < 2\n c = @acts[2] || 100\n c = c/100.0 if c.integer?\n if area_flag\n target_array.each do |t|\n if chance(c)\n t.remove_state(@acts[1])\n get_scene.tsbs_redraw_status(t)\n end\n end\n return\n end\n return unless target\n if chance(c)\n target.remove_state(@acts[1])\n get_scene.tsbs_redraw_status(target)\n end\n end", "def reset\n @assigned = false\n end", "def reset_visiting_state\n @visited = Array.new(@height) { Array.new(@width) }\n end", "def reset_visiting_state\n @visited = Array.new(@height) { Array.new(@width) }\n end", "def reset\n @bridge.reset\n end", "def reset ; end", "def reset_visiting_state\n @visited = Array.new(@width) { Array.new(@height) }\n end", "def reset\n\n end", "def reset_nodes\n # get all nodes for the active game\n self.nodes.update_all(:game_id => nil) \n # reset ownership for all nodes\n end", "def reset\n end", "def reset\n end", "def reset\n end", "def reset\n end", "def reset_is_default_flags\n if self.is_default == true\n self.dataset.weights.get_all_but(self.id).update_all(is_default: false)\n end\n end", "def reset\n end", "def reset\n end", "def reset\n @gold, @metal, @stone, @wood = [5, 1, 1, 1]\n @dwarves, @elves, @gnomes = [3, 3, 0]\n @properties, @score = [12, 0]\n\n self\n end", "def setup_rem_state\n return unless PONY::ERRNO::check_sequence(current_act)\n current_action_targets.each do |target|\n state_id = @acts[1]\n chance = @acts[2] || 100\n chance = chance / 100.0 if c.integer?\n target.remove_state(state_id) if rand < chance\n end\n end", "def reset\n @gold_coins = 0\n @health_points = 10\n @lives = 5\n end", "def reset\n until (@stacksize <= 1)\n pop # retrieve graphics states until we get to the default state\n end\n push # push the retrieved pristine default state back onto the stack\n end", "def reset\n @state = :entry\n end", "def resets\n @resets ||= buttons.select { |f| f.class == Reset }\n end", "def reset_is_default_flags\n if self.is_default == true\n self.time_series.weights.get_all_but(self.id).update_all(is_default: false)\n end\n end", "def reset\n self.curr_ip = self.subnet.split('.')\n self.num_ips = (1 << (32 - Socket.net2bitmask(self.netmask).to_i))\n self.curr_ip_idx = 0\n end", "def reset\n if @stage == :running\n @should_reset = true\n end\n end", "def reset_reprap\n @sp.dtr = 1\n sleep(0.2)\n @sp.dtr = 0\n sleep(0.3)\n end", "def reset\n @equations = nil\n @results = nil\n end", "def reset\n end", "def reset\n end", "def reset()\n end", "def reset\n \n end", "def off!\n put '/state', { 'on' => false, 'transitiontime' => 0 }.to_json\n end", "def reset\n @max_color_distance = @color_distance_limit ? 0 : nil\n @max_shift_distance = @shift_distance_limit ? 0 : nil\n end", "def reset()\n @actual =@inicio\n end", "def process_reset\n node.reset_defaults_and_overrides\n check_for_state_change(\"Default and Override Reset\")\n end", "def reset!; end", "def reset!; end", "def reset!; end", "def reset!; end", "def reset_visit_state\n @maze = @maze.map do |line|\n line.sub('V', '_')\n end\n end", "def reset; end", "def reset; end", "def reset; end", "def reset; end", "def reset; end", "def reset; end", "def reset; end", "def reset; end", "def reset; end", "def reset; end", "def reset; end", "def reset; end", "def reset; end", "def reset; end", "def reset; end", "def reset; end", "def reset; end", "def reset; end", "def reset\n @cur_energy = @max_energy\n end", "def reset\n\t\tend", "def reset_visiting_state\n @visited = Array.new(@columns) { Array.new(@rows) }\n end", "def des\n state = FALSE\n end", "def update_normal_balance\n self.normal_balance = :none\n end", "def reset\n info \"\\n\\n------------ RESET ------------\\n\"\n # ExecApp.killAll ## NOTE: do we want to kill of the started RC on reset ???\n resetState\n RMCommunicator.instance.reset\n end", "def reset\n @nums\n end", "def reset\n @blocks = @original_blocks\n end", "def discard_saved_state\n end", "def reset(*)\n super.tap do\n __debug_sim('*** RESET WORKFLOW STATE ***')\n end\n end", "def reset\n @player_status = \"in\" \n @hands = [] \n @hands_status = [] \n @bets = [] \n @values = [] \n @cur = 0 \n end", "def reset\n $iptr = 0\n $program = []\n $labels = {}\n $binding = binding\nend", "def reset\n # TODO\n end" ]
[ "0.793131", "0.65126204", "0.6357723", "0.6288698", "0.62217224", "0.61153", "0.59013903", "0.5882676", "0.58755016", "0.5801405", "0.5768204", "0.575981", "0.5719362", "0.5677884", "0.56665677", "0.563799", "0.56377774", "0.5635372", "0.5632821", "0.5627946", "0.5625814", "0.5622682", "0.56145", "0.5604072", "0.5594776", "0.55864984", "0.5577374", "0.55576384", "0.55575544", "0.5542139", "0.5537767", "0.5534831", "0.5534831", "0.55329317", "0.55270034", "0.5524565", "0.55202025", "0.5518715", "0.55179274", "0.55179274", "0.55179274", "0.55179274", "0.55126244", "0.5506628", "0.5506628", "0.5503615", "0.54934436", "0.54767704", "0.54764694", "0.54750246", "0.5461199", "0.54603535", "0.5460152", "0.54597837", "0.5459233", "0.5442145", "0.5440273", "0.5440273", "0.5433844", "0.54316187", "0.5428797", "0.5422801", "0.5416019", "0.5413384", "0.54096466", "0.54096466", "0.54096466", "0.54096466", "0.54035956", "0.5399961", "0.5399961", "0.5399961", "0.5399961", "0.5399961", "0.5399961", "0.5399961", "0.5399961", "0.5399961", "0.5399961", "0.5399961", "0.5399961", "0.5399961", "0.5399961", "0.5399961", "0.5399961", "0.5399961", "0.5399961", "0.5395054", "0.5389927", "0.5385204", "0.53747994", "0.5374487", "0.5373231", "0.5365588", "0.5359111", "0.53438336", "0.5336015", "0.53308874", "0.53307676", "0.533007" ]
0.7516543
1
TODO:fix logic, private id shadow business id
def seller seller_id = Product.find(params[:product_id]).owner_id begin if PrivateProfile.find_by_id(seller_id) redirect_to url_for(:controller => :private_profiles, :action => :show, :id => seller_id) return end end begin if BusinessProfile.find_by_id(seller_id) redirect_to url_for(:controller => :business_profiles, :action => :show, :id => seller_id) return end end render_404 end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def id_number; end", "def external_id; end", "def id() end", "def object_id() end", "def local_id; end", "def id_public\n id\n end", "def real_id\n @id\n end", "def real_id\n @id\n end", "def __id__() end", "def generate_id \n end", "def id; end", "def id; end", "def id; end", "def id; end", "def id; end", "def id; end", "def id; end", "def id; end", "def id; end", "def id; end", "def id; end", "def id; end", "def id; 1; end", "def id\n __id\n end", "def rp_id; end", "def id()\n #This is a stub, used for indexing\n end", "def id_generator; end", "def _id\n @id\n end", "def temp_id\n #reverting to just plain id, see issue #89\n self.id\n end", "def abstract_id=(_); end", "def id; 1; end", "def __id; @id || @obj.id; end", "def globally_unique_identifier\n super\n end", "def id\n #NOOP\n end", "def id\n '1234567890'\n end", "def hide_id\n self.hashed_id = (((self.id * PRIME) & MAXID) ^ RNDXOR).to_s(16)\n self.save\n end", "def obfuscated_id\n Cryptography.obfuscate(self.id)\n end", "def valid_id_number; end", "def other_claim_related_id\n end", "def urn_id; :id end", "def urn_id; :id end", "def invalid_id_number; end", "def key_id; end", "def id\n\t\tbuild_id\n\tend", "def numid; end", "def id\n super.to_s.tr('.', '_')\n end", "def system_id\n super\n end", "def hash\n \tcustom_unique_id.hash\n end", "def public_id\n nil\n end", "def numid=(_); end", "def id\n @id_number = 12345\n end", "def dom_id; end", "def dom_id; end", "def dom_id; end", "def dom_id; end", "def id\n object_id\n end", "def id=(_arg0); end", "def id=(_arg0); end", "def id=(_arg0); end", "def blip_id # :nodoc:\n super\n end", "def associated_salesforce_id(_instance)\n raise NotImplementedError\n end", "def owner_access_control_key # :nodoc:\n 'id'\n end", "def get_id()\n @id\n end", "def get_id()\n @id\n end", "def generate_public_id\n self.public_id = Time.now.to_i.to_s 36\n end", "def unfriendly_id?; end", "def __object_unique_id__\n name\n end", "def __object_unique_id__\n name\n end", "def user_id; 1; end", "def make_id\n \"#{self.class.name.downcase}#{id}\"\n end", "def id\n raise NotImplementedError\n end", "def get_id\n @id\n end", "def get_id\n @id\n end", "def get_id\n @id\n end", "def get_id\n @id\n end", "def add_dummy_update_id\n add_dummy_create_id\n end", "def id\n @id || self.class.name.underscore.split('/').last #gsub('/', '_')\n end", "def secure_id\n @secure_id_without_dashes ||= super&.gsub(\"-\", \"\")\n end", "def base_id\n \"#{firstname} #{lastname}\"\n end", "def id\n object.id\n end", "def id\n object.id\n end", "def get_id\n\t\treturn id\n\tend", "def remote_id; end", "def privacy_object_id\r\n\t\t\treturn self.id\r\n\t\tend", "def dom_id\n \"_#{self.object_id}\"\n end", "def obo_id(so_id)\n return \"obo:\" + so_id.sub(':', '_')\n end", "def id; self['_id']; end", "def id2name() end", "def id2name() end", "def chilean_id; end", "def idpath; @idpath ||= define_idpath end", "def id\n key\n end", "def legacy_id\n return @legacy_id\n end", "def id\n raise NotImplementedError\n end", "def key\n id\n end", "def get_id()\n return @id\n end", "def id\n return @id\n end", "def set_id\n self.id = SecureRandom.random_number(9223372036854775807)\n end", "def uwt_id\n GraphQL::Schema::UniqueWithinType.encode(self.class.name, id)\n end", "def generate_machine_id()\n \n end", "def id\n object.object_id\n end" ]
[ "0.6937187", "0.6920891", "0.6897053", "0.68818897", "0.6853511", "0.6838446", "0.67880136", "0.67880136", "0.678048", "0.6696062", "0.66667944", "0.66667944", "0.66667944", "0.66667944", "0.66667944", "0.66667944", "0.66667944", "0.66667944", "0.66667944", "0.66667944", "0.66667944", "0.66667944", "0.6666311", "0.6544884", "0.65417415", "0.65409726", "0.65260434", "0.651596", "0.6493917", "0.64567745", "0.6450868", "0.64263", "0.64185554", "0.641157", "0.6395531", "0.63906276", "0.6389898", "0.6362544", "0.6326994", "0.6307422", "0.6307422", "0.6260011", "0.62497616", "0.62409246", "0.6236022", "0.623526", "0.6229021", "0.62275976", "0.6156447", "0.61479515", "0.6130094", "0.61299205", "0.61299205", "0.61299205", "0.61299205", "0.61169434", "0.6116094", "0.6116094", "0.6116094", "0.6098415", "0.6093055", "0.60928154", "0.6089868", "0.6089868", "0.60835665", "0.60800517", "0.6077312", "0.6077312", "0.6073775", "0.6069056", "0.60543084", "0.6035473", "0.6035473", "0.6035473", "0.6035473", "0.60339093", "0.6025157", "0.6024757", "0.60233456", "0.60219145", "0.60219145", "0.60217947", "0.60120064", "0.5989442", "0.59604615", "0.59592885", "0.5950319", "0.59403175", "0.59403175", "0.5937176", "0.5935282", "0.59319204", "0.5924593", "0.59200376", "0.5920006", "0.59091", "0.59022194", "0.58940583", "0.5891097", "0.58895355", "0.5888038" ]
0.0
-1
Copies workflows to another scope.
def copy workflows = Workflow.accessible_by(@context).where(id: params[:item_ids]) new_workflows = workflows.map { |wf| copy_service.copy(wf, params[:scope]).first } # TODO: change old UI to handle json-response! respond_to do |format| format.html do redirect_to pathify(workflows.first), success: "The workflow has been published successfully!" end format.json { render json: new_workflows, root: "workflows", adapter: :json } end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def copy\n workflows = Workflow.accessible_by(@context).where(id: params[:item_ids])\n\n new_workflows = workflows.map { |wf| copy_service.copy(wf, params[:scope]).first }\n\n # TODO: change old UI to handle json-response!\n respond_to do |format|\n format.html do\n redirect_to pathify(workflows.first),\n success: \"The workflow has been published successfully!\"\n end\n\n format.json { render json: new_workflows, root: Workflow.model_name.plural, adapter: :json }\n end\n rescue StandardError => e\n raise ApiError, Message.bad_request(e.message)\n end", "def merge(new_scopes); end", "def copy(user_id, item_id)\n workflow = Workflow.new\n workflow.users = self.users\n workflow.status = self.status\n workflow.issued_at = self.issued_at\n workflow.decided_at = self.decided_at\n if self.original_by.nil? and self.user_id != 0\n workflow.original_by = self.user_id\n else\n workflow.original_by = self.original_by\n end\n workflow.item_id = item_id\n workflow.user_id = user_id\n\n workflow.save!\n\n return workflow\n end", "def copy\n ref_kanban = Kanban.find(params[:ref_id])\n ref_kanban_panes = KanbanPane.find_all_by_kanban_id(params[:ref_id])\n ref_workflow = KanbanWorkflow.find_all_by_kanban_id(params[:ref_id])\n\n new_kanban = ref_kanban.dup\n new_kanban.project_id = params[:project_id]\n new_kanban.update_attribute(:is_valid, true)\n new_kanban.save!\n ref_kanban_panes.each do |p|\n new_pane = p.dup\n new_pane.kanban_id = new_kanban.id\n new_pane.save!\n end\n\n ref_workflow.each do |w|\n new_w = w.dup\n new_w.kanban_id = new_kanban.id\n new_w.save!\n end\n redirect_to edit_project_kanban_path(new_kanban.project_id, new_kanban.id, :tab => \"Panes\")\n end", "def copy_attributes_and_shares\n new_period.job_copy_source_id = old_period.id\n %i[meal_job_requester_id pick_type quota_type round_duration\n max_rounds_per_worker workers_per_round].each do |attrib|\n new_period[attrib] = old_period[attrib]\n end\n\n old_period.shares.includes(:user).find_each do |share|\n next if share.user.inactive?\n new_period.shares.build(period: new_period, user_id: share.user_id, portion: share.portion,\n priority: share.priority)\n end\n end", "def perform(scope, nodes_ids, session_auth_params)\n @context = Context.build(session_auth_params)\n nodes = Node.where(id: nodes_ids)\n copies = copy_service.copy(nodes, scope)\n notify_user(copies, scope)\n end", "def copy_persistent_tasks\n tasks_to_copy = docket_switchable_tasks.select { |task| selected_task_ids.include?(task.id.to_s) }\n if docket_type == \"direct_review\"\n new_docket_stream.tasks.find_by(type: \"DistributionTask\").cancelled! if tasks_to_copy.any?(&:post_distribution?)\n else\n tasks_to_copy.reject!(&:post_distribution?)\n end\n tasks_to_copy.map { |task| task.copy_with_ancestors_to_stream(new_docket_stream) }\n end", "def copy\n @prev_marketing_campaign_id = session[:marketing_campaign_id]\n marketing_campaign_to_clone = MarketingCampaign.find(params[:id])\n @marketing_campaign = marketing_campaign_to_clone.clone\n @marketing_campaign.campaign_status = 'i' \n end", "def copy_from(other)\n @environment = other.environment\n @load_directories = other.load_directories\n @on_request = other.on_request\n other.request_callbacks.each { |block| self.register_request_callback(&block) }\n other.request_error_callbacks.each { |block| self.register_request_error_callback(&block) }\n other.external_errors.each { |error, block| self.register_external_error(error, &block) }\n end", "def copy_ds_tasks_to_new_stream\n new_completed_task = DocketSwitchGrantedTask.assigned_to_any_user.find_by(appeal: old_docket_stream).dup\n new_completed_task.assign_attributes(\n appeal_id: new_docket_stream.id,\n parent_id: new_docket_stream.root_task.id,\n status: Constants.TASK_STATUSES.completed\n )\n # Disable validation to avoid errors re creating with status of completed\n new_completed_task.save(validate: false)\n end", "def copy_suite_from_belt_scope(scope)\n ::Zim.suite(scope.name) do |suite|\n scope.projects.each do |project|\n next if project.tags.include?('historic')\n next if project.tags.include?('external')\n next if project.tags.include?('deprecated')\n next if project.tags.include?('zim=no')\n git_url = project.tag_value('git_url') || \"https://github.com/#{scope.name}/#{project.name}.git\"\n suite.application(project.name, 'git_url' => git_url, 'tags' => project.tags.dup)\n end\n end\n end", "def copy_organization_from_belt_scope(scope)\n ::Backpack.organization(scope.name) do |o|\n scope.projects.each do |project|\n next if project.tags.include?('backpack=no')\n methods = Repository.instance_methods(false)\n options = {}\n methods.each do |method|\n key = method.to_s.sub(/\\?$/, '')\n if method.to_s.end_with?('?') && methods.include?(\"#{key}=\".to_sym)\n options[key] = true if project.tags.include?(key)\n elsif methods.include?(\"#{key}=\".to_sym)\n value = project.tag_value(key)\n value = value.split(',') if value && key == 'topics'\n options[key] = value if value\n end\n end\n o.repository(project.name, options.merge({:tags => project.tags.dup}))\n end\n end\n end", "def move_within_scope(scope_id)\n send(\"#{scope_name}=\", scope_id)\n save!\n end", "def sharing\n collaborators = api.get_collaborators(app).body.map{|collab| collab['email']}\n target_collaborators = api.get_collaborators(target_app).body.map{|collab| collab['email']}\n\n (collaborators - target_collaborators).each do |email|\n action(\"Copying #{email} to #{target_app} collaborators\") do\n api.post_collaborator(target_app, email)\n end\n end\n end", "def copy\n self.class.copy(client, scope_parameters, id.to_s).try(:first)\n end", "def copy\n move(:copy)\n end", "def clone_requirements_from(original_project)\n original_project.requirements.each do |req|\n r2 = req.dup\n r2.attributes = { project_id: id }\n r2.save\n end\n end", "def copy\n \n end", "def clone\n copy = super\n transaction do\n copy.save!\n\n %w[\n registration_information support information_source advance_directive\n ].each do |assoc|\n copy.send(\"#{assoc}\\=\", send(assoc).clone) if send(assoc)\n end\n\n %w[\n patient_identifiers languages providers medications allergies conditions\n all_results immunizations encounters procedures medical_equipments social_history insurance_providers\n ].each do |assoc|\n send(assoc).each do |item|\n copy.send(assoc) << item.clone\n end\n end\n\n end\n copy\n end", "def copy(from, to)\n @parent.gemset_copy(from, to)\n end", "def carry_scope(acts=nil,scope=nil)\n scope||= get_scope\n return if scope.nil?\n acts.each_with_index do |act,index|\n if act.start_with?('new')\n acts[index]=\"#{act}?scope=#{scope}\"\n end\n end \n end", "def copy\n project_to_clone = Project.find(params[:id])\n @project = project_to_clone.clone\n\n # FIXME add copying of project team members\n\n # date/time transformations\n convert_db_datetime_to_display\n end", "def copy_from(other)\n @stack = other.copy_stack\n end", "def copy(from, to)\n \n end", "def copy\n if params[:copyfrom]\n h = Hash.from_xml(open(params[:copyfrom]))\n if a = h['activity']\n @activity = Activity.new(a)\n end\n else\n id = params[:id]\n @parent = Activity.find(id)\n @activity = @parent.clone\n end\n @activity.user = current_user\n @activity.public = false\n @activity.name << \" (copy)\"\n @activity.uuid = nil\n unless params[:copyfrom]\n @activity.parent = @parent unless params[:copyfrom]\n @activity.parent_version = @parent.version\n end\n render :action => 'new'\n end", "def copy\n orig_questionnaire = Questionnaire.find(params[:id])\n questions = Question.find_all_by_questionnaire_id(params[:id]) \n @questionnaire = orig_questionnaire.clone\n \n if (session[:user]).role.name != \"Teaching Assistant\"\n @questionnaire.instructor_id = session[:user].id\n else # for TA we need to get his instructor id and by default add it to his course for which he is the TA\n @questionnaire.instructor_id = Ta.get_my_instructor((session[:user]).id)\n end\n @questionnaire.name = 'Copy of '+orig_questionnaire.name\n \n begin\n @questionnaire.save! \n @questionnaire.update_attribute('created_at',Time.now)\n questions.each{\n | question |\n newquestion = question.clone\n newquestion.questionnaire_id = @questionnaire.id\n newquestion.save \n \n advice = QuestionAdvice.find_by_question_id(question.id)\n newadvice = advice.clone\n newadvice.question_id = newquestion.id\n newadvice.save\n } \n pFolder = TreeFolder.find_by_name(@questionnaire.display_type)\n parent = FolderNode.find_by_node_object_id(pFolder.id)\n if QuestionnaireNode.find_by_parent_id_and_node_object_id(parent.id,@questionnaire.id) == nil\n QuestionnaireNode.create(:parent_id => parent.id, :node_object_id => @questionnaire.id)\n end\n redirect_to :controller => 'questionnaire', :action => 'view', :id => @questionnaire.id\n rescue\n flash[:error] = 'The questionnaire was not able to be copied. Please check the original course for missing information.'+$! \n redirect_to :action => 'list', :controller => 'tree_display'\n end \n end", "def call\n return broadcast(:invalid) if @participation.invalid?\n \n Participation.transaction do\n copy_participation\n end\n \n broadcast(:ok, @copied_process)\n end", "def clone_positions_for_multiple_quarters\n @service_learning_course = ServiceLearningCourse.find(params[:course])\n @selected_copy_quarter = Quarter.find(params[:copy_quarter_id])\n @selected_copy_course = ServiceLearningCourse.find(params[:copy_course_id])\n \n if params[:select]\n copied_positions = []\n copied_placements = []\n for object_type, ids in params[:select]\n if object_type == 'ServiceLearningPosition'\n for id, val in ids\n position = ServiceLearningPosition.find(id)\n organization_quarter = position.organization_quarter\n begin \n ActiveRecord::Base.transaction do \n @new_oq = OrganizationQuarter.find_by_organization_id_and_quarter_id_and_unit_id(position.organization.id, @selected_copy_quarter.id, @unit)\n if @new_oq.nil?\n @new_oq = organization_quarter.deep_clone!\n @new_oq.update_attribute(:quarter_id, @selected_copy_quarter.id)\n @new_oq.save!\n end \n \n @new_position = position.clone(['details','times','supervisor','location','approved','ideal_number_of_slots'])\n @new_position.update_attribute(:organization_quarter_id, @new_oq.id)\n @new_position.save!\n \n position.placements.for(@service_learning_course).select(&:filled?).each do |placement| \n new_placement = placement.deep_clone!\n new_placement.update_attribute(:service_learning_position_id, @new_position.id)\n new_placement.update_attribute(:service_learning_course_id, @selected_copy_course.id)\n new_placement.save!\n copied_placements << new_placement \n end\n end \n rescue ActiveRecord::RecordInvalid => invalid \n raise ActiveRecord::Rollback\n flash[:error] = \"Sorry, but we couldn't copy #{position.name}. An error occurred.\" \n redirect_to :back\n end\n @new_oq.update_position_counts! \n copied_positions << @new_position\n end\n end\n end\n flash[:notice] = \"Copied #{copied_positions.size} positions with #{copied_placements.size} students who enrolled #{@service_learning_course.title} to #{@selected_copy_quarter.title}.\"\n else\n flash[:error] = \"Please select at least one position first.\"\n redirect_to :back \n end\n respond_to do |format|\n #format.html { redirect_to(service_learning_course_path(@unit, @quarter, @service_learning_course, :anchor => \"organization_matches\")) }\n format.html { redirect_to(service_learning_course_path(@unit, @selected_copy_quarter, @selected_copy_course, :anchor => \"position_matches\")) }\n end \n\n end", "def soft_copy\n copy = View.from_doc(@doc.soft_copy)\n copy.scoped_as = scoped_as\n copy\n end", "def copy\n copies = CopyService::Copies.new\n Job.accessible_by(@context).where(uid: params[:item_ids]).each do |job|\n copies.push(object: job_copier.copy(job, params[:scope]), source: nil)\n end\n\n render json: copies.all, root: \"jobs\", adapter: :json,\n meta: { messages: build_copy_messages(copies) }\n end", "def clone_inputs_to_space\n files = UserFile.accessible_by(@context).where(uid: @inputs.values)\n\n return if files.empty?\n\n api = DIContainer.resolve(\"api.user\")\n\n api.project_invite(\n @context.user.private_files_project,\n \"user-#{CHALLENGE_BOT_DX_USER}\",\n DNAnexusAPI::PROJECT_ACCESS_VIEW,\n suppressEmailNotification: true,\n suppressAllNotifications: true,\n )\n\n begin\n copied_files = challenge_bot_copy_service.copy(files, @challenge.space.scope)\n ensure\n api.project_decrease_permissions(\n @context.user.private_files_project,\n DNAnexusAPI::PROJECT_ACCESS_NONE,\n \"user-#{CHALLENGE_BOT_DX_USER}\",\n )\n end\n copied_files\n end", "def transfer\n @batch = Batch.shod(params[:id])\n @batchs ||= Batch.includes(:course).all\n @students ||= @batch.students\n authorize! :read, @batch\n end", "def create_workflows_export\n Pundit.policy!(@user, @klass).scope_for(:create_workflows_export)\n end", "def copy_actions\r\n end", "def create_workflow_contents_export\n Pundit.policy!(@user, @klass).scope_for(:create_workflow_contents_export)\n end", "def distribute_cc\n\n self.get_target_users.each do |user_id|\n next if self.user_id == user_id\n\n decided_inbox = WorkflowsHelper.get_decided_inbox(user_id)\n copied_item = self.item.copy(user_id, decided_inbox.id)\n end\n end", "def copy!(deployment)\n network = Network.new(self.attributes)\n network.deployment = deployment\n network.master = deployment.master\n # The only validity concern we have is the uniqueness of the name\n # in the new deployment.\n i = 1\n name = network.name\n while i < 1000 && !network.valid? do\n network.name = \"#{name}-#{i}\"\n i += 1\n end\n\n if (i == 1000)\n raise \"Could not create network. Too many networks named '#{name}'.\"\n end\n\n if network.save(:safe => true)\n routes = {}\n services = []\n vehicle_journeys = []\n begin\n for s in self.services\n if routes[s.route.code] == nil\n routes[s.route.code] = s.route.copy!(network)\n end\n route = routes[s.route.code]\n #puts \"Copy Service #{s.id} to route #{route.id} and network #{network.id}\"\n service = s.copy!(route, network)\n #puts \"Cloned to Service #{service.id} \"\n services << service\n for vj in s.vehicle_journeys\n vehicle_journey = vj.copy!(service, network)\n vehicle_journeys << vehicle_journey\n end\n end\n network.reload\n network\n rescue Exception => boom\n routes.values.each {|x| x.delete() }\n services.each {|x| x.delete() }\n vehicle_journeys.each {|x| x.delete() }\n network.delete\n raise \"Cannot create network #{boom}\"\n end\n else\n raise \"Cannot create network #{network.errors.message}\"\n end\n end", "def bequeath\n team = AssignmentTeam.find(params[:id])\n assignment = Assignment.find(team.parent_id)\n if assignment.course_id >= 0\n course = Course.find(assignment.course_id)\n team.copy(course.id)\n flash[:note] = \"The team \\\"\" + team.name + \"\\\" was successfully copied to \\\"\" + course.name + \"\\\"\"\n else\n flash[:error] = \"This assignment is not #{url_for(controller: 'assignment', action: 'assign', id: assignment.id)} with a course.\"\n end\n redirect_to controller: 'teams', action: 'list', id: assignment.id\n end", "def copy_embargo_to(target:)\n return false unless under_embargo?\n\n target.embargo = Embargo.new(clone_attributes)\n self.class.apply_embargo_for(resource: target)\n end", "def copy\n expression_to_clone = Expression.find(params[:id])\n\t\t\t \n\t@expression = expression_to_clone.clone\n\t\n\t@expression.expression_title = \"Copy of '#{expression_to_clone.expression_title}'\"\n \n if @expression.expression_title.length > 100\n flash[:error] = \"The new title '#{@expression.expression_title}' is too long.\"\n redirect_to :action => 'edit', :id => expression_to_clone.id\n return\n end\n\t\n\t@expression.status = Status::PENDING # default to 'pending'\n\t\n\t# delete created_at assigned from expression_to_clone created_at value\n\t# as we need created_at be actual time of creating the copy\n\t@expression.created_at = nil\t\n\t\t\n\t# updated by\n\t@expression.updated_by = get_user.login_id\n\t\n\t# languages\n\texpression_to_clone.languages.each do |l|\n\t @expression.languages << Language.find(l.language_id)\n\tend\n\t\t\n\tif @expression.save_with_frbr\n\t \n\t # copying relationships\n\t success = true\n\t \n\t # FIXME do we need to clone access rights???\n\t # it seems that currently there is no UI for entering them???\n\t #expression_to_clone.expression_access_rights.each do |ar|\n\t # expression_access_right = ExpressionAccessRight.new\n\t # expression_access_right = ar.clone\n\t # expression_access_right.expression_id = @expression.id\n\t # \n\t # success = false if !expression_access_right.save\n\t #end\n\t \t \n\t # manifestations - it is requested to do not copy relationships with manifestations\n\t #expression_to_clone.manifestations.each do |m|\n\t #\tsuccess = false if !m.add_expression(@expression)\n\t #end\n\t \n\t # other relationships\n\t expression_to_clone.expression_relationships.each do |ex_relationship|\n\t \tsuccess = false if !RelationshipHelper.copy_frbr_relationships(@expression, ex_relationship, @login)\n\t end\n\t \n\t notice = 'Expression clone was successfully created.'\n\t notice += ' But some of the relationships failed to be copied.' if !success\n\t \n\t flash[:notice] = notice\n\t \n\t redirect_to :action => 'edit', :id => @expression\n\telse\n\t flash[:error] = 'Expression cloning has failed.'\n\t redirect_to :action => 'edit', :id => expression_to_clone.id\n\tend\t\t\t\n end", "def copy_values_from(other)\n self.name = other.name\n self.contributor = other.contributor\n self.share_mode = other.share_mode\n self.update_mode = other.update_mode\n self.public_view = other.public_view\n self.public_download = other.public_download\n end", "def workflow\r\n if @openstudio_2\r\n super\r\n else\r\n @workflow\r\n end\r\n end", "def initialize_copy(other)\n @steps = other.steps.map do |step|\n step.class.new(self, *step.args)\n end\n @content = other.content.dup\n @url_attributes = other.url_attributes.dup\n end", "def copy_to(other); end", "def copy_moveset\n @moveset = Array.new(@original.skills_set.size)\n @original.skills_set.each_with_index do |skill, index|\n @moveset[index] = Battle::Move[skill.symbol].new(skill.id, skill.pp, skill.ppmax, @scene)\n end\n @skills_set = @moveset\n end", "def copy(src, dest)\n # Define list of attributes excluded from the copy\n excluded_attrs = %w[\n lock_version created_at updated_at id pub_reference_number conference_id\n linkedto_type linkedto_id parent_id title description short_title\n precis short_precis\n ].freeze\n\n # Iterate through the source model's attributes to copy them\n src.attributes.each do |attr, val|\n # Skip the attribute if it meets any of the below conditions:\n # Not an attribute of the destination model;\n # Present in the list of excluded attributes;\n # The destination attribute value is the same as the source value;\n # The source attribute value is nil;\n next if !dest.attributes.key?(attr) ||\n excluded_attrs.include?(attr) ||\n dest.attributes[attr] == val ||\n val.nil?\n\n # If none of the above conditions are met, copy the attribute\n dest.send(\"#{attr}=\", val)\n end\n\n if dest.is_a?(PublishedProgrammeItem)\n dest.parent_id = nil if dest.parent_id.present? && src.parent_id.nil?\n\n set_translated_attrs(%w[title short_title description], src, dest)\n end\n\n dest\n end", "def copy\n nodes = Node.accessible_by(@context).where(id: params[:item_ids])\n\n NodeCopyWorker.perform_async(\n params[:scope],\n nodes.pluck(:id),\n session_auth_params,\n )\n\n render json: nodes, root: \"nodes\", adapter: :json,\n meta: {\n messages: [{\n type: \"success\",\n message: I18n.t(\"api.files.copy.files_are_copying\"),\n }],\n }\n end", "def copy_to( user )\n new_domain = user.domains.build( :name => name )\n if new_domain.save\n areas.each do |area|\n new_area = new_domain.areas.build( :name => area.name )\n if new_area.save\n area.skills.each do |skill|\n new_skill = new_area.skills.build( :name => skill.name )\n if new_skill.save\n skill.levels.each do |level|\n new_level = new_skill.levels.build( :description => level.description )\n new_level.save\n end\n end\n end\n end\n end\n end\n new_domain\n end", "def inherit_scope(other)\n @scope = other.scope\n end", "def set_workflow\n @workflow = Workflow.find(params[:id])\n end", "def bequeath\n team = AssignmentTeam.find(params[:id])\n assignment = Assignment.find(team.parent_id)\n if assignment.course_id >= 0\n course = Course.find(assignment.course_id)\n team.copy(course.id)\n flash[:note] = \"\\\"\"+team.name+\"\\\" was successfully copied to \\\"\"+course.name+\"\\\"\"\n else\n flash[:error] = \"This assignment is not #{url_for(:controller => 'assignment', :action => 'assign', :id => assignment.id)} with a course.\"\n end\n redirect_to :controller => 'teams', :action => 'list', :id => assignment.id\n end", "def copyuser\n\t@user = User.find(params[:id])\n\t@loggedin_user = session[:user_id]\n\t@organizations = Organization.all\n end", "def recreate_in( new_context, changes = nil )\n clone.acquire_for(new_context)\n end", "def copy_to_cooperative\n space = Space.accessible_by(@context).find(unsafe_params[:id])\n object = item_from_uid(unsafe_params[:object_id])\n\n if space.contributor_permission(@context) && space.member_in_cooperative?(@context.user_id)\n if object && space.shared_space\n ActiveRecord::Base.transaction do\n copy_service.copy(object, space.shared_space.uid).each do |new_object|\n SpaceEventService.call(\n space.shared_space.id,\n @context.user_id,\n nil,\n new_object,\n \"copy_to_cooperative\",\n )\n end\n end\n\n flash[:success] = \"#{object.class} successfully copied\"\n end\n else\n flash[:warning] = \"You have no permission to copy object(s) to cooperative.\"\n end\n\n redirect_back(fallback_location: space_path(space))\n end", "def copy\n dup\n end", "def copy_attributes(other, duplicator)\n self.course = duplicator.options[:destination_course]\n self.default_reference_time = duplicator.duplicate(other.default_reference_time)\n\n other_reference_times = other.reference_times - [other.default_reference_time]\n self.reference_times = duplicator.duplicate(other_reference_times).unshift(default_reference_time)\n\n self.title = other.title\n self.description = other.description\n self.published = duplicator.options[:unpublish_all] ? false : other.published\n self.base_exp = other.base_exp\n self.time_bonus_exp = other.time_bonus_exp\n end", "def set_workflow\n @workflow = Workflow.find(params[:id])\n end", "def set_workflow\n @workflow = Workflow.find(params[:id])\n end", "def set_workflow\n @workflow = Workflow.find(params[:id])\n end", "def apply_scopes(target, scopie: default_scopie, hash: params)\n Scopie.apply_scopes(target, hash, method: hash[:action], scopie: scopie)\n end", "def merge!( otherstate )\n\t\t@scopes.push( @scopes.pop + otherstate.scope )\n\t\t# self.attributes.merge!( otherstate.attributes )\n\t\tself.options.merge!( otherstate.options )\n\t\treturn self\n\tend", "def set_workflow\n\t\t@workflow = Workflow.find(params[:id])\n\tend", "def updateAssignments(src, dest)\n if src.programme_item_assignments\n src.programme_item_assignments.each do |srcAssignment|\n if !srcAssignment.destroyed?\n # add the person only if the destination does not have that person\n if (dest.people == nil) || (dest.people.index(srcAssignment.person) == nil)\n # check their role for reserved, if reserved then we do not want that person published\n if (srcAssignment.role != PersonItemRole['Reserved'] && srcAssignment.role != PersonItemRole['Invisible'] )\n assignment = dest.published_programme_item_assignments.new(:person => srcAssignment.person, \n :role => srcAssignment.role, \n :sort_order => srcAssignment.sort_order,\n :description => srcAssignment.description,\n :person_name => srcAssignment.person.getFullPublicationName)\n assignment.save\n end\n else # the destination has the person, but their role may have changed\n # TODO - if the person is assigned twice we need to deal with it correctly... i.e. participant and reserved\n \n # find the index of the person only if the role and sort order are also different\n idx = dest.published_programme_item_assignments.index{ |a| (a.person == srcAssignment.person) && ((a.role != srcAssignment.role) || (a.sort_order != srcAssignment.sort_order))}\n if idx != nil && !dest.published_programme_item_assignments[idx].destroyed?\n if (srcAssignment.role == PersonItemRole['Reserved']) || (srcAssignment.role == PersonItemRole['Invisible'])\n # If the role is changed to reserved or invisible then they should be removed...\n dest.published_programme_item_assignments[idx].destroy\n else \n dest.published_programme_item_assignments[idx].role = srcAssignment.role\n dest.published_programme_item_assignments[idx].description = srcAssignment.description\n dest.published_programme_item_assignments[idx].sort_order = srcAssignment.sort_order\n dest.published_programme_item_assignments[idx].save\n end\n end\n end\n end\n end\n \n # if the destination has a person that the source does not then we need to remove that assignment\n dest.published_programme_item_assignments.each do |pitem|\n if (src.people.index(pitem.person) == nil)\n pitem.destroy\n end\n end\n else # since there are no source assignments we should then remove all the destination assignments (if there are any)\n if dest.published_programme_item_assignments\n dest.published_programme_item_assignments.destroy\n end\n end\n end", "def workflow\n raise \"Could not read workflow from #{@osw_abs_path}\" if @workflow.nil?\n\n @workflow\n end", "def workflow\n raise \"Could not read workflow from #{@osw_abs_path}\" if @workflow.nil?\n\n @workflow\n end", "def assign_workflow(specification_object)\n\n # Merging two workflow specifications can **not** be done automically, so\n # just make the latest specification win. Same for inheritance -\n # definition in the subclass wins.\n if respond_to? :inherited_workflow_spec # undefine methods defined by the old workflow_spec\n inherited_workflow_spec.states.values.each do |state|\n state_name = state.name\n module_eval do\n undef_method \"#{state_name}?\"\n end\n\n state.events.flat.each do |event|\n event_name = event.name\n module_eval do\n undef_method \"#{event_name}!\".to_sym\n undef_method \"can_#{event_name}?\"\n end\n end\n end\n end\n\n @workflow_spec = specification_object\n @workflow_spec.states.values.each do |state|\n state_name = state.name\n module_eval do\n define_method \"#{state_name}?\" do\n state_name == current_state.name\n end\n end\n\n state.events.flat.each do |event|\n event_name = event.name\n module_eval do\n define_method \"#{event_name}!\".to_sym do |*args, **kwargs|\n process_event!(event_name, *args, **kwargs)\n end\n\n define_method \"can_#{event_name}?\" do\n return !!current_state.events.first_applicable(event_name, self)\n end\n end\n end\n end\n end", "def sync!(other)\n allowed_envs = deploy_groups.map(&:environment).map(&:permalink) << 'global'\n allowed_groups = deploy_groups.map(&:permalink) << 'global'\n\n keys = other.client.kv.list_recursive\n\n # we can only write the keys that are allowed to live in this server\n keys.select! do |key|\n scope = Samson::Secrets::Manager.parse_id(key)\n allowed_envs.include?(scope.fetch(:environment_permalink)) &&\n allowed_groups.include?(scope.fetch(:deploy_group_permalink))\n end\n\n Samson::Parallelizer.map(keys.each_slice(100).to_a) do |keys|\n # create new clients to avoid any kind of blocking or race conditions\n other_client = other.create_client\n local_client = create_client\n\n keys.each do |key|\n secret = other_client.kv.read(key).data\n local_client.kv.write(key, secret)\n end\n end\n end", "def set_workflow\n @workflow = Workflow.find(params[:id])\n end", "def copy\n new_attributes = self.attributes\n new_attributes.delete(:id)\n file = WSFile.create(new_attributes)\n owner = self.permissions(level: 'owner').user.first\n Permission.create(user: owner, file: file, level: \"owner\")\n self.assets.each do |asset|\n file.assets.push asset\n end\n self.children.each do |child|\n file.children.push child.copy\n end\n file.save\n file.data = self.data\n file\n end", "def run_scope(scope, machine, klass, states); end", "def copy_activities_from_previous_quote\n copied = 0\n prev_quote = self.get_previous_quote_version\n \n if prev_quote.present?\n if prev_quote.quote_activities.present?\n \n # Remove all existing activities\n self.quote_activities.destroy_all\n \n # Copy previous activities over\n prev_quote.quote_activities.position_ordered.each do |activity|\n new_activity = activity.dup\n new_activity.position = nil\n new_activity.quote_id = self.id\n new_activity.save!\n end\n copied = 2\n else\n copied = 1\n end\n end\n \n copied\n end", "def apply\n\t\tunless @already_added\n\t\t\t@space.entities.add @clone\n\t\t\t@already_added = true\n\t\tend\n\t\t\n\t\t@move_action.apply\n\tend", "def copy_with_ancestors_to_stream(new_appeal_stream, extra_excluded_attributes: [], new_attributes: {})\n return unless parent\n\n new_task_attributes = attributes\n .except(*ATTRIBUTES_EXCLUDED_FROM_TASK_COPY, *extra_excluded_attributes)\n .merge(new_attributes)\n new_task_attributes[\"appeal_id\"] = new_appeal_stream.id\n\n # This method recurses until the parent is nil or a task of its type is already present on the new stream\n # We reload the new_appeal_stream to ensure we are always working off an updated snapshot of task tree\n existing_new_parent = new_appeal_stream.reload.tasks.find { |task| task.type == parent.type }\n new_parent = existing_new_parent || parent.copy_with_ancestors_to_stream(new_appeal_stream)\n\n # Do not copy orphaned branches\n return unless new_parent\n\n new_task_attributes[\"parent_id\"] = new_parent.id\n\n # Skip validation since these are not new tasks (and don't need to have a status of assigned, for example)\n new_stream_task = self.class.new(new_task_attributes)\n # Note that if we also want to skip 'before_create', 'after_create', 'before_save', and 'after_save' callbacks\n # (such as in TimedHoldTask) or even things like 'validate :status_is_valid_on_create on: :create',\n # see SanitizedJsonImporter::SkipCallbacks for a possible solution.\n new_stream_task.save(validate: false)\n\n new_stream_task\n end", "def targeted_workflows\n Workflow.for_target_model(self.class)\n end", "def assign_to_project\n proj_id = self.work.project.id\n self.update_attributes(project_id: proj_id)\n end", "def copy\n obj = self.dup\n obj.attributes = {\n :name => \"Copy of #{name}\",\n :active => false,\n :created_at => nil,\n :updated_at => nil\n }\n obj\n end", "def workflow\n end", "def new_workflow(new_workflow_name)\n\t\t\tensure_hash_has_symbol(self, :_id)\n\n\t\t\tthis_workflow_type=WorkflowTypes.db_get_with_id :_id=>self[:_id]\n\t\t\traise \"Cannot generate workflows for a non-existing workflow type - have you committed this workflow type to db yet?\" if this_workflow_type.nil?\n\n\t\t\twf=Workflowz.new\n\t\t\twf.update :_id=>new_workflow_name, :type=>self[:_id]\n\t\t\twf\n\t\tend", "def rebuild_contributions(copy_statuses)\n p = self.parent\n\n self.contributions.destroy_all\n\n p.contributions.each do|c|\n new_c = c.clone\n new_c.contribution_types << c.contribution_types\n self.contributions << new_c\n end\n end", "def copy\n self.public_send('|', 'pbcopy')\n self\n end", "def duplicate\n super do |cloned_resource|\n cloned_resource.title = \"Copy #{@resource.title[0...Integral.title_length_maximum - 5]}\"\n cloned_resource.view_count = 0\n cloned_resource.build_active_block_list(content: @resource.active_block_list.content, listable: cloned_resource)\n cloned_resource.tag_list = @resource.tag_list_on(@resource.tag_context)\n cloned_resource.slug = @resource.slug\n cloned_resource.status = :draft\n cloned_resource.published_at = nil\n end\n end", "def workflow=(value)\n @workflow = value\n end", "def batch_copy(batch_client)\n self.class.batch_copy(batch_client, client, scope_parameters, id.to_s)\n end", "def copy_from(source_list, &block); end", "def new_workflow!(new_workflow_name)\n\t\t\twf=new_workflow(new_workflow_name)\n\t\t\traise \"Could not save new workflow to db\" unless wf.db_insert\n\t\t\twf\n\t\tend", "def prep_sandbox_for_batch batch_path\n relative_input_file_name = INPUT_PATH + batch_path\n sandbox_name = SANDBOX_PATH + batch_path\n\n FileUtils.cp_r relative_input_file_name, sandbox_name\n #$stderr.puts sandbox_name + \"/.svn\"\n FileUtils.rm_r sandbox_name + \"/.svn\"\n \n# d = Dir.new(relative_input_file_name)\n# d.each do |f|\n# next if f.eql?(\".\") or f.eql?(\"..\") or f.eql?(\".svn\")#\n#\n# # If f is directory , call prep_sandbox on it\n# path = relative_input_file_name + \"/\" + \"#{f}\"\n# if File.stat(path).directory?\n# copy_batch path\n# else\n# sandbox_name = SANDBOX_PATH + batch_path + \"/\" + f\n# begin\n# $stderr.puts path\n# $stderr.puts sandbox_name\n# FileUtils.cp path, sandbox_name\n# rescue Exception => error\n# pending \"Could not copy file #{path} to sandbox!\"\n# end\n# end\n# end\nend", "def duplicate_workflow_status\r\n return if self.workflow_statuses.none?\r\n self.workflow_statuses.create(workflow_status_template_id: self.workflow_statuses.last.workflow_status_template_id)\r\n end", "def copy_list \n\n\tend", "def copy(defaults=[], context={})\n self.class.find(self.class.rpc_execute('copy', self.id, defaults, context), :context => context)\n end", "def copy(assignment_id)\n new_team = AssignmentTeam.create_team_and_node(assignment_id)\n new_team.name = name\n new_team.save\n copy_members(new_team)\n end", "def copy_to_user(user)\n activity = self.dup\n activity.title = self.title\n activity.user_id = user.id\n activity.from_id = self.id\n activity.activity_sequence = nil\n activity.strategy_id = nil\n activity.course_id = self.course_id\n activity.goal = self.goal.copy_to_user(user) if self.goal\n activity.save\n activity\n end", "def transfer_projects(user_member_id)\n self.update!(user_id: user_member_id)\n Project.where('space_id = ?', self.id).find_each do |p|\n p.update!(user_id: user_member_id)\n end\n end", "def sync_workspace_permissions(source_user_id, target_user_id)\n source_user = find_user(source_user_id)\n target_user = find_user(target_user_id)\n if source_user.nil? then\n @logger.warn \" Source user: #{source_user_id} Not found. Skipping sync of permissions to #{target_user_id}.\"\n return\n elsif target_user.nil then\n @logger.warn \" Target user: #{target_user_id} Not found. Skipping sync of permissions for #{target_user_id}.\"\n return\n end\n\n # Check to make sure source user has permissions\n permissions_existing = target_user.UserPermissions\n source_permissions = source_user.UserPermissions\n\n if source_permissions.nil? then\n @logger.warn \" Source user: #{source_user_id} does not have any permissions assigned. Skipping sync of permissions to #{target_user_id}.\"\n return\n end \n\n # build permission hashes by Workspace ObjectID\n source_permissions_by_workspace = {}\n source_permissions.each do | this_source_permission |\n if this_source_permission._type == \"WorkspacePermission\" then\n source_permissions_by_workspace[this_source_permission.Workspace.ObjectID.to_s] = this_source_permission\n end\n end\n\n permissions_existing_by_workspace = {}\n permissions_existing.each do | this_permission |\n if this_permission._type == \"WorkspacePermission\" then\n permissions_existing_by_workspace[this_permission.Workspace.ObjectID.to_s] = this_permission\n end\n end\n\n # Prepare arrays of permissions to update, create, or delete\n permissions_to_update = []\n permissions_to_create = []\n permissions_to_delete = []\n\n # Check target permissions list for permissions to create and/or update\n source_permissions_by_workspace.each_pair do | this_source_workspace_oid, this_source_permission |\n\n # If target hash doesn't contain the OID referenced in the source permission set, it's a new\n # permission we need to create\n if !permissions_existing_by_workspace.has_key?(this_source_workspace_oid) then\n permissions_to_create.push(this_source_permission)\n\n # We found the OID key, so there is an existing permission for this Workspace. Is it different\n # from the target permission?\n else\n this_source_role = this_source_permission.Role\n this_source_workspace = find_workspace(this_source_workspace_oid)\n this_source_workspace_name = this_source_workspace[\"Name\"]\n\n if workspace_permissions_different?(this_source_workspace, target_user, this_source_role) then\n existing_permission = permissions_existing_by_workspace[this_source_workspace_oid]\n this_existing_workspace = existing_permission.Workspace\n this_existing_workspace_name = this_existing_workspace[\"Name\"]\n this_existing_role = existing_permission.Role\n @logger.info \"Existing Permission: #{this_existing_workspace_name}: #{this_existing_role}\"\n @logger.info \"Updated Permission: #{this_source_workspace_name}: #{this_source_role}\"\n permissions_to_update.push(this_source_permission)\n end\n end\n end\n\n # Loop through target permissions list and check for Workspace Permissions that don't exist\n # in source permissions template, indicating they need to be removed\n permissions_existing_by_workspace.each_pair do | this_existing_workspace_oid, this_existing_permission |\n if !source_permissions_by_workspace.has_key?(this_existing_workspace_oid) then\n permissions_to_delete.push(this_existing_permission)\n end\n end\n\n # Process creates\n number_new_permissions = 0\n permissions_to_create.each do | this_new_permission |\n this_workspace = find_workspace(this_new_permission.Workspace.ObjectID.to_s)\n if !this_workspace.nil? then\n this_workspace_name = this_workspace[\"Name\"]\n this_role = this_new_permission.Role\n\n @logger.info \"Workspace: #{this_workspace_name}\"\n @logger.info \"Creating #{this_role} permission on #{this_workspace_name} from #{source_user_id} to: #{target_user_id}.\"\n create_workspace_permission(target_user, this_workspace, this_role)\n number_new_permissions += 1\n end\n end\n\n # Process updates\n number_updated_permissions = 0\n permissions_to_update.each do | this_new_permission |\n this_workspace = find_workspace(this_new_permission.Workspace.ObjectID.to_s)\n if !this_workspace.nil? then\n this_workspace_name = this_workspace[\"Name\"]\n this_role = this_new_permission.Role\n\n @logger.info \"Workspace: #{this_workspace_name}\"\n @logger.info \"Updating #{this_role} permission on #{this_workspace_name} from #{source_user_id} to: #{target_user_id}.\"\n create_workspace_permission(target_user, this_workspace, this_role)\n number_updated_permissions += 1\n end\n end\n\n # Process deletes\n number_removed_permissions = 0\n permissions_to_delete.each do | this_deleted_permission |\n this_workspace = find_workspace(this_deleted_permission.Workspace.ObjectID.to_s)\n if !this_workspace.nil? then\n this_workspace_name = this_workspace[\"Name\"]\n this_role = this_deleted_permission.Role\n\n @logger.info \"Workspace: #{this_workspace_name}\"\n @logger.info \"Removing #{this_role} permission to #{this_workspace_name} from #{target_user_id} since it is not present on source: #{source_user_id}.\"\n if !@upgrade_only_mode then\n delete_workspace_permission(target_user, this_workspace)\n number_removed_permissions += 1\n else\n @logger.info \" #{target_user_id} - upgrade_only_mode == true.\"\n @logger.info \" Proposed Permission removal would downgrade permissions. No permission removal applied.\"\n end\n end\n end\n @logger.info \"#{number_new_permissions} Permissions Created; #{number_updated_permissions} Permissions Updated; #{number_removed_permissions} Permissions Removed.\"\n end", "def clone_course \n if params[:copy_course_id]\n @service_learning_course ||= ServiceLearningCourse.find(params[:copy_course_id])\n \n if slc2 = @service_learning_course.deep_clone!\n slc2.update_attribute(:quarter_id, @quarter.id)\n flash[:notice] = \"Successfully cloned #{@service_learning_course.title} for #{slc2.quarter.title}. You can customize the details below.\" \n redirect_to edit_service_learning_course_path(@unit, slc2.quarter, slc2)\n else\n flash[:error] = \"Sorry, but we couldn't copy that course. An error occurred.\"\n redirect_to :back\n end\n end \n end", "def deep_copy(new_attributes = {})\n self.class.transaction do\n dup.tap do |blueprint|\n # TODO: there may be other attributes that need to be reset for the new template\n new_attributes.reverse_merge(:status => nil).each do |attr, value|\n blueprint.send(\"#{attr}=\", value)\n end\n copy_service_template(blueprint, bundle, true)\n blueprint.save!\n end\n end\n end", "def source(name, tap)\n sources[name] = tap\n incoming_scopes[name] = Scope.source_scope(name, mode.source_tap(name, tap), @flow_scope)\n outgoing_scopes[name] = incoming_scopes[name]\n end", "def subscope\n self.clone\n end", "def target_scope\n AssociationRelation.create(klass, self).merge!(klass.scope_for_association)\n end", "def copy\n projectid = params[:project_id]\n subprojectid = params[:subproject_id]\n versiontocopy = params[:versiontocopy]\n subsubproject_to_copy = Subsubproject.find(versiontocopy)\n new_subsubproject = Subsubproject.find(versiontocopy).dup\n new_subsubproject.name = new_subsubproject.name + ' (neu)'\n new_subsubproject.master = false\n new_subsubproject.save!\n\n # copy/duplicate offertpositions\n subsubproject_to_copy.offertpositions.each do |offertposition|\n new_offertposition = offertposition.dup\n new_offertposition.subsubproject_id = new_subsubproject.id\n new_offertposition.save!\n end\n\n # copy/duplicate grobengineerings\n grobengineerings_to_copy = Grobengineering.where(:subsubproject_id => versiontocopy).order(:id)\n grobengineerings_to_copy.each do |grobengineering|\n new_record = grobengineering.dup\n new_record.subsubproject_id = new_subsubproject.id\n offertposition = Offertposition.where(:subsubproject_id => new_subsubproject.id, :name => grobengineering.offertposition.name).first\n if !offertposition.nil?\n new_record.offertposition_id = offertposition.id\n end\n new_record.save!\n end\n\n redirect_to project_subproject_path(projectid, subprojectid),\n :notice => 'Version erfolgreich kopiert'\n\n end", "def update_copy_session\n @user = current_user\n session[:copy_flag] = true\n end" ]
[ "0.6871361", "0.57982564", "0.5650359", "0.5604749", "0.5523248", "0.55140465", "0.5383086", "0.5368381", "0.53668875", "0.5338356", "0.52970976", "0.5240788", "0.52288944", "0.5172689", "0.51283437", "0.51116115", "0.50960404", "0.50477606", "0.5039503", "0.50284374", "0.5015285", "0.49456277", "0.49371856", "0.491249", "0.48927972", "0.4892484", "0.4868185", "0.48622337", "0.48568198", "0.48397744", "0.48364192", "0.48285118", "0.48244688", "0.4820091", "0.48133323", "0.48105696", "0.4804835", "0.48042545", "0.47905114", "0.47900334", "0.47868255", "0.4773659", "0.47545755", "0.4752852", "0.4748798", "0.4732083", "0.47211716", "0.4719132", "0.4716661", "0.47164053", "0.4710893", "0.46986938", "0.46897486", "0.4687966", "0.4687637", "0.4686866", "0.46728352", "0.46728352", "0.46728352", "0.466902", "0.46636847", "0.46616265", "0.4656593", "0.46533144", "0.46523905", "0.4650144", "0.4648923", "0.46371153", "0.46293315", "0.4622809", "0.46209687", "0.4619636", "0.46188378", "0.46185502", "0.4615727", "0.4613639", "0.46134678", "0.46101627", "0.45983484", "0.45979726", "0.45976222", "0.4592526", "0.45916116", "0.4575822", "0.45650715", "0.45636013", "0.4562174", "0.45603707", "0.45575073", "0.4554381", "0.45521125", "0.45517254", "0.45450234", "0.45440552", "0.45401832", "0.45392567", "0.45368773", "0.45223603", "0.45186588", "0.4514786" ]
0.6953001
0
noREST Methods confirm_payment_user_payment_reward_receivers POST /users/:user_id/payment/reward_receivers/:shipping_order_id/confirm_payment
def confirm_payment if @shipping_order.transacted redirect_to(:back) else if @shipping_order.update( status: 'Started' ) confirm_shipping_payment else flash[:error] = t('errors.messages.not_saved') redirect_to(:back) end end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def request_shipping_fee\n\t\t@reward = Reward.find(@reward_receiver.reward_id)\n\t\t#Select shipping amount based on different situiations\n\t\tif @reward.shippings.where(country: @reward_receiver.shipping_address.country).first\n\t\t\t@amount = @reward.shippings.where(country: @reward_receiver.shipping_address.country).first.amount\n\t\telse\n\t\t\tif @reward.shipping_anywhere\n\t\t\t\t@amount = @reward.shipping_anywhere.amount\n\t\t\tend\n\t\tend\n\t\tif @shipping_order = ShippingOrder.find_by_reward_receiver_id(@reward_receiver.id)\n\t\telse\n\t\t\t@shipping_order = ShippingOrder.create(\n\t\t\t\tuser_id: @reward_receiver.user_id,\n\t\t\t\tamount: @amount,\n\t\t\t\tcurrency: @reward.currency,\n\t\t\t\tstatus: 'Sent',\n\t\t\t\tcountry: @reward_receiver.shipping_address.country,\n\t\t\t\tcity: @reward_receiver.shipping_address.city,\n\t\t\t\tline1: @reward_receiver.shipping_address.line1,\n\t\t\t\tpostal_code: @reward_receiver.shipping_address.postal_code,\n\t\t\t\tstate: @reward_receiver.shipping_address.state,\n\t\t\t\tname: @reward_receiver.shipping_address.name,\n\t\t\t\treward_id: @reward_receiver.reward_id,\n\t\t\t\treward_receiver_id: @reward_receiver.id,\n\t\t\t\tdue: 30.days.from_now\n\t\t\t)\n\t\tend\n\t\t@reward_receiver.update(\n\t\t\tstatus: 'shipping_fee_request_sent'\n\t\t)\n\t\t#Send order email\n Payment::ShippingOrdersMailer.send_confirmation(shipping_order_id: @shipping_order.id).deliver_now\n\t\t#Send order notification\n\t\tNotification.create(\n\t\t\tuser_id: @reward_receiver.user_id,\n trackable_id: @shipping_order.id,\n trackable_type: \"ShippingOrder\",\n notification_type: \"send_shipping_order_confirmation\"\n\t\t)\n\t\tredirect_to(:back)\n\tend", "def ship_reward_now\n\t\t@reward_receiver = RewardReceiver.find(params[:reward_receiver_id])\n\t\t@reward_receiver.update(reward_receiver_params)\n\t\tif @reward_receiver.update(\n\t\t\tstatus: \"shipped\"\n\t\t)\n\t\t#Send email\n\t\t#Send notification\n\t\t#Add xp\n\t\t@user.add_score(\"ship_reward\")\n\t\tend\n\t\tredirect_to show_user_studio_rewards_path(@reward_receiver.reward.user_id,@reward_receiver.reward_id)\n\tend", "def confirm\n @payment_gateway = @order.payment_gateway_class.new(order: @order)\n if @payment_gateway.collect_payment?\n head :bad_request\n else\n @order.complete!\n head :ok\n end\n end", "def order_confirmation\n @user, @order = params[:user], params[:order]\n mail(to: @user.email, subject: \"Order Confirmed\")\n end", "def repayment_notification(user)\n @user = user\n\n mail to: user.email, subject: \"Scholarship Confirmation\"\n end", "def buyer_confirmed\n end", "def call(user, email, reward, shipping_address)\n @user = user\n @reward = reward\n # admin = \"astropowerbox@gmail.com\"\n admin = \"news.article.sysetm@gmail.com\"\n @shipping_address = shipping_address\n mail to: email, subject: 'Redemption details'\n end", "def notify_payment\n begin\n user = User.find(params['referenceId'].split(\"-\").first)\n check_payment(\"POST\", user)\n render :text => \"Thank you!\"\n rescue Exception => ex\n logger.error \"params: #{params.inspect}\"\n logger.error \"a problem occured when processing a payment: #{ex.message} \\n #{ex.backtrace}\"\n render :text => \"A problem occured\"\n end\n end", "def confirm_receieved(shipment)\n open_shipment(shipment)\n confirm_received.click\n confirm.click\n end", "def received (payment)\n @payment = payment\n\n mail to: payment.user.email, subject: \"Подтверждение пополнения баланса на kupibazar.com\"\n end", "def order_confirmation\n user = User.first\n order = Order.last\n UserMailer.order_confirmation(user, order)\n end", "def order_confirmation(user)\n # byebug\n @user = user\n mail to: user.email, subject: \"Order Confirmation\"\n end", "def final_confirmation\n if session[:all_free_shipping]\n carrier = \"Free Shipping\"\n method = \"Free Shipping\"\n else\n order_id = params[:order][:id]\n carrier = params[:order][:carrier]\n method = params[:order][:shipping_method]\n end\n\n coupon_code = session[:coupon]\n\n @cart = find_cart\n @order = session[:order]\n\n @order.set_freight_ship_to session[:ship_to]\n @order.set_freight_options session\n\n if valid_coupon_code?(coupon_code, @order.totalize_items)\n @order.coupon = coupon_code\n end\n\n @order.carrier = carrier\n @order.taxes = round(@cart.totalize_products * state_tax(@order.billing_state)).to_f\n @order.shipping_method = shipping_method(method)\n @order.shipping_approx = shipping_approx(@order.carrier, method)\n session[:order] = @order\n end", "def send_friendship_request(other_user)\n friendship_requests.create!(requested_user: other_user) if !self.friends_with?(other_user)\n end", "def thank_you\n # debugger\n @order_date = DateTime.now\n @shipping = 20000\n @total = order_subtotal + @shipping\n order = {\n \"total\" => @total,\n \"shipping\" => @shipping,\n \"items\" => session[:purchase]\n }\n # debugger\n OrderMailer.order_confirmation(session[:address], order).deliver_now\n end", "def confirm\n order = current_order || raise(ActiveRecord::RecordNotFound)\n order.payments.create!(\n {\n source: Spree::PaypalExpressCheckout.create(\n {\n token: params[:token],\n payer_id: params[:PayerID],\n payment_id: params[:paymentId]\n }\n ),\n amount: sprintf(\"%0.02f\", order.total),\n payment_method: payment_method\n }\n )\n order.next\n if order.complete?\n flash.notice = Spree.t(:order_processed_successfully)\n flash[:order_completed] = true\n session[:order_id] = nil\n redirect_to completion_route(order)\n else\n redirect_to checkout_state_path(order.state)\n end\n end", "def paypal_confirm\n @token, @payer_id = params[:token], params[:PayerID]\n if @token and @payer_id\n @details = EXPRESS_GATEWAY.details_for(@token)\n\n if @details.success?\n @address = \"#{@details.address['company']} #{@details.address['address1']} #{@details.address['address2']} #{@details.address['city']} #{@details.address['state']} #{@details.address['zip']} #{@details.address['country']}\"\n @cart.update_attributes! :name => @details.name,\n :address => @address,\n :email => @details.email,\n :phone => @details.contact_phone,\n :instructions => @details.message\n else\n flash[:error] = \"could not perform EXPRESS_GATEWAY.details\"\n redirect_to :controller=>:store, :action=>:error\n end\n else\n flash[:error] = \"could not find token or payer id\"\n redirect_to :controller=>:store, :action=>:error\n end\n end", "def order_confirmation(buyer)\n @order = Order.last\n @buyer = buyer\n\n mail to: @buyer, subject: \"Order Completed!\", cc: \"foodbylags@gmail.com\"\n end", "def confirm_friend(user)\n friendships_unique = pending_accept.where(user_id: user.id).first\n friendships_unique.confirmed = true\n row = Friendship.new(user_id: friendships_unique.friend_id, friend_id: friendships_unique.user_id, confirmed: true)\n row.save\n friendships_unique.save\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 notify_of_redemption(user, redemption)\n @user = user\n @admin = redemption.reward.manager_with_default\n @reward = redemption.reward\n @redemption = redemption\n @mail_styler = company_styler(user.company)\n I18n.with_locale(user.locale) do\n mail(to: @user.email, subject: t(\"rewards.your_redemption_is_pending\", title: redemption.reward.title), track_opens: true)\n end\n end", "def wepay_postfill\n # If the user approved the 'preapproval' and \n if params.has_key?('preapproval_id')\n @order = Order.find_by_token(params[:preapproval_id])\n unless @order.nil?\n wepay = WePay.new(Settings.wepay_client_id, Settings.wepay_access_token, _use_stage = (!Rails.env.production?))\n # Let's find the user information on Wepay end..\n response = wepay.call('/preapproval', Settings.wepay_access_token, {\n :preapproval_id => params[:preapproval_id]\n })\n \n @order.wepay_postfill(response)\n if params['status'] != 'approved' \n redirect_to :action => :share, :uuid => @order.uuid\n else\n redirect_to root_url\n end\n else\n redirect_to root_url\n end\n else\n redirect_to root_url\n end\n end", "def donate\n\n @context_user = @receiver.user\n \n # Test that the transfer money between the two people is a viable option\n rec_acc = @receiver.monetary_processor_account\n pay_acc = @sender.monetary_processor_account\n \n rec_usid = rec_acc.account_identifier\n pay_usid = pay_acc.account_identifier\n \n @donation.update_attributes do |d|\n d.receiver_wmid = rec_acc\n d.sender_wmid = pay_acc\n end\n store_donation\n \n res = WebMoney::Ext::Client.get_max_transaction_amount(pay_usid, rec_usid, @donation.purse_type[0].to_i)\n \n # Verify maximum transaction possible\n @max_amount = res.maxAmount\n if @max_amount < @amount.to_f\n @amount = @max_amount\n if @amount.to_i != -1\n flash.now[:warning] = \"The maximum that you can contribute is %s.\" / \"#{@amount}\"\n end\n end\n \n # We are confirmed, lets do it!\n if params[:confirm]\n \n # confirm their password\n @account_setting = current_user.account_setting\n unless @account_setting.validate_password(current_user,params[:password])\n flash.now[:error] = \"Invalid Password\".t\n return\n end\n \n # want to see the result logged for debugging?\n # WebMoney::Ext::Client.config.merge!({:debug => true, :wiredump => true})\n transfer = WebMoneyTransfer.create(\n :source_wmid => @sender.webmoney_account,\n :destination_wmid => @receiver.webmoney_account,\n :purse_type => @donation.purse_type[0].to_i,\n :amount => @donation.amount)\n \n res = WebMoney::Ext::Client.send_funds(\n pay_usid,\n rec_usid,\n transfer.request_number,\n @donation.purse_type[0].to_i,\n @donation.amount,\n @donation.item_name)\n \n if res.errordesc == 'Success'\n MonetaryDonation.from_webmoney_donation(@donation).save\n \n transfer.update_attribute(:success, true)\n flash[:success] = \"You have successfully transfered %s\" / [@donation.amount]\n clear_donation\n redirect_back_or_default '/'\n else\n transfer.update_attributes(:success => false, :response => res.errordesc)\n flash.now[:error] = res.errordesc.t\n end\n end\n end", "def create\n payer_email = params[:payer_email]\n txn_type = params[:txn_type] # subscr_failed, subscr_cancel, subscr_payment, subscr_signup, subscr_eot, subscr_modify\n \n if params[:reason_code] == 'refund'\n # TODO: just notify me that somebody refunded, keep their is_customer flag set to true\n else\n # add/flag customer\n u = User.find_or_create_by_email(payer_email)\n u.first_name = params[:first_name] # overwrite whatever we've got with Paypal's info\n u.last_name = params[:last_name]\n u.password = 'temporary'\n u.is_customer = true\n u.save\n CustomerMailer.deliver_purchase_complete(u) # send them a link\n AdminMailer.deliver_purchase_notification(u) # let me know they were added\n subject = 'Customer added'\n end\n \n render :text => 'OK'\n end", "def order_shipped(order)\n @order = order\n\n mail(to: @order.user.email , subject: 'Order Confirmation')\n end", "def shipping_charges_payment\n {'PaymentType' => payment_type,\n 'Payor' => {'AccountNumber' => @model.payor_account_number},\n :order! => ['PaymentType', 'Payor']}\n end", "def confirm\n begin\n @result = Braintree::TransparentRedirect.confirm(request.query_string)\n if @result.success?\n current_user.update_user_with_plan_and_braintree_id(session[:user_plan], @result.customer.id)\n session[:user_plan]=nil\n flash[:success] = \"You have successfully converted to paid member. Now you can send messages\"\n redirect_to user_conversations_path(current_user.id)\n else\n flash[:error] = \"Your payment was not success. Check your card information.\"\n redirect_to user_conversations_path(current_user.id)\n end\n rescue\n flash[:error] = \"Your payment was not success. Check your card information.\"\n redirect_to user_conversations_path(current_user.id)\n end\n end", "def ouroboros_accept\n MorLog.my_debug('Ouroboros payment : accept', 1)\n @payment = Payment.find(:first, :conditions => \"id = #{params[:order_id].to_i}\")\n if @payment\n @user = @payment.user\n MorLog.my_debug(\"Ouroboros payment : user - #{@user.id}\", 1)\n @enabled = Confline.get_value(\"Ouroboros_Enabled\", @user.owner_id).to_i\n if @enabled.to_i == 1\n if @payment.pending_reason.to_s == 'Unnotified payment'\n key = Confline.get_value(\"Ouroboros_Secret_key\", @user.owner_id)\n @hash = Ouroboros::Hash.reply_hash(params, key)\n if @hash == params[:signature]\n if params[:amount].to_d == @payment.amount.to_d*100\n @currency = Confline.get_value('Ouroboros_Default_Currency', @user.owner_id)\n rate = count_exchange_rate(session[:default_currency], @payment.currency)\n @user.balance += @payment.gross.to_d / rate\n @user.save\n @payment.completed = 1\n @payment.transaction_id = params[:tid]\n @payment.shipped_at = Time.now\n @payment.payer_email = @user.email\n @payment.payment_hash = params[:signature]\n @payment.pending_reason = ''\n @payment.save\n MorLog.my_debug(\"Ouroboros payment : payment - #{@payment.id}\", 1) if @payment\n MorLog.my_debug(\"Ouroboros payment : amount - #{@payment.gross.to_d / rate}\", 1)\n @error = 0\n else\n @error = 5\n MorLog.my_debug('Ouroboros payment : Amount missmach')\n MorLog.my_debug(' SYSTEM :' + @payment.amount.to_s)\n MorLog.my_debug(' Ouroboros :' + (params[:amount].to_d/100).to_s)\n end\n else\n @error = 4\n MorLog.my_debug('Ouroboros payment : Hash missmach')\n MorLog.my_debug(' SYSTEM :' + @hash)\n MorLog.my_debug(' Ouroboros :' + params[:signature])\n end\n else\n @error = 3\n MorLog.my_debug('Ouroboros payment : Unnotified payment.')\n MorLog.my_debug(' SYSTEM : ' + @payment.pending_reason.to_s)\n MorLog.my_debug(' Ouroboros : Notified payment')\n end\n else\n @error = 2\n MorLog.my_debug('Ouroboros payment : Ouroboros disabled')\n MorLog.my_debug(' SYSTEM : '+ @enabled.to_s)\n end\n else\n @error = 1\n MorLog.my_debug('Ouroboros payment : Payment was not found')\n end\n end", "def confirmation\n @merchant = @current_merchant\n @order = Order.find_by(id: params[:id])\n\n check_merchant\n end", "def confirm_order\n end", "def rental_confirmation(user)\n @user = user\n \n mail to: @user.email_address, subject: \"Rental confirmation\"\n end", "def instant_payment_notification\n begin\n if valid_withdrawal_response?(params)\n MonetaryWithdrawal.find_by_id(params[:unique_id_1]).update_attribute(:paid, true)\n elsif DonationProcessors::Paypal::Activation.valid_masspay_response?(params) || DonationProcessors::Paypal::Activation.valid_paypal_activation?(params)\n DonationProcessors::Paypal::Activation.from_paypal_params(params)\n else\n @donation = MonetaryDonation.from_paypal_params(params)\n @donation.add_to_kroogi_circle(@invite_kroogi)\n @donation.invite = @invite\n @donation.save(false)\n end\n rescue Kroogi::Error => e\n AdminNotifier.async_deliver_admin_alert(\"Error receiving payment notification from PayPal: #{e.inspect}. Params:\\n#{params.inspect}\")\n end\n render :nothing => true\n end", "def friendship_params\n params.require(:friendship).permit(:confirm)\n end", "def send_reconfirmation_instructions\n end", "def rewardpurchase\n @reward = Reward.find(params[:id]).clone\n @rewardpurchase = @reward.rewardpurchases.create(params.permit(:reward_id,:user_id,:rewardname,:rewardbusiness,:rewardcost))\n @rewardpurchase.rewardname = @reward.name.dup\n @rewardpurchase.rewardbusiness = @reward.business.name.dup\n @rewardpurchase.rewardcost = @reward.cost.to_s.dup\n @rewardpurchase.user_id = current_user.id\n @rewardpurchase.rewarddescription = @reward.description\n \n \n if current_user.karma >= @reward.cost\n respond_to do |format|\n if @rewardpurchase.save\n current_user.purchase_reward(@reward.cost)\n format.html { redirect_to root_path, notice: 'Reward was successfully purchased.' }\n format.json { render json: @rewardpurchase, status: :created, location: @rewardpurchase }\n else\n format.html { redirect_to @reward}\n format.json { render json: @rewardpurchase.errors, status: :unprocessable_entity }\n end\n end\n else\n redirect_to :back, notice: \"You do not have enough points to purchase this reward.\"\n end\n end", "def order_confirmation (user, cart, product, customer, pickup)\n @user = user\n @cart = cart\n @product = product\n @customer = customer\n @pickup = pickup\n\n mail to: user.email, subject: \"A new order has been placed\"\n end", "def send_confirmations_to_owner\n return @send_confirmations_to_owner\n end", "def payments_for(_other_user)\n fail NotImplementedError\n end", "def paid\n\t\tif params[:confirm].to_i == 1\n\t\t\tif @order.armor_enabled?\n\t\t\t\t@order.api_testing_set_to_paid\n\t\t\telse #is a prepay order\n\t\t\t\t@order.prepay_mark_as_paid\n\t\t\tend\n\t\t\tif @order.errors.any?\n\t\t\t\tflash.now[:notice] = @order.errors.full_messages\n\t\t\telse\n\t\t\t\t@success = true\n\t\t\t\tsleep(5) if @order.armor_enabled? #pause to allow update of status from webhook if armor\n\t\t\tend\n\t\tend\n\t\trespond_to do |format|\n\t\t\tformat.html { redirect_to order_url(@order) }\n\t\t\tformat.js\n\t\tend\n\tend", "def notify_payment\n @pack = Packages.get_packages_payment\n @pay = Payment.get_all_payments\n if( @pack != nil ) && ( @pay != nil )\n @pack.each do |t|\n @pay.each do |s|\n if( t.id == s.packages_id )\n if( t.senders_id == s.users_id )\n @notification = Notifications.create(t.senders_id, \"as a sender an amount has been deducted from your account\")\n elsif( t.carriers_id == s.users_id )\n @notification = Notifications.create(t.carriers_id, \"as a carrier an amount has been deducted from your account\")\n end\n end\n end\n end\n end\n return;\n end", "def order_goride_confirm(opts = {})\n clear_screen(opts)\n form = View.order_goride_confirm(opts)\n\n drivers = Driver.load\n driver = Driver.find(form[:origin_coord], form[:type], drivers)\n\n promo = Promo.load\n promo = Promo.find(form[:promo], promo)\n\n case form[:steps].last[:option].to_i\n when 1\n user = form[:user]\n if user.gopay < form[:est_price]\n form[:flash_msg] = \"Sorry, insufficient Go Pay credit\"\n order_goride_confirm(form)\n else\n form[:flash_msg] = []\n if driver.nil?\n form[:flash_msg] << \"Sorry, your order was not successfully created.\"\n form[:flash_msg] << \"The driver is busy\"\n else\n form[:driver] = driver['driver']\n form[:flash_msg] << \"Your order was successfully created.\"\n form[:flash_msg] << \"The driver is #{driver['driver']}\"\n\n if promo.nil?\n user.gopay -= form[:est_price]\n user.save!\n form[:flash_msg] << \"Sorry, you don't have a promo code.\"\n else\n if promo['type'] == 'cash'\n form[:est_price] -= promo['amount']\n form[:est_price] = 0 if form[:est_price] < 0\n else\n form[:est_price] -= (form[:est_price] * promo['amount'] / 100)\n end\n user.gopay -= form[:est_price]\n user.save!\n form[:flash_msg] << \"Yeay, you have a promo code. You just pay Rp #{form[:est_price]}\"\n end\n\n order = Order.new(\n timestamp: Time.now,\n origin: form[:origin],\n destination: form[:destination],\n est_price: form[:est_price],\n type: form[:type],\n driver: form[:driver]\n )\n\n Driver.changes_coord(form[:driver], form[:destination_coord])\n order.save!\n form[:order] = order\n end\n main_menu(form)\n end\n when 2\n form[:flash_msg] = []\n if driver.nil?\n form[:flash_msg] << \"Sorry, your order was not successfully created.\"\n form[:flash_msg] << \"The driver is busy\"\n else\n form[:driver] = driver['driver']\n form[:flash_msg] << \"Your order was successfully created.\"\n form[:flash_msg] << \"The driver is #{driver['driver']}\"\n\n if promo.nil?\n form[:flash_msg] << \"Sorry, you don't have a promo code.\"\n else\n if promo['type'] == 'cash'\n form[:est_price] -= promo['amount']\n form[:est_price] = 0 if form[:est_price] < 0\n else\n form[:est_price] -= (form[:est_price] * promo['amount'] / 100)\n end\n form[:flash_msg] << \"Yeay, you have a promo code. You just pay Rp #{form[:est_price]}\"\n end\n\n order = Order.new(\n timestamp: Time.now,\n origin: form[:origin],\n destination: form[:destination],\n est_price: form[:est_price],\n type: form[:type],\n driver: form[:driver]\n )\n\n Driver.changes_coord(form[:driver], form[:destination_coord])\n order.save!\n form[:order] = order\n end\n main_menu(form)\n when 3\n order_goride(form)\n when 4\n main_menu(form)\n else\n form[:flash_msg] = \"Wrong option entered, please retry.\"\n order_goride_confirm(form)\n end\n end", "def confirm\n @order.confirm_notes = params[:order][:confirm_notes]\n @order.approx_cost = (@order.approx_cost.to_f * 100.0).floor\n @order.confirm\n \n if @order.confirm_notes.present? \n OrderNote.create(:message => @order.confirm_notes, :order_id => @order.id, :author_id => @order.assigned_to.id) rescue nil \n end\n\n @order.approx_cost = (@order.approx_cost.to_f / 100.0).floor\n \n render 'status'\n end", "def notify_admin_of_redemption(user, redemption)\n @company = user.company\n @redemption = redemption\n @redeeming_user = user\n @reward = redemption.reward\n @reward_variant = redemption.reward_variant\n @reward_title = \"#{@reward.title} (#{@reward_variant.label})\"\n @mail_styler = company_styler(user.company)\n\n @admins, @approve_url = if @reward.manager.present?\n [[@reward.manager], manager_admin_redemptions_url(network: @company.domain)]\n else\n [@reward.company.company_admins, company_admin_redemptions_url(network: @company.domain)]\n end\n\n I18n.with_locale(user.locale) do\n mail(to: @admins.map(&:email), subject: t(\"rewards.user_has_redeemed\", name: @redeeming_user.full_name), track_opens: true)\n end\n end", "def confirmation\n @order = params[:order]\n mail to: @order.client.email, subject: \"Ordem de Serviço para #{@order.client.razao_social}\"\n end", "def paypal_params order, ip, back_url\n PaymentsHelper::paypal_params @user, back_url, order\n end", "def confirm_object(confirmation_datetime)\n return self if not self.confirmable?\n \n self.is_confirmed = true \n self.confirmed_at = confirmation_datetime\n self.save \n \n self.post_confirm_update_stock_mutation\n # self.post_confirm_update_price_mutation \n \n # po_detail =self.purchase_order_detail\n # po_detail.pending_receival -= self.quantity \n po_detail = self.purchase_order_detail \n po_detail.execute_receival( self.quantity ) \n end", "def confirm_order(user, order)\n @user = user\n @order = order\n @greeting = \"This is a confirmation email to let you know we have received your order. You can view the order at #{url_for(@order)}.\"\n\n mail to: \"#{@user.email}\", bcc: \"shilohkevin@gmail.com, batreyud@gmail.com\", subject: \"AudioPrint Order ##{@order.id} Confirmation\"\n end", "def confirm_members\n ur = UserReservation.find(params[:user_reservation_id])\n\n #need to check the current user owns the reservation\n\n if ur.check_outstanding.zero? then\n ur.reservation_confirmed!\n else\n ur.payment_attempted!\n end\n\n render json: {message:\"Members Verified for #{ur.id}\", user_reservation:ur}\n\n end", "def confirmation\n # Read the confirmation data from the request\n @confirmation = TBK::Webpay::Confirmation.new({\n request_ip: request.ip,\n body: request.raw_post\n })\n\n # confirmation is invalid for some reason (wrong order_id or amount, double payment, etc...)\n if @confirmation.amount != 5000.0\n render text: @confirmation.reject\n return # reject and stop execution\n end\n\n if @confirmation.success?\n # EXITO!\n # perform everything you have to do here.\n self.last_confirmation = @confirmation\n end\n\n # Acknowledge payment\n render text: @confirmation.acknowledge\n end", "def checkout\n \n # there must be a payment\n @payment = session[:payment]\n if !@payment || !@payment.amount\n @message = \"Sorry an internal error has occured\"\n render :action => 'error'\n return\n end\n\n # the donation can change based on parameters supplied\n if @payment.amount < 1\n # collect both possible donations\n donation = params[:donation]\n donation2 = params[:donation2]\n donation2 = donation if donation2\n donation = donation2.to_i\n @payment.update_attributes( :amount => donation )\n end\n if @payment.amount < 1\n @message = \" bad donation amount entered. Please hit back and try again\"\n render :action => 'error'\n return\n end\n\n # capture the company match if there is one\n matching_company = params[:matching_company]\n if matching_company\n @payment.update_attributes( :matching_company => matching_company)\n end\n\n # try get a party if there is one passed - this overrides anything from before.\n @party = nil\n @party = User.find(params[:party].to_i) if params[:party]\n @partyid = 0\n @partyid = @party.id if @party\n @payment.update_attributes( :owner_id => @partyid ) if @partyid > 0\n \n #if @payment.owner_id == 0\n # @message = \"Sorry no person to donate to found\"\n # render :action => 'error'\n # return\n #end\n\n # move payment along to the next stage\n @payment.update_attributes( :description=> Payment::CHECKOUT , :amount => donation )\n\n @notify_url = url_for(\n :controller=>\"payment\",\n :action => 'payment_received',\n :id => @payment.id,\n :only_path => false\n )\n\n @return_url = url_for(\n :controller=>\"payment\",\n :action => 'confirm_standard',\n :only_path => false\n )\n\n @paypal_business_email = SETTINGS[:paypal_business_email]\n @business_key = PAYPAL_MYPRIVKEY\n @business_cert = PAYPAL_MYPUBCERT\n @business_certid = SETTINGS[:paypal_cert]\n @action_url = \"http://www.paypal.com/cgi-bin/webscr\"\n Paypal::Notification.ipn_url = @action_url\n Paypal::Notification.paypal_cert = PAYPAL_CERT\n\n end", "def create\n @payment = Payment.new(payment_params)\n @user = User.find(params[:user_id])\n @payment.proofreader_id = current_user.id\n @payment.request = current_user.balance \n \n \n Stripe.api_key = ENV[\"STRIPE_API_KEY\"]\n token = params[:stripeToken]\n\n recipient = Stripe::Recipient.create(\n :name => @payment.legalname,\n :type => \"individual\",\n :bank_account => token\n )\n current_user.recipient = recipient.id\n current_user.save\n \n\n transfer = Stripe::Transfer.create(\n :amount => (@payment.request * 97).floor,\n :currency => \"usd\",\n :recipient => current_user.recipient\n )\n\n current_user.balance = 0\n current_user.save\n\n respond_to do |format|\n if @payment.save\n format.html { redirect_to dashboard_path, notice: 'Payment was successfully made. You should see your money in your account within 7 business days.' }\n format.json { render action: 'show', status: :created, location: @payment }\n else\n format.html { render action: 'new' }\n format.json { render json: @payment.errors, status: :unprocessable_entity }\n end\n end\n end", "def ship!(consignment_number, user = nil)\n run_callbacks :ship do\n self.shipped_at = Time.now\n self.shipper = user if user\n self.status = 'shipped'\n self.consignment_number = consignment_number\n self.save!\n Shoppe::OrderMailer.shipped(self).deliver_now\n end\n end", "def accept\n load_order\n # If the order has been canceled, the retailer can no longer accept it\n if @order.state == 'canceled'\n flash[\"notice\"] = 'This order has been canceled - do not process it!'\n elsif @order.payments.blank?\n flash[:error] = \"Something went wrong with the payment on this order. Please hold off on shipping and contact ReserveBar.\"\n Spree::OrderMailer.no_payment_error_notification(@order).deliver\n elsif @order.accepted_at.blank? && (@current_retailer && @current_retailer.id == @order.retailer_id)\n @order.update_attribute(:accepted_at, Time.now)\n @order.create_profit_and_loss\n\n # If the order only has one payment on it (all order here should have only a single payment)\n # and the total order amount is lower than the payment amount, due to adjustments made after the order was submitted\n # reduce the amount in the payment to the order total\n if @order.payments.count == 1 && @order.payment.pending? && @order.total < @order.payment.amount\n @order.payment.update_attribute(:amount, @order.total)\n @order.payments.reload\n end\n\n begin\n @order.payments.each do |payment|\n payment.payment_source.send(\"capture\", payment)\n end\n rescue Spree::Core::GatewayError => error\n # Try to authorize and capture a new payment on the same source\n begin\n unless @order.payments.count > 1\n payment = @order.payment\n credit_card = payment.payment_source\n # check retailer matches merchant account of payment_source, in case order was moved\n if credit_card.bt_merchant_id == @order.retailer.bt_merchant_id\n new_payment = payment.dup\n new_payment.response_code = nil\n new_payment.save\n # authorize and capture new payment\n credit_card.authorize(new_payment.amount, new_payment)\n credit_card.send(\"capture\", new_payment)\n else\n raise 'Order changed Retailers'\n end\n else\n raise 'More than one payment'\n end\n rescue\n @order.update_attribute(:accepted_at, nil)\n # Handle messaging to retailer - error flash that something\n flash[:error] = \"Something went wrong with the payment on this order. Please hold off on shipping and contact ReserveBar.\"\n # Dump error to separate log\n log_payment_error(error)\n # Send email to reservbar that something went wrong\n Spree::OrderMailer.capture_payment_error_notification(@order, error).deliver\n end\n end\n end\n redirect_to admin_order_url(@order)\n end", "def ship_confirm_request(shipper, recipient, package, options = {})\n shipment = create_shipment(shipper, recipient, package, options)\n request = ShipConfirmRequest.new(@credentials, shipment, options)\n execute(request)\n end", "def order_delivered\n @user, @order = params[:user], params[:order]\n mail(to: @user.email, subject: \"Order delivered!\")\n end", "def payment_params\n params.require(:payment).permit(:amount, :receiver, :refunded, :completed, :user_id)\n end", "def paid_email(payment)\n @payment = payment\n\n mail(:to => User.find(@payment.user_id).email, :subject => \"You've been paid back!\", :cc => @payment.email)\n end", "def send_booking_confirmation_notifications\n\n notify_manager_confirmation\n notify_customer\n \n end", "def notify\n @order = Order.find(params[:order_id])\n @payment_gateway = @order.payment_gateway_class.new(order: @order)\n number = @payment_gateway.return(params)\n\n if number\n @order.payments\n .find_or_create_by(number: number)\n .update(amount: @order.grand_total_with_tax)\n @order.complete! if @order.should_complete?\n head :ok\n else\n head :unprocessable_entity\n end\n end", "def confirm\n #@sub_items = Spree::Order.get_receipt_items(current_user.id)\n order_ids = params[:confirmed_order_ids]\n if order_ids.present?\n @sub_items = Spree::Order.get_snack_queue_updated_orders(order_ids)\n @delivery_dates = Spree::Order.get_delivery_dates(order_ids)\n\n else\n redirect_to main_app.profile_users_path and return if @sub_items.blank?\n end\n\n #after confirmation if user wishes to reload page then it'll auto redirect user to profile section.\n end", "def create\n # You maybe want to log this notification\n notify = Paypal::Notification.new request.raw_post\n \n # Split the item_id\n account_id = notify.item_id\n \n @user = User.find account_id\n\n if notify.acknowledge\n # Make sure you received the expected payment!\n if notify.complete? and 9.99 == Decimal.new( params[:mc_gross] ) and notify.type == \"subscr_payment\"\n # All your bussiness logic goes here\n @user.premium = true\n @user.valid_till = Date.today + 1.month\n @user.save\n render :nothing => true\n end\n end\n end", "def process_payment\n @order.update_with_totals(order_params)\n processor = new_processor(@order, params[:stripeToken])\n checkout_response = checkout(processor).pay!\n \n if checkout_response[:status] == \"succeeded\"\n successful_order\n elsif checkout_response[:status] == \"pending_confirmation\" \n @order.pending_confirmation!\n redirect_to checkout_response[:second_step_url]\n else\n failed_order\n end\n end", "def order_receipt(user_name, user_email, order, total_amount)\n @user = user_name\n @order = order\n @total_amount = total_amount\n mail(to: user_email, subject: \"Thank you for your order ##{@order.id}\")\n end", "def refund_payment(customer, reason)\n refund = Stripe::Refund.create({\n :charge => self.charge,\n :refund_application_fee => true\n },\n {\n :stripe_account => self.reservation.listing.user.uid\n })\n\n refund\n end", "def friend_request(user, other_user)\n @friendship = Friendship.where(other_friend_id: other_user).where(friend_id: user).first\n @user = user\n @other_user = other_user\n\n mail to: @other_user.email, subject: \"Friend request.\"\n end", "def exchange_request\n @order = Order.find(params[:id])\n if @order\n @exchangeable_books = params[:books]\n user = User.find(@order.seller_id)\n @order.notification_sent = true\n @order.save\n TasksController.send_notification( user,@current_user,\"Book exchange request\", \"https://www.google.com\")\n render json:{status: 'Success', message: \"Your request is sent to book owner (\"+user.name+\")\"},status: :ok\n end\n end", "def notify\n payment_method=PaymentMethod.find_by_id(params[:payment_method_id])\n notify = ActiveMerchant::Billing::Integrations::Paypal::Notification.new(request.raw_post)\n @order = ::Order.find_by_number(notify.item_id)\n if notify.acknowledge\n begin\n if notify.complete? and @order.total.to_f == notify.amount.to_f\n p=@order.payment\n p.complete\n @order.state='complete'\n @order.finalize!\n else\n Rails.logger.warn \"Warning:: Order #{notify.item_id} was not authorised - reason #{notify.message rescue ''}\"\n p=@order.payment\n p.fail\n p.save\n end\n\n rescue => e\n p=@order.payment\n p.fail\n p.save\n raise\n\n end\n end\n\n render :text=>'', :status=>200\n\n end", "def amazon_postfill\n unless params[:callerReference].blank?\n @order = Order.postfill!(params)\n end\n # \"A\" means the user cancelled the preorder before clicking \"Confirm\" on Amazon Payments.\n if params['status'] != 'A' && @order.present?\n redirect_to :action => :share, :uuid => @order.uuid\n else\n redirect_to root_url\n end\n end", "def confirmation\n @order = Order.find_by(id: session[:order_id])\n @order.assign_attributes(order_update_params[:order])\n\n #updates status if shipping info exists(after order confirmation)\n @order.assign_attributes(order_state: \"paid\") if params[:order][:carrier_code] != nil\n\n if @order.save\n reset_cart\n render :order_confirmation\n else\n @user = User.find_by(id: session[:user_id])\n render :shipping\n end\n end", "def confirm_friend(user)\n friendship = inverse_friendships.find { |friendship| friendship.user == user }\n friendship.confirmed = true\n friendship.save\n end", "def confirmed_order_params\n params.require(:confirmed_order).permit(:user_id, :payment_method, :payment_status)\n end", "def payment_confirmation_required?\n true\n end", "def pay\n @bill = Bill.find_by(id: params[:bill_id].to_i, home_id: params[:home_id].to_i)\n @payment = Payment.new(description: @bill.name, amount: @bill.amount,\n recipient_paypal_email: @bill.user.paypal)\n @recipient = @payment.recipient_paypal_email\n @payment.sender_paypal_email = current_user.paypal\n @payment.paid_at = Time.now.strftime(\"%A, %B %e, %Y %l:%M %P %Z\")\n @amount = @payment.amount\n request = HTTParty.post(\"https://svcs.sandbox.paypal.com/AdaptivePayments/Pay\",\n headers: {\"X-PAYPAL-SECURITY-USERID\" => \"maria.cassino-facilitator_api1.gmail.com\",\n \"X-PAYPAL-SECURITY-PASSWORD\" => \"U9FL2MK962DKPXMR\",\n \"X-PAYPAL-SECURITY-SIGNATURE\" => \"AFcWxV21C7fd0v3bYYYRCpSSRl31A2tjSJXfuAz3het2TLAiz2uCt1eN\",\n \"X-PAYPAL-REQUEST-DATA-FORMAT\" => \"JSON\",\n \"X-PAYPAL-RESPONSE-DATA-FORMAT\" => \"JSON\",\n \"X-PAYPAL-APPLICATION-ID\" => \"APP-80W284485P519543T\"\n },\n body: {actionType: \"PAY\",\n currencyCode: \"USD\",\n receiverList: {\n receiver:[\n {amount: @amount,\n email: @recipient}\n ]\n },\n returnUrl: \"http://www.example.com/success.html\",\n cancelUrl: \"http://www.example.com/failure.html\",\n requestEnvelope:{\n errorLanguage: \"en_US\",\n detailLevel: \"ReturnAll\"\n }}.to_json\n )\n @payment.save\n @bill.paid_by = current_user.id\n @bill.paid = true\n @bill.paid_at = Time.now.strftime(\"%A, %B %e, %Y %l:%M %P %Z\")\n @bill.save\n render :payment\n end", "def confirm\n @model = User::BillingLog.find params[:id]\n @billable = @model.billable\n\n authorize @model\n\n if request.post?\n case @billable.pay_type.to_sym\n when *Billing::PaymentTypeList::BALANCE\n case @billable.class.name\n when 'Billing::Delocoin::Buy'\n run Billing::Delocoin::Buy::Operation::Finish, id: @billable.id do |result|\n roistat.push_async(:delocoin_buy_finish, cost: result['model'].cost)\n end\n\n return redirect_to status_my_billing_path(@model.billing_log.id)\n end\n end\n\n not_found\n end\n\n case @billable.pay_type.to_sym\n when *Billing::PaymentTypeList::YANDEX_KASSA\n @fields = Billing::YandexKassa::RequestFieldsService.new(@billable).perform\n\n render 'my/billing/confirm/yandex_kassa'\n when *Billing::PaymentTypeList::BALANCE\n render 'my/billing/confirm/balance'\n else\n not_found\n end\n end", "def send_confirmation_instructions; end", "def resend_confirmation_instructions; end", "def confirm_delivery\n if @order.complete!\n # update the owner with the refilled boxes\n owner = @order.owner # e.g. node\n current_quantity = owner.current_quantity # e.g. node current quantity\n owner.update(current_quantity: current_quantity + @order.quantity)\n\n render json: {}, status: :ok\n else\n render json: {errors: @order.errors.messages}, status: :bad_request\n end\n end", "def confirm_mandate\n begin\n redirect_flow = GO_CARDLESS_CLIENT.redirect_flows.complete(\n params[:redirect_flow_id],\n params: { session_token: \"#{current_user.id}\" }\n )\n current_user.go_cardless_customer = redirect_flow.links.customer\n current_user.go_cardless_mandate = redirect_flow.links.mandate\n\n if current_user.save(validate: false)\n create_gocardless_subscription\n flash[:notice] = 'Your payment has been successfully completed and subscription added to your GoCardless bank account.'\n else\n flash[:error] = 'Something went wrong!'\n end\n rescue StandardError => e\n flash[:error] = e\n end\n redirect_to root_path\n end", "def confirm_user(user)\n confirmed_interpreter_requests.create(user_id: user.id)\n end", "def confirmation(user)\n @user = user\n @user.generate_confirmation_code\n mail(to: @user.email, subject: \"Confirmation\") do |f|\n f.html\n end\n\n end", "def payment_notification(options={})\n options = options.symbolize_keys\n receivers = fetch_payment_receivers(options)\n @amount = ((options[:amount].to_f)/100)\n @conn_count = options[:connection_count]\n @last4 = options[:last4]\n mail(:to => receivers, :subject => \"Payment Successful!\")\n end", "def send_reward_request(address, promo, rewards_token)\n # set the request url\n url = AMAX_URL\n\n # set the payload\n payload = {\n \"outboundRewardRequest\" => {\n \"app_id\" => @app_id,\n \"app_secret\" => @app_secret,\n \"rewards_token\" => rewards_token,\n \"address\" => address,\n \"promo\" => promo\n }\n }\n\n # convert to JSON\n payload = JSON.generate(payload)\n\n # send post request\n response = send_post_request(url, payload)\n\n return JSON.parse(response)\n end", "def reward_owner_params\n params.require(:reward_owner).permit(:is_confirm,:code, :name, :description, :status)\n end", "def reward\n business.add_to_balance(amount)\n end", "def seller_dispute_order_confirmed(seller)\n @seller=seller\n @url = 'http://badaboum-prod.herokuapp.com/users/sign_in'\n mail(to: @seller.email, subject: \"Litige traité - vente confirmée\")\n end", "def payment_receipt\n mandrill = Mandrill::API.new Rails.application.secrets.mandrill_api_key\n\n event_json = JSON.parse(request.body.read) # event data from Stripe\n\n if event_json[\"type\"] != \"invoice.payment_succeeded\"\n render json: {}, status: 400\n else\n donor = Donor.find_by(stripe_customer_id: event_json[\"data\"][\"object\"][\"customer\"])\n donor = Donor.find_by(stripe_customer_id: \"cus_AT3dv800viOsas\") unless donor # @TODO: remove once fully test -- used for integration environment tests temporarily\n DonorMailer.stripe_payment_receipt(donor).deliver_now if donor && event_json[\"data\"][\"object\"][\"amount_due\"].to_i != 0\n render json: {}, status: 200\n end\n end", "def paypal_callback\n binding.pry\n\n # @user = User.find(params[:invoice]) rescue \"\"\n # if @user.present?\n # @transaction_detail = @user.transaction_details.new(\n # plan_id: params[:custom],\n # payer_id: params[:payer_id],\n # payer_email: params[:payer_email],\n # payment_date: params[:payment_date],\n # payment_status: params[:payment_status],\n # payment_fee: params[:payment_fee],\n # payment: params[:payment_gross],\n # payment_type: params[:payment_type],\n # mc_currency: params[:mc_currency],\n # first_name: params[:first_name],\n # last_name: params[:last_name],\n # txn_id: params[:txn_id],\n # receiver_id: params[:receiver_id],\n # receiver_email: params[:receiver_email],\n # address_name: params[:address_name],\n # address_street: params[:address_street],\n # address_city: params[:address_city],\n # address_state: params[:address_state],\n # address_country: params[:address_country],\n # address_country_code: params[:address_country_code],\n # address_zip: params[:address_zip]\n # )\n end", "def confirm\n begin\n @result = Braintree::TransparentRedirect.confirm(request.query_string)\n if @result.success?\n current_user.update_user_with_plan_and_braintree_id(session[:user_plan], @result.customer.id)\n session[:user_plan]=nil\n flash[:success] = \"You have successfully converted to paid member. Now you can activate to offer by clicking on the Activate button\"\n redirect_to offers_path\n else\n flash[:error] = \"Your payment was not success. Check your card information.\"\n redirect_to offers_path\n end\n rescue\n flash[:error] = \"Your payment was not success. Check your card information.\"\n redirect_to offers_path\n end\n end", "def resend_confirmation_email\n current_user.resend_confirmation_instructions\n respond_to do |format|\n format.html {redirect_to purchase_orders_path, notice: \"Confirmation Email has been re-sent\"}\n end\n end", "def paid(order)\n @order = order\n\n mail :to => order.billing_address.email\n end", "def accept_request(other_user)\n\t\treceived_relationships.find_by(friend_active_id: other_user.id).update_attribute(:accepted, true)\n\tend", "def test_should_confirm_order\n # Execute an earlier test as this one deppends on it.\n # test_should_select_shipping_method\n\n # TODO: The code have an unreachable part, the order_shipping_type_id will never be nil because\n # the database schema don't let it.\n # assert_equal assigns(:order).order_shipping_type_id, nil\n \n # Get the confirm order action when the shipping is nil.\n # get :confirm_order\n # assert_redirected_to :action => :select_shipping_method\n end", "def payment\n # Get the current user's last order (i.e. the current order)\n @order = @current_user.orders.last\n\n # Token automatically created by Checkout and sent through params\n token = params[:stripeToken]\n\n # Invoke action in cart.rb that calculates the total price of all items in the cart\n total_amount = (@cart.get_total_price * 100).to_i\n\n Stripe.api_key = Rails.application.secrets.stripe_api_secret\n\n # Make an API request to create a one-time charge containing the token,\n # currency, total amount (as an integer not a float) and description\n charge = Stripe::Charge.create({\n amount: total_amount,\n currency: 'aud',\n description: 'Purchase from Eight by Eight',\n source: token,\n })\n\n # Update the current order with the Stripe charge response data\n @order.update stripe_token: token, stripe_charge_response: charge\n\n # Checks whether the payment was successful\n unless @order.stripe_charge_response[\"outcome\"][\"network_status\"] == \"approved_by_network\"\n # If the payment was unsuccessful, set a flash error and redirect to orders#confirm_order\n flash[:order_error] = \"Transaction unsuccessful. Please contact your card issuer for more details.\"\n redirect_to confirm_order_path\n return\n end\n\n # Redirect to orders#complete_order\n redirect_to complete_order_path\n end", "def notify_payment\n @pack = Packages.find( :all,:conditions =>{:receivedByCarrier => true} )\n @pay = Payment.find( :all )\n if( @pack != nil ) && ( @pay != nil )\n @pack.each do |t|\n @pay.each do |s|\n if( t.id == s.packages_id )\n if( t.senders_id == s.users_id )\n @notification = Notifications.new\n @notification.users_id = t.senders_id\n @notification.description = \"an amount has been deducted from your account\"\n @notification.save\n elsif( t.carriers_id == s.users_id )\n @notifications = Notifications.new\n @notifications.users_id = t.carriers_id\n @notifications.description = \"an amount of has been deducted from your account\"\n @notifications.save\n end\n end\n end\n end\n end\n return;\n end", "def order_confirmation_buyer(order)\n @order = order\n\n mail(\n to: @order.user.email,\n subject: \" Chouette, tu as commandé #{@order.meal.menu_name}!\"\n )\n end", "def manual_payment(payment_history, cost, total_currency, user_profile, options)\n options ||= { item_ref: '', payment_method: 'cash', bill_to_name: '', payment_date: Time.now,\n notify_data: nil, transaction_id: nil, status: '' }\n amount = Monetize.parse(cost, total_currency)\n\n if payment_history\n new_amount_paid = amount_paid - workshop_price.to_base_currency(payment_history.total) + workshop_price.to_base_currency(amount)\n DmCore::PaymentHistories::UpdateService.call(payment_history, amount, user_profile, options)\n else\n new_amount_paid = amount_paid + workshop_price.to_base_currency(amount)\n payment_history = DmCore::PaymentHistories::CreateService.call(receipt_code, amount, user_profile, options)\n payment_histories << payment_history\n end\n\n if payment_history.errors.empty?\n update_attribute(:amount_paid_cents, new_amount_paid.cents)\n reload\n send('paid!') if balance_owed.cents <= 0 && accepted?\n else\n logger.error(\"===> Error: Registration.manual_payment: #{payment_history.errors.inspect}\")\n end\n payment_history\n end", "def order_confirmation(order)\n @order = order\n mail(to: @order.user.email, subject: 'Order has been received')\n end", "def new_friends_card_purchase_notification (friend, registration)\n @friend = friend\n @registration = registration\n mail(to: @registration.email, subject: 'Your Friends Card Order Receipt')\n end", "def request_button order\n g = Glysellin.gateways[order.payment_method.slug].new(order)\n g.render_request_button\n end", "def confirm_paypal!(token)\n begin\n p = EXPRESS_GATEWAY.details_for(token)\n return errors.add(:base, p.message) && false unless p.success?\n _paid = p.params['order_total'].to_f\n return errors.add(:base, \"The amount paid #{_paid} is different to #{total_amount}\") && false if _paid != total_amount\n self.payment_payer_id = p.params['PayerInfo']['PayerID']\n rescue => e\n Rails.logger.error(\"*********** Saving paypal payment error: #{e.message}\")\n return errors.add(:base, \"Payment not found on paypal server\") && false\n end\n self.attributes = {payment_at: Time.current, payment_kind: 'paypal'}\n save\n end" ]
[ "0.64884776", "0.60414433", "0.59830576", "0.5975201", "0.59442484", "0.59240156", "0.58681536", "0.580634", "0.57849306", "0.576695", "0.573333", "0.56884193", "0.5626151", "0.5610683", "0.56017447", "0.55956084", "0.5595445", "0.5594523", "0.55937845", "0.55859315", "0.55844706", "0.55807143", "0.5576585", "0.55740774", "0.5565272", "0.5545646", "0.5545626", "0.55438507", "0.55338836", "0.55139625", "0.5495262", "0.5486795", "0.54691094", "0.54641074", "0.5429218", "0.5425008", "0.5424034", "0.5421301", "0.54055905", "0.5400742", "0.5393379", "0.5393146", "0.53916454", "0.5384596", "0.5363871", "0.5362589", "0.5356769", "0.53481036", "0.5343324", "0.5337245", "0.5336033", "0.53305244", "0.53271586", "0.5321494", "0.5313692", "0.531034", "0.5303762", "0.53011507", "0.52861285", "0.52835155", "0.5282695", "0.52773404", "0.52763855", "0.5275308", "0.5271234", "0.52683204", "0.5265653", "0.526351", "0.52503645", "0.5246761", "0.5246364", "0.5245492", "0.5242806", "0.52400976", "0.5236464", "0.52345043", "0.5229052", "0.52222514", "0.52132255", "0.52097505", "0.5209267", "0.5203173", "0.5202677", "0.51945126", "0.51913726", "0.5189539", "0.5187822", "0.5181994", "0.51815534", "0.517898", "0.51775014", "0.51721483", "0.51718134", "0.5169451", "0.516527", "0.5164553", "0.51612264", "0.5156891", "0.5156605", "0.51479447" ]
0.54854983
32
This is the actual action that ships the reward ship_reward_now_user_payment_reward_receivers POST
def ship_reward_now @reward_receiver = RewardReceiver.find(params[:reward_receiver_id]) @reward_receiver.update(reward_receiver_params) if @reward_receiver.update( status: "shipped" ) #Send email #Send notification #Add xp @user.add_score("ship_reward") end redirect_to show_user_studio_rewards_path(@reward_receiver.reward.user_id,@reward_receiver.reward_id) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def user_reward_action_params\n params.fetch(:user_reward_action, {})\n end", "def set_user_reward_action\n @user_reward_action = UserRewardAction.find(params[:id])\n end", "def rewardpurchase\n @reward = Reward.find(params[:id]).clone\n @rewardpurchase = @reward.rewardpurchases.create(params.permit(:reward_id,:user_id,:rewardname,:rewardbusiness,:rewardcost))\n @rewardpurchase.rewardname = @reward.name.dup\n @rewardpurchase.rewardbusiness = @reward.business.name.dup\n @rewardpurchase.rewardcost = @reward.cost.to_s.dup\n @rewardpurchase.user_id = current_user.id\n @rewardpurchase.rewarddescription = @reward.description\n \n \n if current_user.karma >= @reward.cost\n respond_to do |format|\n if @rewardpurchase.save\n current_user.purchase_reward(@reward.cost)\n format.html { redirect_to root_path, notice: 'Reward was successfully purchased.' }\n format.json { render json: @rewardpurchase, status: :created, location: @rewardpurchase }\n else\n format.html { redirect_to @reward}\n format.json { render json: @rewardpurchase.errors, status: :unprocessable_entity }\n end\n end\n else\n redirect_to :back, notice: \"You do not have enough points to purchase this reward.\"\n end\n end", "def create\n if @user.hearts >= @reward.cost\n @redemption = Redemption.new()\n @redemption.user = @user\n @redemption.cost = @reward.cost\n @redemption.reward = @reward\n\n if @reward.ifttt?\n key = ENV[\"IFTTT_KEY\"]\n\turl = \"https://maker.ifttt.com/trigger/#{@user.account}#{@reward.event}/with/key/#{key}\"\n\tresponse = RestClient.get url\n\n\trespond_to do |format|\n\t if response.code == 200 && @redemption.save\n @user.hearts = @user.hearts - @reward.cost\n @user.save!\n\n format.json { render json: @redemption.as_json(include: {reward: {only: :name}}).merge({hearts: @user.hearts}), status: :created }\n else\n format.json { render json: nil, status: :not_acceptable }\n end\n end\n elsif @reward.cash?\n \trespond_to do |format|\n if @redemption.save\n @user.hearts = @user.hearts - @reward.cost\n\t @user.save!\n\t SmsMailer.sms_email(Admin.all.first).deliver\n\n\t format.json { render json: @redemption.as_json(include: {reward: {only: :name}}).merge({hearts: @user.hearts}), status: :created }\n\t else\n\t format.json { render json: nil, status: :not_acceptable }\n\t end\n\tend\n end\n else\n respond_to do |format|\n format.json { render json: {message: \"Not enough hearts!\"}, status: :not_acceptable }\n end\n end\n end", "def request_shipping_fee\n\t\t@reward = Reward.find(@reward_receiver.reward_id)\n\t\t#Select shipping amount based on different situiations\n\t\tif @reward.shippings.where(country: @reward_receiver.shipping_address.country).first\n\t\t\t@amount = @reward.shippings.where(country: @reward_receiver.shipping_address.country).first.amount\n\t\telse\n\t\t\tif @reward.shipping_anywhere\n\t\t\t\t@amount = @reward.shipping_anywhere.amount\n\t\t\tend\n\t\tend\n\t\tif @shipping_order = ShippingOrder.find_by_reward_receiver_id(@reward_receiver.id)\n\t\telse\n\t\t\t@shipping_order = ShippingOrder.create(\n\t\t\t\tuser_id: @reward_receiver.user_id,\n\t\t\t\tamount: @amount,\n\t\t\t\tcurrency: @reward.currency,\n\t\t\t\tstatus: 'Sent',\n\t\t\t\tcountry: @reward_receiver.shipping_address.country,\n\t\t\t\tcity: @reward_receiver.shipping_address.city,\n\t\t\t\tline1: @reward_receiver.shipping_address.line1,\n\t\t\t\tpostal_code: @reward_receiver.shipping_address.postal_code,\n\t\t\t\tstate: @reward_receiver.shipping_address.state,\n\t\t\t\tname: @reward_receiver.shipping_address.name,\n\t\t\t\treward_id: @reward_receiver.reward_id,\n\t\t\t\treward_receiver_id: @reward_receiver.id,\n\t\t\t\tdue: 30.days.from_now\n\t\t\t)\n\t\tend\n\t\t@reward_receiver.update(\n\t\t\tstatus: 'shipping_fee_request_sent'\n\t\t)\n\t\t#Send order email\n Payment::ShippingOrdersMailer.send_confirmation(shipping_order_id: @shipping_order.id).deliver_now\n\t\t#Send order notification\n\t\tNotification.create(\n\t\t\tuser_id: @reward_receiver.user_id,\n trackable_id: @shipping_order.id,\n trackable_type: \"ShippingOrder\",\n notification_type: \"send_shipping_order_confirmation\"\n\t\t)\n\t\tredirect_to(:back)\n\tend", "def create\n @reward = current_business.rewards.build(reward_params)\n\n respond_to do |format|\n if @reward.save\n format.html { redirect_to @reward, notice: 'Reward was successfully created.' }\n format.json { render :show, status: :created, location: @reward }\n else\n format.html { render :new }\n format.json { render json: @reward.errors, status: :unprocessable_entity }\n end\n end\n end", "def reward\n business.add_to_balance(amount)\n end", "def default_reward\n\t\tself.rewards.create(:description => \"Thanks!\", :dollar_amount => 1)\n\tend", "def reward_params\n params.require(:reward).permit(:title, :description, :price, :product_id, :user_id)\n end", "def send_reward_request(address, promo, rewards_token)\n # set the request url\n url = AMAX_URL\n\n # set the payload\n payload = {\n \"outboundRewardRequest\" => {\n \"app_id\" => @app_id,\n \"app_secret\" => @app_secret,\n \"rewards_token\" => rewards_token,\n \"address\" => address,\n \"promo\" => promo\n }\n }\n\n # convert to JSON\n payload = JSON.generate(payload)\n\n # send post request\n response = send_post_request(url, payload)\n\n return JSON.parse(response)\n end", "def set_reward_action\n @reward_action = RewardAction.find(params[:id])\n end", "def reward_action_params\n params.fetch(:reward_action, {})\n end", "def allows_reward?\n true\n end", "def claim_your_reward\n InviteMailer.claim_your_reward\n end", "def redemption_params\n params.permit(:reward_id )\n end", "def redeemed_reward_params\n params.require(:redeemed_reward).permit(:name, :timestamp, :price, :user_id)\n end", "def call(user, email, reward, shipping_address)\n @user = user\n @reward = reward\n # admin = \"astropowerbox@gmail.com\"\n admin = \"news.article.sysetm@gmail.com\"\n @shipping_address = shipping_address\n mail to: email, subject: 'Redemption details'\n end", "def add_reward(value)\n self.reward += value\n end", "def reward_params\n params.require(:reward).permit(:result_no, :generate_no, :e_no, :battle_income, :add_income, :attack, :support, :defense, :defeat, :selling, :sub_quest, :enemy_caution, :colosseum_win, :fight_money, :total_income, :ammunition_cost, :preparation_deduction, :preparation_cost, :union_cost, :prize, :union_interest, :parts_sell)\n end", "def allows_reward?\n false\n end", "def reputation_threshold_action\n :offer_reward\n end", "def reward_owner_params\n params.require(:reward_owner).permit(:is_confirm,:code, :name, :description, :status)\n end", "def wepay_postfill\n # If the user approved the 'preapproval' and \n if params.has_key?('preapproval_id')\n @order = Order.find_by_token(params[:preapproval_id])\n unless @order.nil?\n wepay = WePay.new(Settings.wepay_client_id, Settings.wepay_access_token, _use_stage = (!Rails.env.production?))\n # Let's find the user information on Wepay end..\n response = wepay.call('/preapproval', Settings.wepay_access_token, {\n :preapproval_id => params[:preapproval_id]\n })\n \n @order.wepay_postfill(response)\n if params['status'] != 'approved' \n redirect_to :action => :share, :uuid => @order.uuid\n else\n redirect_to root_url\n end\n else\n redirect_to root_url\n end\n else\n redirect_to root_url\n end\n end", "def set_reward\n @product = current_user.products.find(params[:product_id])\n @reward = @product.rewards.find(params[:id])\n end", "def reward_params\n params[:reward].permit(:title, :description, :limit, :price)\n end", "def reward_params\n params.fetch(:reward, {}).permit(:title, :description, :cost, :business_id)\n end", "def active_reward_from_sender?\n !self.kase.rewards.active.find(:all, :conditions => {:sender_id => self.sender.id}).empty?\n end", "def create_loyalty_reward(body:)\n # Prepare query url.\n _query_builder = config.get_base_uri\n _query_builder << '/v2/loyalty/rewards'\n _query_url = APIHelper.clean_url _query_builder\n\n # Prepare headers.\n _headers = {\n 'accept' => 'application/json',\n 'content-type' => 'application/json; charset=utf-8'\n }\n\n # Prepare and execute HttpRequest.\n _request = config.http_client.post(\n _query_url,\n headers: _headers,\n parameters: body.to_json\n )\n OAuth2.apply(config, _request)\n _response = execute_request(_request)\n\n # Return appropriate response type.\n decoded = APIHelper.json_deserialize(_response.raw_body)\n _errors = APIHelper.map_response(decoded, ['errors'])\n ApiResponse.new(\n _response, data: decoded, errors: _errors\n )\n end", "def reward_params\n params.require(:reward).permit(:name, :cost, :description, :expdate)\n end", "def reward_params\n params.require(:reward).permit(\n :name, :image, :require_points, :quantity, :price, :term,\n :store_id, :description, :start_date, :end_date, :claimed_reward_expired)\n end", "def reward\n @reward ||= 0\n end", "def api_v1_reward_params\n params.fetch(:api_v1_reward, {})\n end", "def create\n @goal_reward = GoalReward.new(params[:goal_reward])\n\n respond_to do |format|\n if @goal_reward.save\n format.html { redirect_to [@goal_reward.user, GoalReward], notice: 'Goal reward was successfully created.' }\n format.json { render json: @goal_reward, status: :created, location: @goal_reward }\n else\n format.html { render action: \"new\" }\n format.json { render json: @goal_reward.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @product = Product.find(params[:product_id])\n @reward = @product.rewards.new(reward_params)\n respond_to do |format|\n if @reward.save\n format.html { redirect_to mypage_product_path(@product), notice: 'Reward was successfully created.' }\n format.json { render :show, status: :created, location: @reward }\n else\n format.html { render :new }\n format.json { render json: @reward.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @api_v1_reward = Api::V1::Reward.new(api_v1_reward_params)\n\n respond_to do |format|\n if @api_v1_reward.save\n format.html { redirect_to @api_v1_reward, notice: 'Reward was successfully created.' }\n format.json { render :show, status: :created, location: @api_v1_reward }\n else\n format.html { render :new }\n format.json { render json: @api_v1_reward.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n \n # Get mentor and mentee via params + current user\n # Get sender and receiver based on current user and mentor/mentee params\n if params[:mentor_id]\n @mentor = User.find(params[:mentor_id])\n @mentee = current_user\n @sender = current_user\n @receiver = @mentor\n elsif params[:mentee_id]\n @mentor = current_user\n @mentee = User.find(params[:mentee_id])\n @sender = current_user\n @receiver = @mentee\n else\n redirect_to mentorships_path and return false\n end\n \n # Actually create the Mentorship object\n @mentorship = Mentorship.new( :mentor => @mentor,\n :mentee => @mentee,\n :sender => @sender,\n :receiver => @receiver )\n \n\n @matched_skills = @mentorship.matched_skills\n @matched_skills_skills = @matched_skills.collect{ |ms| ms[:skill] }\n @other_skills = [@mentor.skills, @mentee.skills].flatten.uniq.reject{ |s| @matched_skills_skills.include?(s) }\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @mentorship }\n end\n end", "def redeem_loyalty_reward(reward_id:,\n body:)\n # Prepare query url.\n _query_builder = config.get_base_uri\n _query_builder << '/v2/loyalty/rewards/{reward_id}/redeem'\n _query_builder = APIHelper.append_url_with_template_parameters(\n _query_builder,\n 'reward_id' => { 'value' => reward_id, 'encode' => true }\n )\n _query_url = APIHelper.clean_url _query_builder\n\n # Prepare headers.\n _headers = {\n 'accept' => 'application/json',\n 'content-type' => 'application/json; charset=utf-8'\n }\n\n # Prepare and execute HttpRequest.\n _request = config.http_client.post(\n _query_url,\n headers: _headers,\n parameters: body.to_json\n )\n OAuth2.apply(config, _request)\n _response = execute_request(_request)\n\n # Return appropriate response type.\n decoded = APIHelper.json_deserialize(_response.raw_body)\n _errors = APIHelper.map_response(decoded, ['errors'])\n ApiResponse.new(\n _response, data: decoded, errors: _errors\n )\n end", "def set_reward\n @reward = Reward.find(params[:id])\n end", "def set_reward\n @reward = Reward.find(params[:id])\n end", "def set_reward\n @reward = Reward.find(params[:id])\n end", "def notify_of_redemption(user, redemption)\n @user = user\n @admin = redemption.reward.manager_with_default\n @reward = redemption.reward\n @redemption = redemption\n @mail_styler = company_styler(user.company)\n I18n.with_locale(user.locale) do\n mail(to: @user.email, subject: t(\"rewards.your_redemption_is_pending\", title: redemption.reward.title), track_opens: true)\n end\n end", "def eligible_for_referrer_reward?(user)\n user.sent_referrals.size % SENT_REFERRALS_TARGET == 0\n end", "def send_credits\n @users = User.all\n receiving_user = User.find(params[:id])\n amount_sent = user_params[:credit].to_i\n sending_updated_credits = current_user.credit - amount_sent\n receiving_updated_credits = receiving_user.credit + amount_sent\n if current_user.update_attributes(credit: sending_updated_credits)\n receiving_user.update_attributes(credit: receiving_updated_credits)\n @transaction = Transaction.create(from: current_user.id, to: params[:id], amount: amount_sent)\n flash[:notice] = \"Sucessfully sent #{amount_sent} credits to #{receiving_user.email}\"\n redirect_to users_url\n else \n flash[:errors] = ['Not enough credits, please add more']\n redirect_to users_url\n end \n end", "def lcb_user_reward_params\n params.require(:lcb_user_reward).permit(:lcb_user_id, :give_out, :activity_num, :reward_num, :owner_id, :create_uid, :write_uid, :id, :reward_desc)\n end", "def claim_reward_balance!(permlink); claim_reward_balance(permlink).broadcast!(true); end", "def claim_reward_balance!(permlink); claim_reward_balance(permlink).broadcast!(true); end", "def after_accepted\n # repute points\n self.repute_accept\n \n # cash rewards\n if self.kase && self.kase.offers_reward?\n self.kase.rewards.active.each do |reward|\n reward.cash!\n end\n end\n end", "def create_request\n Friendship.request(@user, @friend)\n flash[:notice] = \"Friend request sent.\"\n redirect_to :back\n end", "def owner_only_offers_reward?\n self.rewards_count == 1 && self.rewards.visible[0].sender == self.person\n end", "def create\n @reward = @publication.rewards.new(reward_params)\n\n respond_to do |format|\n if @reward.save\n format.html { redirect_to @publication, notice: 'Reward was successfully created.' }\n format.json { render :show, status: :created, location: @reward }\n else\n format.html { render :new }\n format.json { render json: @reward.errors, status: :unprocessable_entity }\n end\n end\n end", "def distribute_quest_reward(reward)\n @params = [reward[1], 0, 0, (reward[2] ? reward[2] : 1)]\n case reward[0]\n when :item, 0 then command_126 # Item\n when :weapon, 1 then command_127 # Weapon\n when :armor, 2 then command_128 # Armor\n when :gold, 3 # Gold\n @params = [0, 0, reward[1] ? reward[1] : 0]\n command_125\n when :exp, 4 # Exp\n @params = [0, 0, 0, 0, reward[1] ? reward[1] : 0, true]\n command_315\n end\n end", "def send_friendship_request(other_user)\n friendship_requests.create!(requested_user: other_user) if !self.friends_with?(other_user)\n end", "def after_redeem() end", "def update\n @reward_owner.update(reward_owner_params)\n @reward_owner = RewardOwner.new\n @reward_owners = RewardOwner.all\n end", "def create\n\t\tFriendship::request(@user, @friend)\n\t\tUserMailer::friend_request(\n\t\t\t:user => @user,\n\t\t\t:friend => @friend,\n\t\t\t:user_url => profile_for(@user),\n\t\t\t:accept_url => url_for(:action => \"accept\", :id => @user.screen_name),\n\t\t\t:decline_url => url_for(:action => \"decline\", :id => @user.screen_name)\n\t\t).deliver_now\n\t\tflash[:notice] = \"Friend request sent.\"\n\t\tredirect_to profile_for(@friend)\n\tend", "def grant_reward(user)\n score = user.score # get user score\n # for each category, get the value, if not nil, calculate new value for category\n attributes_to_update = {}\n [:stamina, :strength, :mind, :vitality, :agility].each do |reward_category|\n reward_value = send(\"#{reward_category}_reward\")\n if reward_value.present?\n # new_value = (score.send(reward_category).to_f * (1.0 + (reward_value.to_f / 100.0))).ceil\n new_value = score.send(reward_category).to_i + reward_value.to_i\n new_value = 100 if new_value > 100 # 100% max\n attributes_to_update[reward_category] = new_value\n end\n end\n score.update_attributes!(attributes_to_update)\n end", "def handleCredits\n @requestId = params[:request_id]\n @userMinusId = params[:user_id]\n @userPlusId = Request.find(@requestId).user_id\n\n @userMinus = User.find(@userMinusId)\n @userPlus = User.find(@userPlusId)\n\n @userMinus.credits = @userMinus.credits - 1\n @userPlus.credits = @userPlus.credits + 1\n\n @userMinus.save\n @userPlus.save\n\n # remove confirmed request\n Request.find(@requestId).destroy\n end", "def set_reward_owner\n @reward_owner = RewardOwner.find(params[:id])\n end", "def powerup_reward_field\n $tracer.trace(__method__)\n #unit_test_no_generate: powerup_reward_field, input.className(create_ats_regex_string(\"ats-purnumber\"))\n return ToolTag.new(input.className(create_ats_regex_string(\"ats-purnumber\")), __method__, self)\n end", "def bid\n @auction = Auction.find(params[:auction_id])\n @reward = Reward.find(params[:reward_id])\n @points_already_bid = current_user ? @reward.points_already_raised_by(current_user) : 0\n @donation = Donation.new\n @program = @auction.program\n @karma_page = false\n\n if @program\n @org = @program.organization\n @profile_fields = Profile.profile_fields(current_user, @org)[@org.url] # current_user could be nil\n if @program.auction_type == \"fixed\"\n @opportunities = Profile.fixed_opportunities_for(@org)\n @nonprofit = @org.nonprofits.first\n end\n end\n\n if current_user\n @current_karma = total_karma_for(current_user)\n else\n @current_karma = 0\n end\n\n if current_user && current_user.stripe_cus_id && !@org\n Stripe.api_key = ENV['STRIPE_SECRET_KEY']\n begin\n customer = Stripe::Customer.retrieve(current_user.stripe_cus_id)\n @default_card = customer.sources.retrieve(customer.default_card)\n rescue\n # If a similar Stripe object exists in live mode, but a test mode key was used to make this request.\n @default_card = nil\n end\n end\n end", "def active_reward_from?(person)\n !self.rewards.active.find(:all, :conditions => {:sender_id => person.id}).empty?\n end", "def new\n @goal_reward = user.goal_rewards.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @goal_reward }\n end\n end", "def can_reward_user?(reward)\n return false if reward.required_value.nil? || user.reload.nil?\n\n case reward_type\n when 'collected_coins'\n !user.rewards.include?(reward) && user.total_coins >= reward.required_value\n when 'deaths'\n !user.rewards.include?(reward) && user.deaths_count >= reward.required_value\n when 'killed_turtles'\n !user.rewards.include?(reward) && user.killed_turtles_count >= reward.required_value\n when 'killed_bowsers'\n !user.rewards.include?(reward) && user.killed_bowsers_count >= reward.required_value\n else\n false\n end\n end", "def push_transactions\n AirdropMint.push_transactions_for_pending_rewards(user)\n end", "def character_reward_params\n params[:character_reward]\n end", "def process_me\n\t\t@debit = Debit.find(params[:id])\n\t\tauthorize! :process_me, @debit, :message => \"Action Not Authorized\"\n\t\t@debit.status = \"ready\"\n\t\t@debit.save!( :validate => false )\n\t\tunless @debit.account.club.get_leader.nil?\n\t\t\tNotifier.claimed_email(@debit.account.club.get_leader, @debit).deliver\n\t\tend\n\t\tredirect_to club_path(@debit.account.club), :notice=>\"Debit Readied\"\n\tend", "def create\n @points_spent = PointsSpent.new(params[:points_spent])\n\n # Ensure user has enough points to make the purchase\n @student = Student.find(params[:points_spent][:student_id])\n @reward = Reward.find(params[:points_spent][:reward_id])\n if (@student.xp_gained - @student.xp_used) >= @reward.xp_cost\n # Set points_spent.xp_spent based on the reward chosen\n @points_spent.xp_spent = @reward.xp_cost\n end\n\n respond_to do |format|\n if !@points_spent.xp_spent.nil?\n if @points_spent.save\n flash[:success] = 'Reward granted. Points Spent.'\n format.html { redirect_to student_path(params[:points_spent][:student_id]) }\n format.json { render json: @points_spent, status: :created, location: @points_spent }\n else\n format.html { render action: \"new\" }\n format.json { render json: @points_spent.errors, status: :unprocessable_entity }\n end\n else\n flash[:error] = 'Not enough points to purchase selected reward.'\n format.html { redirect_to student_path(params[:points_spent][:student_id]) }\n end\n end\n end", "def create\n @mentorship_request = MentorshipRequest.new(mentorship_request_params)\n @mentorship_request.user = current_user\n @mentorship_request.status = 'Waiting'\n\n if @mentorship_request.save\n\n mentor_ids = Set[]\n @mentorship_request.tech.each do |t|\n ns = mentor_notifications_with_tech(t)\n ns.each do |n|\n mentor_ids.add(n.user_id)\n end\n end\n\n MentorshipNotification.where(all: true).each do |n|\n mentor_ids.add(n.user_id)\n end\n\n if HackumassWeb::Application::SLACK_ENABLED\n mentor_ids.each do |user_id|\n slack_notify_user(User.where(id: user_id).first.slack_id, \"New mentorship request: \\n #{@mentorship_request.title} \\n\\nfrom #{@mentorship_request.user.full_name}\\n\\nUrgency: #{@mentorship_request.urgency_str}\\n\\nTechnologies: #{@mentorship_request.tech}\\n\\nSee more details: https://#{HackumassWeb::Application::DASHBOARD_URL}/mentorship_requests/#{@mentorship_request.id}\")\n end\n slack_notify_user(@mentorship_request.user.slack_id, \"You just submitted a mentorship request: #{@mentorship_request.title} \\n\\nA mentor should slack you soon. Wait 15 minutes, and if you don't hear from anyone, go to the mentorship table. Best of luck with your issue!\")\n end\n\n redirect_to mentorship_requests_path, notice: 'Mentorship request successfully created. A mentor should contact you soon.'\n else\n render :new # New mentorship request if previous is unsuccessful\n end\n end", "def create\n\n @recharge = Recharge.recharge_by_credit_card(user: current_user, recharge: recharge_params)\n\n respond_to do |format|\n if @recharge.save\n\n # create recharge\n receipt = Receipt.create({user_id: @recharge.user.id, agent_id: @recharge.agent.id, amount: @recharge.amount, ip_address: request.remote_ip})\n receipt.save\n\n format.html { redirect_to @recharge, notice: 'Recharge was successfully created.' }\n else\n format.html { render action: 'new' }\n end\n end\n end", "def process_action(...)\n send_action(...)\n end", "def update\n respond_to do |format|\n if @reward.update(reward_params)\n format.html { redirect_to @reward, notice: 'Reward was successfully updated.' }\n format.json { render :show, status: :ok, location: @reward }\n else\n format.html { render :edit }\n format.json { render json: @reward.errors, status: :unprocessable_entity }\n end\n end\n end", "def notify_admin_of_redemption(user, redemption)\n @company = user.company\n @redemption = redemption\n @redeeming_user = user\n @reward = redemption.reward\n @reward_variant = redemption.reward_variant\n @reward_title = \"#{@reward.title} (#{@reward_variant.label})\"\n @mail_styler = company_styler(user.company)\n\n @admins, @approve_url = if @reward.manager.present?\n [[@reward.manager], manager_admin_redemptions_url(network: @company.domain)]\n else\n [@reward.company.company_admins, company_admin_redemptions_url(network: @company.domain)]\n end\n\n I18n.with_locale(user.locale) do\n mail(to: @admins.map(&:email), subject: t(\"rewards.user_has_redeemed\", name: @redeeming_user.full_name), track_opens: true)\n end\n end", "def allows_reward?\n self.class.allows_reward?\n end", "def buy_credits\n if request.post? || params[:PayerID]\n payment = params[:PayerID] ? current_user.credit_payments.where(payment_token: params[:token]).take : current_user.credit_payments.new(amount: params[:amount])\n make_payment_helper(payment, paypal_cancel_url: url_for(action: :index), success_msg: 'Credits successfully purchased!') do\n current_user.add_credits(payment.amount)\n end\n end\n end", "def accept\n @user = current_user\n @friend = User.find(params[:friend_id])\n @friendship_approved = @user.approve(@friend)\n @friends = @user.friends\n @pending_invited_by = @user.pending_invited_by\n l = Log.new\n l.user_id_1 = @user.id\n l.user_id_2 = @friend.id\n name_1 = if @user.name.nil? then @user.email.split('@')[0] else @user.name end\n name_2 = if @friend.name.nil? then @friend.email.split('@')[0] else @friend.name end\n l.message = \"#{name_1.humanize} accepted friendship of #{name_2.humanize}\"\n l.loggingtype = 0\n l.save\n # Author: Omar\n #adding the notification to the database on accepting a friendship request\n UserNotification.create(owner:@friend.id , user:@user.id, story:nil , comment:nil , notify_type:2 , new:true)\n @friend.notifications = @friend.notifications.to_i + 1\n @friend.save\n flash[:freindship_accept] = \"You and #{name_2.humanize} are now friends $green\"\n \n @user.rank = @user.rank + 4\n @user.save\n @friend.rank = @friend.rank + 4\n @friend.save\n\n redirect_to action: 'pending'\n end", "def mark_as_accepted\n @lead.accepted_at = DateTime.now\n @lead.response_time = @lead.accepted_at - @lead.created_at\n @lead.status = \"accepted\"\n @lead.save\n @users = User.all\n store_user_rankings(@users)\n UserMailer.forward(@lead).deliver_now\n if request.referer.nil?\n redirect_to user_path(@lead.user)\n else\n redirect_to :back\n end\n end", "def create\n @lcb_user_reward = LcbUserReward.new(lcb_user_reward_params)\n\n respond_to do |format|\n if @lcb_user_reward.save\n format.html { redirect_to @lcb_user_reward, notice: 'Lcb user reward was successfully created.' }\n format.json { render :show, status: :created, location: @lcb_user_reward }\n else\n format.html { render :new }\n format.json { render json: @lcb_user_reward.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @reward_type = RewardType.new(reward_type_params)\n\n respond_to do |format|\n if @reward_type.save\n format.html { redirect_to @reward_type, notice: 'Reward type was successfully created.' }\n format.json { render :show, status: :created, location: @reward_type }\n else\n format.html { render :new }\n format.json { render json: @reward_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @reservation = Reservation.new(params[:reservation])\n @reservation.user_id = current_user.id\n\n respond_to do |format|\n if @reservation.save\n\n # UserMailer.booking_create(current_user, @reservation).deliver\n # OwnerMailer.booking_create(@reservation).deliver\n\n Reward.create( user_id: @reservation.user_id, \n reservation_id: @reservation.id, \n points_total: 5*@reservation.party_size, \n points_pending: 5*@reservation.party_size, \n description: \"\")\n \n format.html { redirect_to @reservation, notice: 'Reservation was successfully created.' }\n format.json { render json: @reservation, status: :created, location: @reservation }\n else\n format.html { render action: \"new\" }\n format.json { render json: @reservation.errors, status: :unprocessable_entity }\n end\n end\n end", "def draw_reward(r_id, y)\n reward = @quest.rewards[r_id]\n case reward[0]\n when :item, 0 # Item\n draw_item_reward(y, $data_items[reward[1]], reward[2] ? reward[2] : 1)\n when :weapon, 1 # Weapon\n draw_item_reward(y, $data_weapons[reward[1]], reward[2] ? reward[2] : 1)\n when :armor, 2 # Armor\n draw_item_reward(y, $data_armors[reward[1]], reward[2] ? reward[2] : 1)\n when :gold, 3 # Gold\n draw_basic_data(y, QuestData::ICONS[:reward_gold], \n QuestData::VOCAB[:reward_gold], (reward[1] ? reward[1] : 0).to_s)\n when :exp, 4 # Exp\n draw_basic_data(y, QuestData::ICONS[:reward_exp], \n QuestData::VOCAB[:reward_exp], (reward[1] ? reward[1] : 0).to_s)\n when :string, 5 # String\n draw_basic_data(y, reward[1] ? reward[1] : 0, reward[3] ? reward[3].to_s : \"\", \n reward[2] ? reward[2].to_s : \"\")\n end\n end", "def create\n @reward_profile = RewardProfile.new(params[:reward_profile])\n\n respond_to do |format|\n if @reward_profile.save\n flash[:notice] = 'RewardProfile was successfully created.'\n format.html { redirect_to(@reward_profile) }\n format.xml { render :xml => @reward_profile, :status => :created, :location => @reward_profile }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @reward_profile.errors, :status => :unprocessable_entity }\n end\n end\n end", "def weapon_reward(available_weapons)\n\n #reward is 1 random choice from this array\n reward = available_weapons.sample\n\n #create to CharacterWeapon object to show that player obtains weaopn\n CharacterWeapon.new_character_weapon(self.id, reward.id)\n\n #print weapon details to player\n puts \"#{reward.name}\".bold.blue\n puts \"Weapon Power: #{reward.attack_power}\"\n puts\"#####################################\".blink\n\n #actually equip the weapon, if it will increase this player's attack power\n if reward.attack_power > self.power - 1 || self.power == 1\n #increase the player's attack power\n self.update(power: 1+reward.attack_power)\n end\n end", "def update\n respond_to do |format|\n if @api_v1_reward.update(api_v1_reward_params)\n format.html { redirect_to @api_v1_reward, notice: 'Reward was successfully updated.' }\n format.json { render :show, status: :ok, location: @api_v1_reward }\n else\n format.html { render :edit }\n format.json { render json: @api_v1_reward.errors, status: :unprocessable_entity }\n end\n end\n end", "def check_for_breach\n return nil if pledges.empty? || breached?\n\n funding_goal_breached = funded? && (total_pledged - pledges.last.amount) < funding_goal\n half_funding_goal_breached = funded?(0.50) && (total_pledged - pledges.last.amount) < (funding_goal / 2)\n\n # return if there is nothing to do\n return nil unless funding_goal_breached || half_funding_goal_breached\n\n # it was breached!\n if funding_goal_breached\n update_attributes breached: true, breached_at: DateTime.now\n\n # email the fundraiser creator\n person.send_email :notify_creator_of_fundraiser_breached, fundraiser: self\n\n # email all of the backers\n backers.map { |b| b.send_email :notify_backers_of_fundraiser_breached, fundraiser: self }\n\n # send survey emails to backers that selected a reward which requires more info\n rewards.find_each do |reward|\n reward.pledges.joins(:reward).each(&:send_survey_email) if reward.fulfillment_details?\n end\n\n # last but not least... pay the creator!\n payout!\n end\n\n # half way there, and it wasn't just breached\n if half_funding_goal_breached && !funding_goal_breached\n # email the fundraiser creator\n person.send_email :notify_creator_of_fundraiser_half_completion, fundraiser: self\n\n # email all of the backers\n backers.map { |b| b.send_email :notify_backers_of_fundraiser_half_completion, fundraiser: self }\n end\n end", "def send_bonus!(amt)\n mturk_bonus_assignment(self.mturk_assignment_id, self.mturk_worker_id, amt)\n self.update_attributes(:bonus => amt)\n end", "def amazon_postfill\n unless params[:callerReference].blank?\n @order = Order.postfill!(params)\n end\n # \"A\" means the user cancelled the preorder before clicking \"Confirm\" on Amazon Payments.\n if params['status'] != 'A' && @order.present?\n redirect_to :action => :share, :uuid => @order.uuid\n else\n redirect_to root_url\n end\n end", "def process( wallet )\n\t\tself.add_block do\n\t\t\tself.add_transaction( from: GENESIS_WALLET, to: wallet, amount: MINING_REWARD )\n\t\tend\n\tend", "def set_reward(reward)\n self.send(\"current_#{reward.class.to_s.underscore}=\",reward)\n end", "def update\n respond_to do |format|\n if @reward.update(reward_params)\n format.html { redirect_to @publication, notice: 'Reward was successfully updated.' }\n format.json { render :show, status: :ok, location: @reward }\n else\n format.html { render :edit }\n format.json { render json: @reward.errors, status: :unprocessable_entity }\n end\n end\n end", "def pay_blinds\n @dealer.pay(@game.small_blind)\n @under_the_gun.pay(@game.big_blind)\n end", "def do_pay\n self.paid_at = Time.now.utc\n self.send_paid\n end", "def create\n @friendship = Friendship.new(params[:friendship])\n current_user.un_black_ball(@friendship.proposee)\n @user = @friendship.proposee\n respond_to do |format|\n if @friendship.save\n format.html { redirect_to @friendship, notice: \"Your Friend Request was sent\" }\n format.json { render json: @friendship, status: :created, location: @friendship }\n format.js {}\n else\n format.html { render action: \"new\" }\n format.js {}\n format.json { render json: @friendship.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @reward.update(reward_params)\n format.html { redirect_to mypage_product_path(@product), notice: 'Reward was successfully updated.' }\n format.json { render :show, status: :ok, location: @reward }\n else\n format.html { render :edit }\n format.json { render json: @reward.errors, status: :unprocessable_entity }\n end\n end\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 process\n send_request @action\n end", "def find_reputation_points(reputable, destination, action, tier=nil)\n ReputationReward.action_points(reputable, destination, action, tier=nil)\n end", "def send_payment_and_dispose!\n mturk_bonus_assignment(self.mturk_assignment_id, self.mturk_worker_id)\n mturk_approve_assignment(self.mturk_assignment_id)\n self.update_attributes(:paid_at => Time.now)\n dispose_hit_on_mturk(self.mturk_hit_id) #we can also delete it on mturk, tidy up\n end", "def dean_approve_awards(user)\n for award in awards.valid\n award.update_attribute(:amount_awarded, award.amount_requested) if award.amount_awarded.blank?\n award.update_attribute(:amount_awarded_user_id, user.id)\n end\n update_attribute(:approved_at, Time.now)\n end", "def sendAsGift\n end", "def donate\n\n @context_user = @receiver.user\n \n # Test that the transfer money between the two people is a viable option\n rec_acc = @receiver.monetary_processor_account\n pay_acc = @sender.monetary_processor_account\n \n rec_usid = rec_acc.account_identifier\n pay_usid = pay_acc.account_identifier\n \n @donation.update_attributes do |d|\n d.receiver_wmid = rec_acc\n d.sender_wmid = pay_acc\n end\n store_donation\n \n res = WebMoney::Ext::Client.get_max_transaction_amount(pay_usid, rec_usid, @donation.purse_type[0].to_i)\n \n # Verify maximum transaction possible\n @max_amount = res.maxAmount\n if @max_amount < @amount.to_f\n @amount = @max_amount\n if @amount.to_i != -1\n flash.now[:warning] = \"The maximum that you can contribute is %s.\" / \"#{@amount}\"\n end\n end\n \n # We are confirmed, lets do it!\n if params[:confirm]\n \n # confirm their password\n @account_setting = current_user.account_setting\n unless @account_setting.validate_password(current_user,params[:password])\n flash.now[:error] = \"Invalid Password\".t\n return\n end\n \n # want to see the result logged for debugging?\n # WebMoney::Ext::Client.config.merge!({:debug => true, :wiredump => true})\n transfer = WebMoneyTransfer.create(\n :source_wmid => @sender.webmoney_account,\n :destination_wmid => @receiver.webmoney_account,\n :purse_type => @donation.purse_type[0].to_i,\n :amount => @donation.amount)\n \n res = WebMoney::Ext::Client.send_funds(\n pay_usid,\n rec_usid,\n transfer.request_number,\n @donation.purse_type[0].to_i,\n @donation.amount,\n @donation.item_name)\n \n if res.errordesc == 'Success'\n MonetaryDonation.from_webmoney_donation(@donation).save\n \n transfer.update_attribute(:success, true)\n flash[:success] = \"You have successfully transfered %s\" / [@donation.amount]\n clear_donation\n redirect_back_or_default '/'\n else\n transfer.update_attributes(:success => false, :response => res.errordesc)\n flash.now[:error] = res.errordesc.t\n end\n end\n end" ]
[ "0.62571675", "0.6154065", "0.6122438", "0.6039495", "0.6003704", "0.59771526", "0.5963008", "0.5954132", "0.5932498", "0.59322613", "0.59250814", "0.5878585", "0.5833457", "0.5800626", "0.57559234", "0.57546043", "0.5743966", "0.572459", "0.5718811", "0.56481206", "0.5639043", "0.56353474", "0.56295186", "0.56224537", "0.56070626", "0.5602804", "0.5585376", "0.55653185", "0.5544904", "0.5532034", "0.55176896", "0.55074555", "0.5499537", "0.5494016", "0.54814065", "0.54757553", "0.54728556", "0.54679126", "0.54679126", "0.54679126", "0.5454037", "0.54418314", "0.5434651", "0.54300594", "0.54300284", "0.54300284", "0.54277277", "0.54082465", "0.5407586", "0.54060847", "0.5403627", "0.5402906", "0.5390901", "0.5390776", "0.5381775", "0.5376708", "0.5363802", "0.5345534", "0.53325605", "0.5315338", "0.53147846", "0.52942014", "0.5291543", "0.5280409", "0.5278363", "0.5276963", "0.5265953", "0.52619696", "0.52572286", "0.5228322", "0.5223789", "0.5212246", "0.52107155", "0.5208042", "0.52013797", "0.5199134", "0.5198509", "0.5193265", "0.5189098", "0.5188781", "0.51811284", "0.51796883", "0.5176126", "0.51687044", "0.51579887", "0.51571286", "0.5154874", "0.5153618", "0.5149391", "0.51490206", "0.51446265", "0.5142331", "0.51387346", "0.513767", "0.51340103", "0.5128158", "0.51276165", "0.51208854", "0.5118638", "0.51164466" ]
0.7573464
0
reward_receiver_router_user_payment_reward_receivers GET /users/:user_id/payment/reward_receivers/:reward_receiver_id/:reward_receiver_router/reward_receiver_router def reward_receiver_router case params[:reward_receiver_router] when 'request_shipping_fee' redirect_to request_shipping_fee_user_payment_reward_receivers_path(params[:user_id], params[:reward_receiver_id]) end end request_shipping_fee_user_payment_reward_receivers GET /users/:user_id/payment/reward_receivers/:reward_receiver_id/request_shipping_fee
def request_shipping_fee @reward = Reward.find(@reward_receiver.reward_id) #Select shipping amount based on different situiations if @reward.shippings.where(country: @reward_receiver.shipping_address.country).first @amount = @reward.shippings.where(country: @reward_receiver.shipping_address.country).first.amount else if @reward.shipping_anywhere @amount = @reward.shipping_anywhere.amount end end if @shipping_order = ShippingOrder.find_by_reward_receiver_id(@reward_receiver.id) else @shipping_order = ShippingOrder.create( user_id: @reward_receiver.user_id, amount: @amount, currency: @reward.currency, status: 'Sent', country: @reward_receiver.shipping_address.country, city: @reward_receiver.shipping_address.city, line1: @reward_receiver.shipping_address.line1, postal_code: @reward_receiver.shipping_address.postal_code, state: @reward_receiver.shipping_address.state, name: @reward_receiver.shipping_address.name, reward_id: @reward_receiver.reward_id, reward_receiver_id: @reward_receiver.id, due: 30.days.from_now ) end @reward_receiver.update( status: 'shipping_fee_request_sent' ) #Send order email Payment::ShippingOrdersMailer.send_confirmation(shipping_order_id: @shipping_order.id).deliver_now #Send order notification Notification.create( user_id: @reward_receiver.user_id, trackable_id: @shipping_order.id, trackable_type: "ShippingOrder", notification_type: "send_shipping_order_confirmation" ) redirect_to(:back) end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_route_target server_type, msg, route_param, &block\n if @router_type\n router = case @router_type\n when :roundrobin\n method :rr_route\n when :weight_roundrobin\n method :wrr_route\n when :least_active\n method :la_route\n when :consistent_hash\n method :ch_route\n else\n method :rd_route\n end\n router.call(self, server_type, msg) { |err, server_id|\n block_given? and yield err, server_id\n }\n else\n unless @router.respond_to? :call\n block_given? and yield Exception.new 'invalid router method'\n return\n end\n @router.call(route_param, msg, @route_context) { |err, server_id|\n block_given? and yield err, server_id\n }\n end\n end", "def menu_routing(user, game, router, tracer=2)\n exit_game_reviews if router == 1\n main_menu(user) if router == 2\n login if router == 3\n logout(user) if router == 4\n create_account if router == 5\n my_account(user) if router == 6\n delete_account(user) if router == 7\n choose_game(user) if router == 8\n game_reviews(user, game, tracer) if router == 9\n write_review(user, game, tracer) if router == 10\n update_review(user, game, tracer) if router == 11\n change_name(user) if router == 12\n my_reviews(user, game, tracer) if router == 13\n choose_game(user) if router == 14\n game_menu(user, game, tracer) if router == 15\n update_review_rating(user, game, tracer) if router == 16\n update_review_text(user, game, tracer) if router == 17\n delete_review(user, game, tracer) if router == 18\n read_review(user, Game.find(Review.find(router / 100).game_id), Review.find(router / 100), tracer) if router > 99\nend", "def redirect_returning_user(pathway, options = {})\n params = {}\n case pathway\n\t when \"gift_sent\"\n params[:action] = \"show_organization\"\n params[:organization_id] = options['organization_id']\n\t when \"self\"\n params[:action] = \"give_gift_self\"\n params[:gift_template_id] = options['gift_template_id']\n\t when \"friend\"\n params[:action] = \"give_gift_friends\"\n params[:gift_template_id] = options['gift_template_id']\n\t else\n\t\t flash[:notice] = \"We're sorry, but something went wrong. Please try again.\"\n params[:action] = \"index\"\n\t end\n redirect_to(params) and return\n end", "def respond(received)\n case received['type']\n\n when 'JOINING_NETWORK'\n puts('JOINING_NETWORK')\n\n # Reply with ROUTING_INFO\n @socket.send @msg.ROUTING_INFO(@id, received['node_id'], @port , @rt.getRoutingTableToSend(@port)), 0, '127.0.0.1', received['ip_address']\n\n # Put joining node in routing table\n @rt.updateRoutingTable(received['node_id'], received['ip_address'])\n\n # If there is a node closer to target in routing table forward JOINING_NETWORK_RELAY\n if @rt.routing_table.length > 0\n closest_node_ip = @rt.findCloserNode(received['target_id'], received['node_id'])\n if closest_node_ip != nil\n @socket.send @msg.JOINING_NETWORK_RELAY(received['node_id'], received['target_id'], @id), 0, '127.0.0.1', closest_node_ip\n end\n end\n\n when 'JOINING_NETWORK_RELAY'\n puts('JOINING_NETWORK_RELAY')\n\n # If not target, forward JOINING_NETWORK_RELAY to closer node\n if received['node_id'] != @id\n closest_node_ip = @rt.findCloserNode(received['target_id'], received['node_id'])\n if !closest_node_ip.nil?\n @socket.send @msg.JOINING_NETWORK_RELAY(received['node_id'], received['target_id'], received['gateway_id']), 0, '127.0.0.1', closest_node_ip\n end\n end\n\n # Send ROUTING_INFO to gateway node\n closest_node_ip = @rt.findCloserNode(received['gateway_id'], nil)\n if !closest_node_ip.nil?\n @socket.send @msg.ROUTING_INFO(received['gateway_id'], received['node_id'], @port, @rt.getRoutingTableToSend(@port)), 0, '127.0.0.1', closest_node_ip\n end\n\n when 'ROUTING_INFO'\n puts('ROUTING_INFO')\n\n # Store received routing info\n received['route_table'].each do |x|\n @rt.updateRoutingTable(x['node_id'], x['ip_address'])\n end\n\n # If this is the gateway node forward ROUTING_INFO to joining node\n if received['gateway_id'] == @id\n joining_ip = @rt.routing_table.detect{|x| x[:node_id] == received['node_id']}[:ip_address]\n @socket.send @msg.ROUTING_INFO(@id, received['node_id'], @port, received['route_table']), 0, '127.0.0.1', joining_ip\n end\n\n # If message not intended for this node send it closer to target\n if received['node_id'] != @id\n closest_node_ip = @rt.findCloserNode(received['gateway_id'], nil)\n if !closest_node_ip.nil?\n @socket.send @msg.ROUTING_INFO(received['gateway_id'], received['node_id'], @port, received['route_table']), 0, '127.0.0.1', closest_node_ip\n end\n end\n\n when 'LEAVING_NETWORK'\n puts('LEAVING_NETWORK')\n @rt.deleteRoutingTableEntry(received['node_id']) # Delete leaving node from routing table\n\n when 'INDEX'\n puts('INDEX')\n\n # If message is intended for this node\n if received['target_id'] == @id\n\n # Store new index\n @index.addIndex(received['keyword'], received['link'])\n\n # Respond with ACK_INDEX\n closest_node_ip = @rt.findCloserNode(received['sender_id'], nil)\n if !closest_node_ip.nil?\n @socket.send @msg.ACK_INDEX(received['sender_id'], received['keyword']), 0, '127.0.0.1', closest_node_ip\n end\n\n # If message not for this node, send closer to target\n else\n closest_node_ip = @rt.findCloserNode(received['target_id'], nil)\n if !closest_node_ip.nil?\n @socket.send @msg.INDEX(received['target_id'], received['sender_id'], received['keyword'], received['link']), 0, '127.0.0.1', closest_node_ip\n end\n end\n\n when 'SEARCH'\n puts('SEARCH')\n\n # If message is intended for this node ger results and send SEARCH_RESPONSE\n if received['node_id'] == @id\n closest_node_ip = @rt.findCloserNode(received['sender_id'], nil)\n if !closest_node_ip.nil?\n @socket.send @msg.SEARCH_RESPONSE(received['word'], received['sender_id'], @id, @index.getKeywordIndexes(received['word'].to_s)), 0, '127.0.0.1', closest_node_ip\n end\n\n # If message not for this node, send closer to target\n else\n closest_node_ip = @rt.findCloserNode(received['node_id'], nil)\n if !closest_node_ip.nil?\n @socket.send @msg.SEARCH(received['word'], received['node_id'], received['sender_id']), 0, '127.0.0.1', closest_node_ip\n end\n end\n\n when 'SEARCH_RESPONSE'\n puts('SEARCH_RESPONSE')\n\n # If message is intended for this node\n if received['node_id'] == @id\n\n received['response'].each do |x|\n result = SearchResult.new(received['word'], x['url'], x['rank'])\n ap result\n end\n\n # If message is not intended for this node, send closer to target\n else\n closest_node_ip = @rt.findCloserNode(received['node_id'], nil)\n if !closest_node_ip.nil?\n @socket.send @msg.SEARCH_RESPONSE(received['word'], received['node_id'], received['sender_id'], received['response']), 0, '127.0.0.1', closest_node_ip\n end\n end\n\n when 'PING'\n puts('PING')\n\n # Respond with ACK\n @socket.send @msg.ACK(received['target_id'], @port), 0, '127.0.0.1', received['ip_address']\n\n # Send PING to next node if not final target\n if received['target_id'] != @id\n\n # Send closer to target\n closest_node_ip = @rt.findCloserNode(received['target_id'], nil)\n if !closest_node_ip.nil?\n @socket.send @msg.PING(received['target_id'], received['sender_id'], @port), 0, '127.0.0.1', closest_node_ip\n @pinged_ip = closest_node_ip\n\n # Wait up to 10s for ACK\n time = Time.now\n while Time.now - time < 10 && !@ack_received\n end\n\n # If no ACK received delete node from routing table\n if !@ack_received\n @rt.deleteRoutingTableEntry(@rt.routing_table.detect{|x| x[:ip_address == closest_node_ip]}[:node_id]) # Delete from routing table\n else\n @ack_received = false # If ACK received reset value to false\n end\n end\n end\n\n when 'ACK'\n puts('ACK')\n\n if received['ip_address'] == @pinged_ip # If ACK is from expected node\n @ack_received = true # Indicate that ACK has been received\n end\n\n when 'ACK_INDEX'\n puts('ACK_INDEX')\n\n # If message is intended for this node\n if received['node_id'] == @id\n @ack_index_received = true # Indicate that ACK_INDEX has been received\n\n # If message not intended for this node, send closer to target\n else\n closest_node_ip = @rt.findCloserNode(received['node_id'], nil)\n if !closest_node_ip.nil?\n @socket.send @msg.ACK_INDEX(received['node_id'], received['keyword']), 0, '127.0.0.1', closest_node_ip\n end\n end\n\n end\n end", "def route() request.route end", "def redirect\n if params[:role] == \"restaurant\"\n redirect_to :action => \"new\", :invitation => { :first_name => params[:first_name], :last_name => params[:last_name], :email => params[:email] }\n elsif params[:role] == \"media\"\n redirect_to :controller => \"mediafeed/media_users\", :action => \"new\", :user => { :first_name => params[:first_name], :last_name => params[:last_name], :email => params[:email] }\n end\n end", "def redirect_place #returns the place to redirect to based on origin\n if safe_params[:origin] == \"individual\"\n return (tournament_path(@tournament) + '/registration/individual');\n elsif safe_params[:origin] == \"adjudicators\"\n return (tournament_path(params[:id]) + '/control/adjudicators');\n else\n puts(\"Hack ###\");\n redirect_to root_path;\n return;\n end\n end", "def process( data_exchange )\n validate_instance_variables( binding(), :routes )\n _info(\"Routing exchange from #{origin(data_exchange)}.\")\n unless routes.redirect? data_exchange\n _info(\"Routing failed for exchange #{origin(data_exchange)}.\")\n set_fault( data_exchange )\n end\n end", "def dynamic_reroute\n\n\t#get all passengers\n\tpassengers = Array.new\n\tweb_passengers = WebPassenger.all\n\n\t#cull out passengers that has been picked by a bus\n\tweb_passengers.each do |webPassenger|\n\t\tunless webPassenger.web_bus == nil \n\t\t\tweb_passengers = web_passengers - [webPassenger]\n\t\tend\n\tend\n\n\t#gets all the unhandled locations from database\n\tweb_passengers.each do |passenger| \n\t\tunless passenger.web_locations[0] == nil || passenger.web_locations[1] == nil\n\t\t\tloc_pick = passenger.web_locations.find(:first, :conditions => {:is_pickup => true})\n\t\t\tloc_drop = passenger.web_locations.find(:first, :conditions => {:is_dropdown => true})\n=begin\n\t\t\tif passenger.web_locations[0].is_pickup\n\t\t\t\tloc_pick = Location.new( passenger.web_locations[0].latitude, passenger.web_locations[0].longitude )\n\t\t\t\tloc_drop = Location.new( passenger.web_locations[1].latitude, passenger.web_locations[1].longitude )\n\t\t\telse\n\t\t\t\tloc_pick = Location.new( passenger.web_locations[1].latitude, passenger.web_locations[1].longitude )\n\t\t\t\tloc_drop = Location.new( passenger.web_locations[0].latitude, passenger.web_locations[0].longitude )\n\t\t\tend\n=end\n\t\t\tpassengers << Passenger.new( loc_pick, loc_drop )\n\t\tend\n\tend\n\n\t#gets all the locations from bus paths and store them into web_pathes\n\tweb_pathes = Array.new\n\tweb_buses = WebBus.all\n\tweb_buses.each do |web_bus|\n\t\tweb_locs = web_bus.web_locations.sort_by {|a| a.order_num }\n\t\tweb_pathes << web_locs\n\tend\n\n\tpassengers.each do |passenger|\n\t\tweb_pathes.each do |web_path|\n\t\t\ttemp_var1 = 0\n\t\t\ttemp_order1 = 0\n\t\t\ttemp_var2 = 0\n\t\t\ttemp_order2 = 0\n\t\t\tfor i in 1...(web_path.length)\n\t\t\t\tif temp_var1 == 0 || temp_var1 == -1\n\t\t\t\ttemp_var1 = intersection_chk(web_path[i-1].longitude, web_path[i-1].latitude, web_path[i].longitude, web_path[i].latitude, passenger.pick_location.longitude, passenger.pick_location.latitude, $distance_justification_num)\n\t\t\t\ttemp_inc1 = temp_var1 / intersection_chk(web_path[i-1].longitude, web_path[i-1].latitude, web_path[i].longitude, web_path[i].latitude, web_path[i].longitude, web_path[i].latitude, $distance_justification_num)\n\t\t\t\ttemp_inc1 = temp_inc1 * (web_path[i].order_num - web_path[i-1].order_num) #deBUG segment interval not always equal to reroute_insertion_space_num \n\t\t\t\ttemp_order1 = web_path[i-1].order_num\n\t\t\t\tend\n\t\t\t\tif temp_var2 == 0 || temp_var2 == -1\n\t\t\t\ttemp_var2 = intersection_chk(web_path[i-1].longitude, web_path[i-1].latitude, web_path[i].longitude, web_path[i].latitude, passenger.drop_location.longitude, passenger.drop_location.latitude, $distance_justification_num)\n\t\t\t\ttemp_inc2 = temp_var2 / intersection_chk(web_path[i-1].longitude, web_path[i-1].latitude, web_path[i].longitude, web_path[i].latitude, web_path[i].longitude, web_path[i].latitude, $distance_justification_num)\n\t\t\t\ttemp_inc2 = temp_inc2 * (web_path[i].order_num - web_path[i-1].order_num)\n\t\t\t\ttemp_order2 = web_path[i-1].order_num\n\t\t\t\tend\n\t\t\tend\n\t\t\tif (temp_var2 > temp_var1) && (temp_var1 > 0) && temp_order1 == temp_order2 #pick and drop in the same segment\n\t\t\t\t#case 1\n\t\t\t\tpick_loc = WebLocation.find(:first, :conditions => [\"latitude = ? and longitude = ?\", passenger.pick_location.latitude, passenger.pick_location.longitude])\n\t\t\t\tdrop_loc = WebLocation.find(:first, :conditions => [\"latitude = ? and longitude = ?\", passenger.drop_location.latitude, passenger.drop_location.longitude])\n\t\t\t\tweb_pas = pick_loc.web_passenger\n\t\t\t\t#use temp_order1 + 1 as the pick_location's order_num\n\t\t\t\tpick_loc.order_num = temp_order1 + temp_inc1\n\t\t\t\t#use temp_order2 + 2 as the drop_location's order_num\n\t\t\t\tdrop_loc.order_num = temp_order2 + temp_inc2 \n\t\t\t\t#assign the current bus as pick/drop location's web bus\n\t\t\t\tpick_loc.web_bus = web_path[0].web_bus\n\t\t\t\tdrop_loc.web_bus = web_path[0].web_bus\n\t\t\t\tweb_pas.web_bus = web_path[0].web_bus\n\t\t\t\tif capacity_chk(pick_loc.web_bus) \n\t\t\t\t\tpick_loc.save\n\t\t\t\t\tdrop_loc.save\n\t\t\t\t\tweb_pas.save\n\t\t\t\tend\n\t\t\telsif (temp_var1 > 0) && (temp_var2 > 0) && temp_order2 > temp_order1 #pick and drop in different segments\n\t\t\t\t#case 1\n\t\t\t\tpick_loc = WebLocation.find(:first, :conditions => [\"latitude = ? and longitude = ?\", passenger.pick_location.latitude, passenger.pick_location.longitude])\n\t\t\t\tdrop_loc = WebLocation.find(:first, :conditions => [\"latitude = ? and longitude = ?\", passenger.drop_location.latitude, passenger.drop_location.longitude])\n\t\t\t\tweb_pas = pick_loc.web_passenger\n\t\t\t\t#use temp_order1 + 1 as the pick_location's order_num\n\t\t\t\tpick_loc.order_num = temp_order1 + temp_inc1\n\t\t\t\t#use temp_order2 + 1 as the pick_location's order_num\n\t\t\t\tdrop_loc.order_num = temp_order2 + temp_inc2\n\t\t\t\t#assign the current bus as pick/drop location's web bus\n\t\t\t\tpick_loc.web_bus = web_path[0].web_bus\n\t\t\t\tdrop_loc.web_bus = web_path[0].web_bus\n\t\t\t\tweb_pas.web_bus = web_path[0].web_bus\n\t\t\t\tif capacity_chk(pick_loc.web_bus) \n\t\t\t\t\tpick_loc.save\n\t\t\t\t\tdrop_loc.save\n\t\t\t\t\tweb_pas.save\n\t\t\t\tend\n\t\t\telsif (temp_var1 > 0)\n\t\t\t\t#case 2\n\t\t\telsif (temp_var1 == -1)\n\t\t\t\t#case 3\n\t\t\tend\n\t\tend\n\tend\nend", "def route_based_on_status\n status = group_invite_status&.status\n case status\n when \"unaccepted\", nil\n redirect_to group_assignment_invitation_path(invitation)\n when \"completed\"\n redirect_to successful_invitation_group_assignment_invitation_path if action_name != \"successful_invitation\"\n when *(GroupInviteStatus::ERRORED_STATUSES + GroupInviteStatus::SETUP_STATUSES)\n redirect_to setup_group_assignment_invitation_path if action_name != \"setup\"\n else\n raise InvalidStatusForRouteError, \"No route registered for status: #{status}\"\n end\n end", "def make method\n if params.include?(:user)\n @payment_type_id = params[:user][:payment_type_id].to_i\n @form_url = @user.subscribed_to < Time.zone.now ? make_payment_path(I18n.locale) : make_authorization_path(I18n.locale)\n @method = @user.subscribed_to ? 'sale' : 'authorization'\n case @payment_type_id\n when 1\n self.paypal method\n when 2..3\n self.card method\n else\n redirect_to request.referer, alert: t(:bad_payment, :scope => 'payments.errors') and return\n end\n else\n redirect_to request.referer, alert: t(:no_payment, :scope => 'payments.errors')\n end\n end", "def route14\n end", "def ship_reward_now\n\t\t@reward_receiver = RewardReceiver.find(params[:reward_receiver_id])\n\t\t@reward_receiver.update(reward_receiver_params)\n\t\tif @reward_receiver.update(\n\t\t\tstatus: \"shipped\"\n\t\t)\n\t\t#Send email\n\t\t#Send notification\n\t\t#Add xp\n\t\t@user.add_score(\"ship_reward\")\n\t\tend\n\t\tredirect_to show_user_studio_rewards_path(@reward_receiver.reward.user_id,@reward_receiver.reward_id)\n\tend", "def route(t_obj, value)\n if self.class.common_route\n route_id = @routes.detect{|r| r.name == value}.try(:id)\n t_obj.pickup_route_id = route_id\n t_obj.drop_route_id = route_id\n end\n end", "def set_routes(my_port, name, node_type, keys)\r\n # Give Access To This Node's Name\r\n get \"/peer_name\" do\r\n return name\r\n end\r\n # Give Access To This Node's Type (Client/Miner)\r\n get \"/peer_type\" do\r\n return node_type.to_s\r\n end\r\n # Give Access To This Node's Public Key For Validation & Handshake\r\n get \"/peer_key_public\" do\r\n return \"#{keys[0]},#{keys[2]}\"\r\n end\r\n # Give Access To This Node's Discovered Peers\r\n get \"/peer_peers\" do\r\n peer_ports = \"\"\r\n $peers.length.times do |i|\r\n peer_ports += \",\" if (i != 0)\r\n peer_ports += $peers[i].port.to_s\r\n end\r\n return peer_ports\r\n end\r\n # Another Peer Requests Handshake\r\n post \"/peer_handshake\" do\r\n port = params[\"port\"].chomp.to_i\r\n signature = params[\"signature\"].chomp.to_i\r\n timestamp = params[\"timestamp\"].chomp.to_i\r\n # Handshake Only With Undiscovered Peers\r\n if (search_peers_by_port(port) == -1)\r\n key_public = Faraday.get(\"#{URL}:#{port}/peer_key_public\").body\r\n key_public = key_public.split(\",\") # Convert String To Array\r\n # Validate Node's Authenticity Using RSA Decryption\r\n if (validate_signature(key_public, signature, timestamp))\r\n add_peer(port)\r\n handshake_peer(my_port, port, [keys[1], keys[2]])\r\n end\r\n end\r\n end\r\n # Request To Mine A Block\r\n post \"/mine_block\" do\r\n amount = params[\"amount\"].to_s\r\n payer = params[\"payer\"].to_s\r\n timestamp = params[\"timestamp\"].to_s\r\n signature = params[\"signature\"].to_s\r\n prev_hash = params[\"prev_hash\"].to_s\r\n payee = params[\"payee\"].to_s\r\n miner = my_port.to_s\r\n\r\n payer_peer = search_peers_by_port(payer)\r\n if (payer_peer != -1 && payer_peer.node_type != 3) # Validate if peer exists and is not rogue\r\n mine(amount, payer, payee, miner, timestamp, signature, prev_hash)\r\n else\r\n puts \"Denied mining request from rogue node\".red\r\n $status = \"Denied mining request from rogue node\"\r\n end\r\n end\r\n # Recieve A Mined Block\r\n post \"/block_mined\" do\r\n amount = params[\"amount\"].to_s\r\n payer = params[\"payer\"].to_s\r\n payee = params[\"payee\"].to_s\r\n miner = params[\"miner\"].to_s\r\n timestamp = params[\"timestamp\"].to_s\r\n signature = params[\"signature\"].to_s\r\n prev_hash = params[\"prev_hash\"].to_s\r\n nonce = params[\"nonce\"].to_s\r\n # Add Block If Not Already Mined\r\n block_exists = check_if_block_exists(miner.to_i, timestamp.chomp.to_i)\r\n add_block(amount, payer, payee, miner, timestamp, signature, prev_hash, nonce, true) if (!block_exists)\r\n end\r\n # Peer Sent A Mined Block\r\n post \"/broadcast_block\" do\r\n amount = params[\"amount\"].to_f\r\n signature = params[\"signature\"].to_s\r\n timestamp = params[\"timestamp\"].to_i\r\n prev_hash = params[\"prev_hash\"].to_s\r\n nonce = params[\"nonce\"].to_s\r\n hash = params[\"hash\"].to_s\r\n payer = params[\"payer\"].to_i\r\n payee = params[\"payee\"].to_i\r\n miner = params[\"miner\"].to_i\r\n\r\n payer_peer = search_peers_by_port(payer)\r\n if (prev_hash == \"0000000000000000000000000000000000000000000000000000000000000000\" && $blockchain.length > 0)\r\n # Genesis Node is being shared with everyone, this node does not require as it already has a chain. Ignore.\r\n else\r\n if (payer_peer != -1 && payer_peer.node_type != 3) # Validate if peer exists and is not rogue\r\n is_valid = validate_block(amount, signature, timestamp, prev_hash, nonce, hash, payer, payee, miner)\r\n if (is_valid)\r\n puts \"VALIDATED OK\".green\r\n add_block(amount, payer, payee, miner, timestamp, signature, prev_hash, nonce, false)\r\n end\r\n else\r\n puts \"Denied block broadcast from rogue node\".red\r\n $status = \"Denied block broadcast from rogue node\"\r\n end\r\n end\r\n end\r\n # Broadcast First Block (Genesis Block) To Peers\r\n post \"/genesis\" do\r\n broadcast_block($blockchain[0])\r\n end\r\nend", "def referrer\n if params[:code]\n wechat_api_connect_solver = WechatApi::ConnectSolver.new(params[:code]).resolve\n\n # this is taken from application controller\n if wechat_api_connect_solver.success?\n user = wechat_api_connect_solver.data[:customer]\n\n # we turn him into a real referrer\n ReferrerMaker.new(user).convert!(group_token: params[:token])\n SlackDispatcher.new.message(\"ReferrerMaker was called for user `#{user&.id}`\")\n\n # is it a new user ?\n handle_after_sign_up! user\n\n # we force him to have a landing on package sets\n session[:landing] = :package_sets\n # we finally sign him in\n sign_in_user user\n return\n\n end\n end\n redirect_to root_path\n end", "def routing(rule_name, info)\n\n # Get to the advanced page.\n self.goto_advanced(rule_name, info)\n \n # Get to the \"Routing\" page.\n begin\n @ff.link(:text, 'Routing').click\n self.msg(rule_name, :info, 'routing', 'Reached page \\'Routing\\'.')\n rescue\n self.msg(rule_name, :error, 'routing', 'Did not reach \\'Routing\\' page')\n return\n end\n \n # Check the key.\n if ( info.has_key?('section') and info.has_key?('subsection') ) then\n # Right,go on.\n else\n self.msg(rule_name,:error,'routing','Some key NOT found.')\n return\n end\n \n if info.has_key?('Operation') then\n \n\tcase info['Operation']\n\t\n \t##############################\t\n \t# \"New Route\"\n \t##############################\t\n \twhen 'New route'\n\t begin\n\t\t@ff.link(:text,'New Route').click\n\t\tself.msg(rule_name,:info,'Operation','Reached page of \\'Operation\\' route.')\n\t rescue\n\tputs \"baby\"\n\t\tself.msg(rule_name,:error,'Operation','Can not \\'Operation\\' route page.')\t\n\t\treturn\n\t end\n\t \n\t if @ff.text.include?'Route Settings' then\n\t\t# Right,go on;\n\t else\n\t\tself.msg(rule_name,:error,'Route Setting','Does NOT Enter Route Setting page.')\n\t\treturn\n\t end\n\t # Select name for route;\n\t if info.has_key?('Name')\n\t\t\n\t\tcase info['Name']\n\t\t\n\t\t when 'Broadband Connection (Ethernet)'\n\n\t\t\t# Set name to 'Broadband Connection (Ethernet)'\n\t\t\t@ff.select_list(:name,'combo_device').select(\"Broadband Connection (Ethernet)\")\t\n\t\t\tself.msg(rule_name,:info,'Name',info['Name'])\n\n\t\t when 'Broadband Connection (Coax)'\n\n\t\t\t# Set name to 'Broadband Connection (Ethernet)'\n\t\t\t@ff.select_list(:name,'combo_device').select(\"Broadband Connection (Coax)\")\t\n\t\t\tself.msg(rule_name,:info,'Name',info['Name'])\n\n\t\t when 'WAN PPPoE'\n\n\t\t\t# Set name to 'Broadband Connection (Ethernet)'\n\t\t\t@ff.select_list(:name,'combo_device').select(\"WAN PPPoE)\")\t\n\t\t\tself.msg(rule_name,:info,'Name',info['Name'])\n\t\n\t\t when 'WAN PPPoE 2'\n\n\t\t\t# Set name to 'Broadband Connection (Ethernet)'\n\t\t\t@ff.select_list(:name,'combo_device').select(\"WAN PPPoE 2\")\t\n\t\t\tself.msg(rule_name,:info,'Name',info['Name'])\n\n\t\t when 'Network (Home/Office)'\n\n\t\t\t# Set name to 'Broadband Connection (Ethernet)'\n\t\t\t@ff.select_list(:name,'combo_device').select(\"Network (Home/Office)\")\t\n\t\t\tself.msg(rule_name,:info,'Name',info['Name'])\n\t\t else \n\t\t\t\n\t\t\t# Wrong\n\t\t\tself.msg(rule_name,:error,'Name','Can NOT configure \\'Name\\'.')\n\t\t\treturn\n\t\t \n\t\t end # End of case\n end # End of 'Name'\n\t if info.has_key?('Destination') and info['Destination'].size > 0\n\t\t\n\t\toctets=info['Destination'].split('.')\n\t\t@ff.text_field(:name,'dest0').value=(octets[0])\n\t\t@ff.text_field(:name,'dest1').value=(octets[1])\n\t\t@ff.text_field(:name,'dest2').value=(octets[2])\n\t\t@ff.text_field(:name,'dest3').value=(octets[3])\n\t\tself.msg(rule_name,:info,'Doset_destination',\"Destination = \"+info['Destination'])\n\n\t end\n\t if info.has_key?('Netmask') and info['Netmask'].size > 0\n\t\t\n\t\toctets=info['Netmask'].split('.')\n\t\t@ff.text_field(:name,'netmask0').value=(octets[0])\n\t\t@ff.text_field(:name,'netmask1').value=(octets[1])\n\t\t@ff.text_field(:name,'netmask2').value=(octets[2])\n\t\t@ff.text_field(:name,'netmask3').value=(octets[3])\n\t\tself.msg(rule_name,:info,'Doset_Netmask',\"Netmask = \"+info['Netmask'])\n\n\t end\n\t if info.has_key?('Gateway') and info['Gateway'].size > 0\n\t\t\n\t\toctets=info['Gateway'].split('.')\n\t\t@ff.text_field(:name,'gateway0').value=(octets[0])\n\t\t@ff.text_field(:name,'gateway1').value=(octets[1])\n\t\t@ff.text_field(:name,'gateway2').value=(octets[2])\n\t\t@ff.text_field(:name,'gateway3').value=(octets[3])\n\t\tself.msg(rule_name,:info,'Doset_gateway',\"Gateway = \"+info['Gateway'])\n\n\t end\n\t if info.has_key?('Metric') then\n\t\t\n\t\t@ff.text_field(:name,'metric').value=info['Metric']\n\t\tself.msg(rule_name,:info,'Set metric','Metric value is \\'Metric\\'.')\n\t else\n\t\tself.msg(rule_name,:error,'Set metric','Can Not set metric value to \\'Metric\\'.')\n\t\treturn\n\t end\n\t \n\t # Apply to save new route;\t\t\n\t @ff.link(:text,'Apply').click\n\t self.msg(rule_name,:info,'Apply','\\'Apply\\' to save new route.')\n\n\t if @ff.text.include?'Input Errors'\n\t\t\n\t\t# Find table\n\t\tsTable = false\n\t\t@ff.tables.each do |t|\n\t\t \n\t\t if ( t.text.include? ':' and\n\t\t\t(not t.text.include? 'Input Errors') and \n\t\t\t(not t.text.include? 'Cancel') and\n\t\t\tt.row_count >= 1 ) then\n\t\t\t\tsTable = t\n\t\t\tbreak\n\t\t end\n\t\tend\n\t\t# Wrong here\n\t if sTable == false\n\t\t self.msg(rule_name,:error,'New route','Did NOT find the target table.')\n\t\t return\n\t\tend\n\t\t\n\t\tsTable.each do |row|\n\t\t\t\n\t\t if row[1] == \"\" or row[2] == nil\n\t\t next\n\t\t end\n\t\n\t\t self.msg(rule_name,:error,row[1],row[2])\n\t\tend\n\n\t\t# Cancel\n\t\t@ff.link(:text,'Cancel').click\n\t\treturn\n\t \n\t end # end of 'Input Error'\t\t\t\n\t##############################\t\n \t# \"Multi Route\"\n \t##############################\t\n \twhen 'Multi route'\n\t \n\t if info.has_key?('Max route') then\n\t\tself.msg(rule_name,:info,'Multi route','Go on adding multi-route and Max route is : \\'Max route\\'.')\n\t end\n\t count=1\t\n\t \n\t if info.has_key?('Destination') and info['Destination'].size > 0\n\t\toctets=info['Destination'].split('.')\n\n\t\toctets2=(octets[2]).to_i\n\t\t#puts \"#{octets2}\"\n\t\toctets3=(octets[3]).to_i\n\t\t#puts \"#{octets3}\"\n\t\tself.msg(rule_name,:info,'Get address of destination',\"Destination = \"+info['Destination'])\n\t end\n\t \n\t while count <= info['Max route'].to_i \n\t #for i in octets3.to_i..info['Max route'].to_i\n\t\tbegin\n\t\t @ff.link(:text,'New Route').click\n\t\t self.msg(rule_name,:info,'Operation','Reached page of \\'Operation\\' route.')\n\t\trescue\n\t\t self.msg(rule_name,:error,'Operation','Can not \\'Operation\\' route page.')\t\n\t\t return\n\t\tend\n\t \n\t\tif @ff.text.include?'Route Settings' then\n\t\t # Right,go on;\n\t\telse\n\t\t self.msg(rule_name,:error,'Route Setting','Does NOT Enter Route Setting page.')\n\t\t return\n\t\tend\n\t\t# Select name for route;\n\t\tif info.has_key?('Name')\n\t\t\n\t\t case info['Name']\n\t\t\n\t\t when 'Broadband Connection (Ethernet)'\n\n\t\t\t# Set name to 'Broadband Connection (Ethernet)'\n\t\t\t@ff.select_list(:name,'combo_device').select(\"Broadband Connection (Ethernet)\")\t\n\t\t\tself.msg(rule_name,:info,'Name',info['Name'])\n\n\t\t when 'Broadband Connection (Coax)'\n\n\t\t\t# Set name to 'Broadband Connection (Ethernet)'\n\t\t\t@ff.select_list(:name,'combo_device').select(\"Broadband Connection (Coax)\")\t\n\t\t\tself.msg(rule_name,:info,'Name',info['Name'])\n\n\t\t when 'WAN PPPoE'\n\n\t\t\t# Set name to 'Broadband Connection (Ethernet)'\n\t\t\t@ff.select_list(:name,'combo_device').select(\"WAN PPPoE)\")\t\n\t\t\tself.msg(rule_name,:info,'Name',info['Name'])\n\t\n\t\t when 'WAN PPPoE 2'\n\n\t\t\t# Set name to 'Broadband Connection (Ethernet)'\n\t\t\t@ff.select_list(:name,'combo_device').select(\"WAN PPPoE 2\")\t\n\t\t\tself.msg(rule_name,:info,'Name',info['Name'])\n\n\t\t when 'Network (Home/Office)'\n\n\t\t\t# Set name to 'Broadband Connection (Ethernet)'\n\t\t\t@ff.select_list(:name,'combo_device').select(\"Network (Home/Office)\")\t\n\t\t\tself.msg(rule_name,:info,'Name',info['Name'])\n\t\t else \n\t\t\t\n\t\t\t# Wrong\n\t\t\tself.msg(rule_name,:error,'Name','Can NOT configure \\'Name\\'.')\n\t\t\treturn\n\t\t \n\t\t end # End of case\n\t\tend # End of 'Name'\n\t\tif info.has_key?('Destination') and info['Destination'].size > 0\n\t\t\n\t\t octets=info['Destination'].split('.')\n\n\t\t @ff.text_field(:name,'dest0').value=(octets[0])\n\t\t @ff.text_field(:name,'dest1').value=(octets[1])\n\t\t @ff.text_field(:name,'dest2').value=octets2.to_i\n\t\t @ff.text_field(:name,'dest3').value=octets3.to_i\n\t\t self.msg(rule_name,:info,'Doset_destination',\"Destination = \"+info['Destination'])\n\n\t\tend\n\t\tif info.has_key?('Netmask') and info['Netmask'].size > 0\n\t\t\n\t\t octets=info['Netmask'].split('.')\n\t\t @ff.text_field(:name,'netmask0').value=(octets[0])\n\t\t @ff.text_field(:name,'netmask1').value=(octets[1])\n\t\t @ff.text_field(:name,'netmask2').value=(octets[2])\n\t\t @ff.text_field(:name,'netmask3').value=(octets[3])\n\t\t self.msg(rule_name,:info,'Doset_Netmask',\"Netmask = \"+info['Netmask'])\n\n\t\tend\n\t\tif info.has_key?('Gateway') and info['Gateway'].size > 0\n\t\t\n\t\t octets=info['Gateway'].split('.')\n\t\t @ff.text_field(:name,'gateway0').value=(octets[0])\n\t\t @ff.text_field(:name,'gateway1').value=(octets[1])\n\t\t @ff.text_field(:name,'gateway2').value=(octets[2])\n\t\t @ff.text_field(:name,'gateway3').value=(octets[3])\n\t\t self.msg(rule_name,:info,'Doset_gateway',\"Gateway = \"+info['Gateway'])\n\n\t\tend\n\t\tif info.has_key?('Metric') then\n\t\t\n\t\t @ff.text_field(:name,'metric').value=info['Metric']\n\t\t self.msg(rule_name,:info,'Set metric','Metric value is \\'Metric\\'.')\n\t\telse\n\t\t self.msg(rule_name,:error,'Set metric','Can Not set metric value to \\'Metric\\'.')\n\t\t return\n\t\tend # End of if\n\n\t\t# Apply to save new route;\t\t\n\t\t@ff.link(:text,'Apply').click\n\t\tself.msg(rule_name,:info,'Apply','\\'Apply\\' to save new route.')\n\n\t\tif @ff.text.include?'Input Errors'\n\t\t\n\t\t # Find table\n\t\t sTable = false\n\t\t @ff.tables.each do |t|\n\t\t \n\t\t\t if ( t.text.include? ':' and\n\t\t\t (not t.text.include? 'Input Errors') and \n\t\t\t (not t.text.include? 'Cancel') and\n\t\t\t t.row_count >= 1 ) then\n\t\t\t\t sTable = t\n\t\t\t break\n\t\t\t end\n\t\t end\n\t\t # Wrong here\n\t\t if sTable == false\n\t\t\tself.msg(rule_name,:error,'New route','Did NOT find the target table.')\n\t\t\treturn\n\t\t end\n\t\t\n\t\t sTable.each do |row|\n\t\t\t\n\t\t\tif row[1] == \"\" or row[2] == nil\n\t\t\tnext\n\t\t\tend\n\t\n\t\t\tself.msg(rule_name,:error,row[1],row[2])\n\t\t end\n\n\t\t # Cancel\n\t\t @ff.link(:text,'Cancel').click\n\t\t return\n\t \n\t\tend # end of 'Input Error'\n\t\t\n\t\tcount = count + 1\n\t\tputs \"Adding the No.#{count} route.\"\n\t\toctets3 = octets3 + 1\n\t\t#puts octets3\n\t\t# re-setup ipaddress when the ipaddress over 254;\n\t\tif octets3 == 255 then\n\t\t octets3 = 1\n\t\t octets2 = octets2 + 1\n\t\tend\n\t end # End of while\n\n \t##############################\t\n \t# \"del Route\"\n \t##############################\n \twhen 'del route'\n\t\t\n\t if @ff.text.include?'Routing Table'\n\t\t\n\t\t# Find route table\n\t\tsTable = false\n\t\t@ff.tables.each do |t|\n\t\t if ( t.text.include? 'Routing Table' and \n\t\t\t(not t.text.include? 'Routing Protocols') and \n\t\t\t(not t.text.include? 'IGMP') and\n\t\t\t(not t.text.include? 'Domain Routing') and \n\t\t\tt.row_count >= 2 ) then\n\t\t\t\tsTable = t\n\t\t\tbreak\n\t\t end\n\t\tend\n\t\t\n\t\t# Wrong here\n\t\tif sTable == false\n\t\t\t\n\t\t\tself.msg(rule_name,:error,'Del route','Can NOT find right route table.')\n\t\t\treturn\n\t\tend\n\n\t\tnum = 0\n\t\tsTable.each do |row|\n\t\t if row[7] != nil then\n\t\t\t# row[7].links.each do |l|\n\t\t\t# puts l.name\n\t\t\t# end\n\t\t\tif row[7].link(:name,'route_remove').exist?\n\t\t\t #puts \"haha\"\n\t\t\t #puts @ff.text_field(:name,row[7]).to_s\n\t\t\t @ff.link(:href,row[7].link(:name,'route_remove').href).click\n\t\t\tend\n\t\t end\t\n\t\t\t\t# Output the result\n\t\t\t\t#self.msg(rule_name,:info,'Name' + num.to_s,row[1])\n\t\t\t\t#self.msg(rule_name,:info,'Destination' + num.to_s,row[2])\n\t\t\t\t#self.msg(rule_name,:info,'Gateway' + num.to_s,row[3])\n\t\t\t\t#self.msg(rule_name,:info,'Netmask' + num.to_s,row[4])\n\t\t\t\t#self.msg(rule_name,:info,'Metric' + num.to_s,row[5])\n\t\t\t\t#self.msg(rule_name,:info,'Status' + num.to_s,row[5])\n\t\t\t\t#num = num + 1\n\t\tend # End of table;\n\n end # End of 'Del route'\n\n\t\t# pasre the table of route\n\t\t# delete these\n\t\tself.msg(rule_name,:info,'Del route','Delete the list is successful. ')\n\telse\n \t# Wrong here.\n \tself.msg(rule_name,:error,'routing','No \\'New Route\\' key.')\n \treturn\n \tend # End of Case\n\n end # End of 'Operation'\n \n #-------------------------------------------#\n # \"Internet Group Management Protocol(IGMP)\"\n #-------------------------------------------#\n if info.has_key?('Internet Group Management Protocol(IGMP)') then\n\t# \"Internet Group Management Protocol(IGMP)\"\n \tcase info['Internet Group Management Protocol(IGMP)']\n \t \n\t when 'on'\n \t# Select mcast_enabled\n \t@ff.checkbox(:name,'mcast_enabled').set\n \tself.msg(rule_name,:info,'Internet Group Management Protocol(IGMP)','on')\n \t when 'off'\n \t# Don't select it.\n \t@ff.checkbox(:name,'mcast_enabled').clear\n \tself.msg(rule_name,:info,'Internet Group Management Protocol(IGMP)','off')\n else\n \t# Wrong here.\n \tself.msg(rule_name,:error,'routing','No \\'Internet Group Management Protocol(IGMP)\\' key.')\n \treturn\n \tend\n\n end # End of 'IGMP'\n\n #-------------------------------------------#\n # \"Domain Routing\"\n #-------------------------------------------#\n if info.has_key?('Domain Routing') then\n \t\n\t# \"Internet Group Management Protocol(IGMP)\"\n \tcase info['Domain Routing']\n \n\t when 'on'\n \t# Select it\n \t@ff.checkbox(:name,'dns_routing_enabled').set\n \tself.msg(rule_name,:info,'Domain Routing','on')\n when 'off'\n \t# Don't select it.\n \t@ff.checkbox(:name,'dns_routing_enabled').clear\n \tself.msg(rule_name,:info,'Domain Routing','off')\n \t else\n \t# Wrong here.\n \tself.msg(rule_name,:error,'routing','No \\'Domain Routing\\' key.')\n \treturn\n \t end\n\n end # End of 'Domain Routing'\n \n # Apply for the change\n @ff.link(:text,'Apply').click\n \n # Jump out an \"attention\" message?\n if @ff.text.include? 'Attention'\n \t@ff.link(:text,'Apply').click\n end\n \n # routing success\n self.msg(rule_name,:info,'Routing','SUCCESS')\n\n \n end", "def redirect_place #returns the place to redirect to based on origin\n if safe_params[:origin] == \"individual\"\n return (tournament_path(@tournament) + '/registration/individual');\n elsif safe_params[:origin] == \"teams\"\n return (tournament_path(@tournament) + '/control/teams');\n else\n puts(\"Hack ###\");\n redirect_to root_path;\n return;\n end\n end", "def route9\n redirect_to params[:key]\n end", "def add_route\n type = OrderType.find_by_name('route')\n \n hwb = Order.find(params[:id])\n \n data = params[\"route\"]\n data[\"parent_id\"] = params[:id]\n \n data[\"created_by\"] = self.current_user.account # <-- hardcoded to Transmance compnay id\n data[\"order_type_id\"] = type.id\n data[\"bill_to_id\"] = 1 # <-- hacked to Transmanage company id\n data[\"billing_method_id\"] = 1 # <-- read this from db!!!!!!!!!!!!!!\n data[\"shipping_method_id\"] = 1 # <-- hardcoded.\n data[\"pieces\"] = 1\n data[\"declared_value\"] = 0\n data[\"purpose\"] = ''\n data[\"weight\"] = 0\n data[\"shipping_commodity_id\"] = 1\n\n res = {\n :success => false,\n :data => [],\n :msg => ''\n }\n\n Order.transaction do \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 \n case params[\"pickup_mode\"]\n when \"shipper\" \n params[\"shipper\"] = {\"company_id\" => Order.find(params[:id]).find_entity_by_type(\"shipper\").company.id}\n when \"carrier\"\n params[\"shipper\"] = {\"company_id\" => params[\"carrier\"][\"company_id\"]} \n end\n \n case params[\"delivery_mode\"]\n when \"carrier\"\n params[\"consignee\"] = {\"company_id\" => params[\"carrier\"][\"company_id\"]}\n end\n entities.each do |e| \n data = params[e.name] \n case e.name\n when \"shipper\"\n location = CompanyLocation.find(:first, \n :conditions => \"airport_id = #{params['origin_airport_id']} AND company_id = #{params['shipper']['company_id']}\"\n ) || Company.create_anonymous_location(params[\"shipper\"][\"company_id\"], hwb.find_entity_by_type('shipper').location)\n data[:company_location_id] = location.id\n data[:date_in] = params[\"carrier\"][\"date_in\"] + ' ' + params[\"carrier\"][\"time_in\"]\n when \"consignee\"\n location = CompanyLocation.find(:first, \n :conditions => \"airport_id = #{params['destination_airport_id']} AND company_id = #{params['consignee']['company_id']}\"\n ) || Company.create_anonymous_location(params[\"consignee\"][\"company_id\"], hwb.find_entity_by_type('consignee').location) \n data[:company_location_id] = location.id\n data[:date_in] = params[\"carrier\"][\"date_out\"] + ' ' + params[\"carrier\"][\"time_out\"]\n when \"carrier\" \n data[:company_location_id] = Company.find(params[\"carrier\"][\"company_id\"], :include => [:head_office]).head_office.id \n end\n data[:order_id] = order.id\n data[:order_type_entity_id] = e.id \n oe = OrderEntity.create(data)\n end\n \n res[:success] = true\n res[:data] = {:route => Order.render_route(order)}\n res[:msg] = 'Added order route' \n end\n\n render :json => res.to_json, :layout => false\n\n end", "def rr_route client, server_type, msg, &block\n end", "def wrr_route client, server_type, msg, &block\n end", "def route\n #TODO\n end", "def route_request()\n# begin\n if @object_to_route_to.authorise() == false\n msg = \"No authorisation\"\n additonal_lines_array=nil\n result_screen = PDTTransaction.build_msg_screen_definition(nil,nil,nil,[\"No authorisation\"])\n return result_screen\n end\n @object_to_route_to.pdt_screen_def = @pdt_screen_def\n is_screen_submission = true\n #puts \"MODE TO ROUTE TO i.e. from java = \" + @object_to_route_to.pdt_screen_def.mode.to_s\n if @object_to_route_to.pdt_screen_def.mode.to_s == PdtScreenDefinition.const_get(\"BUTTON1\").to_s\n # puts \"@object_to_route_to.pdt_screen_def.screen_attributes[B1Submit] = \" + @object_to_route_to.pdt_screen_def.buttons[\"B1Submit\"].to_s\n method_to_route_to = @object_to_route_to.pdt_screen_def.buttons[\"B1Submit\"]\n elsif @object_to_route_to.pdt_screen_def.mode.to_s == PdtScreenDefinition.const_get(\"BUTTON2\").to_s\n method_to_route_to = @object_to_route_to.pdt_screen_def.buttons[\"B2Submit\"]\n elsif @object_to_route_to.pdt_screen_def.mode.to_s == PdtScreenDefinition.const_get(\"BUTTON3\").to_s\n method_to_route_to = @object_to_route_to.pdt_screen_def.buttons[\"B3Submit\"]\n elsif @object_to_route_to.pdt_screen_def.mode.to_s == PdtScreenDefinition.const_get(\"ENTERDATA\").to_s\n #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n # what about ENTERDATA - Automatic screen submissions????\n #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n# method_to_route_to = @pdt_method.method_name + \"_submit\"\n raise \"auto_submit_to action missing. Please contact IT!!!\" if @object_to_route_to.pdt_screen_def.screen_attributes[\"auto_submit_to\"] == nil\n method_to_route_to = @object_to_route_to.pdt_screen_def.screen_attributes[\"auto_submit_to\"]\n else#handle menu selections and automatic only\n method_to_route_to = @pdt_method.method_name\n is_screen_submission = false\n end\n\n if(is_screen_submission)\n if(!@object_to_route_to.can_redo)\n @jsession_store.clear_redos\n end\n end\n\n if method_to_route_to == nil\n msg = \"../app/models/pdt_transaction.rb:326:in `route_request' got nil,might have expected a string\"\n additonal_lines_array=nil\n result_screen = PDTTransaction.build_msg_screen_definition(msg,35,7,additonal_lines_array)\n return hash_error_screen(result_screen)\n end\n\n if ! (error = validate_method(method_to_route_to))\n result_screen_def = @object_to_route_to.send(method_to_route_to)\n return result_screen_def\n else\n if @object_to_route_to.pdt_screen_def.mode.to_s == PdtScreenDefinition.const_get(\"CONTROL_VALUE_REPLACE\").to_s\n return \"<error></error>\"\n else\n return hash_error_screen(error)\n end\n end\n# rescue\n# puts $!\n# puts $!.backtrace.join(\"\\n\").to_s\n# end\n end", "def route_for(**url_details)\n @routes.select { |rt| url_details <= rt.url_details }.first\n end", "def rezm_sender_or_receiver(message)\n if params[:action] == \"outbox\"\n rezm_to_user_link(message)\n # Used for both inbox and trashbin\n else\n rezm_from_user_link(message)\n end\n end", "def traverse_route_map(origin, destination, path, matches, &block)\n route_map[origin].each do |route|\n\n new_path = path ? path.dup : Path.new\n new_path << route\n\n action = yield(new_path)\n\n matches << new_path if action == :match\n\n if action == :continue || action == :match\n traverse_route_map(route.destination, destination, new_path, matches, &block)\n end\n\n end\n end", "def defer_to(params = {}, &conditional_block)\n Router.routes << (route = to_route(params, &conditional_block))\n route\n end", "def handle_temporary_redirects(service_response)\n\n case service_response.go_to['by_screen_name']\n when 'verify_email'\n redirect_to :verify_email and return\n when 'verify_device'\n redirect_to :verify_device and return\n when 'verify_sda'\n redirect_to :verify_sda and return\n when 'setup_mfa'\n redirect_to :mfa and return\n when 'authenticate_mfa'\n redirect_to :mfa and return\n when 'token_dashboard'\n redirect_to :dashboard and return\n when 'token_setup'\n redirect_to :token_setup and return\n when 'sandbox_token_dashboard'\n redirect_to \"/#{GlobalConstant::Environment.sandbox_sub_url_prefix}\" and return\n when 'mainnet_token_dashboard'\n redirect_to \"/#{GlobalConstant::Environment.main_sub_env_url_prefix}\" and return\n when 'token_deploy'\n redirect_to :token_deploy and return\n when 'token_mint'\n redirect_to :token_mint and return\n when 'token_mint_progress'\n redirect_to :token_mint_progress and return\n when 'test_economy'\n redirect_to :test_economy and return\n when 'service_unavailable'\n redirect_to :service_unavailable and return\n when 'login'\n redirect_to :login and return\n when 'logout'\n redirect_to :logout and return\n when 'developer'\n redirect_to :developer and return\n when 'company_information'\n redirect_to :company_information and return\n else\n render_error_response_for(service_response)\n end\n\n end", "def set_route_to_market\n @procurement.assign_attributes(procurement_route_params)\n\n unless @procurement.valid?(:route_to_market)\n build_page_details(:results)\n set_results_page_data\n render 'results'\n return true\n end\n\n @procurement.start_direct_award if @procurement[:route_to_market] == 'da_draft'\n @procurement.start_further_competition if @procurement[:route_to_market] == 'further_competition'\n @procurement.save\n\n redirect_to facilities_management_procurement_path(@procurement)\n end", "def legacy\n case params[:path][0]\n when 'list'\n if (params[:path][1] == 'novita.php')\n redirect_to :controller => 'books', :action => 'recent'\n elsif (params[:path][1] == 'sconti.php')\n redirect_to :controller => 'books', :action => 'offers'\n else\n redirect_to :controller => 'books', :action => 'list', :id => params[:path][1].sub('.php','').sub('_',' ')\n end\n when 'search.php'\n redirect_to :controller => 'books', :action => 'search'\n when 'links.php'\n redirect_to :controller => 'books', :action => 'links'\n else\n redirect_to '/' \n end\n end", "def triage_select\n case params['Digits']\n when '*'\n @phone_call.miss! 'after_hours'\n render action: :goodbye, formats: [:xml]\n return\n when '1'\n @phone_call.transfer! Member.robot\n @phone_call.miss! 'after_hours'\n @nurseline_phone_call = @phone_call.transferred_to_phone_call\n render action: :transfer_nurse, formats: [:xml]\n return\n end\n\n redirect_to action: :triage_menu, id: @phone_call.id\n end", "def routes(&block); end", "def routes(&block); end", "def route\n @route ||= Role.available_routes.find {|r| r.conditions[:path_info].to_s == path_info && r.conditions[:request_method].to_s == request_method}\n end", "def process(context)\n request = context.request\n\n router = @processor_map[request.request_method.downcase.to_sym]\n return 404 unless router\n begin\n processor, params = router.routing(request.path)\n rescue FancyServer::PathRouter::NoRouteMatched\n return 404\n rescue FancyServer::PathRouter::DestinationDuplicated => ex\n return {:status => 503, :body => ex.message}\n end\n return 404 unless processor\n context.params.merge!(params)\n processor.respond_to?(:to_proc) ? context.instance_eval(&processor) : processor\n end", "def url_for(options = {})\n options ||= {}\n url = case options\n when String\n options\n when Hash\n options = options.symbolize_keys\n if request.host[Regexp.new(@@retailer_server)] \n# route = options[:use_route]\n options = options.merge!({:only_path => false})\n# debugger\n# options = options.merge!({:use_route => \"proxy\", :extra_data => route}) if route\n elsif (request.domain && request.domain(4)[Regexp.new(@@embedded_optemo_server)]) \n options = options.merge!({:only_path => false}) # reverse merge host and port here as necessary\n else\n options = options.reverse_merge!(:only_path => options[:host].nil?)\n end\n super\n when :back\n controller.request.env[\"HTTP_REFERER\"] || 'javascript:history.back()'\n else\n polymorphic_path(options)\n end\n url\n end", "def handle_temporary_redirects(service_response)\n\n case service_response.go_to['by_screen_name']\n when 'economy_dashboard'\n redirect_to :dashboard and return\n when 'economy_planner_step_one'\n redirect_to :planner_step_one and return\n when 'economy_planner_step_two'\n redirect_to :planner_step_two and return\n when 'economy_planner_step_three'\n redirect_to :planner_step_three and return\n when 'service_unavailable'\n redirect_to :service_unavailable and return\n else\n fail \"unhandled internal redirect: #{service_response.go_to}\"\n end\n\n end", "def redirect_to_station_path\n case current_user.station\nwhen \"milimani family\" then redirect_to 'http://10.66.110.15:81/courtstations/1/casefiles'\n\n\n\nend\nend", "def render_place #returns the place to render based on origin\n if safe_params[:origin] == \"individual\"\n return 'tournaments/individual';\n elsif safe_params[:origin] == \"adjudicators\"\n return 'tournaments/adjudicators';\n else\n puts(\"Hack ###\");\n redirect_to root_path;\n return;\n end\n end", "def redirect\n \n if \"succeeded\" == params[\"state\"]\n # Acknowledge the update payment method hosted page id passed in return URL. \n # The response will have customer and their masked payment details.\n result = ChargeBee::HostedPage.acknowledge(params[\"id\"])\n hosted_page = result.hosted_page\n \n \n id = hosted_page.content.customer.id\n redirect_to \"/update_payment_method/profile?customer_id=#{URI.escape(id)}&updated=#{URI.escape(\"true\")}\"\n \n else\n redirect_to \"/400\"\n end\n end", "def respond( message )\n\n\n # If a joining message adds address to routing table and gateway table before sending a routing info message\n # to it and a joining relay message to a node with a GUID closer to the joining node\n if message[\"type\"] == \"JOINING_NETWORK_SIMPLIFIED\"\n tnh, tm, tn = nextHop( message[\"node_id\"] )\n @gateway_table[message[\"node_id\"]] = { :ip_address => message[\"ip_address\"], :port => message[\"port\"] }\n if @routing_table.has_key?([0,tm,tn]) == false # || diff( joining_guid ) < diff( @routing_table[[0,jm,jn]][\"node_id\"] )\n @routing_table[[0,tm,tn]] = { :node_id => message[\"node_id\"], :ip_address => message[\"ip_address\"], \\\n :port => message[\"port\"] }\n end\n if tnh.ip != nil\n joinMesgRelay = { :type => \"JOINING_NETWORK_RELAY_SIMPLIFIED\", :node_id => message[\"node_id\"], \\\n :gateway_id => @guid, :ip_address => message[\"ip_address\"], \\\n :port => message[\"port\"] }.to_json\n @s.send joinMesgRelay, 0, tnh.ip, tnh.port\n end\n tempRouteTable = []\n @routing_table.each_value { |addr|\n tempRouteTable.push( addr )\n }\n routingInfoMesg = { :type => \"ROUTING_INFO\", :gateway_id => @guid, :node_id => message[\"node_id\"], \\\n :ip_address => @localInetAddr.ip, :port => @localInetAddr.port, :route_table => tempRouteTable }.to_json\n @s.send routingInfoMesg, 0, message[\"ip_address\"], message[\"port\"]\n end\n\n\n # Behalves identically to above except responce to the gateway node instead of the joining node\n if message[\"type\"] == \"JOINING_NETWORK_RELAY_SIMPLIFIED\"\n tnh, tm, tn = nextHop( message[\"node_id\"] )\n nh, gm, gn = nextHop( message[\"gateway_id\"] )\n if @routing_table.has_key?([0,tm,tn]) == false # || diff( joining_guid ) < diff( @routing_table[[0,jm,jn]][\"node_id\"] )\n #puts \"h6\"\n @routing_table[[0,tm,tn]] = { :node_id => message[\"node_id\"], :ip_address => message[\"ip_address\"], \\\n :port => message[\"port\"] }\n end\n if tnh.ip != nil\n joinMesgRelay = { :type => \"JOINING_NETWORK_RELAY_SIMPLIFIED\", :node_id => message[\"node_id\"], \\\n :gateway_id => message[\"gateway_id\"], \\\n :ip_address => message[\"ip_address\"], :port => message[\"port\"] }.to_json\n @s.send joinMesgRelay, 0, tnh.ip, tnh.port\n end\n tempRouteTable = []\n @routing_table.each_value { |addr|\n tempRouteTable.push( addr )\n }\n routingInfoMesg = { :type => \"ROUTING_INFO\", :gateway_id => message[\"gateway_id\"], :node_id => message[\"node_id\"], \\\n :ip_address => @localInetAddr.ip, :port => @localInetAddr.port, :route_table => tempRouteTable }.to_json\n if nh.ip != nil\n @s.send routingInfoMesg, 0, nh.ip, nh.port\n end\n end\n\n\n # When we get a routing info message extract as much useful information out of it as we can and forward it onto the\n # intended target node unless it was intended for our node\n if message[\"type\"] == \"ROUTING_INFO\"\n useRouteInfo( message[\"route_table\"] )\n if message[\"node_id\"] == @guid\n return\n elsif message[\"gateway_id\"] == @guid\n if @gateway_table.has_key?( message[\"node_id\"] )\n p @s.send message.to_json, 0, @gateway_table[message[\"node_id\"]][:ip_address].to_s, @gateway_table[message[\"node_id\"]][:port]\n else\n puts \"Routing_Info message receave error not key in gatewayTable!\"\n end\n else\n nh, gm, gn = nextHop( message[\"node_id\"] )\n message = message.to_json\n if nh.ip != nil\n @s.send message, 0, nh.ip, nh.port\n end\n end\n end\n\n # If we get a leaving message remove the node from the network\n if message[\"type\"] == \"LEAVING_NETWORK\"\n removeAddr( message[\"node_id\"])\n end\n\n # When we receave an index message check it is intended for us and if not forward to next hop otherwise process\n # increase the rank of urls in @linkHash or create a new entry if\n # We have not seen that URL before\n if message[\"type\"] == \"INDEX\"\n if message[\"target_id\"] == @guid\n flag = true\n for i in 0..@linkHash.length-1\n if @linkHash[i][:url] == message[\"link\"]\n @linkHash[i][:rank] += 1\n flag = false\n end\n end\n if flag\n @linkHash << { :url => message[\"link\"], :rank => 1 }\n end\n ackIndexMesg = { :type => \"ACK_INDEX\", :node_id => message[\"sender_id\"], :keyword => message[\"keyword\"] }.to_json\n if message[\"sender_id\"] == @guid\n puts \" \"\n print @name, \" INDEXING myself\" # If we are processing our own indexing message no need to send an ACK\n puts \" \"\n return\n end\n nh, sm, sn = nextHop( message[\"sender_id\"] )\n @s.send ackIndexMesg, 0, nh.ip, nh.port\n else\n nh, tm, tn = nextHop( message[\"target_id\"] )\n if nh.ip != nil\n @s.send message.to_json, 0, nh.ip, nh.port\n end\n end\n end\n\n\n # Keept forwarding until this ACK_INDEX message reaches its destination, when it does set the appropriate flag\n if message[\"type\"] == \"ACK_INDEX\"\n if message[\"node_id\"] == @guid\n wordHash = Hash_Func( message[\"keyword\"] )\n @indexAckWait[ wordHash ] = 2\n else\n nh, m, n = nextHop( message[\"node_id\"] )\n if nh.ip != nil\n @s.send message.to_json, 0, nh.ip, nh.port\n end\n end\n end\n\n\n # Keep forwarding search message until it reaches correct location in which case we append @linkHash to a search\n # responce message and send it to the sending ID\n if message[\"type\"] == \"SEARCH\"\n if message[\"node_id\"] == @guid\n searchResponceMesg = { :type => \"SEARCH_RESPONSE\", :word => message[\"word\"], :node_id => message[\"sender_id\"],\n :sender_id => @guid, :response => @linkHash }.to_json\n nh, sm, sn = nextHop( message[\"sender_id\"] )\n @s.send searchResponceMesg, 0, nh.ip, nh.port\n else\n nh, tm, tn = nextHop( message[\"node_id\"] )\n message = message.to_json\n if nh.ip != nil\n @s.send message, 0, nh.ip, nh.port\n end\n end\n end\n\n # Keep forwarding responce until we reach intended recipient and then put results in flag so origional\n # search thread can process the results\n if message[\"type\"] == \"SEARCH_RESPONSE\"\n if message[\"node_id\"] == @guid\n @searchAckWait[ message[\"sender_id\"] ] = message[\"response\"]\n else\n nh, tm, tn = nextHop( message[\"node_id\"] )\n if nh.ip != nil\n @s.send message.to_json, 0, nh.ip, nh.port\n end\n end\n end\n\n # Upon receaving a PING send onto next hop and generate ACK\n if message[\"type\"] == \"PING\"\n ackMesg = { :type => \"ACK\", :node_id => @guid, :ip_address => @localInetAddr.ip, \\\n :port => @localInetAddr.port }.to_json\n @s.send ackMesg, 0, message[\"ip_address\"], message[\"port\"]\n if message[\"target_id\"] != @guid\n #puts @name, \"PNH\", message[\"target_id\"], Time.now\n nh, m, n = nextHop( message[\"target_id\"] )\n if nh.ip != nil\n message[\"ip_address\"] = @localInetAddr.ip\n message[\"port\"] = @localInetAddr.port\n @s.send message.to_json, 0, nh.ip, nh.port\n end\n end\n end\n\n # Upon receiving an ACK message we know this node is still alive\n if message[\"type\"] == \"ACK\"\n @checkAckWait[ message[\"node_id\"] ] = 2\n end\n end", "def pickup_route(t_obj, value)\n t_obj.pickup_route_id = @routes.detect{|r| r.name == value}.try(:id)\n end", "def routes\n @logger.info \"#{__method__}\"\n fill_in \"JourneyPlanner$txtNumberOfPassengers\", with: \"1\"\n country_routes = list_countries.inject([]) do |country_result, country|\n @logger.info \"routes for #{country}\"\n select(country, :from => \"JourneyPlanner_ddlLeavingFromState\")\n sleep 3\n to_from = list_leaving_from.inject([]) do |from_result, from|\n @logger.info \"routes from #{from}\"\n sleep 2\n select(from, :from => \"JourneyPlanner$ddlLeavingFrom\")\n from_result << {from => list_travelling_to}\n from_result\n end\n country_result << {country => to_from}\n country_result\n end\n end", "def completion_route\n thankyou_order_url(@order)\n end", "def process(request_hash)\n request = Request.new(request_hash)\n case request.path\n when '/'\n index_route(request)\n when %r{^/sleep/\\d+$}\n sleep_route(request)\n else\n Response.new(\n \"No route found for #{request.path}. Try '/' or '/sleep/3'.\",\n status: 404\n )\n end\n end", "def redirect_away(*params)\n store_return_point\n redirect_to(*params)\n end", "def the_update_redirect\n #return {:controller => :recipients, :action => 'show', :id => @recipient} if @recipient\n return {:action => 'index'}\n end", "def handle_routes\n instance_exec(@_roda_app.request, &self.class.router_block)\n end", "def get_routes from, to, options = {}\n options[:start_type] = check_point_type(from) || options[:start_type]\n options[:target_type] = check_point_type(to) || options[:target_type]\n # default options\n options = {\n :time => Time.now, \n :depth => 0, \n :include_coords => true, \n :limit => 2,\n :time_relation => :depature,\n :identify_part_prices => :none }.merge(options)\n\n options[:time] = options[:time].in_time_zone(\"Berlin\") #+ 10.minutes # Ansonsten liegt die erste Verbindung in der Vergangenheit\n page = @agent.get @@options[:url_route]\n \n result = submit_form page.forms.first, from, to, options\t\t\n routes = []\n links = result.links_with(:href => /details=opened!/).select { |l| l.to_s.size > 0} # only select connection links, no warning links\n links.reverse! if options[:time_relation] == :arrival # respect :time_relation for route processing\n \n link_threads = Array.new\n links.each_index do |idx|\n link_threads[idx] = Thread.new {\n # maybe we are too fast in requesting :-)\n (1..5).each do |i|\n page = links[idx].click \n break unless page.title.match(/Fehler/)\n # puts \"link.click error: %i\" % i\n sleep(1)\n end\n Thread.current[:route] = Route.new(page, options)\n }\n break if idx == options[:limit]\n end\n\n link_threads.each { |t| t.abort_on_exception = true}\n routes = link_threads.map { |t| t.join; t[:route] }\n\n # Keine Station gefunden also suchen wir nach der nächstbesten Adresse/Station\n if links.count == 0 && options[:depth] == 0\n if options[:start_type] == :address\n from = find_address(from, options)\n options[:start_type] = from.station_type\n from = from.name\n elsif options[:start_type] == :station\n from = find_station(from, options)\n options[:start_type] = from.station_type\n from = from.name\n end\n \n if options[:target_type] == :address\n to = find_address(to, options)\n options[:target_type] = to.station_type\n to = to.name\n elsif options[:target_type] == :station\n to = find_station(to, options)\n options[:target_type] = to.station_type\n to = to.name\n end\n \n return get_routes from, to, options.merge(:depth => options[:depth]+1)\n end\n \n raise \"no_route\" if routes.count == 0 || links.count == 0\t\t\t\n\n # attach price information for each routepart if necessary\n identify_part_prices(routes, options) unless options[:identify_part_prices] == :none\n \n return routes\n end", "def lbcfg_router(response)\n # we don't want to allow updating LBs in private\n # so if this is a DM, return a helpful message to tell them \"no\"\n return response.reply(t('general.private_message')) if is_dm?(response)\n\n action = response.match_data['action'].downcase\n\n # if the action is unknown, return an error message\n return response.reply(t('router.invalid_action', action: action)) unless %w(enable drain).include?(action)\n\n # wrap the call to the appropriation action function in a rescue block\n # both functions would need similar rescue statements, so let's do it here\n begin\n # call lbcfg_<action> on this Class\n # so if action == 'drain' it'll call lbcfg_drain\n response.reply(send(\"lbcfg_#{action}\".to_sym, response))\n\n rescue DoubleDutch::SpaceCadet::Error => e # catch all SpaceCadet errors\n title = \"An error has occured trying to #{action} the requested node:\"\n reply = render_template('exception', title: title, exception: e.class, message: e.message)\n response.reply(reply)\n\n rescue StandardError => e # catch all remaining errors\n title = \"A generic excpetion has been caught trying to #{action} the requested node:\"\n reply = render_template('exception', title: title, exception: e.class, message: e.message)\n response.reply(reply)\n end\n end", "def set_relay_destination\n @relay_destination = RelayDestination.find(params[:id])\n end", "def menu_network\n case\n when params[:Digits] == \"1\"\n redirect_to(twilio_voice_path \"chainheight\", format: :twiml)\n\n when params[:Digits] == \"2\"\n redirect_to(twilio_voice_path \"difficulty\", format: :twiml)\n\n when params[:Digits] == \"3\"\n redirect_to(twilio_voice_path \"hashrate\", format: :twiml)\n\n when params[:Digits] == \"4\"\n redirect_to(twilio_voice_path format: :twiml)\n\n end\n\n # check if user entered an unrecognized digit\n if ! params[:Digits].blank? then @bad_digit = params[:Digits] end\n end", "def routes=(_arg0); end", "def routes=(_arg0); end", "def routes=(_arg0); end", "def gateway_refund\n resource.direct_refund\n respond_to do |format|\n format.html do\n return redirect_to admin_contributions_path(params[:local_params])\n end\n format.json do\n return render json: []\n end\n end\n end", "def move_to_tier\n requested_profile.move_to_tier!(requested_follow_profile, requested_tier)\n redirect_to :action => 'following_by_tier', :profile_id => current_user.profile, :tier => params[:tier]\n end", "def routing_number; end", "def router; end", "def route(&block)\n @router ||= Router.new\n @router.instance_eval(&block)\n end", "def search_directions\n @query = 1\n @error = 0\n @departure_address = params[:departure_address]\n @arrival_address = params[:arrival_address]\n bus_transit = params[:bus_transit]\n train_transit = params[:train_transit]\n metra_transit = params[:metra_transit]\n @preferred = params[:preferred]\n apikey = \"AIzaSyCDeWWmT-KYmsgSz9d2vCy0KcOmJe114y4\"\n\n if @departure_address != \"\" && @arrival_address != \"\"\n url_safe_dep = URI.encode(@departure_address)\n url_safe_arr = URI.encode(@arrival_address)\n @type_transport = ''\n\n if !bus_transit.nil?\n @type_transport = bus_transit\n end\n\n if !train_transit.nil?\n @type_transport += \"|\" + train_transit\n end\n\n if !metra_transit.nil?\n @type_transport += \"|\" + metra_transit\n end\n\n if !@type_transport != '' && !@preferred.nil? && @preferred != \"\"\n url_safe_typ = URI.encode(@type_transport)\n url_safe_pref = URI.encode(@preferred)\n apiLink = \"https://maps.googleapis.com/maps/api/directions/json?origin=#{url_safe_dep}&destination=#{url_safe_arr}&mode=transit&alternatives=true&transit_mode=#{@url_safe_typ}&transit_routing_preference=#{url_safe_pref}&key=#{apikey}\"\n\n elsif !@type_transport != ''\n url_safe_typ = URI.encode(@type_transport)\n apiLink = \"https://maps.googleapis.com/maps/api/directions/json?origin=#{url_safe_dep}&destination=#{url_safe_arr}&mode=transit&alternatives=true&transit_mode=#{url_safe_typ}&key=#{apikey}\"\n\n elsif !@preferred.nil? && @preferred != \"\"\n url_safe_pref = URI.encode(@preferred)\n apiLink = \"https://maps.googleapis.com/maps/api/directions/json?origin=#{url_safe_dep}&destination=#{url_safe_arr}&mode=transit&alternatives=true&transit_routing_preference=#{url_safe_pref}&key=#{apikey}\"\n else\n apiLink = \"https://maps.googleapis.com/maps/api/directions/json?origin=#{url_safe_dep}&destination=#{url_safe_arr}&mode=transit&alternatives=true\"\n end\n\n @directions = JSON.parse(open(apiLink).read, object_class: OpenStruct)\n\n if @directions.status == \"OK\"\n @routes = @directions.routes\n @error = 0\n else\n @message = \"No station found, try again\"\n @error = 1\n end\n else\n @message = \"Please enter a value for departure and arrival address\"\n @error = 1\n end\n\n #render :json => @routes\n render 'directions'\n end", "def deciding_request\n request_friendship = RequestFriendship.find(params[:rf])\n\n n = current_user.id\n if n != request_friendship.recipient_id\n throw Exception\n end\n\n\n #Para que no sea grande ni saque datos explicitos ponemos un número 1 = ACCEPTED, 2 = REJECTED\n choice = \"ACCEPTED\"\n if (params[:choice] == \"2\")\n choice = \"REJECTED\"\n end\n\n\n result = RequestFriendship.where({recipient_id: current_user.id, sender_id: request_friendship.sender_id,\n status: \"PENDING\"}).last\n\n message_suffix = \"\"\n respond_to do |format|\n if result.update({status: choice})\n if(choice == \"ACCEPTED\")\n Friendship.createFriendship(result)\n message_suffix = \"ACEPTADO\"\n else\n message_suffix = \"DENEGADO\"\n end\n format.html { redirect_to welcome_index_path, notice: 'La petición se ha ' << message_suffix }\n else\n format.html { render 'welcome/index' }\n end\n end\n\n end", "def find_optimal_route(origin:, destination:, arrival_deadline:)\n params = { origin: origin, destination: destination, deadline: arrival_deadline }\n to_transit_path(client.get(API_PATH, params))\n end", "def set_route_to_market\n if params[:commit] == page_details(:results)[:secondary_text]\n @procurement.set_state_to_detailed_search\n @procurement.save\n\n redirect_to facilities_management_beta_procurement_path(@procurement)\n return\n end\n\n @procurement.assign_attributes(procurement_route_params)\n\n unless @procurement.valid?(:route_to_market)\n build_page_details(:results)\n set_results_page_data\n render 'results'\n return true\n end\n\n @procurement.start_direct_award if @procurement[:route_to_market] == 'da_draft'\n @procurement.start_further_competition if @procurement[:route_to_market] == 'further_competition'\n @procurement.save\n\n redirect_to facilities_management_beta_procurement_path(@procurement)\n end", "def add_route(city_code1, city_code2, distance)\n if distance <= 0\n puts 'The distance must be positive'\n return\n end\n if @metros.has_key?(city_code1) && @metros.has_key?(city_code2)\n @metros[city_code1].destination[city_code2] = distance\n end\n end", "def request_booking_proposed(sender, receiver)\n @url = booking_requests_path\n @sender_name = sender.username.titleize\n mail to: receiver.email,\n subject: \"fitafy Booking Request from #{sender.username}\",\n date: Time.now\n end", "def route_for_current_step\n steps_routes_mapping[state] || steps_routes_mapping[:pending]\n end", "def spoof_tr(receiver2spoofer2targets,&block)\n if receiver2spoofer2targets.include? @ping_receiver\n # {\"crash.cs.washington.edu\"=>{\"toil.cs.washington.edu\"=>[[\"74.125.127.106\", 0, 40, 40]]}}\n return @mock_spoofed_ping_controller_return\n else\n return @mock_spoofed_trace_controller_return\n end\n end", "def past_path(params)\n params[:mode_type]=params[:view].eql?(\"presales\") ? \"client\" : \"matter\" if params[:mode_type].blank?\n @remember_path={}\n if params[:from_unbilled].present?\n @remember_path=view_unbilled_entries_tne_invoices_path(:mode_type=>params[:mode_type])\n elsif params[:flag].present?\n matterid = @tne_invoice.matter_id.present? ? @tne_invoice.matter_id : (params[:matter_id].present? ? params[:matter_id] : params[\"tne_invoice\"][\"matter_id\"])\n @remember_path=bill_retainers_matter_matter_billing_retainers_path(:matter_id=>matterid,:from=>\"matters\")\n else\n @remember_path=remember_past_path\n end\n end", "def routing\n if Vagrant::Util::Platform.darwin?\n @gateway = `route -n get default | grep 'gateway' | awk '{print $2}'`.delete(\"\\n\")\n elsif Vagrant::Util::Platform.linux?\n # Not tested\n @gateway = `ip route show`[/default.*/][/\\d+\\.\\d+\\.\\d+\\.\\d+/]\n end\n\n $vagrant.vm.provision :shell,\n run: \"always\",\n path: File.join(__dir__, \"../\", \"/utils/routing.py\"),\n args: \"#{@gateway}\"\n end", "def move_train_backward_by_route\n if @routes.empty? || @trains.empty?\n routes_or_trains_void\n else\n request = [\"Enter the train number [#{@trains.keys.join(', ')}]: \"]\n train = getting(request, :approve_train_for_assign, :select_train)\n train_moved_backward if train.move_train_backward\n end\n end", "def create_curr_location \n if @@form_step == nil \n redirect_to root_path \n end\n if @@form_step == 1 \n @latitude = params[:latitude] \n @longitude = params[:longitude] \n @loc = params[:loc]\n @@request.lat_curr = @latitude \n @@request.long_curr= @longitude \n @@request.currentLoc= @loc\n redirect_to url_for(:controller => \"requests\", :action => \"home\")\n else \n @latitude = params[:latitude] \n @longitude = params[:longitude] \n @destination = params[:loc]\n @@request.lat_destination = @latitude \n @@request.long_destination= @longitude \n @@request.destination= @destination\n unless (@@request.long_curr == nil)\n @@request.distance = distance(@@request.long_curr,@@request.lat_curr,@@request.long_destination,@@request.lat_destination)\n end\n redirect_to url_for(:controller => \"requests\", :action => \"create_route\") \n\n end \n end", "def route_user(action)\n case action\n when 1 then @patients_controller.list\n end\n end", "def get_route\n data = {\n visits: visits,\n fleet: fleet\n }\n\n data[:options] = options if options\n result = Util.send_request(\"POST\", \"vrp\", Routific.token, data)\n RoutificApi::Route.parse(result)\n end", "def route_name; end", "def route_name; end", "def directions\n @start_abbr = Station.name_to_abbr(params[:start])\n @dest_abbr = Station.name_to_abbr(params[:end])\n\n @start = params[:start]\n @dest = params[:end]\n # Should be something like\n # Station.find_fastest(start: @start, end: @end)\n # And it should return Hash\n @fastest = Station.find_fastest(@start_abbr, @dest_abbr)\n\n if @fastest.is_a?(String)\n render :directions\n return\n end\n\n # Should be something like\n # Station.find_optimal(start: @start, end: @end)\n # And it should return Hash\n # @optimal = {\n # transfer: 'civic',\n # currentDeparture: '17:26',\n # upsteamColor: 'RED',\n # upsteamDestination: 'mlbr',\n # transferArrival: '17:30',\n # transferDeparture: '17:42',\n # downstreamColor: 'YELLOW',\n # downstreamDestination: 'ptsb',\n # finalEta: '18:15',\n # chanceOfStand: 'Very likely',\n # chanceOfSeat: 'Likely'\n # }\n @optimal =\n if @fastest[:waitTime] < 5\n \"Cannot catch the same train upstream\"\n else\n Station.find_optimal(@start_abbr, @dest_abbr, @fastest)\n end\n\n # Should be soething like\n # If Optimal chanceOfSeat is bad then\n # Station.find_guaranteed_seat(start: @start, end: @end)\n # And it should return Hash\n # @guaranteed_seat = {\n # transfer: 'UN Plaza',\n # currentDeparture: '17:30',\n # upstreamColor: 'RED',\n # upstreamDestination: 'mlbr',\n # transferArrival: '17:35',\n # transferDeparture: '17:52',\n # downstreamColor: 'YELLOW',\n # downstreamDestination: 'ptsb',\n # finalEta: '18:25',\n # chanceOfStand: 'Very likely',\n # chanceOfSeat: 'Likely'\n # }\n @guaranteed_seat =\n if @optimal.is_a?(String) ||\n @optimal[:chanceOfSeat] != 'Very likely' \n\n Station.find_guaranteed_seat(@start_abbr, @dest_abbr)\n else\n \"Optimal is guaranteed seat\"\n end\n p \"results\"\n p @fastest\n p @optimal\n p @guaranteed_seat\n render :directions\n end", "def view_worker\n @fresh_worker = MtCompanyWorker.find(params[:id]);\n @return_to = params[:ref];\n @return_to ||= \"worker_list\";\n security_breach( @return_to) if (@fresh_worker.mt_company != @mt_company )\n if ( request.post? )\n if ( params[:reason] == \"send_sms\" )\n begin\n SMS::deliver_sms(@fresh_worker.mobile, params[:sms_text]);\n add_confirmation \"SMS SENT\";\n rescue Exception=>e\n add_error e\n end\n end \n end\n end", "def seller\n seller_id = Product.find(params[:product_id]).owner_id\n\n begin\n if PrivateProfile.find_by_id(seller_id)\n redirect_to url_for(:controller => :private_profiles, :action => :show, :id => seller_id)\n return\n end\n end\n begin\n if BusinessProfile.find_by_id(seller_id)\n redirect_to url_for(:controller => :business_profiles, :action => :show, :id => seller_id)\n return\n end\n end\n render_404\n end", "def move_train_forward_by_route\n if @routes.empty? || @trains.empty?\n routes_or_trains_void\n else\n request = [\"Enter train number [#{@trains.keys.join(', ')}]: \"]\n train = getting(request, :approve_train_for_assign, :select_train)\n train_moved_forward_by_route if train.move_train_forward\n end\n end", "def match\n @current_route = Route.find(params[:id])\n \n @dep_lat = @current_route.departure_lat \n @dep_lng = @current_route.departure_lng\n @dep_lat_range = @current_route.distance_departure_range * 0.009\n @dep_lng_range = @current_route.distance_departure_range * 0.008\n \n @arr_lat = @current_route.arrival_lat \n @arr_lng = @current_route.arrival_lng\n @arr_lat_range = @current_route.distance_arrival_range * 0.009\n @arr_lng_range = @current_route.distance_arrival_range * 0.008\n \n @time_min = @current_route.time_range_from\n @time_max = @current_route.time_range_to\n\n @date = @current_route.date\n \n if @current_route.offer == true\n @status = false\n else\n @status = true\n end\n \n @routes = Route.find(:all, :conditions => \n [\"`routes`.`date` = ? AND \n `routes`.`active` = 1 AND \n `routes`.`offer` = ? AND \n (`routes`.`departure_lat` BETWEEN ? AND ?) AND \n (`routes`.`departure_lng` BETWEEN ? AND ?) AND \n (`routes`.`arrival_lat` BETWEEN ? AND ?) AND \n (`routes`.`arrival_lng` BETWEEN ? AND ?) AND \n ( (`routes`.`time_range_to` BETWEEN ? AND ?) OR \n (`routes`.`time_range_from` BETWEEN ? AND ?) OR\n (`routes`.`time_range_from` < ? AND `routes`.`time_range_to` > ?) \n )\",\n @date, \n @status,\n @dep_lat - @dep_lat_range, @dep_lat + @dep_lat_range,\n @dep_lng - @dep_lng_range, @dep_lng + @dep_lng_range,\n @arr_lat - @arr_lat_range, @arr_lat + @arr_lat_range, \n @arr_lng - @arr_lng_range, @arr_lng + @arr_lng_range,\n @time_min, @time_max, @time_min, @time_max, @time_min, @time_max]);\n \n \n # @routes = Route.find(:all, :conditions => \n # [\"`routes`.`date` = ? AND \n # `routes`.`active` = 1 AND \n # `routes`.`offer` = ? AND \n # (`routes`.`departure_lat` BETWEEN ? AND ?) AND \n # (`routes`.`departure_lng` BETWEEN ? AND ?) AND \n # (`routes`.`arrival_lat` BETWEEN ? AND ?) AND \n # (`routes`.`arrival_lng` BETWEEN ? AND ?) AND \n # ((`routes`.`time_range_to` BETWEEN ? AND ?) OR (`routes`.`time_range_from` BETWEEN ? AND ?))\",\n # @date, \n # @status,\n # @dep_lat - @dep_lat_range, @dep_lat + @dep_lat_range,\n # @dep_lng - @dep_lng_range, @dep_lng + @dep_lng_range,\n # @arr_lat - @arr_lat_range, @arr_lat + @arr_lat_range, \n # @arr_lng - @arr_lng_range, @arr_lng + @arr_lng_range,\n # @time_min, @time_max,@time_min, @time_max]);\n \n # @routes = Route.where(:departure_lat => @dep_lat - @dep_lat_range..@dep_lat + @dep_lat_range,\n # :departure_lng => @dep_lng - @dep_lng_range..@dep_lng + @dep_lng_range,\n # :arrival_lat => @arr_lat - @arr_lat_range..@arr_lat + @arr_lat_range, \n # :arrival_lng => @arr_lng - @arr_lng_range..@arr_lng + @arr_lng_range,\n # :date => @date,\n # :time_range_to => @time_min..@time_max,\n # :active => true,\n # :offer => @status).limit(20).all \n \n respond_to do |format|\n format.html \n format.json { render json: @routes }\n end\n end", "def render_place #returns the place to render based on origin\n if safe_params[:origin] == \"individual\"\n return 'tournaments/individual';\n elsif safe_params[:origin] == \"teams\"\n return 'tournaments/teams';\n else\n puts(\"Hack ###\");\n redirect_to root_path;\n return;\n end\n end", "def route\n # Page exists?\n if @node and @node.has_page?\n # Redirect to This Item's first category listing if it exists. To ensure the menus display correctly\n if @node.page_type=='Item' and @node.page.has_better_url?\n redirect_to shortcut_path(:shortcut => @node.page.better_url, :display_item => @node.page_id)\n return false\n else\n page_type = (@node.page_type == 'ItemCategory' ? 'Item' : @node.page_type)\n @item = Item.find(params[:display_item]) unless params[:display_item].blank?\n #render(\"#{page_type.tableize.pluralize}/show\", :layout => @node.layout)\n #render :action => \"#{page_type.tableize.pluralize}/show\", :layout => @node.layout\n render_page_from_node(\"#{page_type.tableize.pluralize}/show\", @node.layout)\n end\n else\n return error_redirect\n end\n end", "def load_resources\n @user = current_user\n @gf_travel_request = GrantFundedTravelRequest.find(params[:id])\n if current_ability.can?(params[:action].to_sym, @gf_travel_request) && current_user.id != @gf_travel_request.user_id\n @back_path = user_approvals_path(current_user)\n else\n @back_path = user_forms_path(current_user)\n end\n end", "def send_to_admin(req, dealership=nil)\n dealership = dealer_dao.get(req.session['dealer_id']) if dealership.nil?\n redirect \"/admin/#{dealership.slug}\"\n end", "def redirect_back_or(default)\n #forwarding_url = session[:forwarding_url] if \"#{session[:forwarding_url]}\".include? \"users/#{@user.id}/edit\" #URL CONTAINS MANY NUMBERS REMMEBER!\n if !session[:forwarding_url].nil? \n forwarding_url = edit_user_path @user #session[:forwarding_url] chenged from this to redirec to edit no matter what edit one was trying to access\n end\n redirect_to(forwarding_url || default) # review this notation; nill if previous statement false (goes to default)\n delete_store\n end", "def my_matching\n redirect_to matching_kases_person_path(@person), :status => :moved_permanently\n return\n end", "def route!(request)\n @@request = request\n @@routes.each do |route|\n if route.first == request.path\n return route.last.call\n break\n end\n end\n end", "def call(user, email, reward, shipping_address)\n @user = user\n @reward = reward\n # admin = \"astropowerbox@gmail.com\"\n admin = \"news.article.sysetm@gmail.com\"\n @shipping_address = shipping_address\n mail to: email, subject: 'Redemption details'\n end", "def route_for(name, *args); end", "def path_of(route_or_controller, action = nil)\n\t\t\tif route_or_controller.is_a?(Flame::Router::Route)\n\t\t\t\troute = route_or_controller\n\t\t\t\tcontroller = route.controller\n\t\t\t\taction = route.action\n\t\t\telse\n\t\t\t\tcontroller = route_or_controller\n\t\t\tend\n\t\t\treverse_routes.dig(controller.to_s, action)\n\t\tend", "def respond(message)\n=begin\n If a joining message adds address to routing table and gateway table before sending a routing info message\n to it and a joining relay message to a node with a GUID closer to the joining node\n=end\n if message[\"type\"] == \"JOINING_NETWORK\"\n tnh, tm, tn = nextHop(message[\"node_id\"])\n @gateway_table[message[\"node_id\"]] = {:ip_address => message[\"ip_address\"], :port => message[\"port\"]}\n if @routing_table.has_key?([0, tm, tn]) == false\n @routing_table[[0, tm, tn]] = {:node_id => message[\"node_id\"], :ip_address => message[\"ip_address\"], \\\n :port => message[\"port\"]}\n end\n if tnh.ip != nil\n joinMsgRelay = {:type => \"JOINING_NETWORK_RELAY\", :node_id => message[\"node_id\"], \\\n :gateway_id => @guid, :ip_address => message[\"ip_address\"], \\\n :port => message[\"port\"]}.to_json\n @socket.send joinMsgRelay, 0, tnh.ip, tnh.port\n end\n tempRouteTable = []\n @routing_table.each_value { |addr|\n tempRouteTable.push(addr)\n }\n routingInfoMsg = {:type => \"ROUTING_INFO\", :gateway_id => @guid, :node_id => message[\"node_id\"], \\\n :ip_address => @localInetAddr.ip, :port => @localInetAddr.port, :route_table => tempRouteTable}.to_json\n @socket.send routingInfoMsg, 0, message[\"ip_address\"], message[\"port\"]\n end\n\n if message[\"type\"] == \"JOINING_NETWORK_RELAY\"\n tnh, tm, tn = nextHop(message[\"node_id\"])\n nh, gm, gn = nextHop(message[\"gateway_id\"])\n if @routing_table.has_key?([0, tm, tn]) == false\n #puts \"h6\"\n @routing_table[[0, tm, tn]] = {:node_id => message[\"node_id\"], :ip_address => message[\"ip_address\"], \\\n :port => message[\"port\"]}\n end\n if tnh.ip != nil\n joinMsgRelay = {:type => \"JOINING_NETWORK_RELAY\", :node_id => message[\"node_id\"], \\\n :gateway_id => message[\"gateway_id\"], \\\n :ip_address => message[\"ip_address\"], :port => message[\"port\"]}.to_json\n @socket.send joinMsgRelay, 0, tnh.ip, tnh.port\n end\n tempRouteTable = []\n @routing_table.each_value { |addr|\n tempRouteTable.push(addr)\n }\n routingInfoMsg = {:type => \"ROUTING_INFO\", :gateway_id => message[\"gateway_id\"], :node_id => message[\"node_id\"], \\\n :ip_address => @localInetAddr.ip, :port => @localInetAddr.port, :route_table => tempRouteTable}.to_json\n if nh.ip != nil\n @socket.send routingInfoMsg, 0, nh.ip, nh.port\n end\n end\n\n=begin\n when getting a routing info message extract as much useful information out of it as we can and forward it onto the\n intended target node unless it was intended for our node\n=end\n if message[\"type\"] == \"ROUTING_INFO\"\n routeInfo(message[\"route_table\"])\n if message[\"node_id\"] == @guid\n return\n elsif message[\"gateway_id\"] == @guid\n if @gateway_table.has_key?(message[\"node_id\"])\n p @socket.send message.to_json, 0, @gateway_table[message[\"node_id\"]][:ip_address].to_s, @gateway_table[message[\"node_id\"]][:port]\n else\n puts \"Routing_Info message receave error not key in gatewayTable!\"\n end\n else\n nh, gm, gn = nextHop(message[\"node_id\"])\n message = message.to_json\n if nh.ip != nil\n @socket.send message, 0, nh.ip, nh.port\n end\n end\n end\n\n # If get a leaving message, remove the node from the network\n if message[\"type\"] == \"LEAVING_NETWORK\"\n removeAddr(message[\"node_id\"])\n end\n\n # When receive an chat message,check if it is intended for\n # If not, forward to next hop\n if message[\"type\"] == \"CHAT\"\n if message[\"target_id\"] == @guid\n flag = true\n for i in 0..@postHash.length-1\n if @postHash[i][:text] == message[\"post\"]\n flag = false\n end\n end\n if flag\n @postHash << {:text => message[\"post\"]}\n end\n ackChatMsg = {:type => \"ACK_CHAT\", :node_id => message[\"sender_id\"], :Tag => message[\"Tag\"]}.to_json\n if message[\"sender_id\"] == @guid\n puts \" \"\n print @name, \" CHATTING WITH YOURSELF\" # If processes own chatting message, no need to send an ACK\n puts \" \"\n return\n end\n nh, sm, sn = nextHop(message[\"sender_id\"])\n @socket.send ackChatMsg, 0, nh.ip, nh.port\n else\n nh, tm, tn = nextHop(message[\"target_id\"])\n if nh.ip != nil\n @socket.send message.to_json, 0, nh.ip, nh.port\n end\n end\n end\n\n\n # Keep forwarding until this ACK_CHAT message reaches its destination\n if message[\"type\"] == \"ACK_CHAT\"\n if message[\"node_id\"] == @guid\n tagHash = Hash_Func(message[\"Tag\"])\n @chatAckWait[tagHash] = 2\n else\n nh, m, n = nextHop(message[\"node_id\"])\n if nh.ip != nil\n @socket.send message.to_json, 0, nh.ip, nh.port\n end\n end\n end\n\n\n=begin\n Keep forwarding chat_retrieve message until it reaches correct location in which case appending @postHash to a\n chat response message and send it to the sender ID\n=end\n if message[\"type\"] == \"CHAT_RETRIEVE\"\n if message[\"node_id\"] == @guid\n chatresponse_msg = {:type => \"CHAT_RESPONSE\", :tag => message[\"tag\"], :node_id => message[\"sender_id\"],\n :sender_id => @guid, :response => @postHash}.to_json\n nh, sm, sn = nextHop(message[\"sender_id\"])\n @socket.send chatresponse_msg, 0, nh.ip, nh.port\n else\n nh, tm, tn = nextHop(message[\"node_id\"])\n message = message.to_json\n if nh.ip != nil\n @socket.send message, 0, nh.ip, nh.port\n end\n end\n end\n\n=begin\n Keep forwarding response until reach intended recipient and then put results in flag.\n Original chat_retrieve thread can process the results\n=end\n if message[\"type\"] == \"CHAT_RESPONSE\"\n if message[\"node_id\"] == @guid\n @chat_retrieveAckWait[message[\"sender_id\"]] = message[\"response\"]\n else\n nh, tm, tn = nextHop(message[\"node_id\"])\n if nh.ip != nil\n @socket.send message.to_json, 0, nh.ip, nh.port\n end\n end\n end\n\n # Upon receiving a PING, sending to next hop and generating ACK\n if message[\"type\"] == \"PING\"\n ackMsg = {:type => \"ACK\", :node_id => @guid, :ip_address => @localInetAddr.ip, \\\n :port => @localInetAddr.port}.to_json\n @socket.send ackMsg, 0, message[\"ip_address\"], message[\"port\"]\n if message[\"target_id\"] != @guid\n #puts @name, \"PNH\", message[\"target_id\"], Time.now\n nh, m, n = nextHop(message[\"target_id\"])\n if nh.ip != nil\n message[\"ip_address\"] = @localInetAddr.ip\n message[\"port\"] = @localInetAddr.port\n @socket.send message.to_json, 0, nh.ip, nh.port\n end\n end\n end\n\n # Receiving an ACK message proves the node is still alive\n if message[\"type\"] == \"ACK\"\n @checkAckWait[message[\"node_id\"]] = 2\n end\n end", "def shared_route(path, controller = nil, &block)\n\t\tunless @active_router\n\t\t\tGReactor.warn \"You should define a listener before adding a shared route - use `Plezi.listen`.\\nCreating a default (empty) listener.\"\n\t\t\tPlezi.listen\n\t\tend\n\t\t@routers_locker.synchronize { @routers.each {|r| r.add_shared_route path, controller, &block } }\n\tend", "def route_to(path, args = {}, protocol = \"http://\")\n request = Request.new({:protocol => protocol, :path => path}.merge(args))\n # Merb::Router.match(request)\n Merb::Router.route_for(request)\n end", "def get_user_route(user)\n try_route(:user, user)\n end", "def add_path(destination, knights_action, knights_path)\n visited_destinations << destination\n knights_path << { position: destination, source: knights_action }\n end", "def route\n @route\n end", "def request_referer(request, uri, referer); end", "def packet_in datapath_id, message\n match = ExactMatch.from( message )\n action, log = lookup_rules( datapath_id, match )\n info \"action=#{ action }, datapath_id=#{ datapath_id.to_hex }, message={#{ match.to_s }}\" if log\n if action == :allow\n #set rules in the switch\n #please fill up the following blank ****** user input from here ******\n send_flow_mod_add( datapath_id,\n :match => match,\n :idle_timeout => 300,\n :hard_timeout => 300,\n :actions => ActionOutput.new( (match.in_port == 1)? 2 : 1 )\n )\n #set rules in the switch for reverse path\n #please fill up the following blank ****** user input from here ******\n # reverse flow has the same attributes, but with source/destination\n # swapped\n reverse_match = Match.new(\n :in_port => (match.in_port == 1)? 2 : 1,\n :dl_src => match.dl_dst, # swapping source and dest\n :dl_dst => match.dl_src, # MAC addresses\n :dl_type => match.dl_type,\n :dl_vlan => match.dl_vlan,\n :dl_vlan_pcp => match.dl_vlan_pcp,\n :nw_tos => match.nw_tos,\n :nw_proto => match.nw_proto,\n :nw_src => match.nw_dst, # swapping source and dest\n :nw_dst => match.nw_src, # IP addresses\n :tp_src => match.tp_dst, # swapping source and dest\n :tp_dst => match.tp_src # TCP ports\n )\n info \"reverse flow: {#{ reverse_match.to_s }}\"\n send_flow_mod_add( datapath_id,\n :match => reverse_match,\n :idle_timeout => 300,\n :hard_timeout => 300,\n :actions => ActionOutput.new( (reverse_match.in_port == 1)? 2 : 1 )\n )\n else \n #set drop rule in the switch\n #please fill up the following blank ****** user input from here ******\n send_flow_mod_add( datapath_id,\n :match => match,\n :idle_timeout => 300,\n :hard_timeout => 300\n )\n end\n end" ]
[ "0.58377457", "0.5802118", "0.564564", "0.55723697", "0.54849094", "0.5454066", "0.54359776", "0.5412983", "0.53737605", "0.53597045", "0.5349736", "0.53322536", "0.532743", "0.53150374", "0.530132", "0.5287566", "0.52838707", "0.5251775", "0.52385974", "0.52003413", "0.51650655", "0.5155923", "0.51355976", "0.5133088", "0.51173884", "0.51068324", "0.50810474", "0.5072508", "0.50662744", "0.5062282", "0.5060698", "0.50543845", "0.49904615", "0.49904615", "0.498972", "0.49843025", "0.49758294", "0.49616215", "0.49552608", "0.49436688", "0.49410954", "0.49408937", "0.49337122", "0.4932772", "0.49279797", "0.49273774", "0.4913199", "0.490767", "0.4899804", "0.48929173", "0.48890454", "0.48842216", "0.48801926", "0.48724696", "0.48724696", "0.48724696", "0.4866477", "0.48580146", "0.48407376", "0.48373222", "0.48364687", "0.4831251", "0.4829518", "0.48203248", "0.4817435", "0.48151302", "0.48071626", "0.48034453", "0.4800473", "0.47977176", "0.4797651", "0.4796851", "0.47942826", "0.47919697", "0.47845706", "0.47796553", "0.47796553", "0.47752705", "0.4773414", "0.47718543", "0.4770886", "0.47686595", "0.47555435", "0.47491783", "0.47472602", "0.4746517", "0.4740202", "0.47367907", "0.4732319", "0.47313505", "0.47308373", "0.47159284", "0.47083148", "0.4701419", "0.47008598", "0.47002846", "0.4700052", "0.46999806", "0.4696635", "0.46866152" ]
0.5240686
18
Search the TISS REST API for the query
def search begin @theses = Thesis.search(params[:query]) if params[:query] rescue Searchable::SearchError => msg flash.now[:error] = msg rescue Searchable::NoSearchResults => msg flash.now[:notice] = msg end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def Search query\n \n APICall(path: \"search.json?query=#{query}\",method: 'GET')\n \n end", "def scsearch(squery)\n\thttp = Net::HTTP.new(\"shell-storm.org\", 80)\n\treq = Net::HTTP::Get.new(\"/api/?s=#{squery.downcase}\", {'User-Agent' => 'Shell-Storm Ruby API - Search'})\n\tres = http.request(req)\n\tcase res\n\twhen Net::HTTPSuccess then\n\t\tt=[ [ \"Author\", 'Platform', 'Description', 'ID' ] ]\n\t\tres.body.split(\"\\n\").each do |entry|\n\t\t\tshow = entry.split(\"::::\")\n\t\t\tt << [ \"#{show[0]}\", \"#{show[1]}\", \"#{show[2]}\", \"#{show[3]}\" ]\n\t\tend\n\t\ttable = t.to_table(:first_row_is_head => true)\n\t\tputs \"#{HC}#{FGRN}\" + table.to_s + \"#{RS}\"\n\telse\n\t\tputs \"#{HC}#{FRED}Seems we made a bad request somehow#{FWHT}....#{RS}\"\n\t\tputs res.value\n\tend\nend", "def search(params = {})\n @api.get(\"api.json\", params)\n end", "def search limit: nil, npa: nil, nxx: nil, page: nil, ratecenter: nil, state: nil, tn: nil\r\n # the base uri for api requests\r\n query_builder = Configuration.BASE_URI.dup\r\n\r\n # prepare query string for API call\r\n query_builder << \"/available-tns/tns/\"\r\n\r\n # process optional query parameters\r\n query_builder = APIHelper.append_url_with_query_parameters query_builder, {\r\n \"limit\" => limit,\r\n \"npa\" => npa,\r\n \"nxx\" => nxx,\r\n \"page\" => page,\r\n \"ratecenter\" => ratecenter,\r\n \"state\" => state,\r\n \"tn\" => tn,\r\n }\r\n\r\n # validate and preprocess url\r\n query_url = APIHelper.clean_url query_builder\r\n\r\n # prepare headers\r\n headers = {\r\n \"user-agent\" => \"Flowroute SDK 1.0\",\r\n \"accept\" => \"application/json\"\r\n }\r\n\r\n response = CustomAuthUtility.append_custom_auth_params method:'GET',\r\n query_url:query_url,\r\n headers:headers\r\n\r\n # Error handling using HTTP status codes\r\n if response.code == 401\r\n raise APIException.new \"NOT AUTHORIZED\", 401, response.raw_body\r\n elsif response.code == 500\r\n raise APIException.new \"APPLICATION/SERVER ERROR\", 500, response.raw_body\r\n elsif !(response.code.between?(200,206)) # [200,206] = HTTP OK\r\n raise APIException.new \"HTTP Response Not OK\", response.code, response.raw_body\r\n end\r\n\r\n response.body\r\n end", "def search(query); end", "def search(query)\n params = { key: self.api_key, cx: self.search_engine_id, q: query }\n uri = URI(BASE_URL)\n uri.query = URI.encode_www_form(params)\n request = build_request(uri)\n\n response = self.execute_search(uri, request)\n format_response(response)\n end", "def search\n # bail out if doing an unauthenticated API request\n failures = []\n respond_to do |format|\n format.html do\n @test_instances, failures = \n TestInstance.query(params[:query_text]) if params[:query_text]\n if @test_instances\n @test_instances = @test_instances.page(params[:page])\n end\n unless failures.empty?\n flash.now[:warning] = 'Invalid search parameters: ' + \n failures.join(', ') + '.'\n end\n @show_instructions = @test_instances.nil?\n end\n format.json do\n if authenticated?\n @test_instances, failures = \n TestInstance.query(params[:query_text]) if params[:query_text]\n if @test_instances\n render json: {\"results\" => @test_instances,\n \"failures\" => failures}.to_json\n else\n render json: {\"results\" => [], \"failures\" => failures}.to_json\n end\n else\n fail_authenticate_json\n end\n end\n end\n end", "def search(query)\n @search_svc.search query\n end", "def search_request(params)\n result = @client.connection.get PATH, params\n Error.check_for_error(result)\n result\n end", "def search(query)\n @client.get('/BikePoint/Search', { query: query })\n end", "def search\n query = {\n 'res_id' => params[:id]\n }\n @search = HTTParty.get('https://developers.zomato.com/api/v2.1/restaurant?', query: query, headers: headers)\n end", "def search_request(params)\n result = @client.connection.get(PATH, params)\n Yelp::Fusion::Error.check_for_error(result)\n result\n end", "def search\n send_request\n parse_response\n end", "def search(params = {})\n http.get(\"/nfse\", params: filter(params)) do |response|\n respond_with_collection(response)\n end\n end", "def index\n @querylists = HTTParty.post(\"http://66.175.217.67:3020/argames/getQuery\", :body => { :checkFilter => '' }, :headers => {\"Authorization\" => \"Bearer \" + ENV[\"API_KEY\"] })\n end", "def search_twitter()\n search_call = \"#{@api_endpoint_twitter}?ors=#{@search_term}&result_type=#{@result_type}&rpp=#{@results_per_page}\"\n @response = http_get search_call\n end", "def search(query, options = {}, remote_ip = nil)\n (headers 'X-Forwarded-For' => remote_ip.to_s) unless remote_ip.nil?\n self.parameters = { 'q' => query }\n options[:page] ||= 1\n options[:count] ||= 5\n parameters['filter'] = options[:filter] if options[:filter]\n parameters['startIndex'] = options[:count] * (options[:page] - 1)\n parameters['maxResults'] = options[:count]\n parameters['key'] = options[:api_key] if options[:api_key]\n parameters['orderBy'] = 'newest' if options[:order_by].eql?('newest')\n parameters['country'] = options[:country] if options[:country]\n Response.new(get(url.to_s))\n end", "def search(query)\n # need to handle invalid data\n q = query.blank? ? DEFAULT_SEARCH_QUERY : query\n @client.search(q, lang: 'en', result_type: 'recent').take(20)\n end", "def search_result\n @search = params[:search]\n query = params[:search] #Query variable is the string a user enters in the search bar.\n url = Addressable::URI.parse('https://api.themoviedb.org/3/search/tv?api_key=fb6a1d3f38c3d97f67df6d141f936f29&language=en-US')\n url.query_values = url.query_values.merge(query: query)\n response = HTTParty.get(url)\n @results = JSON.parse(response.body, symbolize_names: true) \n end", "def search(term, location)\n url = \"#{API_HOST}#{SEARCH_PATH}\"\n params = {\n term: term,\n location: location,\n limit: SEARCH_LIMIT\n }\n#this takes info from params hash\n response = HTTP.auth(bearer_token).get(url, params: params)\n response.parse[\"businesses\"]\nend", "def search(query, options={})\n self.perform_get(\"/search\", {\n :q => query\n }.merge(options|| {}))\n end", "def search_techcrunch\n response_string = RestClient.get\"https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=45aee5b7c7584064ac1b1de6297f5137\"\n response_hash = JSON.parse(response_string.body)\n end", "def index\n query = params[\"query\"]\n unless query.nil? || query == \"\" \n @tweets = Twitter.basic_search(query)\n @wikipedia = Wikipedia.basic_search(query)\n end\n end", "def search(query)\n alert_setup_incomplete && return unless is_setup_ok?\n client = get_client\n query = \"tag:#{query}\" if options[:tag]\n client.search query\n end", "def search\n expose Challenge.search(@oauth_token, params[:keyword])\n end", "def call(query)\n # TODO: handle exceptions\n self.class.get(\"/jokes/search?query=#{query}\")\n end", "def search(project: nil, text: nil, kind: 'subject', tags: { }, page: 1, results: [])\n raise 'no project specified' unless project\n tag_query = tags.each_pair.collect{ |k, v| \"tags[#{ k }]=#{ v }\" }.join '&'\n uri = URI.parse \"https://api.zooniverse.org/projects/#{ project }/talk/search?text=#{ text }&kind=#{ kind }&#{ tag_query }&per_page=20&page=#{ page }\"\n req = Net::HTTP::Get.new uri.to_s\n http = Net::HTTP.new uri.host, uri.port\n http.use_ssl = true\n res = http.request req\n json = JSON.parse res.body\n \n pages = (json['total'] / json['per_page'].to_f).ceil\n \n # More than 1,000 results\n if page == 1 && pages > 50\n puts \"\\n\\nThis query has #{ json['total'] } results.\"\n puts \"It could take a long time and degrade server performance.\"\n puts \"Are you really sure you want to run this query? (y/n)\"\n return unless gets.chomp =~ /y/i\n end\n \n if json['page'] < pages\n puts \"#{ json['page'] } / #{ pages }\"\n search project: project, text: text, kind: kind, tags: tags, page: page + 1, results: results + json['results']\n else\n results + json['results']\n end\nend", "def results\n raw_input = params[:search].to_s\n formatted_input = raw_input.gsub(\" \", \"+\")\n\n @client = HTTParty.get(\"http://api.shopstyle.com/api/v2/products?pid=uid5001-30368749-95&fts='#{formatted_input}'&offset=0&limit=20\")\n\n render json: @client\n end", "def search\n @tweets = TwitterClient.search(params[:query], result_type: 'recent').take(20)\n render json: @tweets\n end", "def search\n stuff = params[:q]\n ntee_id = params[:ntee_id]\n results = Typhoeus.get(\"https://projects.propublica.org/nonprofits/api/v1/search.json\", :params => {:q => stuff, 'ntee[id]' => ntee_id })\n @nonprofit_result = JSON.parse(results.body)\n end", "def find\n\t\t#puts \"find, line \" + \"37\"\n\t\tclnt = JSONClient.new\n\t\theader = {'Cookie' => 'Summon-Two=true'}\n\t\turi = URI.parse(URI.encode(\"http://tufts.summon.serialssolutions.com/api/search?pn=1&ho=t&q=\" + params[:title]))\n\t\tresponse = clnt.get(uri, nil, header)\n\t\tjson_response = response.content\n\t\tif json_response.keys.include?(\"documents\")\n\t\t\t@result = response.content[\"documents\"]\n\n\t\t\t\n\t\telse\n\t\t\t@result = ''\n\t\tend\n\tend", "def search\n \t@whosaidit = params[:whosaidit]\n \t@query = params[:query]\n\n if params[:enableRT] == true\n @RToption = \"-RT\"\n else\n @RToption = \"\"\n end\n\n \t# user and keyword\n \t# @tweets = $twitter.search(\"to:#{@whosaidit} \"+ @query + \" filter:images\").take(20)\n\n \t# just keyword\n \t# @tweets = $twitter.search(@query + \" filter:images\").take(20)\n\n \t# just user\n \t@tweets = $twitter.search(\"from:#{@whosaidit}\" + \" filter:images \"+\"#{@RToption}\").take(30)\n \n \t# puts @tweets.first.inspect\n \t@twitteranalysis = \"\"\n \trender \"index\"\n end", "def search\n query = params[:q]\n works = ActiveFedora::SolrService.query(query, fq: @fq, fl: @fl, df: @df, rows: @max_rows) \n format_solr_keys(works)\n render(json: works)\n end", "def getResultsFromSearch(query, type, guts, ppOverride)\n request('getResultsFromSearch', {'query' => query, 'type' => type, 'guts' => guts, 'ppOverride' => ppOverride})\nend", "def search(query_string)\n query_string.blank? ? perform(:get, @resource_type.to_s) : perform(:get, \"#{@resource_type}?#{query_string}\")\n end", "def search(query, options = {}); end", "def request_search(options, format = :xml)\r\n\t\t\turi = URI \"#{API_URL}edsapi/rest/Search?#{options}\"\r\n\t\t\t@log << uri.to_s << \" -- \"\r\n\t\t\t#return uri.request_uri\r\n\t\t\treq = Net::HTTP::Get.new(uri.request_uri)\r\n\r\n\t\t\treq['x-authenticationToken'] = @auth_token\r\n\t\t\treq['x-sessionToken'] = @session_token\r\n\t\t\treq['Accept'] = 'application/json' #if format == :json\r\n\r\n\t\t\tNet::HTTP.start(uri.hostname, uri.port, :read_timeout => 10) { |http|\r\n \t\t\tbegin\r\n\t\t\t return http.request(req).body\r\n\t\t\trescue Timeout::Error, Net::ReadTimeout, Errno::EINVAL, Errno::ECONNRESET, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e\r\n\t\t\t raise \"No response from server\"\r\n\t\t\tend\r\n\t\t\t}\r\n end", "def search(options={})\n params = []\n options.each do |key, value|\n params << \"#{key}=#{value}\"\n end\n ethon = ethon_easy_json_requester\n ethon.url = uri_escape(\"#{base_api_url}search/query?#{params.join('&')}\")\n ethon.perform\n check_and_raise_failure(ethon)\n server_responded_at = Time.now\n {\n requested_url: ethon.url,\n server_responded_at: server_responded_at,\n results: parse_search_response(ethon.response_body)\n }\n end", "def search(query, reverse = false)\n doc = fetch_parsed_response(query, reverse)\n doc && doc['status'] == \"OK\" ? doc : nil\n end", "def search\n unless params[:search].blank?\n @search = Sunspot.search(KyuEntry) do\n fulltext params[:search]\n end\n @kyu = @search.results\n end\n end", "def search\n\n end", "def search\n\n end", "def ask_query(query)\n root_url = 'https://research.tsadra.org/api.php?'\n research_query = root_url + query\n client = MediawikiApi::Client.new(research_query)\n\n client.log_in(ENV['RESEARCH_WIKI_USERNAME'], ENV['RESEARCH_WIKI_PASSWORD'])\n response = client.query\n response.data\n end", "def search\n end", "def search(params={})\n rpc_call :search, params\n end", "def search\n end", "def search\n end", "def search\n end", "def search\n end", "def search\n end", "def search\n end", "def search\n end", "def search\n end", "def search\n end", "def search\n end", "def search\n terms = @authority.search(url_search)\n render json: terms\n end", "def search\n @users = User.search(@search_term)\n @tweets = Tweet.search(@search_term)\n @tags = Tag.search(@search_term)\n end", "def search(query_string, page = 1)\n oauth_response = access_token.get(\"/api/v1/search.json\", :search => query_string, :page => page)\n JSON.parse(oauth_response)\n end", "def search \n\n end", "def index\n @docs = SearchController.search(params[:query]) if params[:query].present?\n end", "def search(query, qrserver_id=0, requestheaders = {}, verbose = false, params = {})\n search_with_timeout(10, query, qrserver_id, requestheaders, verbose, params)\n end", "def search_by_keyword\n space(1)\n puts \"What do you want to search for?\"\n space(1)\n keyword = get_input\n url = \"https://app.ticketmaster.com/discovery/v2/events?apikey=pyLDDCYURYJ8LZfAUnOayESRsPBTWnKM&keyword=#{keyword}&locale=en&sort=date,asc\"\n response = RestClient.get(url)\n if JSON.parse(response)[\"_embedded\"][\"events\"]\n attractions = JSON.parse(response)[\"_embedded\"][\"events\"]\n attractions[0...20]\n else\n puts \"Sorry, your search returned no results. Try again.\"\n search_by_city\n end\nend", "def search; end", "def search\n @hits = []\n\n if params[:query]\n search = DesignMethod.solr_search do\n fulltext params[:query] do\n highlight\n minimum_match 0\n end\n end\n store_location\n @hits = search.hits\n @results = search.results\n end\n\n respond_to do |format|\n format.html\n format.json { render json: @results }\n end\n end", "def search(query, opts = {})\r\n page = opts[:page] || 1\r\n uri = url_for('search', opts)\r\n response = RestClient.get(uri, params: { q: query, page: page })\r\n JSON.parse response\r\n end", "def search\n @q = params[:q]\n @results = Series.external_search(@q)\n\n respond_to do |format|\n format.html # search.html.haml\n format.json { render json: @results.to_json }\n end\n end", "def index\n if params[:search]\n @tutorials = Tutorial.search(params[:search]).order(\"created_at DESC\")\n else\n @tutorials = Tutorial.all.order('created_at DESC')\n end\n=begin\n #for sunspot\n @search = Tutorial.search do\n fulltext params[:search]\n end\n @tutorials = @search.results\n=end\n end", "def srch(opts={})\n\t\t\t\tsrch_client.search(opts)\n\t\t\tend", "def search\n Api.search_all_apis params[:postcode]\n end", "def search\n spotyfy_client = SpotyfyClient.new(params[:search])\n spotyfy_client.perform\n items = SpotyfyService.parse_hash(spotyfy_client.body)\n render :json => items.to_json\n end", "def query\n sanitize search_params['query']\n end", "def index \n unless(params[:search==nil]) \n @requests = Request.search(params[:search]) \n end \n end", "def search(user, query, collection, wiki)\n end", "def search\n\n @tasks = []\n \n PgSearch.multisearch(params['search-string']).where(:searchable_type => \"Task\").find_each do |document|\n @tasks << document.searchable\n end\n\n respond_to do |format|\n format.html { render action: \"index\" }\n format.json { render json: @task.errors, status: :unprocessable_entity }\n end\n \n end", "def search\n\n # define the elasticsearch result \"size\" (limit)\n limit = params['limit'].to_i\n # define the elasticsearch result \"from\" (offset)\n offset = params['offset'].to_i\n # Pass through\n hack = params['hack']\n # Default output\n searchResults = ''\n # If we have filters, we need to parse them\n if params['filters'].present?\n filters = []\n # For each of the filters format them and stuff them into an array\n params['filters'].each do |key, filter|\n\n if [\n 'properties.educationalAlignment.properties.targetName',\n 'properties.inLanguage',\n 'properties.isBasedOnUrl',\n 'properties.thumbnailUrl',\n 'properties.timeRequired',\n 'properties.typicalAgeRange',\n 'properties.url',\n 'properties.useRightsUrl'\n ].include?(key)\n searchKey = \"schema-org.#{key}.original\"\n matchTerm = 'term'\n else\n searchKey = \"schema-org.#{key}\"\n matchTerm = 'match'\n end\n\n if filter.keys.count > 1\n # This is more complex because this filter type needs the keys or'd together\n orFilters = []\n filter.keys.each do |f|\n orFilters << { 'query' => { matchTerm => { searchKey => f.to_s } } }\n end\n filters << { 'or' => orFilters }\n else\n # This should be simple, there is only one of this filter key\n filters << { 'query' => { matchTerm => { searchKey => filter.keys.first.to_s } } }\n end\n end\n\n # If the query is present we need to match it\n if params['query'].present?\n query = { 'match' => { '_all' => params['query'] } }\n filter = { 'and' => filters }\n # If no query is present then we can wildcard against anything\n else\n query = { 'match_all' => { } }\n filter = { 'and' => filters }\n end\n # if not filter is present then just match against query\n else\n query = { 'match' => { '_all' => params['query'] } }\n end\n\n # Build the payload from the various parts\n payload = {\n 'size' => limit,\n 'from' => offset,\n 'query' => {\n 'filtered' => {\n 'query' => query,\n 'filter' => filter\n }\n },\n \"facets\" => {\n \"intendedEndUserRole\" => {\n \"terms\" => {\n \"field\" => \"schema-org.properties.intendedEndUserRole.original\",\n \"global\" => true,\n \"all_terms\" => true\n }\n },\n \"typicalAgeRange\" => {\n \"terms\" => {\n \"field\" => \"schema-org.properties.typicalAgeRange.original\",\n \"global\" => true,\n \"all_terms\" => true\n }\n },\n \"educationalUse\" => {\n \"terms\" => {\n \"field\" => \"schema-org.properties.educationalUse.original\",\n \"global\" => true,\n \"all_terms\" => true\n }\n },\n \"interactivityType\" => {\n \"terms\" => {\n \"field\" => \"schema-org.properties.interactivityType.original\",\n \"global\" => true,\n \"all_terms\" => true\n }\n },\n \"learningResourceType\" => {\n \"terms\" => {\n \"field\" => \"schema-org.properties.learningResourceType.original\",\n \"global\" => true,\n \"all_terms\" => true\n }\n },\n \"mediaType\" => {\n \"terms\" => {\n \"field\" => \"schema-org.properties.mediaType.original\",\n \"global\" => true,\n \"all_terms\" => true\n }\n }\n }\n }\n\n#puts \"PAYLOAD\"; puts Rails.configuration.elastic_search_url; puts payload.to_json\n\n # Okay after all that mess, lets make the request\n request = RestClient::Request.new( :method => :get, :url => Rails.configuration.elastic_search_url, :payload => payload.to_json )\n # Since this can error lets catch it\n begin\n searchResults = request.execute\n results = JSON.parse(searchResults)\n results[:hack] = hack\n\n#puts \"RESPONSE\"; puts results.to_json\n\n respond_to do |format|\n format.json { render json: results }\n end\n rescue => e\n # @TODO Need to return the correct error type and then an error message to be shown to user.\n respond_to do |format|\n format.json { render json: searchResults }\n end\n#puts \"ERROR!\"; puts e.response\n end\n\n end", "def show\n begin\n @search_by_nutrients = @client.search_by_nutrients(params[:min],params[:max],params[:value1],params[:value2 ])\n rescue RuntimeError\n @error = true\n end\n end", "def do_search(url, use_get = false)\n if use_get\n request = Net::HTTP::Get.new(url)\n Rails.logger.debug(\"GET Search url: #{url}\")\n else\n request = Net::HTTP::Post.new(url)\n Rails.logger.debug(\"POST Search url: #{url} \")\n end\n response = do_http_request(request)\n if response.code.to_s != '200'\n raise RequestFailedException.new(\"#{response.code}: #{response.body}\")\n end\n results = ASUtils.json_parse(response.body)\n results\n end", "def index\n @txdotlights = Txdotlight.all.paginate(:per_page =>15, :page => params[:page])\n .where(\"intersection ILIKE ?\",\"%#{params[:address_search]}%\").where(\"name ILIKE ?\",\"%#{params[:name_search]}%\").where(\"callback ILIKE ?\",\"%#{params[:phone_search]}%\").where(\"unitassigned ILIKE ?\",\"%#{params[:unit_search]}%\")\n end", "def recipe_search_results_for(search, number=100)\n Faraday.get \"#{RECIPE_SEARCH_URL}#{search}&number=#{number}&apiKey=#{spoonacular_key}\"\n end", "def show\n search_url = \"https://seeiendom.kartverket.no/api/soekEtterEiendom?searchstring=#{CGI.escape(@address_search.search_string)}\"\n @search_result_json = HTTParty.get(search_url)\n end", "def simple_search(query)\n search({:query => query})\n end", "def make_search(url)\n #make the web request\n data = RestClient.get url\n JSON.parse(data)\nend", "def index\n # Generate sunspot search\n @records = record_default_search\n\n respond_with(@records)\n end", "def search\n response = make_request\n begin\n response_hash = JSON.parse(response.body)\n rescue JSON::ParserError\n raise RequestException\n else\n response_hash\n end\n end", "def search\n add_breadcrumb :search\n @start = Time.now\n @search = User.search(:include => [:tags]) do\n fulltext params[:q] do\n fields(:bio, :name => 2.0)\n end\n order_by sort_column, sort_direction\n paginate :page => params[:page], :per_page => 21\n end\n\n respond_to do |format|\n format.html { render :action => \"index\" }\n format.xml { render :xml => @search }\n format.xml { render :json => @search }\n end\n end", "def search\n results = @test.search(test_params)\n return render json: {results: results, total: results.total_entries}\n end", "def search_requests( cid )\n url = \"#{self.url}?auth=#{self.authtoken}&cid=#{cid}\"\n status, response = rest_get( url )\n return status, response['details'] if ok?( status ) && response['details']\n return status, ''\n end", "def query(params)\n request(Resources::RESOURCE_QUERY, HTTP_METHOD_POST, params)\n end", "def search(term)\n url = \"#{API_HOST}#{SEARCH_PATH}\"\n params = {\n term: term,\n # location: DEFAULT_LOCATION,\n latitude: 37.784517,\n longitude: -122.397194,\n limit: SEARCH_LIMIT,\n open_now: true\n }\n\n response = HTTP.auth(ENV[\"AUTHORIZATION\"]).get(url, params: params)\n\n response.parse\n end", "def search(query, options={})\n api_response = @api_client.make_api_request(:GET, \"artist/search\", {:q => query}, options)\n @api_client.artist_digestor.nested_list_from_xml(api_response.content.search_results, :search_result, :search_results)\n end", "def index\n # @search = Shelter.search do\n # fulltext params[:search]\n # end\n # @shelters = @search.results\n @shelters = Shelter.all\nend", "def search(query, results = nil)\n params = { :query => query }\n params[:results] = results unless results.nil?\n get :webSearch, params\n end", "def search(options = {})\n self.date = options[:date] || date\n self.hd = options[:hd] || hd\n response = HTTParty.get(DEFAULT_URL, query: attributes)\n handle_response(response)\n end", "def search\n @google = Rails.application.secrets.google_api_key\n puts query[\"query\"]\n @response = HTTParty.get(\"https://www.googleapis.com/books/v1/volumes?q=#{query[\"query\"]}&key=#{@google}\")\n render json: {data: @response}\n end", "def execute_search(query)\n search_resource.retrieve(query)\n end", "def index\n from_param = (params[:p].to_i * 10)\n @recipes = RecipeApi.search(params[:query], from_param )\n end", "def searches\n wrapping!(\n search(\n root_uri,\n data_raw.to_s.gsub('=>', ':')\n )\n )\n end", "def index\n authorize! :read, Recipe\n @query = params[:query]\n @search_result = Recipe.search do\n fulltext params[:query]\n if params[:course_type_ids].present?\n all_of do\n params[:course_type_ids].each do |filter|\n with(:course_type_ids, filter)\n end\n end\n end\n if params[:exclu_course_type_ids].present?\n all_of do\n params[:exclu_course_type_ids].each do |filter|\n without(:course_type_ids, filter)\n end\n end\n end\n if params[:difficulty].present?\n all_of do\n params[:difficulty].each do |filter|\n with(:difficulty, filter)\n end\n end\n end\n if params[:exclu_difficulty].present?\n all_of do\n params[:exclu_difficulty].each do |filter|\n without(:difficulty, filter)\n end\n end\n end\n if params[:cost].present?\n all_of do\n params[:cost].each do |filter|\n with(:cost, filter)\n end\n end\n end\n if params[:exclu_cost].present?\n all_of do\n params[:exclu_cost].each do |filter|\n without(:cost, filter)\n end\n end\n end\n if params[:category_ids].present?\n all_of do\n params[:category_ids].each do |filter|\n with(:category_ids, filter)\n end\n end\n end\n if params[:exclu_category_ids].present?\n all_of do\n params[:exclu_category_ids].each do |filter|\n without(:category_ids, filter)\n end\n end\n end\n if params[:main_ingredient_ids].present?\n all_of do\n params[:main_ingredient_ids].each do |filter|\n with(:main_ingredient_ids, filter)\n end\n end\n end\n if params[:exclu_main_ingredient_ids].present?\n all_of do\n params[:exclu_main_ingredient_ids].each do |filter|\n without(:main_ingredient_ids, filter)\n end\n end\n end\n if params[:source_ids].present?\n all_of do\n params[:source_ids].each do |filter|\n with(:source_ids, filter)\n end\n end\n end\n if params[:exclu_source_ids].present?\n all_of do\n params[:exclu_source_ids].each do |filter|\n without(:source_ids, filter)\n end\n end\n end\n facet :course_type_ids\n facet :category_ids\n facet :main_ingredient_ids\n facet :source_ids\n facet :difficulty, :sort => :index\n facet :cost, :sort => :index\n paginate :page => params[:page] || 1, :per_page => 10\n order_by(:score, :desc)\n order_by(:created_at, :desc)\n end\n @query_params = params.except( :page )\n \n filters = [\n :course_type_ids, \n :exclu_course_type_ids, \n :difficulty, \n :exclu_difficulty, \n :cost, \n :exclu_cost, \n :category_ids, \n :exclu_category_ids, \n :main_ingredient_ids, \n :exclu_main_ingredient_ids, \n :source_ids, \n :exclu_source_ids\n ]\n filters.each do |filter|\n if params[filter].present?\n params[filter].map!{ |x| x.to_i }\n end\n end\n \n # @search_result.facet(:main_ingredient_ids).rows.sort!{|a,b| (a.count <=> b.count) == 0 ? (a.instance.name <=> b.instance.name) : (a.count <=> b.count)*(-1) }\n # @search_result.facet(:course_type_ids).rows.sort!{|a,b| (a.count <=> b.count) == 0 ? (a.instance.name <=> b.instance.name) : (a.count <=> b.count)*(-1) }\n # @search_result.facet(:category_ids).rows.sort!{|a,b| (a.count <=> b.count) == 0 ? (a.instance.name <=> b.instance.name) : (a.count <=> b.count)*(-1) }\n # @search_result.facet(:source_ids).rows.sort!{|a,b| (a.count <=> b.count) == 0 ? (a.instance.name <=> b.instance.name) : (a.count <=> b.count)*(-1) }\n \n sort_alphabetical(@search_result.facet(:main_ingredient_ids).rows)\n sort_alphabetical(@search_result.facet(:course_type_ids).rows)\n sort_alphabetical(@search_result.facet(:category_ids).rows)\n sort_alphabetical(@search_result.facet(:source_ids).rows)\n end", "def search\r\nend", "def query(s)\n\n response = RestClient.get \"http://#{@host}/api/\" + s\n\n Rexle.new(response.body).root.xpath('./*').inject({}) do |r,x|\n x.text ? r.merge(x.name => x.text.unescape) : r\n end\n\n end" ]
[ "0.7764589", "0.72229016", "0.71741825", "0.7070183", "0.7052473", "0.69716257", "0.69406587", "0.6938641", "0.6921789", "0.6898469", "0.684355", "0.68409854", "0.6797582", "0.6792282", "0.6767056", "0.6765203", "0.6751859", "0.6746635", "0.66900384", "0.6680971", "0.6678334", "0.66571516", "0.6638068", "0.6631461", "0.6604497", "0.66001993", "0.65947324", "0.6592697", "0.65842044", "0.6581924", "0.65771276", "0.65743047", "0.6537059", "0.65188634", "0.65136814", "0.65009934", "0.6499938", "0.6495591", "0.64899033", "0.647901", "0.646182", "0.6455625", "0.645173", "0.64267457", "0.6425809", "0.64179724", "0.64179724", "0.64179724", "0.64179724", "0.64179724", "0.64179724", "0.64179724", "0.64179724", "0.64179724", "0.64179724", "0.6417054", "0.6411308", "0.6401576", "0.6395659", "0.63942105", "0.63911617", "0.6388102", "0.63822526", "0.6381215", "0.63810843", "0.6380988", "0.6377277", "0.6358397", "0.63400716", "0.63239604", "0.63193816", "0.63138723", "0.630094", "0.6300024", "0.629554", "0.62940633", "0.6280026", "0.6279797", "0.6277904", "0.6277213", "0.6269832", "0.6258657", "0.6256383", "0.62490886", "0.624672", "0.6235848", "0.62343204", "0.62250406", "0.62237996", "0.62209696", "0.62207913", "0.62202513", "0.62195176", "0.6214718", "0.6210178", "0.6207621", "0.6204205", "0.62013763", "0.61983955", "0.61966443" ]
0.644545
43
Show the given thesis with the given tiss_id
def show @thesis = Thesis.load params[:id] end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_thesis\n @thesis = Thesis.find(params[:id])\n end", "def display_resource(thesis)\n \"Thesis: #{thesis.title}\"\n end", "def show\n @issuance = Issuance.where(id: params[:id]).first\n end", "def show\n @tuiter = Tuiter.find(params[:id])\n end", "def index\n @theses = Thesis.all\n \n end", "def show\n @sour = @swit.sours.find(params[:id])\n end", "def show\n @thesis_review = ThesisReview.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @thesis_review }\n end\n end", "def show\n @st_ipi = StIpi.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @st_ipi }\n end\n end", "def show\n @technician = Technician.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @technician }\n end\n end", "def show\n @sesh = Sesh.find(params[:id])\n end", "def show\n @cst_ipi = CstIpi.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @cst_ipi }\n end\n end", "def show\n @comentarii = ComentariuFisier.where(fisier_id: @fisier.id)\n @capitol = Capitol.find(@fisier.capitol_id)\n @studentid = Licenta.find(@capitol.licenta_id).user_id\n @student = User.find(@studentid)\n @tema = Tema.find(Licenta.find(@capitol.licenta_id).tema_id)\n end", "def show\n @sipoc = Sipoc.find(params[:id])\n end", "def set_thesis_examination\n @thesis_examination = ThesisExamination.find(params[:id])\n end", "def show\n @stress = current_user.stresses.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n end\n end", "def show\n @fisierele = Fisier.where(capitol_id: @capitol.id)\n @todouri = Todo.where(capitol_id: @capitol.id)\n @comentarii = ComentariuCapitol.where(capitol_id: @capitol.id)\n @studentid = Licenta.find(@capitol.licenta_id).user_id\n @student = User.find(@studentid)\n @tema = Tema.find(Licenta.find(@capitol.licenta_id).tema_id)\n end", "def thesis\n 'Thesis/Dissertation' if record.find { |a| a.tag == '502' }\n end", "def show\n @strelki = Strelki.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @strelki }\n end\n end", "def show\n @sti = Sti.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @sti }\n end\n end", "def get(scrt_id)\n run_action { get! scrt_id }\n end", "def show\n @spaethi = Spaethi.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @spaethi }\n end\n end", "def show\n @problem_test_cases = ProblemTestCase.where(problemid: params[:id])\n @myid = params[:id]\n end", "def show\n @thesis_proposal = ThesisProposal.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @thesis_proposal }\n end\n end", "def show\n @orc_ata = OrcAta.find(params[:id])\n @orc_ata_itens = OrcAtaIten.find(:all, :conditions => ['orc_ata_id=? ',@orc_ata.id ])\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @orc_ata }\n end\n end", "def show\n @trivia = Trivia.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @trivia }\n end\n end", "def thesis_params\n params.require(:thesis).permit(:projectid, :tutor, :descripcion, :user_id, :area_interest_id,:line_investigations, :line_investigation_id, :program_id, :cohorts_id, :titulo, :project_id, :thesis_id)\n end", "def show\n @sitio = Sitio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @sitio }\n end\n end", "def show\n @tsp = Tsp.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json:@tsp }\n end\n end", "def show\n @survey_tung = SurveyTung.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @survey_tung }\n end\n end", "def set_tssk\n @tssk = Tssk.find(params[:id])\n end", "def show\n @temposervico = TempoServico.find(params[:id])\n profid = @temposervico.professor_id\n @professor = Professor.find(:all, :conditions => [\"id = ? and desligado = 0\", profid])\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @temposervico }\n end\n end", "def show\n @st_pi = StPi.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @st_pi }\n end\n end", "def show\n @scaleticket = Scaleticket.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @scaleticket }\n end\n end", "def set_thesis_supervision\n @thesis_supervision = ThesisSupervision.find(params[:id])\n end", "def show\n @trivia_item = Trivia.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @trivia_item }\n end\n end", "def show\n @course = Course.load params[:id] # load object from TISS REST API\n end", "def show\n @subject = Subject.find(params[:subject_id])\n @lessons = ClassJournal.where(subject: @subject, form: @pupil.form).first.lessons\n end", "def toc\n @magissue = Magissue.find(params[:id])\n end", "def show_tsd_super_table\n @data_list = DataList.find(params[:id])\n @all_tsd_files = JSON.parse(open(\"http://readtsd.herokuapp.com/listnames/json\").read)[\"file_list\"]\n @tsd_file = params[:tsd_file].nil? ? @all_tsd_files[0] : params[:tsd_file]\n render \"tsd_super_tableview\"\n end", "def show\n @students = Student.where(school: @school.id)\n @teachers = Teacher.where(school: @school.id) \n end", "def show\n @scholar = Scholar.find(params[:id])\n end", "def index\n @tssks = Tssk.all\n end", "def show\n @cst_icm = CstIcm.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @cst_icm }\n end\n end", "def show\n symptom = Symptom.find(params[:id])\n render response: { symptom: symptom }\n end", "def show\n @user_subject = UserSubject.find(params[:id])\n end", "def show\n @evaluation = Evaluation.friendly.find params[:id]\n @tutee = Tutee.find params[:tutee_id]\n end", "def show\n @lookup_scantask = LookupScantask.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @lookup_scantask }\n end\n end", "def show\n @schedules=@teaching.get_schedules\n end", "def show\n @story = Story.find(params[:id]) # place dans l'objet @story accessible par la vue les infos de la story[id]\n end", "def show\n @syllabus = Syllabus.find params[:id]\n end", "def show\r\n @disciplines_study = DisciplinesStudy.find(params[:id])\r\n\r\n respond_to do |format|\r\n format.html # show.html.erb\r\n format.json { render json: @disciplines_study }\r\n end\r\n end", "def show\n @trek = Trek.find_by_id(params[:id])\n unless @trek.nil?\n @user = User.find_by_id(@trek.user_id)\n if @user.nil?\n redirect_to treks_path,\n :alert => \"User not found for trek #{@trek.title}.\"\n end\n else\n redirect_to treks_path, :alert => \"Trek not found.\"\n end\n end", "def show\n @subject_class = @test.subject_class\n @students = @test.subject_class.students.order(:name)\n @test_questions = @test.test_questions\n @test_question = TestQuestion.new\n @test_question.test_id = @test.id\n end", "def show\n @sprint = Sprint.find(params[:id])\n @stat = Status.find(4)\n @stories = Story.where(\"status_id = ?\", @stat.id)\n @examples = @sprint.stories \n @project_id = @examples.first.project_id\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @sprint }\n end\n end", "def show\n @tuoshui = Tuoshui.find(params[:id])\n end", "def show\n \n logger.info(\"!!!!!!!!!!! #{params[:id]} !!!!!!\")\n @undergraduateprogram = UndergraduateProgram.where(['id = ?', params[:id]])\n end", "def get_synthetics_test(test_id)\n request(Net::HTTP::Get, \"/api/#{API_VERSION}/synthetics/tests/#{test_id}\", nil, nil, false)\n end", "def show\n #not usgin\n #@sire = Sire.find(params[:id]) \n \n #respond_to do |format|\n # format.html # show.html.erb\n # format.xml { render :xml => @sire }\n #end\n end", "def show\n @cartella_clinica=CartellaClinica.find(params[:id])\n @id=session[:test_id]\n end", "def show\n @id = params[:id] #this is the id of the course, used in template to create a link to show the studetns of a course\n @course = Course.find_by_id(params[:id])\n end", "def show\n if params[:print_it] == \"true\"\n @printable = true;\n end\n if @can_show\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @timetable }\n end\n else\n flash[:notice] = I18n.t('timetable.instructions')\n end\n end", "def show_school\n\t\tschool = params[:id]\n\tend", "def show\n @synthinstance = Synthinstance.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @synthinstance }\n end\n end", "def show\n @weeklytimetable = Weeklytimetable.find(params[:id])\n\n common_subjects = [\"Sains Perubatan Asas\", \"Anatomi & Fisiologi\", \"Sains Tingkahlaku\", \"Komunikasi & Sains Pengurusan\"]\n @common_subject_lecturers_ids = Staff.find(:all, :joins=>:position, :conditions=>['unit IN(?)', common_subjects]).map(&:id)\n current_roles = Role.find(:all, :joins=>:logins, :conditions=>['logins.id=?', Login.current_login.id]).map(&:authname)\n @is_admin=true if current_roles.include?(\"administration\") || current_roles.include?(\"weeklytimetables_module_admin\") || current_roles.include?(\"weeklytimetables_module_viewer\") || current_roles.include?(\"weeklytimetables_module_user\")\n @is_common_lecturer=true if @common_subject_lecturers_ids.include?(Login.current_login.staff_id)\n \n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @weeklytimetable }\n end\n end", "def show\n @test = TkdTest.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @test }\n end\n end", "def show\n if current_user.member?\n # 自分で投稿した内容のみ表示する。\n @subject_of_speech = current_user.subject_of_speeches.find(params[:id])\n else\n @subject_of_speech = SubjectOfSpeech.find(params[:id])\n end\n\n @keywords = @subject_of_speech.keywords.split(\",\")\n # binding.pry\n @costars = eval(@subject_of_speech.costar)\n end", "def show\n @service_order_details = ServiceOrderDetail.where(:service_order_id => params[:id])\n @citation = Citation.where(:id => @service_order.citation_id).select(:id)\n @citation_details = CitationDetail.where(:citation_id => @citation)\n end", "def show\n @timetable = Timetable.find(params[:id])\n respond_with @timetable\n \n end", "def show(id)\n only_provides :html\n @tweet = Tweet.get(id)\n raise NotFound unless @tweet\n display @tweet\n end", "def show\n @slitting = Slitting.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @slitting }\n end\n end", "def show\n @semester_subject = SemesterSubject.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @semester_subject }\n end\n end", "def show\n @assessment_insti_test = AssessmentInstiTest.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json:@assessment_insti_test }\n end\n end", "def show\n @tredit_action = TreditAction.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @tredit_action }\n end\n end", "def show\n @tredit_action = TreditAction.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @tredit_action }\n end\n end", "def show\n \n \n @itineraries = @tour.itinerary\n \n end", "def show\n @resource = Resource.find(params[:id])\n @terms = Term.all_iit_subjects\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @resource }\n end\n end", "def show\n @notas = Nota.find_all_by_student_id(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @nota }\n end\n end", "def show\n @toilet = Toilet.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @toilet }\n end\n end", "def show\n\t\t@sticki = Sticki.find(params[:id])\n\tend", "def show\n @tupian = Tupian.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @tupian }\n end\n end", "def show\n @spit = Spit.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @spit }\n end\n end", "def show\n @test_subject_evaluation = @test_subject.test_subject_evaluations.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @test_subject_evaluation }\n end\n end", "def show\n @intertext = Intertext.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @intertext }\n end\n end", "def detail\n @index = Index.find(params['id'])\n @scholarships = ExtraScholarship.find_all_unpaid_by_index(@index.id)\n end", "def index\n @thesis_supervisions = ThesisSupervision.all\n end", "def show\n @institute = Institute.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @institute }\n end\n end", "def show\n @timecard = Timecard.find(params[:id])\n end", "def show\n @suspects = Suspect.all\n # @curr_suspect = @suspect\n # @curr_suspect_id = params[:id]\n # puts \"@curr_suspect_id_test=\" + @curr_suspect.id.to_s\n end", "def show\n @tours = Tour.find(params[:id])\n end", "def show\n @synonyme = @stoff.stoff_synonyms.pluck(:synonym)\n @transporte = Transport.where(\"stoff_id = ?\", @stoff).order(datum: :desc).paginate(page: params[:page], per_page: 20)\n end", "def show\n @situacoes_juridica = SituacoesJuridica.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @situacoes_juridica }\n end\n end", "def show\n @insumolabores = Insumolabore.where(:labor_id => params[:id])\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 show\n if params[:teacher_id]\n @school = Teacher.find(params[:teacher_id]).school\n else\n @school = School.find(params[:id])\n end\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @school }\n end\n end", "def show\n @srsa = Srsa.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @srsa }\n end\n end", "def show\n\n @subject = Subject.find(params[:id])\n\n end", "def show\n @solicitation = Solicitation.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @solicitation }\n end\n end", "def show\n @pacient = Pacient.find(params[:pacient_id])\n @evaluare = @pacient.evaluares.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n end\n end", "def show\n @classtable = Classtable.find(params[:id])\n #@classtable = Classtable.find(:all, :conditions => { :school_id => @classtable1.id })\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @classtable }\n end\n end", "def show\n @tstat = Tstat.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @tstat }\n end\n end" ]
[ "0.69233584", "0.66976506", "0.63381547", "0.6287084", "0.6270265", "0.62337285", "0.6196108", "0.6163608", "0.6042122", "0.6031026", "0.60042626", "0.59876084", "0.5986726", "0.59836763", "0.5972753", "0.5943741", "0.59387267", "0.59319234", "0.59302306", "0.59246606", "0.58780867", "0.5856486", "0.5829944", "0.5828667", "0.58267534", "0.5800636", "0.5796977", "0.57894844", "0.5785081", "0.57777053", "0.57230353", "0.5719483", "0.5718385", "0.57074374", "0.56733066", "0.56713486", "0.56630564", "0.5647252", "0.5641568", "0.5635498", "0.5633606", "0.5623217", "0.562123", "0.5617162", "0.5616309", "0.56147057", "0.56138945", "0.56080645", "0.56027067", "0.5600714", "0.55886257", "0.55843246", "0.55804837", "0.55791104", "0.5573256", "0.55613744", "0.5557375", "0.55566955", "0.55507386", "0.55487275", "0.55460924", "0.5543194", "0.5541327", "0.55393505", "0.55387276", "0.55363095", "0.55308956", "0.5529852", "0.55286485", "0.5527877", "0.5526341", "0.55239886", "0.5523281", "0.5523281", "0.5519581", "0.55174387", "0.55161816", "0.55131716", "0.551125", "0.5504918", "0.55043834", "0.5501473", "0.5498154", "0.5496741", "0.5495801", "0.5493262", "0.5491028", "0.548839", "0.54870665", "0.54868567", "0.54842776", "0.5478095", "0.5477234", "0.54754007", "0.5469045", "0.54668415", "0.54634905", "0.546329", "0.54618996", "0.546163" ]
0.72106856
0
|1||2||3| |4||5||6| |7||8||9| [0][0] [0][1] [0][2] [1][0] [1][1] [1][2] [2][0] [2][1] [2][2]
def cpu_defend if check_position_1 return elsif check_position_2 elsif check_position_3 elsif check_position_4 elsif check_position_6 elsif check_position_7 elsif check_position_8 elsif check_position_9 return else cpu_place_move end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def input4\n [\n [1, 0, 0, 0, 1],\n [0, 0, 0, 1, 3],\n [0, 1, 0, 0, 5],\n [0, 0, 1, 0, 8]\n ]\nend", "def input1\n [\n [1, 0, 0, 0, 1],\n [0, 1, 0, 0, 5],\n [0, 0, 1, 0, 4],\n [0, 0, 0, 1, 3]\n ]\nend", "def make_diamond(arr, rows)\n start = 1\n 1.upto(rows) do |iteration|\n arr << start\n iteration < (rows / 2.0).ceil ? start += 2 : start -= 2\n break if arr.length == rows\n end\n arr\nend", "def nest_array(board)\n nested_board = []\n 9.times { nested_board << board.slice!(0..8)}\n return nested_board\nend", "def represent\n # grid_array will be an array of strings that represent our grid in NxN format\n grid_array=[]\n @h.times{|r| grid_array<<@grid[r*@w,@w].split('')*' '}\n grid_array\n end", "def board_2d\n # slice the array into groups of 4 to create 2d-array\n @board.enum_slice(4).to_a\n end", "def input2\n [\n [3, 2,-4, 3],\n [2, 3, 3, 15],\n [5, -3, 1, 14]\n ]\nend", "def visualize_array\n(0...ROWS).each { |row|\n (0...COLS).each { |col|\n print row.to_s + \" \" + col.to_s + \" \"\n print \"(\" + (COLS*row + col).to_s + \") \" # index into board array\n }\n puts\n}\nend", "def spiral(n)\n results = []\n n.times do\n results << []\n end\n results\n\n counter = 1\n start_column = 0\n end_column = n - 1\n start_row = 0\n end_row = n - 1\n\n while start_column <= end_column && start_row <= end_row\n # top row\n loop do\n i = start_column\n results[start_row][i] = counter\n counter += 1\n end\n start_row +=1\n end\n\n # right column\n\n\n\nend", "def spiral_access(two_d, count = 0, &block)\n height = two_d.length - 1\n width = two_d.first.length - 1\n\n return if height/2 < count || width/2 < count\n\n (count..(width - count)).each do |x|\n block.call two_d[count][x]\n end\n\n ((count + 1)..(height-count)).each do |y|\n block.call two_d[y][width - count]\n end\n\n (width - 1 - count).downto count do |x|\n block.call two_d[height - count][x]\n end\n\n (height - 1 - count).downto count+1 do |y|\n block.call two_d[y][count]\n end\n\n spiral_access two_d, count+1, &block\n\nend", "def spiral_access array, &block\n\nn = array[0].size - 1\ni = 0\n\nuntil n<i\narray[i][i..n].each{|num| block.call num}\n(i+1).upto(n){|num| block.call array[num][n]}\narray[n].reverse[i+1..n].each{|num| block.call num}\n(i+1).upto(n-1){|num| block.call array.reverse[num][i]}\n\ni +=1\nn-= 1\nend\nend", "def right(r, sc, ec, array, final_array) #r for row, sc start column, end column\n (sc..ec).each do |num|\n final_array << array[r][num]\n end\nend", "def spiral_access(arr, &block)\n #count how many rows = e.g. length of first\n if arr.length > 1\n rows = arr.length - 1\n columns = arr[0].length - 1\n #puts rows, columns\n #count how many columns, e.g. in the first array\n #create a placeholder\n var_arr = []\n #first go across the top\n var_arr= arr[0]\n var_arr.each {|nr| block.call(nr)}\n # then take the last element in each array\n (1..(columns-1)).each do |x|\n var_arr = arr[x]\n block.call(var_arr.delete_at(columns))\n end\n #then go reverse along the last array\n var_arr = arr.delete_at(-1).reverse\n var_arr.each {|nr| block.call(nr)}\n #puts var_arr.join(' ')\n #then take the first elements up till n2\n (columns-1).downto(1) do |x|\n var_arr = arr[x]\n #puts var_arr.join(' ')\n block.call(var_arr.delete_at(0))\n end\n arr.delete_at(0)\n #puts arr.join(' ')\n spiral_access(arr,&block)\n elsif arr.length == 1\n arr[0].any? ? block.call(arr[0][0]) : arr[0]\n else\n arr\n\n end\n\n #then call it again for the rest\nend", "def eight_queens_possibilities(current_row, taken_columns, positions)\n\nend", "def find_all_sequences(x,y)\n ret = []\n ret << [[x,y],[x+1,y],[x+2,y],[x+3,y]] if x+3 <= 19\n ret << [[x,y],[x,y+1],[x,y+2],[x,y+3]] if y+3 <= 19\n ret << [[x,y],[x+1,y+1],[x+2,y+2],[x+3,y+3]] if y+3 <= 19 && x+3 <= 19\n ret << [[x,y],[x-1,y+1],[x-2,y+2],[x-3,y+3]] if x-3 >= 0 && y+3 <= 19\n ret\nend", "def spiral_order(a)\n return [] if a.empty?\n res = []\n left, top = 0, 0\n bottom, right = a.length - 1, a[0].length - 1\n\n while left <= right && top <= bottom\n for i in (left..right)\n res << a[top][i]\n end\n top += 1\n for i in (top..bottom)\n res << a[i][right]\n end\n right -= 1\n if top <= bottom\n # decreament for loop\n for i in (right).downto(left)\n res << a[bottom][i] \n end\n bottom -= 1\n end\n if left <= right\n for i in (bottom).downto(top)\n res << a[i][left]\n end\n left += 1\n end\n end\n res\nend", "def indices(i)\n [(i/WIDTH),(i-1) % (WIDTH)]\n end", "def indices(i)\n [(i/WIDTH),(i-1) % (WIDTH)]\n end", "def repeated_number_ranges(arr)\n\n\nend", "def initialize\n flat_array = Array.new(9){ ' ' }\n # it will be easier to put X's and O's on the board\n # if I let @spaces be an array of arrays.\n @spaces = flat_array.each_slice(3).to_a\n # that was the old #rows method. \n end", "def get_row_cells row\n\t\treturn (row * 9...row * 9 + 9).to_a\n\tend", "def row(p)\n x = p * (p - 1)\n y = x + p - 1\n x.upto(y) {|i| cell(p.odd? ? x - i + y : i) }\n end", "def rect(a, b, screen)\n screen[0...b].each do |row|\n row[0...a] = (\"#\"*a).split(\"\")\n end\n\n screen\nend", "def pyramid(n)\n outer_array = []\n 0.upto(n) do |i|\n next if i == 0\n outer_array << Array.new(i, i)\n end\n outer_array\nend", "def two_d_translate(arr)\n result = []\n\tarr.each do |subArray|\n subArray[1].times do \n result.push(subArray[0])\n end\n end\n return result\nend", "def coordinate_list\n @board.each_index.inject([]) do |result,row_index|\n result.concat( \n @board[row_index].each_index.collect do |column_index|\n [row_index + 1, column_index + 1]\n end\n )\n end\n end", "def redesign\n x = @mat[0].length\n y = @mat.size\n (1..y-2).each do |i|\n (1..x-2).each do |j|\n @mat[i][j] = \"0\"\n end\n end\n\n divide(1,x-2,1,y-2)\n end", "def three_row_grid\n grid = []\n grid << [\n Cell.new(:alive, 0, 0),\n Cell.new(:alive, 0, 1),\n Cell.new(:dead, 0, 2)\n ]\n grid << [\n Cell.new(:alive, 1, 0),\n Cell.new(:dead, 1, 1),\n Cell.new(:dead, 1, 2)\n ]\n grid << [\n Cell.new(:dead, 2, 0),\n Cell.new(:dead, 2, 1),\n Cell.new(:dead, 2, 2)\n ]\n grid\nend", "def two_d_translate(arr)\n one_d_arr = []\n arr.each do | outer |\n outer.each.with_index do | inner, i |\n if i == 0\n outer[1].times do\n one_d_arr << inner\n end\n end\n end\n end\n return one_d_arr\nend", "def grid(n, m)\n Array.new(n) { Array.new(n) } # If you attempted to write this as Array.new(n, Array.new(m)) the contents would be repeated for each array rather\nend", "def split(grid, n)\n grid.split('/').each_slice(n).map do |rows|\n results = Array.new(rows.first.length / n) {[]}\n rows.map {|row| row.split('').each_slice(n).each_with_index {|r, i| results[i] << r.join('')}}\n results.map {|r| r.join('/')}\n end\nend", "def spiral_access(two_d, &block)\n len = two_d.length\n\n return if two_d[0].length <= 0\n\n if len == 1\n yield(two_d[0][0])\n\n elsif len == 2\n yield(two_d[0][0])\n yield(two_d[0][1])\n yield(two_d[1][1])\n yield(two_d[1][0])\n\n elsif len > 2\n # top row\n 0.upto len - 1 do |i|\n yield(two_d[0][i])\n end\n\n # right column\n 1.upto len - 1 do |i|\n yield(two_d[i][len - 1])\n end\n\n # bottom row\n (len - 2).downto 0 do |i|\n yield(two_d[len - 1][i])\n end\n\n # left column\n (len - 2).downto 1 do |i|\n yield(two_d[i][0])\n end\n\n second_two_d = []\n 1.upto (len - 2) do |i|\n second_two_d << two_d[i][1..len - 2]\n end\n\n spiral_access(second_two_d, &block)\n\n else\n return\n\n end\nend", "def walk_grid(g, n)\n Enumerator.new do |enum|\n 0.upto(g.size-1) do |y|\n 0.upto(g.size-1) do |x|\n x_ok = x < (g.size-n)\n y_ok = y < (g.size-n)\n enum.yield :horizontal, fetch_tuple(g, x, y, 1, 0, n) if x_ok\n enum.yield :vertical, fetch_tuple(g, x, y, 0, 1, n) if y_ok\n enum.yield :diagonal, fetch_tuple(g, x, y, 1, 1, n) if x_ok && y_ok\n end\n end\n end.lazy\nend", "def matrix(x, y, z)\n sub_array = []\n y.times do\n sub_array.push(z);\n end\n #sub_array\n array = [];\n x.times do\n array.push(sub_array)\n end\n array\nend", "def cracklepop3\n (1..100).zip(Array.new 100, nil).map do |i,x|\n [i%3, i%5].map.with_index do |y, j| \n x = x.to_s + ['crackle','pop'][j] if y==0\n end\n x ? x : i\n end\nend", "def consecutive(arr)\r\n\r\nend", "def test_with_irregular_array3D2; show([[[0,0,0]],\n [[0,0,0],[1,1,1]]]) end", "def pattern\n @nz.map { |nz_cell| nz_cell[0..1] }\n end", "def reverse_segments(arr)\n result = []\n (arr.size / 8).times do\n result << arr.shift(8)\n end\n result.reverse\nend", "def two_d_translate(arr)\r\n newArray = []\r\n arr.each do |ele|\r\n ele[1].times do\r\n newArray << ele[0]\r\n end\r\n end\r\n return newArray\r\nend", "def lattice_path(array)\n temp = [1]\n sum = array[0] + array[1]\n temp << sum\n sum = sum + array[2]\n temp << sum\n temp << array.last\n sum = temp.inject(:+)\n temp << (sum * 2)\n return temp\nend", "def connect_cells\n @grid.each_with_index do |columns, col_i|\n columns.each_with_index do |cell, cell_i|\n cell.left = @grid[col_i-1][cell_i] if col_i != 0 \n cell.up = @grid[col_i][cell_i+1] if cell_i + 1 < columns.length\n cell.right = @grid[col_i+1][cell_i] if col_i + 1 < @grid.length\n cell.down = @grid[col_i][cell_i-1] if cell_i != 0\n cell.lu = @grid[col_i-1][cell_i+1] if col_i != 0 && cell_i + 1 < columns.length\n cell.ld = @grid[col_i-1][cell_i-1] if col_i != 0 && cell_i != 0\n cell.ru = @grid[col_i+1][cell_i+1] if col_i + 1 < @grid.length && cell_i + 1 < columns.length\n cell.rd = @grid[col_i+1][cell_i-1] if col_i + 1 < @grid.length && cell_i != 0\n end\n end\n end", "def navidad(n)\n result = \"\"\n n.times do |ind| \n i = ind + 1 \n (n-i).times do \n result += \" \"\n end\n i.times do\n result += \"* \" \n end\n result += \"\\n\" \n end\n \n 3.times do |i|\n if i != 2\n n.times do |b|\n if (n+1)/2 == b+1\n result += \"* \"\n else\n result += \" \"\n end \n end\n result += \"\\n\"\n else\n n.times do |b| \n if ((n+1)/2)-2 == b || ((n+1)/2)-1 == b || (n+1)/2 == b\n result += \"* \"\n else\n result += \" \"\n end \n end\n end\n end \n result\nend", "def spiral_access(arr, &block)\n n = -1\n r = 0\n len = arr[0].length\n increments = [1, len, -1, -len]\n loop do\n 4.times do |index|\n repeat = [len - r, arr.length - r] * 2\n (repeat[index]).times do\n n += increments[index]\n block.call arr[n / len ][n % len] if n >= 0\n end\n return if len == r\n r += 1 if index.even?\n end\n end\nend", "def towerBuilder(n_floors)\n layer = width = n_floors + (n_floors - 1)\n result = []\n\n while layer > 0\n result.unshift((\"*\" * layer).center(width))\n layer -= 2\n end\n result\nend", "def print_grid(points,size)\n grid = []\n for i in 0..size-1\n grid.push([])\n for j in 0..size-1\n if points.include? [j,i]\n # grid.last.push(\"#{j.to_s.reverse[0]}#{i.to_s.reverse[0]}\")\n grid.last.push(\"#{j}#{i}\")\n else\n grid.last.push(\"__\")\n end\n end\n end\n grid.reverse!\n grid.map {|x| puts x.join(\" \")}\nend", "def two_d_translate(array)\n new_array = []\n array.each do |sub_array|\n num = sub_array[1]\n ele = sub_array[0]\n num.times { new_array << ele }\n end\n\n new_array\nend", "def nbor node, dims, dir\n if (dir == :north && node[1] > 0) then return [node[0], node[1]-1] end\n if (dir == :south && node[1] < dims[1] - 1) then return [node[0], node[1]+1] end\n if (dir == :east && node[0] < dims[0] - 1) then return [node[0]+1, node[1]] end\n if (dir == :west && node[0] > 0) then return [node[0]-1, node[1]] end\n\n nil\nend", "def triple_sequence(start, length)\n \tarry = []\n\t(1..length).each do | count|\n\n if count == 1\n arry << start\n else\n arry << arry[count-2] * 3\n end\n end\n return arry\nend", "def spiral_access(arrs, iteration = 0, &block)\n maxY = arrs.length - 1\n maxX = arrs.first.length - 1\n \n return if maxY/2 < iteration || maxX/2 < iteration\n \n # top row\n iteration.upto maxX-iteration do |x|\n block.call arrs[iteration][x]\n end\n\n # right column\n (iteration + 1).upto maxY-iteration do |y|\n block.call arrs[y][maxX-iteration]\n end\n\n # bottom row\n (maxX - 1 - iteration).downto iteration do |x|\n block.call arrays[maxY-iteration][x]\n end\n\n # left column\n (maxY - 1 - iteration).downto iteration+1 do |y|\n block.call arrays[y][iteration]\n end\n\n spiral_access arrs, iteration+1, &block\n \nend", "def triple_sequence(start, length)\n\n new_arr = []\n new_arr << start\n (1..length-1).each do |num|\n start *= 3\n new_arr << start\n end\n return new_arr\n\nend", "def ject(ary)\nr = [ary]\nw = []\n\nr.flatten.each do |y| \n\tif y == 0\n\t\tw << 0\n\telse\n\t\t3.times {|idx| w << ( y / (idx + 2) )}\n\tend\nend\nw\nend", "def neighborhood(cell)\n Set.new((cell[0]-1..cell[0]+1).map{|x| (cell[1]-1..cell[1]+1).map{|y| [x,y]}}.\n flatten(1)) - Set.new([cell])\nend", "def vertical size, coordinates\n coords = []\n sc = coordinates[0]\n coords << sc\n (size - 1).times do\n coords << sc.next\n sc = sc.next\n end\n coords.map {|x| x + \"#{coordinates[1..-1]}\"}\n end", "def discover_points # step 1\r\n x = 0\r\n y = 0\r\n @image_arr.each do |row|\r\n x = 0\r\n row.each do |cell|\r\n if cell == 1 # discovered the cell is 1\r\n @ordinal_arr.push([y,x]) # this is where i push the ordinals.\r\n puts \"#{y},#{x}\"\r\n end\r\n x = x + 1\r\n end\r\n y = y + 1\r\n puts \"\" \r\n end\r\n end", "def grid(n, m)\n arr = Array.new(n) { Array.new(m, :N) }\n arr\nend", "def triple_sequence(start, length)\n\tarr = [start]\n \t(1...length).each do |item|\n \tarr.push(arr[-1]*3)\n end\n \treturn arr\nend", "def square_arrays\n squares = []\n org_row = 0\n org_col = 0\n (0..8).each do |i|\n squares[i] = []\n (org_row..org_row+2).each do |k|\n (org_col..org_col+2).each do |j|\n squares[i].push(@board[k][j])\n end \n end\n if org_row == 6\n org_col += 3 \n org_row = 0\n else\n org_row += 3 \n end\n end \n squares\n end", "def fifteen \n size_x = 10 \n size_y = 10\n row = []\n for i in 1..size_x\n row.push(0)\n end\n\n @@mat = []\n\n for i in 1..size_y\n @@mat.push(row.clone)\n end\n \n move(0,0)\n\n return @@mat[size_x-1][size_y-1]\n\nend", "def lattice_path(array)\n temp = [1]\n count = 2\n sum = array[0] + array[1]\n temp.push(sum)\n while count < array.length - 1\n sum = sum + array[count]\n temp << sum\n count += 1\n end\n \n temp << array.last\n sum = temp.inject(:+)\n temp << (sum * 2)\n return temp\nend", "def create_grid(board_array)\n\t# split into triplets\n\ttriplets_array = []\n board_array.each { |array| triplets_array << array.each_slice(3).to_a }\n\n # shuffle the triplets\n shuffle_container = [[], [], []]\n 9.times do |row|\n 3.times do |column|\n current_array = triplets_array[row][column]\n shuffle_container[column] << current_array\n end\n end\n\n # flatten and re-split\n final_array = []\n shuffle_container.flatten.each_slice(9) { |array| final_array << array }\n\n return final_array\nend", "def paintMatrix(a)\n\t\n\tputs \" | 1 | 2 | 3 | 4 | 5 | 6\".green\n\tputs \"\"\n\tfor i in 0..5\n\t\tif ( i != 0 )\n\t\tputs \" \"\n\t\tend\n\t\tfor j in 0..5\n\t\t\t\tprint \" | \".blue\n\t\t\t\tprint \"#{a[i][j]}\"\n\t\tend\n\t\tputs \"\"\n\tend\n\tputs\"\"\n\tend", "def two_d_translate(array)\n new_arr = []\n array.each do |arr|\n arr[1].times {new_arr << arr[0]}\n end\n new_arr\nend", "def index(x, y)\n (y - 1) * width + (x - 1)\n end", "def make_board\n board = Array.new(8) { Array.new(8) { Array.new(2) } }\n board.each_with_index do |row, row_i|\n row.each_with_index { |column, column_i| column[0], column[1] = row_i, column_i }\n end\n end", "def test_with_irregular_array3D1; show([[[0,0,0],[1,1,1]],\n [[0,0,0]]]) end", "def triple_sequence(start, length)\n\n new_arr = [start]\n #new_arr << start\n (1..length-1).each do |num|\n start *= 3\n new_arr << start\n end\n return new_arr\n\nend", "def adj_cell(array)\n # Set last letter in ordinal.\n last_letter_ord = array[-1][0].ord\n \n # Set last number in ordinal.\n last_num_ord = array[-1][1].ord\n \n # If two or more cells chosen, pick the next logical.\n if array.length >= 2\n # Set bias for letter and number from last two coordinates.\n letter_bias_ord = array[-1][0].ord - array[-2][0].ord \n num_bias_ord = array[-1][1].ord - array[-2][1].ord\n\n # Chose new letter and number based on the direction of previous choices.\n new_letter = (last_letter_ord + letter_bias_ord).chr\n new_num = (last_num_ord + num_bias_ord).chr\n\n # Create output array with the new coordinate.\n output_array = array << (new_letter + new_num)\n else\n # Array of 4 possible ordinal directions for new cells.\n change_array = [[-1, 0], [0, -1], [0, 1], [1, 0]]\n possible_cells = []\n \n # Create an array of all 4 possible coordinates around origin coordinate.\n change_array.each do |letter, num|\n possible_cells << (last_letter_ord + letter).chr + (last_num_ord + num).chr\n end\n\n # Pick a cell from the possible cells.\n array << possible_cells.sample\n # Create output array with the new coordinate.\n output_array = array.sort\n end\n output_array\n end", "def get_subgrid(cords)\n subgrid = []\n x_pos = cords[0] - cords[0] % 3\n (x_pos..x_pos + 2).each do |row_num|\n y_pos = cords[1] - cords[1] % 3\n subgrid += @grid[row_num][y_pos, 3]\n end\n subgrid\n end", "def matrix\n end", "def spiral_matrix(n)\n result = []\n n.times { result.push([])}\n\n counter = 1;\n start_column = 0; end_column = n - 1\n start_row = 0; end_row = n - 1\n while start_column <= end_column && start_row <= end_row\n (start_column..end_column).each do |i|\n result[start_row][i] = counter\n counter += 1\n end\n start_row += 1\n \n (start_row..end_row).each do |i|\n result[i][end_column] = counter\n counter += 1\n end\n end_column -= 1\n \n (start_column..end_column).reverse_each do |i|\n result[end_row][i] = counter\n counter += 1\n end\n end_row -= 1\n \n (start_row..end_row).reverse_each do |i|\n result[i][start_column] = counter\n counter += 1\n end\n start_column += 1\n end\n\n result\nend", "def pyramid(n)\n arr = Array.new(n)\n\n for i in 0..arr.length-1\n arr[i] = Array.new(n)\n end\n\n for y in 0..n/2\n if y == n/2\n if arr[y][y] == nil?\n arr[y][y] = y+1\n end\n break\n end\n for x in y..n-2-y\n arr[y][x] = y+1\n arr[x][n-1-y] = y+1\n arr[n-1-y][n-1-y-x] = y+1\n arr[n-1-y-x][y] = y+1\n end\n end\n\n for a in 0..arr.length-1\n for b in 0..arr[a].length-1\n print \"[#{arr[a][b]}]\"\n end\n print \"\\n\"\n end\n\n return arr\nend", "def get_col_cells col\n\t\treturn (col...9 ** 2).step(9).to_a\n\tend", "def corners\n\t\t[[0,0],[0,@m-1],[@n-1,0],[@n-1,@m-1]]\n\tend", "def spiral_order(n)\n row_begin = 0\n row_end = n - 1\n column_begin = 0\n column_end = n - 1\n counter = 1\n results = Matrix.build(n){|row,col| 0 } #creates a matrix n x n, with 0 as value\n direction = 0\n\n while(row_begin <= row_end && column_begin <= column_end)\n if(direction == 0)\n column_begin.upto(column_end) do |i|\n results[row_begin,i] = counter\n counter += 1\n end\n row_begin += 1\n direction = 1\n elsif(direction == 1)\n row_begin.upto(row_end) do |j|\n results[j,column_end] = counter\n counter += 1\n end\n column_end -= 1\n direction = 2\n elsif(direction == 2)\n column_end.downto(column_begin) do |k|\n results[row_end,k] = counter\n counter += 1\n end\n row_end -= 1\n direction =3\n\n elsif(direction == 3)\n row_end.downto(row_begin) do |l|\n results[l,column_begin] = counter\n counter += 1\n end\n column_begin += 1\n direction = 0\n end\n end\n return results.to_a #results will be a matrix so call .to_a to return an array of arrays\nend", "def print_grid # prints 3 X 3 grid with values\n puts \"\\n\"\n @grid.each_slice(3) { |row| puts row.join(' | ') }\n puts \"\\n\"\n end", "def slices(n)\n digits.each_cons(n).to_a\n end", "def two_d_translate(arr)\n new_arr = []\n\n arr.each do |subArray|\n ele = subArray[0]\n num = subArray[1]\n\n num.times { new_arr << ele }\n end\n\n return new_arr\nend", "def board\n @sudoku_board.each_slice(9) {|row| puts row.join}\n\n end", "def generate_solved_array(dim)\n tiles = dim.times.map {|i| dim.times.map {|j| (j+1)+dim*(i)}}\n tiles[dim-1][dim-1] = nil\n tiles\n end", "def test_with_irregular_array2D1; show([[0.1,0.9], [0.5]]) end", "def combos floor\n indices = []\n floor.each_char.with_index do |x, i|\n indices << i if x == '1'\n end\n\n indices.combination(1).to_a + indices.combination(2).to_a\n end", "def right_tri(tri)\n\nend", "def victoire\n \n [[@a1, @a2, @a3],\n [@a1, @b2, @c3],\n [@a1, @b1, @c1],\n [@b1, @b2, @b3],\n [@c1, @c2, @c3],\n [@c1, @b2, @a3],\n [@a2, @b2, @c2],\n [@a3, @b3, @c3]]\n end", "def initialize\n @array = []\n x,y = 0,0\n while x < 8\n while y < 8\n @array << [x,y]\n y += 1\n end\n x += 1\n y = 0\n end\n @array\n end", "def spiral(rows, cols)\n # check for and handle wonky inputs\n if !rows.is_a?(Integer) || rows <= -1\n puts \"Whoops: Input rows = #{rows} is invalid; rows must be an integer >= 0.\"\n return\n elsif !cols.is_a?(Integer) || cols <= -1\n puts \"Whoops: Input cols = #{cols} is invalid; cols must be an integer >= 0.\"\n return\n end\n\n # prepare rows & columns in array of arrays\n res = Array.new(rows) { Array.new(cols) }\n level = 0 # count of cycles\n num = 1\n\n until num > (rows * cols)\n # top going right\n level.upto(cols-level-1) do |i|\n res[level][i] = num\n num += 1\n end\n break if num > (rows * cols)\n\n # right going down\n (level+1).upto(rows-level-1) do |i|\n res[i][cols-level-1] = num\n num += 1\n end\n break if num > (rows * cols)\n\n # bottom going left\n (cols-level-2).downto(level) do |i|\n res[rows-level-1][i] = num\n num += 1\n end\n break if num > (rows * cols)\n\n # left going up\n (rows-level-2).downto(level+1) do |i|\n res[i][level] = num\n num += 1\n end\n level += 1 # level completed\n end\n\n # print as matrix\n res.each {|sub_arr| print sub_arr, \"\\n\"}\nend", "def sim(m, w, h)\n\to = m.map{|x|x.clone}\n\t(1..w-2).each do |x|\n\t\t(1..h-2).each do |y|\n\t\t\tnext if m[y][x] == ?.\n\t\t\toccupied=[-1,0,1].product([-1,0,1]).count{|dx,dy|(dx!=0||dy!=0) && m[y+dy][x+dx]==?#}\n\t\t\to[y][x] = ?# if m[y][x] == ?L && occupied == 0\n\t\t\to[y][x] = ?L if m[y][x] == ?# && occupied >= 4\n\t\tend\n\tend\n\treturn o\nend", "def create_board(size)\n return (0...size).map{|b| (0...size).map{|bb| 0}}\n end", "def create_pattern(piece)\n Array.new(4,piece).join\n end", "def rows\n 3.times.map{|n| board_state[n * 3, 3]}\n end", "def esxlRecurse i, j\n esxlStraightRecurse(i, j) + esxlDiagonalRecurse(i, j)\nend", "def n_dim_ruler(arr)\n\t\n\ta = arr\n\td = []\n\n\tloop{\n\t\t\n\t\tl = a.length()\n\t\td.push(l.to_s)\n\t\t\n\t\tif a[0].instance_of?(Array) \n\t\t\ta = a[0]\n\t\telse\n\t\t\tbreak\n\t\tend\n\t\n\t}\n\n\treturn d.join(\" \")\n\nend", "def get_other_block_cells cell\n\t\tblock = get_block cell\n\t\tfirst_cell = cell / 27 * 27\n\t\treturn (first_cell...first_cell + 27).select { |r| block == r / 27 * 3 + r % 9 / 3 }.to_a - [cell]\n\tend", "def test_with_irregular_array2D2; show([[0.5], [0.1,0.9]]) end", "def walk(grid, x, y)\n [N, S, E, W].shuffle.each do |dir|\n nx, ny = x + DX[dir], y + DY[dir]\n if nx >= 0 && ny >= 0 && ny < grid.length && nx < grid[ny].length && grid[ny][nx] == 0\n grid[y][x] |= dir\n grid[ny][nx] |= OPPOSITE[dir]\n \n return [nx, ny]\n end\n end\n \n nil\nend", "def spiral_access(array2d, &block)\n\n if array2d.length * array2d[0].length == 0 then return end\n\n i = 0\n\n x = 0\n x_dir = 1\n\n y = 0\n y_dir = 0\n\n t = 0\n while true do\n\n if t == (array2d.length * array2d[0].length) then break end\n\n block.call array2d[y][x]\n\n if x_dir > 0 then\n x += 1\n if x >= array2d.length - i then\n\n x = array2d.length - i - 1\n y += 1\n\n x_dir = 0\n y_dir = 1\n end\n\n elsif x_dir < 0 then\n x -= 1\n if x < i then\n x = i\n y -= 1\n\n x_dir = 0\n y_dir = -1\n end\n\n elsif y_dir > 0 then\n y += 1\n if y >= array2d[0].length - i then\n\n y = array2d[0].length - i - 1\n x -= 1\n\n x_dir = -1\n y_dir = 0\n end\n\n elsif y_dir < 0 then\n y -= 1\n if y <= i then\n\n i += 1\n\n y = i\n x += 1\n\n x_dir = 1\n y_dir = 0\n end\n end\n\n t += 1\n \n end\nend", "def get_block_cells block\n\t\tblock_cells = []\n\t\t(block / 3 * 3...block / 3 * 3 + 3).each do |r|\n\t\t\t(block % 3 * 3...block % 3 * 3 + 3).each do |c|\n\t\t\t\tblock_cells << r * 9 + c\n\t\t\tend\n\t\tend\n\treturn block_cells\n\n\tend", "def split_rows\n\t\t@board.values.each_slice(15).to_a\n\tend", "def iterate(arr)\n # TODO 3\n arrNew = []\n (0...arr.count).each do |x|\n arrNew[x] = []\n (0...arr.count).each do |y|\n if num_neighbors(x, y, arr) == 3\n arrNew[x][y] = \"X\"\n else\n arrNew[x][y] = \".\"\n end\n end\n end\n\n arrNew\nend", "def calc_tree\n tree = []\n n = 1\n while n <= @n\n result = []\n result = [[0, 1]] if n == 1\n tree.each do |row|\n line1 = []\n line2 = []\n row.each_with_index do |elem, i|\n line1 << \"#{elem}0\" if i.positive?\n line2 << \"#{elem}0\" if i.zero?\n line2 << \"#{elem}1\"\n end\n result << line1 unless row.count == 1\n result << line2\n end\n tree = result\n n += 1\n end\n tree\n end", "def get_surrounding_tiles(row, column, cell)\n surrounding_tiles = []\n index = GAME_BOARD[column-1].index(cell)\n if column == 1 \n if index == 0\n surrounding_tiles << GAME_BOARD[column-1][index+1]\n surrounding_tiles << GAME_BOARD[column][index]\n elsif index == 8\n surrounding_tiles << GAME_BOARD[column-1][index-1]\n surrounding_tiles << GAME_BOARD[column][index]\n else\n surrounding_tiles << GAME_BOARD[column-1][index-1] \n surrounding_tiles << GAME_BOARD[column-1][index+1] \n surrounding_tiles << GAME_BOARD[column][index]\n end\n elsif column == 12\n if index == 0\n surrounding_tiles << GAME_BOARD[column-1][index+1]\n surrounding_tiles << GAME_BOARD[column-2][index] \n elsif index == 8\n surrounding_tiles << GAME_BOARD[column-1][index-1]\n surrounding_tiles << GAME_BOARD[column-2][index] \n else\n surrounding_tiles << GAME_BOARD[column-1][index-1] \n surrounding_tiles << GAME_BOARD[column-1][index+1] \n surrounding_tiles << GAME_BOARD[column-2][index]\n end\n elsif index == 0\n surrounding_tiles << GAME_BOARD[column-1][index+1] \n surrounding_tiles << GAME_BOARD[column][index]\n surrounding_tiles << GAME_BOARD[column-2][index]\n elsif index == 8\n surrounding_tiles << GAME_BOARD[column-1][index-1] \n surrounding_tiles << GAME_BOARD[column][index]\n surrounding_tiles << GAME_BOARD[column-2][index]\n else\n surrounding_tiles << GAME_BOARD[column-1][index+1] \n surrounding_tiles << GAME_BOARD[column-1][index-1] \n surrounding_tiles << GAME_BOARD[column][index]\n surrounding_tiles << GAME_BOARD[column-2][index]\n end\n\n surrounding_tiles\n end" ]
[ "0.6503528", "0.6357327", "0.6091897", "0.6091593", "0.607279", "0.6065504", "0.60297275", "0.59254587", "0.59208584", "0.58373344", "0.58352804", "0.58193326", "0.57934755", "0.579264", "0.5735498", "0.56862223", "0.5674831", "0.5674831", "0.56702644", "0.56648517", "0.5657474", "0.5654388", "0.56494814", "0.56466967", "0.5642367", "0.56423646", "0.5641105", "0.5619444", "0.56186837", "0.5604665", "0.560461", "0.55802983", "0.5580187", "0.55682445", "0.55661273", "0.55649227", "0.5540701", "0.5530306", "0.55255437", "0.55209166", "0.55149037", "0.5514433", "0.5511852", "0.54989463", "0.5495951", "0.54745346", "0.5471719", "0.54696053", "0.5459341", "0.5458456", "0.54494476", "0.54421204", "0.54401994", "0.543356", "0.5429676", "0.5423376", "0.54194784", "0.5416474", "0.541433", "0.5413889", "0.54100186", "0.5409667", "0.5408271", "0.54082114", "0.5405712", "0.54028857", "0.5397361", "0.53957576", "0.5389588", "0.538546", "0.5381242", "0.53779775", "0.53741914", "0.5370391", "0.5368876", "0.5367994", "0.5365716", "0.53578526", "0.53567296", "0.5355259", "0.5352632", "0.53499025", "0.53457934", "0.53441364", "0.53437686", "0.53418756", "0.5341822", "0.53378415", "0.53347546", "0.5334557", "0.533311", "0.5333016", "0.53318524", "0.53318477", "0.53299177", "0.5328912", "0.532491", "0.5323213", "0.53211695", "0.53211385", "0.531968" ]
0.0
-1
Show invalid properties with the reasons. Usually used together with valid?
def list_invalid_properties invalid_properties = Array.new if !@display_name.nil? && @display_name.to_s.length > 255 invalid_properties.push('invalid value for "display_name", the character length must be smaller than or equal to 255.') end if !@description.nil? && @description.to_s.length > 1024 invalid_properties.push('invalid value for "description", the character length must be smaller than or equal to 1024.') end if @tcp_closed.nil? invalid_properties.push('invalid value for "tcp_closed", tcp_closed cannot be nil.') end if @tcp_closed > 4320000 invalid_properties.push('invalid value for "tcp_closed", must be smaller than or equal to 4320000.') end if @tcp_closed < 10 invalid_properties.push('invalid value for "tcp_closed", must be greater than or equal to 10.') end if @tcp_opening.nil? invalid_properties.push('invalid value for "tcp_opening", tcp_opening cannot be nil.') end if @tcp_opening > 4320000 invalid_properties.push('invalid value for "tcp_opening", must be smaller than or equal to 4320000.') end if @tcp_opening < 10 invalid_properties.push('invalid value for "tcp_opening", must be greater than or equal to 10.') end if @udp_single.nil? invalid_properties.push('invalid value for "udp_single", udp_single cannot be nil.') end if @udp_single > 4320000 invalid_properties.push('invalid value for "udp_single", must be smaller than or equal to 4320000.') end if @udp_single < 10 invalid_properties.push('invalid value for "udp_single", must be greater than or equal to 10.') end if @tcp_finwait.nil? invalid_properties.push('invalid value for "tcp_finwait", tcp_finwait cannot be nil.') end if @tcp_finwait > 4320000 invalid_properties.push('invalid value for "tcp_finwait", must be smaller than or equal to 4320000.') end if @tcp_finwait < 10 invalid_properties.push('invalid value for "tcp_finwait", must be greater than or equal to 10.') end if @tcp_first_packet.nil? invalid_properties.push('invalid value for "tcp_first_packet", tcp_first_packet cannot be nil.') end if @tcp_first_packet > 4320000 invalid_properties.push('invalid value for "tcp_first_packet", must be smaller than or equal to 4320000.') end if @tcp_first_packet < 10 invalid_properties.push('invalid value for "tcp_first_packet", must be greater than or equal to 10.') end if @tcp_closing.nil? invalid_properties.push('invalid value for "tcp_closing", tcp_closing cannot be nil.') end if @tcp_closing > 4320000 invalid_properties.push('invalid value for "tcp_closing", must be smaller than or equal to 4320000.') end if @tcp_closing < 10 invalid_properties.push('invalid value for "tcp_closing", must be greater than or equal to 10.') end if @tcp_established.nil? invalid_properties.push('invalid value for "tcp_established", tcp_established cannot be nil.') end if @tcp_established > 4320000 invalid_properties.push('invalid value for "tcp_established", must be smaller than or equal to 4320000.') end if @tcp_established < 120 invalid_properties.push('invalid value for "tcp_established", must be greater than or equal to 120.') end if @udp_multiple.nil? invalid_properties.push('invalid value for "udp_multiple", udp_multiple cannot be nil.') end if @udp_multiple > 4320000 invalid_properties.push('invalid value for "udp_multiple", must be smaller than or equal to 4320000.') end if @udp_multiple < 10 invalid_properties.push('invalid value for "udp_multiple", must be greater than or equal to 10.') end if @icmp_error_reply.nil? invalid_properties.push('invalid value for "icmp_error_reply", icmp_error_reply cannot be nil.') end if @icmp_error_reply > 4320000 invalid_properties.push('invalid value for "icmp_error_reply", must be smaller than or equal to 4320000.') end if @icmp_error_reply < 10 invalid_properties.push('invalid value for "icmp_error_reply", must be greater than or equal to 10.') end if @udp_first_packet.nil? invalid_properties.push('invalid value for "udp_first_packet", udp_first_packet cannot be nil.') end if @udp_first_packet > 4320000 invalid_properties.push('invalid value for "udp_first_packet", must be smaller than or equal to 4320000.') end if @udp_first_packet < 10 invalid_properties.push('invalid value for "udp_first_packet", must be greater than or equal to 10.') end if @icmp_first_packet.nil? invalid_properties.push('invalid value for "icmp_first_packet", icmp_first_packet cannot be nil.') end if @icmp_first_packet > 4320000 invalid_properties.push('invalid value for "icmp_first_packet", must be smaller than or equal to 4320000.') end if @icmp_first_packet < 10 invalid_properties.push('invalid value for "icmp_first_packet", must be greater than or equal to 10.') end invalid_properties end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def list_invalid_properties\n invalid_properties = super\n if @class_id.nil?\n invalid_properties.push('invalid value for \"class_id\", class_id cannot be nil.')\n end\n\n if @object_type.nil?\n invalid_properties.push('invalid value for \"object_type\", object_type cannot be nil.')\n end\n\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = super\n if @class_id.nil?\n invalid_properties.push('invalid value for \"class_id\", class_id cannot be nil.')\n end\n\n if @object_type.nil?\n invalid_properties.push('invalid value for \"object_type\", object_type cannot be nil.')\n end\n\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = super\n if @class_id.nil?\n invalid_properties.push('invalid value for \"class_id\", class_id cannot be nil.')\n end\n\n if @object_type.nil?\n invalid_properties.push('invalid value for \"object_type\", object_type cannot be nil.')\n end\n\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = super\n if @class_id.nil?\n invalid_properties.push('invalid value for \"class_id\", class_id cannot be nil.')\n end\n\n if @object_type.nil?\n invalid_properties.push('invalid value for \"object_type\", object_type cannot be nil.')\n end\n\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = super\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = super\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = super\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = super\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = super\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = super\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = super\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = super\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = super\n if @class_id.nil?\n invalid_properties.push('invalid value for \"class_id\", class_id cannot be nil.')\n end\n\n if @object_type.nil?\n invalid_properties.push('invalid value for \"object_type\", object_type cannot be nil.')\n end\n\n pattern = Regexp.new(/^$|^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/)\n if !@uuid.nil? && @uuid !~ pattern\n invalid_properties.push(\"invalid value for \\\"uuid\\\", must conform to the pattern #{pattern}.\")\n end\n\n pattern = Regexp.new(/^$|^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/)\n if !@vdisk_id.nil? && @vdisk_id !~ pattern\n invalid_properties.push(\"invalid value for \\\"vdisk_id\\\", must conform to the pattern #{pattern}.\")\n end\n\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = super\n if @style.nil?\n invalid_properties.push('invalid value for \"style\", style cannot be nil.')\n end\n\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = super\n if @class_id.nil?\n invalid_properties.push('invalid value for \"class_id\", class_id cannot be nil.')\n end\n\n if @object_type.nil?\n invalid_properties.push('invalid value for \"object_type\", object_type cannot be nil.')\n end\n\n if !@name.nil? && @name.to_s.length > 31\n invalid_properties.push('invalid value for \"name\", the character length must be smaller than or equal to 31.')\n end\n\n pattern = Regexp.new(/^[a-zA-Z0-9\\-\\._:]+$/)\n if !@name.nil? && @name !~ pattern\n invalid_properties.push(\"invalid value for \\\"name\\\", must conform to the pattern #{pattern}.\")\n end\n\n pattern = Regexp.new(/^$|((^20|5[0-9a-fA-F]{1}):([0-9a-fA-F]{2}:){6}([0-9a-fA-F]{2}))/)\n if !@static_wwpn_address.nil? && @static_wwpn_address !~ pattern\n invalid_properties.push(\"invalid value for \\\"static_wwpn_address\\\", must conform to the pattern #{pattern}.\")\n end\n\n pattern = Regexp.new(/^$|((^20|5[0-9a-fA-F]{1}):([0-9a-fA-F]{2}:){6}([0-9a-fA-F]{2}))/)\n if !@wwpn.nil? && @wwpn !~ pattern\n invalid_properties.push(\"invalid value for \\\"wwpn\\\", must conform to the pattern #{pattern}.\")\n end\n\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = super\n if @is_object_icon.nil?\n invalid_properties.push('invalid value for \"is_object_icon\", is_object_icon cannot be nil.')\n end\n\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n if @input_currency.nil?\n invalid_properties.push('invalid value for \"input_currency\", input_currency cannot be nil.')\n end\n\n if @sender.nil?\n invalid_properties.push('invalid value for \"sender\", sender cannot be nil.')\n end\n\n if @recipients.nil?\n invalid_properties.push('invalid value for \"recipients\", recipients cannot be nil.')\n end\n\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = super\n if @index.nil?\n invalid_properties.push('invalid value for \"index\", index cannot be nil.')\n end\n\n if @orientation.nil?\n invalid_properties.push('invalid value for \"orientation\", orientation cannot be nil.')\n end\n\n if @size.nil?\n invalid_properties.push('invalid value for \"size\", size cannot be nil.')\n end\n\n if @type.nil?\n invalid_properties.push('invalid value for \"type\", type cannot be nil.')\n end\n\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = super\n if @direction.nil?\n invalid_properties.push('invalid value for \"direction\", direction cannot be nil.')\n end\n\n if @shape.nil?\n invalid_properties.push('invalid value for \"shape\", shape cannot be nil.')\n end\n\n if @linear_angle.nil?\n invalid_properties.push('invalid value for \"linear_angle\", linear_angle cannot be nil.')\n end\n\n if @is_scaled.nil?\n invalid_properties.push('invalid value for \"is_scaled\", is_scaled cannot be nil.')\n end\n\n if @tile_flip.nil?\n invalid_properties.push('invalid value for \"tile_flip\", tile_flip cannot be nil.')\n end\n\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n if @format.nil?\n invalid_properties.push('invalid value for \"format\", format cannot be nil.')\n end\n\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = Array.new\n invalid_properties\n end" ]
[ "0.76497203", "0.76497203", "0.76497203", "0.76497203", "0.7637422", "0.7637422", "0.7637422", "0.7637422", "0.7637422", "0.7637422", "0.7637422", "0.7637422", "0.7356452", "0.7334807", "0.72685325", "0.7238964", "0.7231359", "0.72258264", "0.7208294", "0.71760833", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241", "0.7170241" ]
0.0
-1
Check to see if the all the properties in the model are valid
def valid? return false if !@display_name.nil? && @display_name.to_s.length > 255 return false if !@description.nil? && @description.to_s.length > 1024 return false if @tcp_closed.nil? return false if @tcp_closed > 4320000 return false if @tcp_closed < 10 return false if @tcp_opening.nil? return false if @tcp_opening > 4320000 return false if @tcp_opening < 10 return false if @udp_single.nil? return false if @udp_single > 4320000 return false if @udp_single < 10 return false if @tcp_finwait.nil? return false if @tcp_finwait > 4320000 return false if @tcp_finwait < 10 return false if @tcp_first_packet.nil? return false if @tcp_first_packet > 4320000 return false if @tcp_first_packet < 10 return false if @tcp_closing.nil? return false if @tcp_closing > 4320000 return false if @tcp_closing < 10 return false if @tcp_established.nil? return false if @tcp_established > 4320000 return false if @tcp_established < 120 return false if @udp_multiple.nil? return false if @udp_multiple > 4320000 return false if @udp_multiple < 10 return false if @icmp_error_reply.nil? return false if @icmp_error_reply > 4320000 return false if @icmp_error_reply < 10 return false if @udp_first_packet.nil? return false if @udp_first_packet > 4320000 return false if @udp_first_packet < 10 return false if @icmp_first_packet.nil? return false if @icmp_first_packet > 4320000 return false if @icmp_first_packet < 10 true end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def validate_properties\n true\n end", "def validate_properties\n true\n end", "def validate\n super\n\n check_optional_property :collection, String\n check_optional_property :create, String\n check_optional_property :delete, String\n check_optional_property :flush, String\n check_optional_property :prefetch, String\n check_optional_property :request_to_query, String\n check_optional_property :resource_to_request_patch, String\n check_optional_property :return_if_object, String\n check_optional_property :self_link, String\n end", "def valid_attributes?\n true\n end", "def valid_attributes?\n attribute_errors.empty?\n end", "def valid?\n return false if @property_code.nil?\n return false if @property_name.nil?\n return false if @location.nil?\n return false if @total_price.nil?\n return false if @min_daily_rate.nil?\n return true\n end", "def validate_presence_of(klazz, properties)\r\n instance = klazz.new \r\n instance.should_not be_valid\r\n \r\n properties.each do |property| \r\n instance.errors.should be_invalid(property)\r\n err_properties = instance.errors[property]\r\n if err_properties.is_a? Array\r\n err_properties.include?(ActiveRecord::Errors.default_error_messages[:blank]).should be_true\r\n else\r\n err_properties.should == ActiveRecord::Errors.default_error_messages[:blank] \r\n end\r\n end \r\n end", "def validate_attributes!(attributes)\n invalid_properties = attributes.keys.map(&:to_s) - self.attributes.keys\n raise UndefinedPropertyError, \"Undefined properties: #{invalid_properties.join(',')}\" if invalid_properties.size > 0\n end", "def model_valid?\n true\n end", "def model_valid?\n true\n end", "def valid?\n self.errors = []\n self.content_type.fields.each do |field|\n if field.required\n if self.dynamic_getter(field.name).blank?\n self.errors << field.name\n end\n end\n end\n self.errors.blank?\n end", "def valid?\n validate\n @model.errors.on(:preferences).blank?\n end", "def validate_properties\n if @properties.keys.count > 0\n if @properties.key?(:label)\n unless @properties[:label] =~ /^[a-zA-Z][\\w|\\s]*$/\n raise 'property label validation error'\n end\n end\n\n if @properties.key?(:default_aggregate)\n unless @properties[:default_aggregate] =~ /^max$|^min$|^avg$|^count$/i\n raise 'property default_aggregate validation error'\n end\n end\n end\n end", "def validate_properties\n @properties.each do |property, values|\n valid_values = validate_values(property, values)\n\n if valid_values.is_a?(Array) && valid_values == [] || valid_values.nil?\n @properties.delete(property)\n else\n @properties[property] = valid_values\n end\n end\n end", "def validate\n valid?\n end", "def validate_attributes!(attributes)\n return attributes if attributes.blank?\n invalid_properties = attributes.keys.map(&:to_s) - self.attributes.keys\n invalid_properties.reject! { |name| self.respond_to?(\"#{name}=\") }\n fail UndefinedPropertyError, \"Undefined properties: #{invalid_properties.join(',')}\" if !invalid_properties.empty?\n end", "def is_valid; end", "def valid?\n # TODO validate nested objects\n output = super\n errors.empty? && output\n end", "def property_checks\n errors.add(:base, \"You can't have a Thing without properties\") if property_keys.empty?\n\n self.property_keys.each do |key|\n errors.add(:properties, \"'#{key}' is an invalid property for this List\") unless available_property_keys.include?(key)\n end\n end", "def valid_for_attributes( model, attributes )\n unless model.valid?\n errors = model.errors\n our_errors = Array.new\n errors.each { |attr,error|\n if attributes.include? attr\n our_errors << [attr,error]\n end\n }\n errors.clear\n our_errors.each { |attr,error| errors.add(attr,error) }\n return false unless errors.empty?\n end\n return true\n end", "def valid?\n type_validator = EnumAttributeValidator.new('String', [\"person\", \"business\"])\n return false unless type_validator.valid?(@type)\n return false if @country.nil?\n return false if @street.nil?\n return false if @postal_code.nil?\n return false if @city.nil?\n return false if @email.nil?\n return false if @ip.nil?\n identification_type_validator = EnumAttributeValidator.new('String', [\"DL\", \"PP\", \"ID\", \"OT\"])\n return false unless identification_type_validator.valid?(@identification_type)\n legal_entity_type_validator = EnumAttributeValidator.new('String', [\"sole_proprietorship\", \"partnership\", \"privately_owned_company\", \"publicly_owned_company\", \"government_owned_entity\", \"trust\", \"ngo\", \"club_and_society\", \"go\", \"other\", \"financial_institution\", \"mto\"])\n return false unless legal_entity_type_validator.valid?(@legal_entity_type)\n nature_of_business_validator = EnumAttributeValidator.new('String', [\"personal\", \"agriculture_and_hunting\", \"forestry\", \"fishing\", \"agricultural_by_products\", \"coal_mining\", \"oil_mining\", \"iron_ore_mining\", \"other_metal_and_diamond_mining\", \"other_mineral_mining\", \"manufacturing_of_food_drink_tobacco\", \"manufacturing_of_textiles_leather_fur_furniture\", \"manufacture_of_wooden_products_furniture\", \"manufacture_of_paper_pulp_allied_products\", \"manufacture_of_chemicals_medical_petroleum_rubber_plastic_products\", \"manufacture_of_pottery_china_glass_stone\", \"manufacture_of_iron_steel_non_ferrous_metals_basic_industries\", \"manufacture_of_metal_products_electrical_and_scientific_engineering\", \"manufacture_of_jewelry_musical_instruments_toys\", \"electricity_gas_and_water\", \"construction\", \"wholesale_trade\", \"retail_trade\", \"catering_incl_hotels\", \"transport_storage\", \"communications\", \"finance_and_holding_companies\", \"insurance\", \"business_services\", \"real_estate_development_investment\", \"central_state_governments\", \"community_services_defence_police_prisons_etc\", \"social_services_education_health_care\", \"personal_services_leisure_services\", \"personal_services_domestic_laundry_repairs\", \"personal_services_embassies_international_organisations\"])\n return false unless nature_of_business_validator.valid?(@nature_of_business)\n return false if @documents.nil?\n gender_validator = EnumAttributeValidator.new('String', [\"M\", \"F\", \"O\"])\n return false unless gender_validator.valid?(@gender)\n true\n end", "def valid?\n return false if !super\n return false if @index.nil?\n return false if @orientation.nil?\n orientation_validator = EnumAttributeValidator.new('String', ['Horizontal', 'Vertical'])\n return false unless orientation_validator.valid?(@orientation)\n return false if @size.nil?\n size_validator = EnumAttributeValidator.new('String', ['Full', 'Half', 'Quarter'])\n return false unless size_validator.valid?(@size)\n return false if @type.nil?\n type_validator = EnumAttributeValidator.new('String', ['Title', 'Body', 'CenteredTitle', 'Subtitle', 'DateAndTime', 'SlideNumber', 'Footer', 'Header', 'Object', 'Chart', 'Table', 'ClipArt', 'Diagram', 'Media', 'SlideImage', 'Picture'])\n return false unless type_validator.valid?(@type)\n true\n end", "def validate\n validate_string_attributes\n @relations.map(&:validate)\n end", "def is_valid?\n end", "def run_validations\n true\n end", "def validate\n validate_params\n validate_colour\n validate_coordinates\n validate_dimension\n end", "def checkAttributeRequirements\n if @valid_attributes.empty?\n @error_text = \"No valid attributes found\"\n return false\n elsif (@mandatory_attributes_from_db & @valid_attributes) != @mandatory_attributes_from_db\n missing_attr = @mandatory_attributes_from_db - (@mandatory_attributes_from_db & @valid_attributes)\n\n x_attr_txt = \"\"\n missing_attr.each {|x_attr| x_attr_txt += x_attr[:name] + \", \"}\n @error_text = \"Mandatory attributes #{x_attr_txt[0..-3]} is/are missing\"\n return false\n end\n\n return true\n end", "def validations\n {}\n end", "def validatable?\n true\n end", "def validate\n validate_params\n validate_coordinates\n validate_colour\n validate_dimension\n end", "def validate_required\n [\n :project_name,\n :status,\n :requester_id,\n :subject_expert_id,\n :sponsor_id,\n :vision,\n :goal,\n :description,\n :scope,\n :advice_required,\n :program_id,\n :train_id,\n :funding_method,\n :cost_center,\n :funding_status,\n :budget_allocated,\n :priority,\n :start_date,\n :end_date,\n :risk_rating,\n :risks,\n :projected_revenue,\n ].each do |field|\n if self.attributes[field.to_s].nil? || self.attributes[field.to_s].blank?\n # intentionally vague!\n add_validation 'All fields are required to perform further validations'\n return false\n end\n end\n true\n end", "def validate\n validate_root\n validate_associated\n valid?\n end", "def validate\n true\n end", "def valid?\n return false if @id.nil?\n return false if @created.nil?\n return false if @modified.nil?\n return false if @company_name.nil?\n return false if @company_name.to_s.length < 1\n return false if @domain_name.nil?\n return false if @state.nil?\n state_validator = EnumAttributeValidator.new('String', [\"active\", \"deactivated\"])\n return false unless state_validator.valid?(@state)\n return false if @billing_email.nil?\n return false if @application_count.nil?\n return false if @user_count.nil?\n return false if @campaigns_active_count.nil?\n return false if @campaigns_inactive_count.nil?\n true\n end", "def valid?\n _errors_before = self.errors.dup\n _s = super\n validate_attributes\n _errors_before.each { |e| append_error(_errors_before,e) }\n self.errors.empty?\n end", "def valid?\n true\n end", "def validate!\n expected_props, required_props = @properties.keys, @required\n\n unless is_a?(Dialect) || is_a?(Template)\n expected_props = expected_props + INHERITED_PROPERTIES.keys\n end\n\n # It has only expected properties (exclude metadata)\n keys = self.keys - [:\"@context\"]\n keys = keys.reject {|k| k.to_s.include?(':')} unless is_a?(Dialect)\n raise \"#{type} has unexpected keys: #{keys - expected_props}\" unless keys.all? {|k| expected_props.include?(k)}\n\n # It has required properties\n raise \"#{type} missing required keys: #{required_props & keys}\" unless (required_props & keys) == required_props\n\n # Every property is valid\n keys.each do |key|\n value = self[key]\n is_valid = case key\n when :columns\n column_names = value.map(&:name)\n value.is_a?(Array) &&\n value.all? {|v| v.is_a?(Column) && v.validate!} &&\n begin\n # The name properties of the column descriptions must be unique within a given table description.\n column_names = value.map(&:name)\n raise \"Columns must have unique names\" if column_names.uniq != column_names\n true\n end\n when :commentPrefix then value.is_a?(String) && value.length == 1\n when :datatype then value.is_a?(String) && DATATYPES.keys.map(&:to_s).include?(value)\n when :default then value.is_a?(String)\n when :delimiter then value.is_a?(String) && value.length == 1\n when :dialect then value.is_a?(Dialect) && value.validate!\n when :doubleQuote then %w(true false 1 0).include?(value.to_s.downcase)\n when :encoding then Encoding.find(value)\n when :foreignKeys\n # An array of foreign key definitions that define how the values from specified columns within this table link to rows within this table or other tables. A foreign key definition is a JSON object with the properties:\n value.is_a?(Array) && value.all? do |fk|\n raise \"Foreign key must be an object\" unless fk.is_a?(Hash)\n columns, reference = fk['columns'], fk['reference']\n raise \"Foreign key missing columns and reference\" unless columns && reference\n raise \"Foreign key has extra entries\" unless fk.keys.length == 2\n raise \"Foreign key must reference columns\" unless Array(columns).all? {|k| self.columns.any? {|c| c.name == k}}\n raise \"Foreign key reference must be an Object\" unless reference.is_a?(Hash)\n\n if reference.has_key?('resource')\n raise \"Foreign key having a resource reference, must not have a schema\" if reference.has_key?('schema')\n # FIXME resource is a URL of a specific resource (table) which must exist\n elsif reference.has_key?('schema')\n # FIXME schema is a URL of a specific schema which must exist\n end\n # FIXME: columns\n true\n end\n when :format then value.is_a?(String)\n when :header then %w(true false 1 0).include?(value.to_s.downcase)\n when :headerColumnCount, :headerRowCount\n value.is_a?(Numeric) && value.integer? && value > 0\n when :length\n # Applications must raise an error if length, maxLength or minLength are specified and the cell value is not a list (ie separator is not specified), a string or one of its subtypes, or a binary value.\n raise \"Use if minLength or maxLength with length requires separator\" if self[:minLength] || self[:maxLength] && !self[:separator]\n raise \"Use of both length and minLength requires they be equal\" unless self.fetch(:minLength, value) == value\n raise \"Use of both length and maxLength requires they be equal\" unless self.fetch(:maxLength, value) == value\n value.is_a?(Numeric) && value.integer? && value > 0\n when :language then BCP47::Language.identify(value)\n when :lineTerminator then value.is_a?(String)\n when :minimum, :maximum, :minInclusive, :maxInclusive, :minExclusive, :maxExclusive\n value.is_a?(Numeric) ||\n RDF::Literal::Date.new(value).valid? ||\n RDF::Literal::Time.new(value).valid? ||\n RDF::Literal::DateTime.new(value).valid?\n when :minLength, :maxLength\n value.is_a?(Numeric) && value.integer? && value > 0\n when :name then value.is_a?(String) && !name.start_with?(\"_\")\n when :notes then value.is_a?(Array) && value.all? {|v| v.is_a?(Hash)}\n when :null then value.is_a?(String)\n when :predicateUrl then Array(value).all? {|v| RDF::URI(v).valid?}\n when :primaryKey\n # A column reference property that holds either a single reference to a column description object or an array of references.\n Array(value).all? do |k|\n self.columns.any? {|c| c.name == k}\n end\n when :quoteChar then value.is_a?(String) && value.length == 1\n when :required then %w(true false 1 0).include?(value.to_s.downcase)\n when :resources then value.is_a?(Array) && value.all? {|v| v.is_a?(Table) && v.validate!}\n when :schema then value.is_a?(Schema) && value.validate!\n when :separator then value.nil? || value.is_a?(String) && value.length == 1\n when :skipInitialSpace then %w(true false 1 0).include?(value.to_s.downcase)\n when :skipBlankRows then %w(true false 1 0).include?(value.to_s.downcase)\n when :skipColumns then value.is_a?(Numeric) && value.integer? && value >= 0\n when :skipRows then value.is_a?(Numeric) && value.integer? && value >= 0\n when :source then %w(json rdf).include?(value)\n when :\"table-direction\" then %w(rtl ltr default).include?(value)\n when :targetFormat, :templateFormat then RDF::URI(value).valid?\n when :templates then value.is_a?(Array) && value.all? {|v| v.is_a?(Template) && v.validate!}\n when :\"text-direction\" then %w(rtl ltr).include?(value)\n when :title then valid_natural_language_property?(value)\n when :trim then %w(true false 1 0 start end).include?(value.to_s.downcase)\n when :urlTemplate then value.is_a?(String)\n when :@id then @id.valid?\n when :@type then value.to_sym == type\n else\n raise \"?!?! shouldn't get here for key #{key}\"\n end\n raise \"#{type} has invalid #{key}: #{value.inspect}\" unless is_valid\n end\n\n self\n end", "def valid?\n return false if @subject_property.nil?\n return false if @proprietorship.nil?\n proprietorship_validator = EnumAttributeValidator.new('String', [\"Unknown\", \"Sole\", \"Joint\"])\n return false unless proprietorship_validator.valid?(@proprietorship)\n return false if @surname.nil?\n return false if @forename.nil?\n return false if @middle_name.nil?\n return true\n end", "def valid?\n return false if @class_id.nil?\n class_id_validator = EnumAttributeValidator.new('String', [\"cond.HclStatusDetail\"])\n return false unless class_id_validator.valid?(@class_id)\n return false if @object_type.nil?\n object_type_validator = EnumAttributeValidator.new('String', [\"cond.HclStatusDetail\"])\n return false unless object_type_validator.valid?(@object_type)\n hardware_status_validator = EnumAttributeValidator.new('String', [\"Missing-Os-Driver-Info\", \"Incompatible-Server-With-Component\", \"Incompatible-Processor\", \"Incompatible-Os-Info\", \"Incompatible-Component-Model\", \"Incompatible-Firmware\", \"Incompatible-Driver\", \"Incompatible-Firmware-Driver\", \"Service-Unavailable\", \"Service-Error\", \"Unrecognized-Protocol\", \"Not-Evaluated\", \"Compatible\"])\n return false unless hardware_status_validator.valid?(@hardware_status)\n reason_validator = EnumAttributeValidator.new('String', [\"Missing-Os-Driver-Info\", \"Incompatible-Server-With-Component\", \"Incompatible-Processor\", \"Incompatible-Os-Info\", \"Incompatible-Component-Model\", \"Incompatible-Firmware\", \"Incompatible-Driver\", \"Incompatible-Firmware-Driver\", \"Service-Unavailable\", \"Service-Error\", \"Unrecognized-Protocol\", \"Not-Evaluated\", \"Compatible\"])\n return false unless reason_validator.valid?(@reason)\n software_status_validator = EnumAttributeValidator.new('String', [\"Missing-Os-Driver-Info\", \"Incompatible-Server-With-Component\", \"Incompatible-Processor\", \"Incompatible-Os-Info\", \"Incompatible-Component-Model\", \"Incompatible-Firmware\", \"Incompatible-Driver\", \"Incompatible-Firmware-Driver\", \"Service-Unavailable\", \"Service-Error\", \"Unrecognized-Protocol\", \"Not-Evaluated\", \"Compatible\"])\n return false unless software_status_validator.valid?(@software_status)\n status_validator = EnumAttributeValidator.new('String', [\"Incomplete\", \"Not-Found\", \"Not-Listed\", \"Validated\", \"Not-Evaluated\"])\n return false unless status_validator.valid?(@status)\n true && super\n end", "def core_attributes_valid\n core_attributes = [@rateable, @rater, @ratee, @rating_type]\n return if core_attributes.all? { |atr| atr.present? && atr.valid? }\n errors.add('message', 'Not all core attributes present and valid.')\n end", "def valid?\n super\n errors.empty?\n end", "def valid?\n \n if @account_id.nil?\n false\n elsif @campaign_id.nil?\n false\n elsif @csp_id.nil?\n false\n elsif @status.nil?\n false\n elsif @create_date.nil?\n false\n elsif @auto_renewal.nil?\n false\n elsif @brand_id.nil?\n false\n elsif @usecase.nil?\n false\n elsif @sub_usecases.nil?\n false\n elsif @description.nil?\n false\n elsif @embedded_link.nil?\n false\n elsif @embedded_phone.nil?\n false\n elsif @affiliate_marketing.nil?\n false\n elsif @number_pool.nil?\n false\n elsif @age_gated.nil?\n false\n elsif @direct_lending.nil?\n false\n elsif @subscriber_optin.nil?\n false\n elsif @subscriber_optout.nil?\n false\n elsif @subscriber_help.nil?\n false\n elsif @sample1.nil?\n false\n elsif @mock.nil?\n false\n else\n list_invalid_properties.length() == 0\n end\n end", "def valid?(metadata)\n validate.each do |attr|\n return false if metadata[attr.to_sym].nil? || metadata[attr.to_sym].zero?\n end\n end", "def is_valid\n return true\n end", "def validate_attrs\n @target.present? && !@target.errors.any? && @actor.present? && @action_key.present?\n end", "def list_invalid_properties\n invalid_properties = super\n if @class_id.nil?\n invalid_properties.push('invalid value for \"class_id\", class_id cannot be nil.')\n end\n\n if @object_type.nil?\n invalid_properties.push('invalid value for \"object_type\", object_type cannot be nil.')\n end\n\n if !@name.nil? && @name.to_s.length > 31\n invalid_properties.push('invalid value for \"name\", the character length must be smaller than or equal to 31.')\n end\n\n pattern = Regexp.new(/^[a-zA-Z0-9\\-\\._:]+$/)\n if !@name.nil? && @name !~ pattern\n invalid_properties.push(\"invalid value for \\\"name\\\", must conform to the pattern #{pattern}.\")\n end\n\n pattern = Regexp.new(/^$|((^20|5[0-9a-fA-F]{1}):([0-9a-fA-F]{2}:){6}([0-9a-fA-F]{2}))/)\n if !@static_wwpn_address.nil? && @static_wwpn_address !~ pattern\n invalid_properties.push(\"invalid value for \\\"static_wwpn_address\\\", must conform to the pattern #{pattern}.\")\n end\n\n pattern = Regexp.new(/^$|((^20|5[0-9a-fA-F]{1}):([0-9a-fA-F]{2}:){6}([0-9a-fA-F]{2}))/)\n if !@wwpn.nil? && @wwpn !~ pattern\n invalid_properties.push(\"invalid value for \\\"wwpn\\\", must conform to the pattern #{pattern}.\")\n end\n\n invalid_properties\n end", "def valid_save?\n valid = true\n\n if self.name.nil? || self.name == \"\"\n valid = false\n end\n\n if self.general_info.nil? || self.general_info == \"\"\n valid = false\n end\n\n if self.technical_specs.nil? || self.technical_specs == \"\"\n valid = false\n end\n\n if self.where_to_buy.nil? || self.where_to_buy == \"\"\n valid = false\n end\n\n return valid\n end", "def valid?\n schema.validate(self)\n end", "def valid?\n reset_errors\n valid_date?\n valid_user?\n valid_activity_type?\n self.errors.empty?\n end", "def valid?\n validate\n end", "def product_attributes_must_not_be_empty\n\n\t\t# Instance\n\t\tproduct = Product.new\n\n\t\tassert product.invalid?\n\t\tassert product.errors[:title].any?\n\t\tassert product.errors[:description].any?\n\t\tassert product.errors[:price].any?\n\t\tassert product.errors[:image_url].any?\n\tend", "def valid?\n return false if @id.nil?\n return false if @id !~ Regexp.new(/^psc_[a-zA-Z0-9]+$/)\n carrier_validator = EnumAttributeValidator.new('String', [\"USPS\"])\n return false unless carrier_validator.valid?(@carrier)\n return false if !@front_template_id.nil? && @front_template_id !~ Regexp.new(/^tmpl_[a-zA-Z0-9]+$/)\n return false if !@back_template_id.nil? && @back_template_id !~ Regexp.new(/^tmpl_[a-zA-Z0-9]+$/)\n return false if !@front_template_version_id.nil? && @front_template_version_id !~ Regexp.new(/^vrsn_[a-zA-Z0-9]+$/)\n return false if !@back_template_version_id.nil? && @back_template_version_id !~ Regexp.new(/^vrsn_[a-zA-Z0-9]+$/)\n object_validator = EnumAttributeValidator.new('String', [\"postcard\"])\n return false unless object_validator.valid?(@object)\n return false if @url.nil?\n return false if @url !~ Regexp.new(/^https:\\/\\/(lob-assets|lob-assets-staging)\\.com\\/(letters|postcards|bank-accounts|checks|self-mailers|cards)\\/[a-z]{3,4}_[a-z0-9]{15,16}(\\.pdf|_thumb_[a-z]+_[0-9]+\\.png)\\?(version=[a-z0-9-]*&)?expires=[0-9]{10}&signature=[a-zA-Z0-9_-]+$/)\n return false if !@description.nil? && @description.to_s.length > 255\n true\n end", "def valid?\n return false if @class_id.nil?\n class_id_validator = EnumAttributeValidator.new('String', [\"network.ElementSummary\"])\n return false unless class_id_validator.valid?(@class_id)\n return false if @object_type.nil?\n object_type_validator = EnumAttributeValidator.new('String', [\"network.ElementSummary\"])\n return false unless object_type_validator.valid?(@object_type)\n ethernet_switching_mode_validator = EnumAttributeValidator.new('String', [\"end-host\", \"switch\"])\n return false unless ethernet_switching_mode_validator.valid?(@ethernet_switching_mode)\n fc_switching_mode_validator = EnumAttributeValidator.new('String', [\"end-host\", \"switch\"])\n return false unless fc_switching_mode_validator.valid?(@fc_switching_mode)\n management_mode_validator = EnumAttributeValidator.new('String', [\"IntersightStandalone\", \"UCSM\", \"Intersight\"])\n return false unless management_mode_validator.valid?(@management_mode)\n thermal_validator = EnumAttributeValidator.new('String', [\"unknown\", \"ok\", \"upper-non-recoverable\", \"upper-critical\", \"upper-non-critical\", \"lower-non-critical\", \"lower-critical\", \"lower-non-recoverable\"])\n return false unless thermal_validator.valid?(@thermal)\n true && super\n end", "def valid?\n\t\t\t\ttrue\n\t\t\tend", "def validate\r\n validate! rescue false\r\n end", "def validate\n validate_string_attributes\n end", "def valid?\n self.errors = Mongomatic::Errors.new\n do_callback(:before_validate)\n check_required_fields\n validate\n do_callback(:after_validate)\n self.errors.empty?\n end", "def valid\n @valid\n end", "def valid_objects\n all_objects.select { |o| o.valid? }\n end", "def valid?\n return false if @summary.nil?\n return false if @summary.to_s.length > 100\n record_type_validator = EnumAttributeValidator.new('String', [\"ServiceTicket\", \"ProjectTicket\", \"ProjectIssue\"])\n return false unless record_type_validator.valid?(@record_type)\n return false if !@wbs_code.nil? && @wbs_code.to_s.length > 50\n return false if @company.nil?\n return false if !@site_name.nil? && @site_name.to_s.length > 50\n return false if !@address_line1.nil? && @address_line1.to_s.length > 50\n return false if !@address_line2.nil? && @address_line2.to_s.length > 50\n return false if !@city.nil? && @city.to_s.length > 50\n return false if !@state_identifier.nil? && @state_identifier.to_s.length > 50\n return false if !@zip.nil? && @zip.to_s.length > 12\n return false if !@contact_phone_number.nil? && @contact_phone_number.to_s.length > 20\n return false if !@contact_phone_extension.nil? && @contact_phone_extension.to_s.length > 15\n return false if !@contact_email_address.nil? && @contact_email_address.to_s.length > 250\n severity_validator = EnumAttributeValidator.new('String', [\"Low\", \"Medium\", \"High\"])\n return false unless severity_validator.valid?(@severity)\n impact_validator = EnumAttributeValidator.new('String', [\"Low\", \"Medium\", \"High\"])\n return false unless impact_validator.valid?(@impact)\n return false if !@external_x_ref.nil? && @external_x_ref.to_s.length > 100\n return false if !@po_number.nil? && @po_number.to_s.length > 50\n return false if !@automatic_email_cc.nil? && @automatic_email_cc.to_s.length > 1000\n sub_billing_method_validator = EnumAttributeValidator.new('String', [\"ActualRates\", \"FixedFee\", \"NotToExceed\", \"OverrideRate\"])\n return false unless sub_billing_method_validator.valid?(@sub_billing_method)\n knowledge_base_link_type_validator = EnumAttributeValidator.new('String', [\"ServiceTicket\", \"ProjectTicket\", \"ProjectIssue\", \"KnowledgeBaseArticle\", \"Time\", \"Activity\"])\n return false unless knowledge_base_link_type_validator.valid?(@knowledge_base_link_type)\n bill_time_validator = EnumAttributeValidator.new('String', [\"Billable\", \"DoNotBill\", \"NoCharge\", \"NoDefault\"])\n return false unless bill_time_validator.valid?(@bill_time)\n bill_expenses_validator = EnumAttributeValidator.new('String', [\"Billable\", \"DoNotBill\", \"NoCharge\", \"NoDefault\"])\n return false unless bill_expenses_validator.valid?(@bill_expenses)\n bill_products_validator = EnumAttributeValidator.new('String', [\"Billable\", \"DoNotBill\", \"NoCharge\", \"NoDefault\"])\n return false unless bill_products_validator.valid?(@bill_products)\n predecessor_type_validator = EnumAttributeValidator.new('String', [\"Ticket\", \"Phase\"])\n return false unless predecessor_type_validator.valid?(@predecessor_type)\n return true\n end", "def validate!\n true\n end", "def valid?\n return false if @class_id.nil?\n class_id_validator = EnumAttributeValidator.new('String', [\"vnic.FcIf\"])\n return false unless class_id_validator.valid?(@class_id)\n return false if @object_type.nil?\n object_type_validator = EnumAttributeValidator.new('String', [\"vnic.FcIf\"])\n return false unless object_type_validator.valid?(@object_type)\n return false if !@name.nil? && @name.to_s.length > 31\n return false if !@name.nil? && @name !~ Regexp.new(/^[a-zA-Z0-9\\-\\._:]+$/)\n return false if !@static_wwpn_address.nil? && @static_wwpn_address !~ Regexp.new(/^$|((^20|5[0-9a-fA-F]{1}):([0-9a-fA-F]{2}:){6}([0-9a-fA-F]{2}))/)\n type_validator = EnumAttributeValidator.new('String', [\"fc-initiator\", \"fc-nvme-initiator\", \"fc-nvme-target\", \"fc-target\"])\n return false unless type_validator.valid?(@type)\n return false if !@wwpn.nil? && @wwpn !~ Regexp.new(/^$|((^20|5[0-9a-fA-F]{1}):([0-9a-fA-F]{2}:){6}([0-9a-fA-F]{2}))/)\n wwpn_address_type_validator = EnumAttributeValidator.new('String', [\"POOL\", \"STATIC\"])\n return false unless wwpn_address_type_validator.valid?(@wwpn_address_type)\n true && super\n end", "def valid?\n validate_survivors and validate_items && validate_records\n end", "def valid?\n return false if @id.nil?\n return false if @next_send.nil?\n return false if @rrule.nil?\n return false if @session.nil?\n return false if @last_sent.nil?\n return false if @contact_name.nil?\n return false if @parameters.nil?\n return false if @type.nil?\n type_validator = EnumAttributeValidator.new('String', ['Once', 'Hourly', 'Daily', 'Weekly', 'Monthly', 'Yearly'])\n return false unless type_validator.valid?(@type)\n return false if @summary.nil?\n return false if @text_parameters.nil?\n return false if @first_occurrence.nil?\n return false if @last_occurrence.nil?\n return false if @recipients_count.nil?\n return false if @timezone.nil?\n return false if @completed.nil?\n return false if @avatar.nil?\n return false if @created_at.nil?\n true\n end", "def valid?\n return false if !@description.nil? && @description.to_s.length > 255\n return false if @routing_number.nil?\n return false if @routing_number.to_s.length > 9\n return false if @routing_number.to_s.length < 9\n return false if @account_number.nil?\n return false if @account_number.to_s.length > 17\n return false if @account_type.nil?\n account_type_validator = EnumAttributeValidator.new('String', [\"company\", \"individual\"])\n return false unless account_type_validator.valid?(@account_type)\n return false if @signatory.nil?\n return false if @signatory.to_s.length > 30\n return false if @id.nil?\n return false if @id !~ Regexp.new(/^bank_[a-zA-Z0-9]+$/)\n return false if !@signature_url.nil? && @signature_url !~ Regexp.new(/^https:\\/\\/lob-assets\\.com\\/(letters|postcards|bank-accounts|checks|self-mailers|cards)\\/[a-z]{3,4}_[a-z0-9]{15,16}(\\.pdf|_thumb_[a-z]+_[0-9]+\\.png)\\?(version=[a-z0-9-]*&)?expires=[0-9]{10}&signature=[a-zA-Z0-9_-]+$/)\n return false if @date_created.nil?\n return false if @date_modified.nil?\n return false if @object.nil?\n object_validator = EnumAttributeValidator.new('String', [\"bank_account\"])\n return false unless object_validator.valid?(@object)\n true\n end", "def valid?\n true\n end", "def valid?\n true\n end", "def valid?\n true\n end", "def valid?\n true\n end", "def valid?\n return false if @id.nil?\n return false if @account_id.nil?\n return false if @organization_id.nil?\n return false if @product_id.nil?\n return false if @product_rate_plan_id.nil?\n return false if @name.nil?\n type_validator = EnumAttributeValidator.new('String', [\"Subscription\", \"FixedTerm\", \"Trial\"])\n return false unless type_validator.valid?(@type)\n return false if @state.nil?\n state_validator = EnumAttributeValidator.new('String', [\"Trial\", \"Provisioned\", \"Paid\", \"AwaitingPayment\", \"Cancelled\", \"Failed\", \"Expired\"])\n return false unless state_validator.valid?(@state)\n return false if @initial_period_start.nil?\n return false if @trial_end.nil?\n managed_by_validator = EnumAttributeValidator.new('String', [\"BillForward\", \"Stripe\"])\n return false unless managed_by_validator.valid?(@managed_by)\n return false if @version_start.nil?\n return false if @version_number.nil?\n return false if @current_time.nil?\n failed_payment_behaviour_validator = EnumAttributeValidator.new('String', [\"CancelSubscription\", \"None\"])\n return false unless failed_payment_behaviour_validator.valid?(@failed_payment_behaviour)\n return true\n end", "def validate_fields\n %w[email author].each do |field|\n value = self.send(field)\n abort \"Hoe #{field} value not set. aborting\" if value.nil? or value.empty?\n end\n end", "def valid?\n return false if @name.nil?\n return false if @name.to_s.length < 1\n return false if @timezone.nil?\n return false if @timezone.to_s.length < 1\n return false if @currency.nil?\n return false if @currency.to_s.length < 1\n case_sensitivity_validator = EnumAttributeValidator.new('String', [\"sensitive\", \"insensitive-uppercase\", \"insensitive-lowercase\"])\n return false unless case_sensitivity_validator.valid?(@case_sensitivity)\n campaign_priority_validator = EnumAttributeValidator.new('String', [\"universal\", \"stackable\", \"exclusive\"])\n return false unless campaign_priority_validator.valid?(@campaign_priority)\n exclusive_campaigns_strategy_validator = EnumAttributeValidator.new('String', [\"listOrder\", \"lowestDiscount\", \"highestDiscount\"])\n return false unless exclusive_campaigns_strategy_validator.valid?(@exclusive_campaigns_strategy)\n default_discount_scope_validator = EnumAttributeValidator.new('String', [\"sessionTotal\", \"cartItems\", \"additionalCosts\"])\n return false unless default_discount_scope_validator.valid?(@default_discount_scope)\n default_discount_additional_cost_per_item_scope_validator = EnumAttributeValidator.new('String', [\"price\", \"itemTotal\", \"additionalCosts\"])\n return false unless default_discount_additional_cost_per_item_scope_validator.valid?(@default_discount_additional_cost_per_item_scope)\n true\n end", "def valid?\n run_validation\n @errors.empty?\n end", "def valid?\n MANDATORY_ATTRIBUTES.each{|a| return false unless self[a]}\n true\n end", "def valid?\n return false if @id.nil?\n return false if @token.nil?\n return false if @tipo.nil?\n tipo_validator = EnumAttributeValidator.new('String', ['fatture', 'proforma', 'ordini', 'preventivi', 'ndc'])\n return false unless tipo_validator.valid?(@tipo)\n return false if @nome.nil?\n return false if @indirizzo_via.nil?\n return false if @indirizzo_cap.nil?\n return false if @indirizzo_citta.nil?\n return false if @indirizzo_provincia.nil?\n return false if @paese.nil?\n lingua_validator = EnumAttributeValidator.new('String', ['it', 'en', 'de'])\n return false unless lingua_validator.valid?(@lingua)\n return false if @piva.nil?\n return false if @cf.nil?\n return false if @numero.nil?\n return false if @valuta.nil?\n return false if @valuta_cambio.nil?\n return false if @prezzi_ivati.nil?\n return false if @importo_netto.nil?\n return false if @importo_iva.nil?\n return false if @importo_totale.nil?\n mostra_totali_validator = EnumAttributeValidator.new('String', ['tutti', 'netto', 'nessuno'])\n return false unless mostra_totali_validator.valid?(@mostra_totali)\n return false if @lista_articoli.nil?\n pa_tipo_cliente_validator = EnumAttributeValidator.new('String', ['PA', 'B2B'])\n return false unless pa_tipo_cliente_validator.valid?(@pa_tipo_cliente)\n pa_tipo_validator = EnumAttributeValidator.new('String', ['ordine', 'convenzione', 'contratto', 'nessuno'])\n return false unless pa_tipo_validator.valid?(@pa_tipo)\n pa_esigibilita_validator = EnumAttributeValidator.new('String', ['I', 'D', 'S', 'N'])\n return false unless pa_esigibilita_validator.valid?(@pa_esigibilita)\n true\n end", "def list_invalid_properties\n invalid_properties = super\n if @class_id.nil?\n invalid_properties.push('invalid value for \"class_id\", class_id cannot be nil.')\n end\n\n if @object_type.nil?\n invalid_properties.push('invalid value for \"object_type\", object_type cannot be nil.')\n end\n\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = super\n if @class_id.nil?\n invalid_properties.push('invalid value for \"class_id\", class_id cannot be nil.')\n end\n\n if @object_type.nil?\n invalid_properties.push('invalid value for \"object_type\", object_type cannot be nil.')\n end\n\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = super\n if @class_id.nil?\n invalid_properties.push('invalid value for \"class_id\", class_id cannot be nil.')\n end\n\n if @object_type.nil?\n invalid_properties.push('invalid value for \"object_type\", object_type cannot be nil.')\n end\n\n invalid_properties\n end", "def list_invalid_properties\n invalid_properties = super\n if @class_id.nil?\n invalid_properties.push('invalid value for \"class_id\", class_id cannot be nil.')\n end\n\n if @object_type.nil?\n invalid_properties.push('invalid value for \"object_type\", object_type cannot be nil.')\n end\n\n invalid_properties\n end", "def valid?\n return false if @name.nil?\n return false if @name.to_s.length > 50\n return false if @prefix_suffix_option.nil?\n prefix_suffix_option_validator = EnumAttributeValidator.new('String', [\"Prefix\", \"Suffix\"])\n return false unless prefix_suffix_option_validator.valid?(@prefix_suffix_option)\n return false if !@invoice_pre_suffix.nil? && @invoice_pre_suffix.to_s.length > 5\n application_units_validator = EnumAttributeValidator.new('String', [\"Amount\", \"Hours\", \"Incidents\"])\n return false unless application_units_validator.valid?(@application_units)\n application_cycle_validator = EnumAttributeValidator.new('String', [\"Contract2Weeks\", \"Contract4Weeks\", \"ContractYear\", \"CalendarMonth\", \"CalendarQuarter\", \"CalendarWeek\", \"ContractQuarter\", \"CalendarYear\"])\n return false unless application_cycle_validator.valid?(@application_cycle)\n return false if @employee_comp_rate.nil?\n employee_comp_rate_validator = EnumAttributeValidator.new('String', [\"Actual\", \"Hourly\"])\n return false unless employee_comp_rate_validator.valid?(@employee_comp_rate)\n return false if @employee_comp_not_exceed.nil?\n employee_comp_not_exceed_validator = EnumAttributeValidator.new('String', [\"Billing\", \"Percent\", \"Amount\"])\n return false unless employee_comp_not_exceed_validator.valid?(@employee_comp_not_exceed)\n return false if @invoicing_cycle.nil?\n invoicing_cycle_validator = EnumAttributeValidator.new('String', [\"CalendarYear\", \"ContractYear\"])\n return false unless invoicing_cycle_validator.valid?(@invoicing_cycle)\n return false if !@invoice_description.nil? && @invoice_description.to_s.length > 4000\n return false if @bill_time.nil?\n bill_time_validator = EnumAttributeValidator.new('String', [\"Billable\", \"DoNotBill\", \"NoCharge\", \"NoDefault\"])\n return false unless bill_time_validator.valid?(@bill_time)\n return false if @bill_expenses.nil?\n bill_expenses_validator = EnumAttributeValidator.new('String', [\"Billable\", \"DoNotBill\", \"NoCharge\", \"NoDefault\"])\n return false unless bill_expenses_validator.valid?(@bill_expenses)\n return false if @bill_products.nil?\n bill_products_validator = EnumAttributeValidator.new('String', [\"Billable\", \"DoNotBill\", \"NoCharge\", \"NoDefault\"])\n return false unless bill_products_validator.valid?(@bill_products)\n return true\n end", "def validate\n end", "def valid?\n return false if @to.nil?\n return false if @from.nil?\n carrier_validator = EnumAttributeValidator.new('String', [\"USPS\"])\n return false unless carrier_validator.valid?(@carrier)\n return false if @date_created.nil?\n return false if @date_modified.nil?\n return false if @id.nil?\n return false if @id !~ Regexp.new(/^ltr_[a-zA-Z0-9]+$/)\n return false if !@template_id.nil? && @template_id !~ Regexp.new(/^tmpl_[a-zA-Z0-9]+$/)\n return false if !@template_version_id.nil? && @template_version_id !~ Regexp.new(/^vrsn_[a-zA-Z0-9]+$/)\n return false if !@url.nil? && @url !~ Regexp.new(/^https:\\/\\/(lob-assets|lob-assets-staging)\\.com\\/(letters|postcards|bank-accounts|checks|self-mailers|cards)\\/[a-z]{3,4}_[a-z0-9]{15,16}(\\.pdf|_thumb_[a-z]+_[0-9]+\\.png)\\?(version=[a-z0-9-]*&)?expires=[0-9]{10}&signature=[a-zA-Z0-9_-]+$/)\n return false if @object.nil?\n object_validator = EnumAttributeValidator.new('String', [\"letter\"])\n return false unless object_validator.valid?(@object)\n return false if !@description.nil? && @description.to_s.length > 255\n return false if !@tracking_events.nil? && @tracking_events.length > 0\n address_placement_validator = EnumAttributeValidator.new('String', [\"top_first_page\", \"insert_blank_page\", \"bottom_first_page_center\", \"bottom_first_page\"])\n return false unless address_placement_validator.valid?(@address_placement)\n true\n end", "def valid_attributes\n {}\n end", "def valid_attributes\n {}\n end", "def valid_attributes\n {}\n end", "def valid_attributes\n {}\n end", "def valid_attributes\n {}\n end", "def valid_attributes\n {}\n end", "def valid_attributes\n {}\n end", "def valid_attributes\n {}\n end", "def supports_validations?\n true\n end", "def valid?\n @errors = self.class.valid_against_schema?(self.class.json_schema, self)\n @errors.empty?\n end", "def valid?\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n end", "def valid?\n return false if @first_name.nil?\n return false if @first_name.to_s.length > 30\n return false if !@last_name.nil? && @last_name.to_s.length > 30\n return false if !@address_line1.nil? && @address_line1.to_s.length > 50\n return false if !@address_line2.nil? && @address_line2.to_s.length > 50\n return false if !@city.nil? && @city.to_s.length > 50\n return false if !@state.nil? && @state.to_s.length > 50\n return false if !@zip.nil? && @zip.to_s.length > 12\n return false if !@country.nil? && @country.to_s.length > 50\n return false if !@security_identifier.nil? && @security_identifier.to_s.length > 184\n return false if !@title.nil? && @title.to_s.length > 100\n return false if !@school.nil? && @school.to_s.length > 50\n return false if !@nick_name.nil? && @nick_name.to_s.length > 30\n return false if !@significant_other.nil? && @significant_other.to_s.length > 30\n return false if !@portal_password.nil? && @portal_password.to_s.length > 15\n return false if !@portal_security_level.nil? && @portal_security_level > 6.0\n return false if !@portal_security_level.nil? && @portal_security_level < 1.0\n gender_validator = EnumAttributeValidator.new('String', [\"Male\", \"Female\"])\n return false unless gender_validator.valid?(@gender)\n presence_validator = EnumAttributeValidator.new('String', [\"Online\", \"DoNotDisturb\", \"Away\", \"Offline\", \"NoAgent\"])\n return false unless presence_validator.valid?(@presence)\n return true\n end", "def validated?; end", "def valid?\n return false if @name.nil?\n return false if @slug.nil?\n return false if @status.nil?\n status_validator = EnumAttributeValidator.new('String', ['enabled', 'disabled'])\n return false unless status_validator.valid?(@status)\n return false if @type.nil?\n type_validator = EnumAttributeValidator.new('String', ['digital', 'physical'])\n return false unless type_validator.valid?(@type)\n return false if @sku.nil?\n return false if @price.nil?\n availability_validator = EnumAttributeValidator.new('String', ['available', 'comingSoon', 'retired'])\n return false unless availability_validator.valid?(@availability)\n stock_status_validator = EnumAttributeValidator.new('String', ['available', 'alert', 'unavailable'])\n return false unless stock_status_validator.valid?(@stock_status)\n return false if @categories.nil?\n true\n end", "def valid?\n self.valid\n end", "def valid?\n true\n end", "def valid?\n true\n end", "def valid?\n true\n end", "def valid?\n true\n end" ]
[ "0.78992486", "0.78992486", "0.70971805", "0.70782334", "0.7032205", "0.7031276", "0.69510347", "0.6869891", "0.6858077", "0.6858077", "0.68287027", "0.6823878", "0.6820306", "0.68144894", "0.6794656", "0.6752167", "0.66843414", "0.6676546", "0.6667755", "0.66296124", "0.66184515", "0.6608204", "0.6599208", "0.6594276", "0.6584302", "0.6580472", "0.6578095", "0.6558585", "0.6555879", "0.6542414", "0.6536983", "0.6533884", "0.65315515", "0.65311855", "0.65267456", "0.65258855", "0.6520786", "0.65205675", "0.6511026", "0.6498394", "0.64966303", "0.64935124", "0.6491113", "0.64885867", "0.6479024", "0.6473706", "0.64679337", "0.6467217", "0.6461245", "0.64601135", "0.64553183", "0.64540446", "0.6447954", "0.64393955", "0.6434162", "0.64312094", "0.6428205", "0.6426148", "0.6412439", "0.64070046", "0.64044213", "0.6403482", "0.6399368", "0.63979715", "0.63858813", "0.63855004", "0.63855004", "0.63855004", "0.63855004", "0.63740236", "0.6367379", "0.63645166", "0.6362151", "0.63599974", "0.6357385", "0.63549066", "0.63549066", "0.63549066", "0.63549066", "0.6354845", "0.6354207", "0.6350302", "0.6344303", "0.6344303", "0.6344303", "0.6344303", "0.6344303", "0.6344303", "0.6344303", "0.6344303", "0.63435715", "0.63406414", "0.63344824", "0.6333158", "0.63313466", "0.63294095", "0.6327076", "0.63247603", "0.63247603", "0.63247603", "0.63247603" ]
0.0
-1
Custom attribute writer method with validation
def display_name=(display_name) if !display_name.nil? && display_name.to_s.length > 255 fail ArgumentError, 'invalid value for "display_name", the character length must be smaller than or equal to 255.' end @display_name = display_name end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def attr_writer_tag(text); end", "def allowed_attributes=(_arg0); end", "def allowed_attributes=(_arg0); end", "def writer(*args)\n attr_writer(*args)\n args\n end", "def define_write_method(attr_name)\n evaluate_attribute_method attr_name, \"def #{attr_name}=(new_value);write_attribute('#{attr_name}', new_value);end\", \"#{attr_name}=\"\n end", "def attr_writer(*vars)\n # avoid tracking attributes that are added by the class_attribute\n # as these are class attributes and not instance attributes.\n tracked_vars = vars.reject {|var| respond_to? var }\n add_tracked_attrs(false, true, *tracked_vars)\n vars.extract_options!\n super\n end", "def attr_writer(sym, *more) end", "def is_attribute?; end", "def validate_exclusion_of(attr); end", "def register_attributes\n raise \"Not implemented in #{self.class}\"\n end", "def method_missing(method_name, *args)\n return super unless permitted_attributes.include?(method_name)\n begin\n object.send(:\"#{method_name}=\", args.first)\n rescue => e\n if params.has_key?(method_name)\n message = \"Unable to process value for :#{method_name}, no attribute writer. Be sure to override the automatic setters for all params that do not map straight to a model attribute.\"\n Rails.logger.warn({message: message,\n missing_writer: method_name,\n value: args.first,\n error: e})\n self.errors << {status: 422, message: message}\n else\n raise e\n end\n end\n end", "def timeliness_validation_for(attr_names, type)\n super\n attr_names.each { |attr_name| define_timeliness_write_method(attr_name) }\n end", "def create_setter_for(attribute, options)\n setter_method = \"#{attribute}=\"\n\n define_method setter_method do |value|\n if options[:allow_blank] || value != \"\"\n write_attribute(attribute, value)\n end\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each {|attr_name| attr_internal_define(attr_name, :writer)}\n end", "def escape_attr input\n escape input, attr_regexp, attr_mapping\n end", "def make_writer( attrtype )\n\t\tself.log.debug \"Generating an attribute writer for %p\" % [ attrtype ]\n\t\tattrname = attrtype.name\n\t\tif attrtype.single?\n\t\t\tself.log.debug \" attribute is SINGLE, so generating a scalar writer...\"\n\t\t\treturn lambda {|newvalue| self[attrname] = newvalue }\n\t\telse\n\t\t\tself.log.debug \" attribute isn't SINGLE, so generating an array writer...\"\n\t\t\treturn lambda {|*newvalues| self[attrname] = newvalues.flatten }\n\t\tend\n\tend", "def write_attribute(name, value)\n # Simply check if the accessor is allowed to write the field\n # (if so, go to superclass and do it)\n @bypass_auth ||= false\n if allowed_to_write(name) || @bypass_auth\n super(name, value)\n end\n end", "def mattr_writer(*syms, &proc)\n receiver = self\n options = syms.extract_options!\n syms.each do |sym|\n raise NameError.new('invalid attribute name') unless sym =~ /^[_A-Za-z]\\w*$/\n class_exec do\n define_singleton_method \"#{sym}=\" do |obj|\n class_variable_set(\"@@#{sym}\", obj)\n end\n end\n\n unless options[:instance_writer] == false || options[:instance_accessor] == false\n class_exec do\n define_method \"#{sym}=\" do |obj|\n receiver.class_variable_set(\"@@#{sym}\", obj)\n end\n end\n end\n send(\"#{sym}=\", proc.call) if proc\n end\n end", "def write_attribute(attribute, value)\n false\n end", "def add_attribute attribute\n return attribute unless @document_self\n\n # mainly to check for redefinition of an attribute as a method\n # TODO find a policy for 'attr_reader :foo' + 'def foo=()'\n register = false\n\n key = nil\n\n if attribute.rw.index 'R' then\n key = attribute.pretty_name\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name + '='] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if attribute.rw.index 'W' then\n key = attribute.pretty_name + '='\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if register then\n attribute.visibility = @visibility\n add_to @attributes, attribute\n resolve_aliases attribute\n end\n\n attribute\n end", "def define_writer_method(mod)\n writer_method_name = \"#{name}=\"\n attribute = self\n\n mod.send(:define_method, writer_method_name) { |value| attribute.set(self, value) }\n mod.send(writer_visibility, writer_method_name)\n\n self\n end", "def allowed_to_write(name)\n # no point allowing attribute writes if we can't save them?\n if allowed_to_save\n name = name.to_s\n validation_methods = self.class.write_validations(name) \n if validation_methods.nil?\n # We haven't registered any filters on this attribute, so allow the write.\n true\n elsif validation_methods.check :accessor => accessor, :model => self\n # One of the authentication methods worked, so allow the write.\n true\n else\n # We had filters but none of them passed. Disallow write.\n false\n end\n else\n false\n end\n end", "def assert_attr_writer(obj, method)\n assert_respond_to obj, \"#{method}=\"\nend", "def add_attribute(name, &block); end", "def authenticates_writes_to(attr, options={})\n authenticates_access\n @write_validation_map ||= {}\n @write_validation_map[attr.to_s] ||= AuthMethodList.new\n @write_validation_map[attr.to_s].add_method(options)\n end", "def write_attribute_3(param1, param2)\n\twrite_attribute(param1, param2)\n end", "def write_attribute(attr_name, value) #:doc:\n @attributes[attr_name] = empty_string_for_number_column?(attr_name, value) ? nil : value\n end", "def add_writer_tags(klass, new_method, member)\n member_tag = member_tag_for_member(klass, member, :write)\n return_type = return_type_from_tag(member_tag)\n setter_doc_text = member_tag ? member_tag.text : \"Sets the attribute #{member}\"\n new_method.docstring.replace(setter_doc_text)\n new_method.add_tag YARD::Tags::Tag.new(:param, \"the value to set the attribute #{member} to.\", return_type, \"value\")\n new_method.add_tag YARD::Tags::Tag.new(:return, \"the newly set value\", return_type)\n end", "def print_attribute(*) end", "def attribute(name); end", "def add_checked_attribute(clazz, attribute)\r\n eval <<END\r\n class #{clazz}\r\n\r\n def #{attribute}=(value)\r\n raise 'Invalid attribute' unless value\r\n @#{attribute}=value\r\n end\r\n\r\n def #{attribute}\r\n #{attribute}\r\n end\r\n end\r\nEND\r\nend", "def attr(name); end", "def is_attribute?(line)\n (line =~ /(\\s+)attr_(writer|reader|accessor)\\s+:[a-zA-Z_0-9]+/) == 0\n end", "def attribute(name, value)\n\t if !@inStartTag\n\t\traise WriterError.new('attribute outside of tag start')\n\t end\n\t @io << \" #{name}=\\\"#{NQXML.encode(value.to_s)}\\\"\"\n\tend", "def set_attribute(name, value); end", "def dataset_writer(*attributes)\n attributes.flatten.each do |attr_name|\n next if method_defined?(\"#{attr_name}=\")\n\n class_eval <<-RUBY, __FILE__, __LINE__ + 1\n def #{attr_name}=(value)\n dataset_set(:#{attr_name}, value)\n end\n RUBY\n end\n end", "def validated_attribute_names(params); end", "def require_format_of(attribute)\r\n RequireFormatOf.new(attribute)\r\n end", "def attr_writer(*fields)\n check_fields(fields)\n added_fields = jiak.data.writable(*fields)\n added_fields.each do |field|\n class_eval <<-EOM\n def #{field}=(val)\n @jiak.object.data.#{field} = val\n self.class.do_auto_update(self)\n end\n EOM\n end\n nil\n end", "def html_attr(*attrs)\n options = attrs.extract_options!.reverse_merge({\n :level => :super_relaxed\n })\n attrs.each do |att|\n class_eval \"def #{att}=(val); self[:#{att}] = sanitize(val, :#{options[:level]}); end\"\n end\n end", "def validate_attributes=(new_attribute)\n @validate_attributes = new_attribute\n end", "def html_attributes(attr); end", "def instance_write(attr, value)\n setter = :\"#{@name_string}_#{attr}=\"\n instance.send(setter, value) if instance.respond_to?(setter)\n end", "def valid_xml_attribute(name, options={:level => :warning})\n\t\t\t\tvalidate(\"Invalid XML attribute '#{name}'\", options) { name.to_s.match(/^([^[:punct:]0-9<>]|_)[^<>\"']*/) }\n\t\t\tend", "def attr_writer(*args)\n sym_args=args_to_sym(args)\n sym_args.each do |value|\n self.instance_eval(\"def #{value}=(arg); @#{value}=arg;end;\")\n end\n \n end", "def define_writer_method(attribute, method_name, visibility)\n define_method(method_name) { |value| attribute.set(self, value) }\n send(visibility, method_name)\n self\n end", "def write_attribute(name, val)\n if @embedded_models.include? name\n @embedded_models[name].model = val\n elsif @attribute_objects.include? name\n @attribute_objects[name].value = val\n else\n return false\n end\n\n run_callbacks :attribute_change\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def attr; end", "def attribute(*args)\n define_expressions(Attribute, args)\n end", "def write_attribute(name, value)\n name = name.to_s\n\n # The attribute already has an unsaved change.\n if attribute_changed?(name)\n old = changed_attributes[name]\n changed_attributes.delete(name) unless field_changed?(name, old, value)\n else\n attribute_will_change(name) if field_changed?(name, old, value)\n end\n\n # Carry on.\n super(name, value)\n end", "def define_magic_attr(name)\n define_method name do |*attrs|\n raise ArgumentError.new(\"wrong number of arguments\") if attrs.size > 1\n send(\"#{name}=\", attrs.first) if attrs.size == 1\n instance_variable_get(\"@#{name}\")\n end\n\n attr_writer name\n end", "def configurable_writer(attribute, code=nil, &block)\n if block_given? and not code\n Halcyon.class.send(:define_method, :\"#{attribute}=\", block)\n elsif code and not block_given?\n Halcyon.class.send(:eval, <<-\"end;\")\n def #{attribute.to_s}=(value)\n #{code % [attribute.to_sym.inspect]}\n end\n end;\n else\n raise ArgumentError.new(\"Either a block or a code string should be supplied.\")\n end\n end", "def method_missing(name, *args, &block)\n if /\\Ahas_validated_(?<type>\\w*)_attribute\\Z/ =~ name\n has_validated_attribute(type, *args, &block)\n else\n super\n end\n end", "def add_checked_attribute(klass, attribute)\n klass.class_eval do\n define_method attribute do\n instance_variable_get(\"@#{attribute}\")\n end\n\n define_method \"#{attribute}=\" do |value|\n raise 'Invalid attribute' unless value\n \n instance_variable_set(\"@#{attribute}\", value)\n end\n end\nend", "def method_missing(meth, *args, &blk)\n match = meth.to_s.match(/^([a-zA-Z\\_]+)(=|$)$/)\n if match\n attribute, setter = match[1], !match[2].blank?\n if setter\n write_attribute(attribute, args.first)\n else\n read_attribute(attribute)\n end\n else\n super(meth, *args, &blk)\n end\n end", "def valid_attributes\n { name: 'do this' }\n end", "def make_attributes_definitions_or_croak(attrArgs, &attrBlok)\n eye = :'m_attrs_defs'\n\n # Work with attribute as strings\n \n $DEBUG && logger_me(eye, logger_fmt_kls(:attrArgs => attrArgs, :attrBlok => attrBlok))\n\n mustbe_attributes_specification_or_croak(attrArgs, eye, \"attrArgs not attributes_specification\")\n \n #STOPATTRARGSINSUPER\n \n #attrAll = mustbe_not_empty_or_croak(mustbe_array_key_or_nil_or_croak(attrArgs, :all, eye, \"all attributes not array\"), eye, \"all attributes is empty\").map(&:to_s)\n attrAll = mustbe_not_empty_or_croak(mustbe_attributes_specification_all_key_or_croak(attrArgs, :all, eye), eye, \"all attributes is empty\").map(&:to_s)\n \n\n #puts(\"\\n\\n\\nATTR ALL >#{attrAll}<\")\n\n #STOPMAKEATTRSPECSENTRY\n\n attrInc = mustbe_attributes_specification_include_key_or_nil_or_croak(attrArgs, :include, eye) # mustbe all strings\n #puts(\"ATTR INC >#{attrInc.class}< >#{attrInc}< >#{is_value_not_empty?(attrInc)}<\")\n attrInc && mustbe_not_empty_or_croak(attrInc, eye, \"include attributes is empty\")\n\n attrExc = mustbe_attributes_specification_exclude_key_or_nil_or_croak(attrArgs, :exclude, eye) || []\n \n attrMapNom = mustbe_attributes_definitions_key_or_nil_or_croak(attrArgs, :definitions, eye) || {}\n attrMap = attrMapNom && potrubi_util_map_hash_kv(attrMapNom) {|k,v| [k.to_s, v]} # keys all strings\n\n # Ensure all consistent\n \n attrInc && mustbe_subset_or_croak(attrInc, attrAll, eye, \"include attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrExc, attrAll, eye, \"exclude attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrMap.keys, attrAll, eye, \"attribute map contains unknown attributes\")\n \n attrUse = ((attrInc || attrAll) - attrExc).uniq # list of unique attributes to report on\n\n # consolidate \"faked up\" attr specs with ones provided to get the composite attrSpecs\n \n attrDefsNom = potrubi_util_array_to_hash(attrUse).merge(attrMap.select {|k,v| attrUse.include?(k)}) # consolidated \"faked up\" attr specs with ones provided\n\n attrDefs = potrubi_util_map_hash_v(attrDefsNom) do | attrName, attrSpecNom|\n\n attrSpec =\n case attrSpecNom\n when NilClass then {}\n when Hash then\n attrSpecNom.each_with_object({}) do | (verbName, verbSpec), h1 |\n case verbName\n when :pass_thru then h1[:pass_thru] = verbSpec # dont touch; just pass through\n when :event_defaults then # add these to pass_thru\n h1[:pass_thru] = (h1[:pass_thru] || {}).merge(verbName => verbSpec)\n when :map, :select, :metric then\n h1[verbName] = {\n :method_name => \"#{verbName}_#{attrName}_#{rand(1000000)}\", # make a unqiue name\n :method_spec => verbSpec # spec must be valid to dynamic_define_methods\n }\n else\n logic_exception(verbName, eye, \"attrName >#{attrName}< verbName >#{verbName}< value should be impossible\")\n end\n end\n \n else\n logic_exception(attrrSpecNom, eye, \"attrSpecNom value should be impossible\")\n end\n\n attrSpec\n \n end\n \n $DEBUG && logger_mx(eye, logger_fmt_kls(:attrDefs => attrDefs))\n\n mustbe_attributes_definitions_or_croak(attrDefs, eye, \"attrDefs failed contract\")\n\n #STOPMAKEATTRSPECS\n \n end", "def create_writer(klass, member)\n # We want to convert these members into attributes just like\n # as if they were declared using attr_accessor.\n new_meth = register MethodObject.new(klass, \"#{member}=\", :instance) do |o|\n o.parameters = [['value', nil]]\n o.signature ||= \"def #{member}=(value)\"\n o.source ||= \"#{o.signature}\\n @#{member} = value\\nend\"\n end\n add_writer_tags(klass, new_meth, member)\n klass.attributes[:instance][member][:write] = new_meth\n end", "def create_setter!\n @target.class_eval <<-EOS\n #{writer_visibility.to_s}\n def #{name}=(value)\n attribute_set(#{name.inspect}, value)\n end\n EOS\n rescue SyntaxError\n raise SyntaxError.new(column)\n end", "def attribute name, type, conditions= DEFAULT_ATTRIBUTE_CONDITIONS\n RMOF.complete_conditions conditions, DEFAULT_ATTRIBUTE_CONDITIONS\n @attributes= {} unless instance_variable_defined? :@attributes\n @attributes[name]= [name, type, conditions]\n unless method_defined? :__attributes then \n define_method( :__attributes) do \n @attributes\n end \n end\n at= \"@#{name}\".to_sym\n getter= \"#{name}\".to_sym\n setter= \"#{name}=\".to_sym\n completion= \"__complete_#{name}\".to_sym\n define_method( getter) do\n if instance_variable_defined? at then instance_variable_get at\n else conditions[:default]\n end\n end\n define_method( setter) do |val|\n instance_variable_set at, val\n end\n define_method( completion) do\n RMOF.validate( self.send(getter), name, type, conditions)\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def create_setter(name, meth)\n define_method(\"#{meth}=\") do |value|\n write_attribute(name, value)\n end\n end", "def sanitized_allowed_attributes=(attributes); end", "def sanitized_allowed_attributes=(attributes); end", "def oattr(name, type)\n case type\n when :custom\n # Do nothing, just register attr below.\n when :writer\n attr_writer name\n else\n raise ArgumentError, \"Unknown type: #{type.inspect}\"\n end\n\n # Register and return.\n name.tap { oattrs << name}\n end", "def valid_attributes\n { name: \"Expert\" }\n end", "def attributes(*method_names, **options)\n add_attributes(method_names, **options, strategy: :write_value_using_method_strategy)\n end", "def []=(attr_name, value)\n writer_method = \"#{attr_name}=\"\n send(writer_method, value) if respond_to?(writer_method)\n end", "def write_extended_attributes(attrs)\n attrs.each do |k, val|\n self.send((k.to_s + \"=\").to_sym, val) if is_flex_attribute?(k)\n end\n self\n end", "def valid_attributes\n { \"username\" => \"MyString\" }\n end", "def cattr_writer(*fields)\n metaclass.send :attr_writer, *fields\n end", "def write_attribute(attr, value)\n if attribute_encrypted?(attr)\n conductor_for(attr).encrypt(value)\n else\n super(attr, value)\n end\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_number_value(\"offsetInDays\", @offset_in_days)\n writer.write_enum_value(\"timeBasedAttribute\", @time_based_attribute)\n end", "def define_attribute_method(attr_name, _owner: generated_attribute_methods)\n CodeGenerator.batch(_owner, __FILE__, __LINE__) do |owner|\n attribute_method_matchers.each do |matcher|\n method_name = matcher.method_name(attr_name)\n\n unless instance_method_already_implemented?(method_name)\n generate_method = \"define_method_#{matcher.target}\"\n\n if respond_to?(generate_method, true)\n send(generate_method, attr_name.to_s, owner: owner)\n else\n define_proxy_call true, owner, method_name, matcher.target, attr_name.to_s\n end\n end\n end\n attribute_method_matchers_cache.clear\n end\n end", "def has_attributes?; end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_boolean_value(\"isExpirationRequired\", @is_expiration_required)\n writer.write_duration_value(\"maximumDuration\", @maximum_duration)\n end", "def add_attributes(item)\n [:class, :instance].each do |attr_loc|\n # Grab attributes for the current location (class or instance)\n attrs = item.attributes[attr_loc]\n attrs.each do |name, attribute|\n reader = attribute[:read]\n writer = attribute[:write]\n\n unless reader || writer\n Logging.warn(\"attribute is not readable or writable somehow, skipping\", attribute)\n next\n end\n\n # Get all given types\n yard_types = []\n if reader\n next if @hide_private && reader.visibility == :private\n yard_types += reader.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n reader.tags('param').flat_map(&:types)\n end\n if writer\n next if @hide_private && writer.visibility == :private\n yard_types += writer.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n writer.tags('param').flat_map(&:types)\n end\n\n # Use untyped if not types specified anywhere, otherwise try to\n # compute Parlour type given all these types\n if yard_types.empty?\n Logging.omit(\"no YARD type given for #{name.inspect}, using untyped\", reader || writer)\n parlour_type = Parlour::Types::Untyped.new\n elsif yard_types.all? { |x| x == 'nil' }\n # Nil attributes are extremely unusual, so just use untyped\n parlour_type = Parlour::Types::Untyped.new\n else\n parlour_type = TypeConverter.yard_to_parlour(\n yard_types, reader || writer, @type_converter_config)\n end\n\n # Generate attribute\n if reader && writer\n kind = :accessor\n elsif reader\n kind = :reader\n elsif writer\n kind = :writer\n end\n\n if @exclude_untyped && parlour_type.is_a?(Parlour::Types::Untyped)\n Logging.omit(\"excluding untyped attribute\", reader || writer, immediate: true)\n next\n end\n\n case @mode\n when :rbi\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n class_attribute: (attr_loc == :class)\n ) do |m|\n add_comments(reader || writer, m)\n end\n when :rbs\n if attr_loc == :class\n # RBS doesn't support class attr_accessors so create individual methods\n\n if reader\n @current_object.create_method(\n name.to_s,\n [Parlour::RbsGenerator::MethodSignature.new([], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(reader, m)\n end\n end\n\n if writer\n @current_object.create_method(\n \"#{name}=\",\n [Parlour::RbsGenerator::MethodSignature.new([Parlour::RbsGenerator::Parameter.new(\n \"value\",\n type: parlour_type,\n required: true\n )], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(writer, m)\n end\n end\n else\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n ) do |m|\n add_comments(reader || writer, m)\n end\n end\n end\n end\n end\n end", "def []=(attr_name, value)\r\n if attr_name.is_a?(String) and attr_name != attr_name.split(ID_SEP).first\r\n attr_name = attr_name.split(ID_SEP)\r\n end\r\n\r\n if attr_name.is_a? Array\r\n value = value.split(ID_SEP) if value.is_a? String\r\n unless value.length == attr_name.length\r\n raise \"Number of attr_names and values do not match\"\r\n end\r\n #breakpoint\r\n [attr_name, value].transpose.map {|name,val| write_attribute(name.to_s, val)}\r\n else\r\n write_attribute(attr_name, value)\r\n end\r\n end", "def attr(symbol, writable=false) end", "def define_writer!(k, definition)\n define_method(\"#{k}=\") do |value|\n # Recursively convert hash and array of hash to schematized objects\n value = ensure_schema value, definition[:schema]\n\n # Initial value\n instance_variable_set \"@#{k}\", value\n\n # Dirty tracking\n self.changed_attributes ||= Set.new\n self.changed_attributes << k\n end\n end", "def validate\n validate_string_attributes\n end", "def write_attribute_with_dynamo(field_name, value)\n if is_dynamo_field?(field_name)\n # Store these guys for now. We don't actually save the field value until the model is saved ( i.e my_supplier.save ).\n # If we were to save the field_value now we wouldn't be able to know the id of the model to link this value to it.\n # @see delay_save\n @all_fields_and_values ||= []\n @all_fields_and_values << {:dynamo_field=>cached_dynamo_field_by_name(field_name), :value=>value}\n end\n # If its a 'normal' attribute let rails write it in the usual way.\n write_attribute_without_dynamo(field_name, value)\n end", "def define_attr_accessor(attr)\n attr_accessor(attr)\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n writer.write_collection_of_object_values(\"attributeMappings\", @attribute_mappings)\n writer.write_boolean_value(\"enabled\", @enabled)\n writer.write_enum_value(\"flowTypes\", @flow_types)\n writer.write_collection_of_object_values(\"metadata\", @metadata)\n writer.write_string_value(\"name\", @name)\n writer.write_string_value(\"@odata.type\", @odata_type)\n writer.write_object_value(\"scope\", @scope)\n writer.write_string_value(\"sourceObjectName\", @source_object_name)\n writer.write_string_value(\"targetObjectName\", @target_object_name)\n writer.write_additional_data(@additional_data)\n end", "def validate_attribute_syntax\n\t\t@values.each do |attribute, values|\n\t\t\t[ values ].flatten.each do |value|\n\t\t\t\tbegin\n\t\t\t\t\tself.get_converted_attribute( attribute.to_sym, value )\n\t\t\t\trescue => err\n\t\t\t\t\tself.log.error \"validation for %p failed: %s: %s\" %\n\t\t\t\t\t\t[ attribute, err.class.name, err.message ]\n\t\t\t\t\tattrtype = self.find_attribute_type( attribute )\n\t\t\t\t\tself.errors.add( attribute, \"isn't a valid %s value\" %\n\t\t\t\t\t\t[ attrtype.syntax ? attrtype.syntax.desc : attrtype.syntax_oid ] )\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def valid_attributes\n { }\n end", "def validatable_attributes(atts, opts)\n am, an, ab, m = opts.values_at(:allow_missing, :allow_nil, :allow_blank, :message)\n Array(atts).each do |a|\n next if am && !values.has_key?(a)\n v = send(a)\n next if an && v.nil?\n next if ab && v.respond_to?(:blank?) && v.blank?\n if message = yield(a, v, m)\n errors.add(a, message)\n end\n end\n end", "def valid_attributes\n { }\n end", "def valid_attributes\n { }\n end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def require_attr(name)\n send(name).tap do |_|\n raise \"Attribute must be set: #{name}\" if _.nil?\n end\n end", "def write_attributes(attributes)\n _attributes = attributes.select do |name, value|\n if self.is_dynamic_field?(name)\n self.dynamic_setter(name, value)\n false\n else\n true\n end\n end\n\n super(_attributes)\n end", "def attribute; end", "def attribute; end" ]
[ "0.6472992", "0.6315012", "0.6315012", "0.62821025", "0.6279224", "0.6211609", "0.61891466", "0.6182247", "0.60683644", "0.6032628", "0.5995443", "0.5988785", "0.5959885", "0.5938289", "0.5931089", "0.58951056", "0.5859927", "0.5851703", "0.58493423", "0.58465594", "0.58328366", "0.5823013", "0.5822229", "0.57850474", "0.5701491", "0.5696689", "0.5682951", "0.5678094", "0.566814", "0.5657499", "0.56555206", "0.5642589", "0.56219065", "0.5615893", "0.56105876", "0.559851", "0.5598089", "0.55940455", "0.5585137", "0.55848545", "0.55796933", "0.5571477", "0.5567006", "0.55667996", "0.55652434", "0.5562926", "0.55600035", "0.55590326", "0.55590326", "0.5554599", "0.5554599", "0.55407417", "0.5534935", "0.5527733", "0.55271375", "0.55238813", "0.5501504", "0.5497003", "0.5496233", "0.54927665", "0.5464706", "0.54617554", "0.5461167", "0.5451583", "0.54498726", "0.54498726", "0.54359984", "0.5430996", "0.5430996", "0.5426488", "0.5418467", "0.54153895", "0.54107565", "0.5407886", "0.5401234", "0.54008496", "0.5400268", "0.53910094", "0.53827274", "0.5377731", "0.5375473", "0.5374833", "0.53720397", "0.5370215", "0.5363264", "0.5361161", "0.5360557", "0.5351706", "0.53514725", "0.53492516", "0.53459316", "0.5341237", "0.5328037", "0.5328037", "0.53230566", "0.53230566", "0.53230566", "0.5319575", "0.531832", "0.5315559", "0.5315559" ]
0.0
-1
Custom attribute writer method with validation
def description=(description) if !description.nil? && description.to_s.length > 1024 fail ArgumentError, 'invalid value for "description", the character length must be smaller than or equal to 1024.' end @description = description end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def attr_writer_tag(text); end", "def allowed_attributes=(_arg0); end", "def allowed_attributes=(_arg0); end", "def writer(*args)\n attr_writer(*args)\n args\n end", "def define_write_method(attr_name)\n evaluate_attribute_method attr_name, \"def #{attr_name}=(new_value);write_attribute('#{attr_name}', new_value);end\", \"#{attr_name}=\"\n end", "def attr_writer(*vars)\n # avoid tracking attributes that are added by the class_attribute\n # as these are class attributes and not instance attributes.\n tracked_vars = vars.reject {|var| respond_to? var }\n add_tracked_attrs(false, true, *tracked_vars)\n vars.extract_options!\n super\n end", "def attr_writer(sym, *more) end", "def is_attribute?; end", "def validate_exclusion_of(attr); end", "def register_attributes\n raise \"Not implemented in #{self.class}\"\n end", "def method_missing(method_name, *args)\n return super unless permitted_attributes.include?(method_name)\n begin\n object.send(:\"#{method_name}=\", args.first)\n rescue => e\n if params.has_key?(method_name)\n message = \"Unable to process value for :#{method_name}, no attribute writer. Be sure to override the automatic setters for all params that do not map straight to a model attribute.\"\n Rails.logger.warn({message: message,\n missing_writer: method_name,\n value: args.first,\n error: e})\n self.errors << {status: 422, message: message}\n else\n raise e\n end\n end\n end", "def timeliness_validation_for(attr_names, type)\n super\n attr_names.each { |attr_name| define_timeliness_write_method(attr_name) }\n end", "def create_setter_for(attribute, options)\n setter_method = \"#{attribute}=\"\n\n define_method setter_method do |value|\n if options[:allow_blank] || value != \"\"\n write_attribute(attribute, value)\n end\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each {|attr_name| attr_internal_define(attr_name, :writer)}\n end", "def escape_attr input\n escape input, attr_regexp, attr_mapping\n end", "def make_writer( attrtype )\n\t\tself.log.debug \"Generating an attribute writer for %p\" % [ attrtype ]\n\t\tattrname = attrtype.name\n\t\tif attrtype.single?\n\t\t\tself.log.debug \" attribute is SINGLE, so generating a scalar writer...\"\n\t\t\treturn lambda {|newvalue| self[attrname] = newvalue }\n\t\telse\n\t\t\tself.log.debug \" attribute isn't SINGLE, so generating an array writer...\"\n\t\t\treturn lambda {|*newvalues| self[attrname] = newvalues.flatten }\n\t\tend\n\tend", "def write_attribute(name, value)\n # Simply check if the accessor is allowed to write the field\n # (if so, go to superclass and do it)\n @bypass_auth ||= false\n if allowed_to_write(name) || @bypass_auth\n super(name, value)\n end\n end", "def mattr_writer(*syms, &proc)\n receiver = self\n options = syms.extract_options!\n syms.each do |sym|\n raise NameError.new('invalid attribute name') unless sym =~ /^[_A-Za-z]\\w*$/\n class_exec do\n define_singleton_method \"#{sym}=\" do |obj|\n class_variable_set(\"@@#{sym}\", obj)\n end\n end\n\n unless options[:instance_writer] == false || options[:instance_accessor] == false\n class_exec do\n define_method \"#{sym}=\" do |obj|\n receiver.class_variable_set(\"@@#{sym}\", obj)\n end\n end\n end\n send(\"#{sym}=\", proc.call) if proc\n end\n end", "def write_attribute(attribute, value)\n false\n end", "def add_attribute attribute\n return attribute unless @document_self\n\n # mainly to check for redefinition of an attribute as a method\n # TODO find a policy for 'attr_reader :foo' + 'def foo=()'\n register = false\n\n key = nil\n\n if attribute.rw.index 'R' then\n key = attribute.pretty_name\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name + '='] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if attribute.rw.index 'W' then\n key = attribute.pretty_name + '='\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if register then\n attribute.visibility = @visibility\n add_to @attributes, attribute\n resolve_aliases attribute\n end\n\n attribute\n end", "def define_writer_method(mod)\n writer_method_name = \"#{name}=\"\n attribute = self\n\n mod.send(:define_method, writer_method_name) { |value| attribute.set(self, value) }\n mod.send(writer_visibility, writer_method_name)\n\n self\n end", "def allowed_to_write(name)\n # no point allowing attribute writes if we can't save them?\n if allowed_to_save\n name = name.to_s\n validation_methods = self.class.write_validations(name) \n if validation_methods.nil?\n # We haven't registered any filters on this attribute, so allow the write.\n true\n elsif validation_methods.check :accessor => accessor, :model => self\n # One of the authentication methods worked, so allow the write.\n true\n else\n # We had filters but none of them passed. Disallow write.\n false\n end\n else\n false\n end\n end", "def assert_attr_writer(obj, method)\n assert_respond_to obj, \"#{method}=\"\nend", "def add_attribute(name, &block); end", "def authenticates_writes_to(attr, options={})\n authenticates_access\n @write_validation_map ||= {}\n @write_validation_map[attr.to_s] ||= AuthMethodList.new\n @write_validation_map[attr.to_s].add_method(options)\n end", "def write_attribute_3(param1, param2)\n\twrite_attribute(param1, param2)\n end", "def write_attribute(attr_name, value) #:doc:\n @attributes[attr_name] = empty_string_for_number_column?(attr_name, value) ? nil : value\n end", "def add_writer_tags(klass, new_method, member)\n member_tag = member_tag_for_member(klass, member, :write)\n return_type = return_type_from_tag(member_tag)\n setter_doc_text = member_tag ? member_tag.text : \"Sets the attribute #{member}\"\n new_method.docstring.replace(setter_doc_text)\n new_method.add_tag YARD::Tags::Tag.new(:param, \"the value to set the attribute #{member} to.\", return_type, \"value\")\n new_method.add_tag YARD::Tags::Tag.new(:return, \"the newly set value\", return_type)\n end", "def print_attribute(*) end", "def attribute(name); end", "def add_checked_attribute(clazz, attribute)\r\n eval <<END\r\n class #{clazz}\r\n\r\n def #{attribute}=(value)\r\n raise 'Invalid attribute' unless value\r\n @#{attribute}=value\r\n end\r\n\r\n def #{attribute}\r\n #{attribute}\r\n end\r\n end\r\nEND\r\nend", "def attr(name); end", "def is_attribute?(line)\n (line =~ /(\\s+)attr_(writer|reader|accessor)\\s+:[a-zA-Z_0-9]+/) == 0\n end", "def attribute(name, value)\n\t if !@inStartTag\n\t\traise WriterError.new('attribute outside of tag start')\n\t end\n\t @io << \" #{name}=\\\"#{NQXML.encode(value.to_s)}\\\"\"\n\tend", "def set_attribute(name, value); end", "def dataset_writer(*attributes)\n attributes.flatten.each do |attr_name|\n next if method_defined?(\"#{attr_name}=\")\n\n class_eval <<-RUBY, __FILE__, __LINE__ + 1\n def #{attr_name}=(value)\n dataset_set(:#{attr_name}, value)\n end\n RUBY\n end\n end", "def validated_attribute_names(params); end", "def require_format_of(attribute)\r\n RequireFormatOf.new(attribute)\r\n end", "def attr_writer(*fields)\n check_fields(fields)\n added_fields = jiak.data.writable(*fields)\n added_fields.each do |field|\n class_eval <<-EOM\n def #{field}=(val)\n @jiak.object.data.#{field} = val\n self.class.do_auto_update(self)\n end\n EOM\n end\n nil\n end", "def html_attr(*attrs)\n options = attrs.extract_options!.reverse_merge({\n :level => :super_relaxed\n })\n attrs.each do |att|\n class_eval \"def #{att}=(val); self[:#{att}] = sanitize(val, :#{options[:level]}); end\"\n end\n end", "def validate_attributes=(new_attribute)\n @validate_attributes = new_attribute\n end", "def html_attributes(attr); end", "def instance_write(attr, value)\n setter = :\"#{@name_string}_#{attr}=\"\n instance.send(setter, value) if instance.respond_to?(setter)\n end", "def valid_xml_attribute(name, options={:level => :warning})\n\t\t\t\tvalidate(\"Invalid XML attribute '#{name}'\", options) { name.to_s.match(/^([^[:punct:]0-9<>]|_)[^<>\"']*/) }\n\t\t\tend", "def attr_writer(*args)\n sym_args=args_to_sym(args)\n sym_args.each do |value|\n self.instance_eval(\"def #{value}=(arg); @#{value}=arg;end;\")\n end\n \n end", "def define_writer_method(attribute, method_name, visibility)\n define_method(method_name) { |value| attribute.set(self, value) }\n send(visibility, method_name)\n self\n end", "def write_attribute(name, val)\n if @embedded_models.include? name\n @embedded_models[name].model = val\n elsif @attribute_objects.include? name\n @attribute_objects[name].value = val\n else\n return false\n end\n\n run_callbacks :attribute_change\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def attr; end", "def attribute(*args)\n define_expressions(Attribute, args)\n end", "def write_attribute(name, value)\n name = name.to_s\n\n # The attribute already has an unsaved change.\n if attribute_changed?(name)\n old = changed_attributes[name]\n changed_attributes.delete(name) unless field_changed?(name, old, value)\n else\n attribute_will_change(name) if field_changed?(name, old, value)\n end\n\n # Carry on.\n super(name, value)\n end", "def define_magic_attr(name)\n define_method name do |*attrs|\n raise ArgumentError.new(\"wrong number of arguments\") if attrs.size > 1\n send(\"#{name}=\", attrs.first) if attrs.size == 1\n instance_variable_get(\"@#{name}\")\n end\n\n attr_writer name\n end", "def configurable_writer(attribute, code=nil, &block)\n if block_given? and not code\n Halcyon.class.send(:define_method, :\"#{attribute}=\", block)\n elsif code and not block_given?\n Halcyon.class.send(:eval, <<-\"end;\")\n def #{attribute.to_s}=(value)\n #{code % [attribute.to_sym.inspect]}\n end\n end;\n else\n raise ArgumentError.new(\"Either a block or a code string should be supplied.\")\n end\n end", "def method_missing(name, *args, &block)\n if /\\Ahas_validated_(?<type>\\w*)_attribute\\Z/ =~ name\n has_validated_attribute(type, *args, &block)\n else\n super\n end\n end", "def add_checked_attribute(klass, attribute)\n klass.class_eval do\n define_method attribute do\n instance_variable_get(\"@#{attribute}\")\n end\n\n define_method \"#{attribute}=\" do |value|\n raise 'Invalid attribute' unless value\n \n instance_variable_set(\"@#{attribute}\", value)\n end\n end\nend", "def method_missing(meth, *args, &blk)\n match = meth.to_s.match(/^([a-zA-Z\\_]+)(=|$)$/)\n if match\n attribute, setter = match[1], !match[2].blank?\n if setter\n write_attribute(attribute, args.first)\n else\n read_attribute(attribute)\n end\n else\n super(meth, *args, &blk)\n end\n end", "def valid_attributes\n { name: 'do this' }\n end", "def make_attributes_definitions_or_croak(attrArgs, &attrBlok)\n eye = :'m_attrs_defs'\n\n # Work with attribute as strings\n \n $DEBUG && logger_me(eye, logger_fmt_kls(:attrArgs => attrArgs, :attrBlok => attrBlok))\n\n mustbe_attributes_specification_or_croak(attrArgs, eye, \"attrArgs not attributes_specification\")\n \n #STOPATTRARGSINSUPER\n \n #attrAll = mustbe_not_empty_or_croak(mustbe_array_key_or_nil_or_croak(attrArgs, :all, eye, \"all attributes not array\"), eye, \"all attributes is empty\").map(&:to_s)\n attrAll = mustbe_not_empty_or_croak(mustbe_attributes_specification_all_key_or_croak(attrArgs, :all, eye), eye, \"all attributes is empty\").map(&:to_s)\n \n\n #puts(\"\\n\\n\\nATTR ALL >#{attrAll}<\")\n\n #STOPMAKEATTRSPECSENTRY\n\n attrInc = mustbe_attributes_specification_include_key_or_nil_or_croak(attrArgs, :include, eye) # mustbe all strings\n #puts(\"ATTR INC >#{attrInc.class}< >#{attrInc}< >#{is_value_not_empty?(attrInc)}<\")\n attrInc && mustbe_not_empty_or_croak(attrInc, eye, \"include attributes is empty\")\n\n attrExc = mustbe_attributes_specification_exclude_key_or_nil_or_croak(attrArgs, :exclude, eye) || []\n \n attrMapNom = mustbe_attributes_definitions_key_or_nil_or_croak(attrArgs, :definitions, eye) || {}\n attrMap = attrMapNom && potrubi_util_map_hash_kv(attrMapNom) {|k,v| [k.to_s, v]} # keys all strings\n\n # Ensure all consistent\n \n attrInc && mustbe_subset_or_croak(attrInc, attrAll, eye, \"include attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrExc, attrAll, eye, \"exclude attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrMap.keys, attrAll, eye, \"attribute map contains unknown attributes\")\n \n attrUse = ((attrInc || attrAll) - attrExc).uniq # list of unique attributes to report on\n\n # consolidate \"faked up\" attr specs with ones provided to get the composite attrSpecs\n \n attrDefsNom = potrubi_util_array_to_hash(attrUse).merge(attrMap.select {|k,v| attrUse.include?(k)}) # consolidated \"faked up\" attr specs with ones provided\n\n attrDefs = potrubi_util_map_hash_v(attrDefsNom) do | attrName, attrSpecNom|\n\n attrSpec =\n case attrSpecNom\n when NilClass then {}\n when Hash then\n attrSpecNom.each_with_object({}) do | (verbName, verbSpec), h1 |\n case verbName\n when :pass_thru then h1[:pass_thru] = verbSpec # dont touch; just pass through\n when :event_defaults then # add these to pass_thru\n h1[:pass_thru] = (h1[:pass_thru] || {}).merge(verbName => verbSpec)\n when :map, :select, :metric then\n h1[verbName] = {\n :method_name => \"#{verbName}_#{attrName}_#{rand(1000000)}\", # make a unqiue name\n :method_spec => verbSpec # spec must be valid to dynamic_define_methods\n }\n else\n logic_exception(verbName, eye, \"attrName >#{attrName}< verbName >#{verbName}< value should be impossible\")\n end\n end\n \n else\n logic_exception(attrrSpecNom, eye, \"attrSpecNom value should be impossible\")\n end\n\n attrSpec\n \n end\n \n $DEBUG && logger_mx(eye, logger_fmt_kls(:attrDefs => attrDefs))\n\n mustbe_attributes_definitions_or_croak(attrDefs, eye, \"attrDefs failed contract\")\n\n #STOPMAKEATTRSPECS\n \n end", "def create_writer(klass, member)\n # We want to convert these members into attributes just like\n # as if they were declared using attr_accessor.\n new_meth = register MethodObject.new(klass, \"#{member}=\", :instance) do |o|\n o.parameters = [['value', nil]]\n o.signature ||= \"def #{member}=(value)\"\n o.source ||= \"#{o.signature}\\n @#{member} = value\\nend\"\n end\n add_writer_tags(klass, new_meth, member)\n klass.attributes[:instance][member][:write] = new_meth\n end", "def create_setter!\n @target.class_eval <<-EOS\n #{writer_visibility.to_s}\n def #{name}=(value)\n attribute_set(#{name.inspect}, value)\n end\n EOS\n rescue SyntaxError\n raise SyntaxError.new(column)\n end", "def attribute name, type, conditions= DEFAULT_ATTRIBUTE_CONDITIONS\n RMOF.complete_conditions conditions, DEFAULT_ATTRIBUTE_CONDITIONS\n @attributes= {} unless instance_variable_defined? :@attributes\n @attributes[name]= [name, type, conditions]\n unless method_defined? :__attributes then \n define_method( :__attributes) do \n @attributes\n end \n end\n at= \"@#{name}\".to_sym\n getter= \"#{name}\".to_sym\n setter= \"#{name}=\".to_sym\n completion= \"__complete_#{name}\".to_sym\n define_method( getter) do\n if instance_variable_defined? at then instance_variable_get at\n else conditions[:default]\n end\n end\n define_method( setter) do |val|\n instance_variable_set at, val\n end\n define_method( completion) do\n RMOF.validate( self.send(getter), name, type, conditions)\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def create_setter(name, meth)\n define_method(\"#{meth}=\") do |value|\n write_attribute(name, value)\n end\n end", "def sanitized_allowed_attributes=(attributes); end", "def sanitized_allowed_attributes=(attributes); end", "def oattr(name, type)\n case type\n when :custom\n # Do nothing, just register attr below.\n when :writer\n attr_writer name\n else\n raise ArgumentError, \"Unknown type: #{type.inspect}\"\n end\n\n # Register and return.\n name.tap { oattrs << name}\n end", "def valid_attributes\n { name: \"Expert\" }\n end", "def attributes(*method_names, **options)\n add_attributes(method_names, **options, strategy: :write_value_using_method_strategy)\n end", "def []=(attr_name, value)\n writer_method = \"#{attr_name}=\"\n send(writer_method, value) if respond_to?(writer_method)\n end", "def write_extended_attributes(attrs)\n attrs.each do |k, val|\n self.send((k.to_s + \"=\").to_sym, val) if is_flex_attribute?(k)\n end\n self\n end", "def valid_attributes\n { \"username\" => \"MyString\" }\n end", "def cattr_writer(*fields)\n metaclass.send :attr_writer, *fields\n end", "def write_attribute(attr, value)\n if attribute_encrypted?(attr)\n conductor_for(attr).encrypt(value)\n else\n super(attr, value)\n end\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_number_value(\"offsetInDays\", @offset_in_days)\n writer.write_enum_value(\"timeBasedAttribute\", @time_based_attribute)\n end", "def define_attribute_method(attr_name, _owner: generated_attribute_methods)\n CodeGenerator.batch(_owner, __FILE__, __LINE__) do |owner|\n attribute_method_matchers.each do |matcher|\n method_name = matcher.method_name(attr_name)\n\n unless instance_method_already_implemented?(method_name)\n generate_method = \"define_method_#{matcher.target}\"\n\n if respond_to?(generate_method, true)\n send(generate_method, attr_name.to_s, owner: owner)\n else\n define_proxy_call true, owner, method_name, matcher.target, attr_name.to_s\n end\n end\n end\n attribute_method_matchers_cache.clear\n end\n end", "def has_attributes?; end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_boolean_value(\"isExpirationRequired\", @is_expiration_required)\n writer.write_duration_value(\"maximumDuration\", @maximum_duration)\n end", "def add_attributes(item)\n [:class, :instance].each do |attr_loc|\n # Grab attributes for the current location (class or instance)\n attrs = item.attributes[attr_loc]\n attrs.each do |name, attribute|\n reader = attribute[:read]\n writer = attribute[:write]\n\n unless reader || writer\n Logging.warn(\"attribute is not readable or writable somehow, skipping\", attribute)\n next\n end\n\n # Get all given types\n yard_types = []\n if reader\n next if @hide_private && reader.visibility == :private\n yard_types += reader.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n reader.tags('param').flat_map(&:types)\n end\n if writer\n next if @hide_private && writer.visibility == :private\n yard_types += writer.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n writer.tags('param').flat_map(&:types)\n end\n\n # Use untyped if not types specified anywhere, otherwise try to\n # compute Parlour type given all these types\n if yard_types.empty?\n Logging.omit(\"no YARD type given for #{name.inspect}, using untyped\", reader || writer)\n parlour_type = Parlour::Types::Untyped.new\n elsif yard_types.all? { |x| x == 'nil' }\n # Nil attributes are extremely unusual, so just use untyped\n parlour_type = Parlour::Types::Untyped.new\n else\n parlour_type = TypeConverter.yard_to_parlour(\n yard_types, reader || writer, @type_converter_config)\n end\n\n # Generate attribute\n if reader && writer\n kind = :accessor\n elsif reader\n kind = :reader\n elsif writer\n kind = :writer\n end\n\n if @exclude_untyped && parlour_type.is_a?(Parlour::Types::Untyped)\n Logging.omit(\"excluding untyped attribute\", reader || writer, immediate: true)\n next\n end\n\n case @mode\n when :rbi\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n class_attribute: (attr_loc == :class)\n ) do |m|\n add_comments(reader || writer, m)\n end\n when :rbs\n if attr_loc == :class\n # RBS doesn't support class attr_accessors so create individual methods\n\n if reader\n @current_object.create_method(\n name.to_s,\n [Parlour::RbsGenerator::MethodSignature.new([], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(reader, m)\n end\n end\n\n if writer\n @current_object.create_method(\n \"#{name}=\",\n [Parlour::RbsGenerator::MethodSignature.new([Parlour::RbsGenerator::Parameter.new(\n \"value\",\n type: parlour_type,\n required: true\n )], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(writer, m)\n end\n end\n else\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n ) do |m|\n add_comments(reader || writer, m)\n end\n end\n end\n end\n end\n end", "def []=(attr_name, value)\r\n if attr_name.is_a?(String) and attr_name != attr_name.split(ID_SEP).first\r\n attr_name = attr_name.split(ID_SEP)\r\n end\r\n\r\n if attr_name.is_a? Array\r\n value = value.split(ID_SEP) if value.is_a? String\r\n unless value.length == attr_name.length\r\n raise \"Number of attr_names and values do not match\"\r\n end\r\n #breakpoint\r\n [attr_name, value].transpose.map {|name,val| write_attribute(name.to_s, val)}\r\n else\r\n write_attribute(attr_name, value)\r\n end\r\n end", "def attr(symbol, writable=false) end", "def define_writer!(k, definition)\n define_method(\"#{k}=\") do |value|\n # Recursively convert hash and array of hash to schematized objects\n value = ensure_schema value, definition[:schema]\n\n # Initial value\n instance_variable_set \"@#{k}\", value\n\n # Dirty tracking\n self.changed_attributes ||= Set.new\n self.changed_attributes << k\n end\n end", "def validate\n validate_string_attributes\n end", "def write_attribute_with_dynamo(field_name, value)\n if is_dynamo_field?(field_name)\n # Store these guys for now. We don't actually save the field value until the model is saved ( i.e my_supplier.save ).\n # If we were to save the field_value now we wouldn't be able to know the id of the model to link this value to it.\n # @see delay_save\n @all_fields_and_values ||= []\n @all_fields_and_values << {:dynamo_field=>cached_dynamo_field_by_name(field_name), :value=>value}\n end\n # If its a 'normal' attribute let rails write it in the usual way.\n write_attribute_without_dynamo(field_name, value)\n end", "def define_attr_accessor(attr)\n attr_accessor(attr)\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n writer.write_collection_of_object_values(\"attributeMappings\", @attribute_mappings)\n writer.write_boolean_value(\"enabled\", @enabled)\n writer.write_enum_value(\"flowTypes\", @flow_types)\n writer.write_collection_of_object_values(\"metadata\", @metadata)\n writer.write_string_value(\"name\", @name)\n writer.write_string_value(\"@odata.type\", @odata_type)\n writer.write_object_value(\"scope\", @scope)\n writer.write_string_value(\"sourceObjectName\", @source_object_name)\n writer.write_string_value(\"targetObjectName\", @target_object_name)\n writer.write_additional_data(@additional_data)\n end", "def validate_attribute_syntax\n\t\t@values.each do |attribute, values|\n\t\t\t[ values ].flatten.each do |value|\n\t\t\t\tbegin\n\t\t\t\t\tself.get_converted_attribute( attribute.to_sym, value )\n\t\t\t\trescue => err\n\t\t\t\t\tself.log.error \"validation for %p failed: %s: %s\" %\n\t\t\t\t\t\t[ attribute, err.class.name, err.message ]\n\t\t\t\t\tattrtype = self.find_attribute_type( attribute )\n\t\t\t\t\tself.errors.add( attribute, \"isn't a valid %s value\" %\n\t\t\t\t\t\t[ attrtype.syntax ? attrtype.syntax.desc : attrtype.syntax_oid ] )\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def valid_attributes\n { }\n end", "def validatable_attributes(atts, opts)\n am, an, ab, m = opts.values_at(:allow_missing, :allow_nil, :allow_blank, :message)\n Array(atts).each do |a|\n next if am && !values.has_key?(a)\n v = send(a)\n next if an && v.nil?\n next if ab && v.respond_to?(:blank?) && v.blank?\n if message = yield(a, v, m)\n errors.add(a, message)\n end\n end\n end", "def valid_attributes\n { }\n end", "def valid_attributes\n { }\n end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def require_attr(name)\n send(name).tap do |_|\n raise \"Attribute must be set: #{name}\" if _.nil?\n end\n end", "def write_attributes(attributes)\n _attributes = attributes.select do |name, value|\n if self.is_dynamic_field?(name)\n self.dynamic_setter(name, value)\n false\n else\n true\n end\n end\n\n super(_attributes)\n end", "def attribute; end", "def attribute; end" ]
[ "0.6472992", "0.6315012", "0.6315012", "0.62821025", "0.6279224", "0.6211609", "0.61891466", "0.6182247", "0.60683644", "0.6032628", "0.5995443", "0.5988785", "0.5959885", "0.5938289", "0.5931089", "0.58951056", "0.5859927", "0.5851703", "0.58493423", "0.58465594", "0.58328366", "0.5823013", "0.5822229", "0.57850474", "0.5701491", "0.5696689", "0.5682951", "0.5678094", "0.566814", "0.5657499", "0.56555206", "0.5642589", "0.56219065", "0.5615893", "0.56105876", "0.559851", "0.5598089", "0.55940455", "0.5585137", "0.55848545", "0.55796933", "0.5571477", "0.5567006", "0.55667996", "0.55652434", "0.5562926", "0.55600035", "0.55590326", "0.55590326", "0.5554599", "0.5554599", "0.55407417", "0.5534935", "0.5527733", "0.55271375", "0.55238813", "0.5501504", "0.5497003", "0.5496233", "0.54927665", "0.5464706", "0.54617554", "0.5461167", "0.5451583", "0.54498726", "0.54498726", "0.54359984", "0.5430996", "0.5430996", "0.5426488", "0.5418467", "0.54153895", "0.54107565", "0.5407886", "0.5401234", "0.54008496", "0.5400268", "0.53910094", "0.53827274", "0.5377731", "0.5375473", "0.5374833", "0.53720397", "0.5370215", "0.5363264", "0.5361161", "0.5360557", "0.5351706", "0.53514725", "0.53492516", "0.53459316", "0.5341237", "0.5328037", "0.5328037", "0.53230566", "0.53230566", "0.53230566", "0.5319575", "0.531832", "0.5315559", "0.5315559" ]
0.0
-1
Custom attribute writer method with validation
def tcp_closed=(tcp_closed) if tcp_closed.nil? fail ArgumentError, 'tcp_closed cannot be nil' end if tcp_closed > 4320000 fail ArgumentError, 'invalid value for "tcp_closed", must be smaller than or equal to 4320000.' end if tcp_closed < 10 fail ArgumentError, 'invalid value for "tcp_closed", must be greater than or equal to 10.' end @tcp_closed = tcp_closed end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def attr_writer_tag(text); end", "def allowed_attributes=(_arg0); end", "def allowed_attributes=(_arg0); end", "def writer(*args)\n attr_writer(*args)\n args\n end", "def define_write_method(attr_name)\n evaluate_attribute_method attr_name, \"def #{attr_name}=(new_value);write_attribute('#{attr_name}', new_value);end\", \"#{attr_name}=\"\n end", "def attr_writer(*vars)\n # avoid tracking attributes that are added by the class_attribute\n # as these are class attributes and not instance attributes.\n tracked_vars = vars.reject {|var| respond_to? var }\n add_tracked_attrs(false, true, *tracked_vars)\n vars.extract_options!\n super\n end", "def attr_writer(sym, *more) end", "def is_attribute?; end", "def validate_exclusion_of(attr); end", "def register_attributes\n raise \"Not implemented in #{self.class}\"\n end", "def method_missing(method_name, *args)\n return super unless permitted_attributes.include?(method_name)\n begin\n object.send(:\"#{method_name}=\", args.first)\n rescue => e\n if params.has_key?(method_name)\n message = \"Unable to process value for :#{method_name}, no attribute writer. Be sure to override the automatic setters for all params that do not map straight to a model attribute.\"\n Rails.logger.warn({message: message,\n missing_writer: method_name,\n value: args.first,\n error: e})\n self.errors << {status: 422, message: message}\n else\n raise e\n end\n end\n end", "def timeliness_validation_for(attr_names, type)\n super\n attr_names.each { |attr_name| define_timeliness_write_method(attr_name) }\n end", "def create_setter_for(attribute, options)\n setter_method = \"#{attribute}=\"\n\n define_method setter_method do |value|\n if options[:allow_blank] || value != \"\"\n write_attribute(attribute, value)\n end\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each {|attr_name| attr_internal_define(attr_name, :writer)}\n end", "def escape_attr input\n escape input, attr_regexp, attr_mapping\n end", "def make_writer( attrtype )\n\t\tself.log.debug \"Generating an attribute writer for %p\" % [ attrtype ]\n\t\tattrname = attrtype.name\n\t\tif attrtype.single?\n\t\t\tself.log.debug \" attribute is SINGLE, so generating a scalar writer...\"\n\t\t\treturn lambda {|newvalue| self[attrname] = newvalue }\n\t\telse\n\t\t\tself.log.debug \" attribute isn't SINGLE, so generating an array writer...\"\n\t\t\treturn lambda {|*newvalues| self[attrname] = newvalues.flatten }\n\t\tend\n\tend", "def write_attribute(name, value)\n # Simply check if the accessor is allowed to write the field\n # (if so, go to superclass and do it)\n @bypass_auth ||= false\n if allowed_to_write(name) || @bypass_auth\n super(name, value)\n end\n end", "def mattr_writer(*syms, &proc)\n receiver = self\n options = syms.extract_options!\n syms.each do |sym|\n raise NameError.new('invalid attribute name') unless sym =~ /^[_A-Za-z]\\w*$/\n class_exec do\n define_singleton_method \"#{sym}=\" do |obj|\n class_variable_set(\"@@#{sym}\", obj)\n end\n end\n\n unless options[:instance_writer] == false || options[:instance_accessor] == false\n class_exec do\n define_method \"#{sym}=\" do |obj|\n receiver.class_variable_set(\"@@#{sym}\", obj)\n end\n end\n end\n send(\"#{sym}=\", proc.call) if proc\n end\n end", "def write_attribute(attribute, value)\n false\n end", "def add_attribute attribute\n return attribute unless @document_self\n\n # mainly to check for redefinition of an attribute as a method\n # TODO find a policy for 'attr_reader :foo' + 'def foo=()'\n register = false\n\n key = nil\n\n if attribute.rw.index 'R' then\n key = attribute.pretty_name\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name + '='] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if attribute.rw.index 'W' then\n key = attribute.pretty_name + '='\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if register then\n attribute.visibility = @visibility\n add_to @attributes, attribute\n resolve_aliases attribute\n end\n\n attribute\n end", "def define_writer_method(mod)\n writer_method_name = \"#{name}=\"\n attribute = self\n\n mod.send(:define_method, writer_method_name) { |value| attribute.set(self, value) }\n mod.send(writer_visibility, writer_method_name)\n\n self\n end", "def allowed_to_write(name)\n # no point allowing attribute writes if we can't save them?\n if allowed_to_save\n name = name.to_s\n validation_methods = self.class.write_validations(name) \n if validation_methods.nil?\n # We haven't registered any filters on this attribute, so allow the write.\n true\n elsif validation_methods.check :accessor => accessor, :model => self\n # One of the authentication methods worked, so allow the write.\n true\n else\n # We had filters but none of them passed. Disallow write.\n false\n end\n else\n false\n end\n end", "def assert_attr_writer(obj, method)\n assert_respond_to obj, \"#{method}=\"\nend", "def add_attribute(name, &block); end", "def authenticates_writes_to(attr, options={})\n authenticates_access\n @write_validation_map ||= {}\n @write_validation_map[attr.to_s] ||= AuthMethodList.new\n @write_validation_map[attr.to_s].add_method(options)\n end", "def write_attribute_3(param1, param2)\n\twrite_attribute(param1, param2)\n end", "def write_attribute(attr_name, value) #:doc:\n @attributes[attr_name] = empty_string_for_number_column?(attr_name, value) ? nil : value\n end", "def add_writer_tags(klass, new_method, member)\n member_tag = member_tag_for_member(klass, member, :write)\n return_type = return_type_from_tag(member_tag)\n setter_doc_text = member_tag ? member_tag.text : \"Sets the attribute #{member}\"\n new_method.docstring.replace(setter_doc_text)\n new_method.add_tag YARD::Tags::Tag.new(:param, \"the value to set the attribute #{member} to.\", return_type, \"value\")\n new_method.add_tag YARD::Tags::Tag.new(:return, \"the newly set value\", return_type)\n end", "def print_attribute(*) end", "def attribute(name); end", "def add_checked_attribute(clazz, attribute)\r\n eval <<END\r\n class #{clazz}\r\n\r\n def #{attribute}=(value)\r\n raise 'Invalid attribute' unless value\r\n @#{attribute}=value\r\n end\r\n\r\n def #{attribute}\r\n #{attribute}\r\n end\r\n end\r\nEND\r\nend", "def attr(name); end", "def is_attribute?(line)\n (line =~ /(\\s+)attr_(writer|reader|accessor)\\s+:[a-zA-Z_0-9]+/) == 0\n end", "def attribute(name, value)\n\t if !@inStartTag\n\t\traise WriterError.new('attribute outside of tag start')\n\t end\n\t @io << \" #{name}=\\\"#{NQXML.encode(value.to_s)}\\\"\"\n\tend", "def set_attribute(name, value); end", "def dataset_writer(*attributes)\n attributes.flatten.each do |attr_name|\n next if method_defined?(\"#{attr_name}=\")\n\n class_eval <<-RUBY, __FILE__, __LINE__ + 1\n def #{attr_name}=(value)\n dataset_set(:#{attr_name}, value)\n end\n RUBY\n end\n end", "def validated_attribute_names(params); end", "def require_format_of(attribute)\r\n RequireFormatOf.new(attribute)\r\n end", "def attr_writer(*fields)\n check_fields(fields)\n added_fields = jiak.data.writable(*fields)\n added_fields.each do |field|\n class_eval <<-EOM\n def #{field}=(val)\n @jiak.object.data.#{field} = val\n self.class.do_auto_update(self)\n end\n EOM\n end\n nil\n end", "def html_attr(*attrs)\n options = attrs.extract_options!.reverse_merge({\n :level => :super_relaxed\n })\n attrs.each do |att|\n class_eval \"def #{att}=(val); self[:#{att}] = sanitize(val, :#{options[:level]}); end\"\n end\n end", "def validate_attributes=(new_attribute)\n @validate_attributes = new_attribute\n end", "def html_attributes(attr); end", "def instance_write(attr, value)\n setter = :\"#{@name_string}_#{attr}=\"\n instance.send(setter, value) if instance.respond_to?(setter)\n end", "def valid_xml_attribute(name, options={:level => :warning})\n\t\t\t\tvalidate(\"Invalid XML attribute '#{name}'\", options) { name.to_s.match(/^([^[:punct:]0-9<>]|_)[^<>\"']*/) }\n\t\t\tend", "def attr_writer(*args)\n sym_args=args_to_sym(args)\n sym_args.each do |value|\n self.instance_eval(\"def #{value}=(arg); @#{value}=arg;end;\")\n end\n \n end", "def define_writer_method(attribute, method_name, visibility)\n define_method(method_name) { |value| attribute.set(self, value) }\n send(visibility, method_name)\n self\n end", "def write_attribute(name, val)\n if @embedded_models.include? name\n @embedded_models[name].model = val\n elsif @attribute_objects.include? name\n @attribute_objects[name].value = val\n else\n return false\n end\n\n run_callbacks :attribute_change\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def attr; end", "def attribute(*args)\n define_expressions(Attribute, args)\n end", "def write_attribute(name, value)\n name = name.to_s\n\n # The attribute already has an unsaved change.\n if attribute_changed?(name)\n old = changed_attributes[name]\n changed_attributes.delete(name) unless field_changed?(name, old, value)\n else\n attribute_will_change(name) if field_changed?(name, old, value)\n end\n\n # Carry on.\n super(name, value)\n end", "def define_magic_attr(name)\n define_method name do |*attrs|\n raise ArgumentError.new(\"wrong number of arguments\") if attrs.size > 1\n send(\"#{name}=\", attrs.first) if attrs.size == 1\n instance_variable_get(\"@#{name}\")\n end\n\n attr_writer name\n end", "def configurable_writer(attribute, code=nil, &block)\n if block_given? and not code\n Halcyon.class.send(:define_method, :\"#{attribute}=\", block)\n elsif code and not block_given?\n Halcyon.class.send(:eval, <<-\"end;\")\n def #{attribute.to_s}=(value)\n #{code % [attribute.to_sym.inspect]}\n end\n end;\n else\n raise ArgumentError.new(\"Either a block or a code string should be supplied.\")\n end\n end", "def method_missing(name, *args, &block)\n if /\\Ahas_validated_(?<type>\\w*)_attribute\\Z/ =~ name\n has_validated_attribute(type, *args, &block)\n else\n super\n end\n end", "def add_checked_attribute(klass, attribute)\n klass.class_eval do\n define_method attribute do\n instance_variable_get(\"@#{attribute}\")\n end\n\n define_method \"#{attribute}=\" do |value|\n raise 'Invalid attribute' unless value\n \n instance_variable_set(\"@#{attribute}\", value)\n end\n end\nend", "def method_missing(meth, *args, &blk)\n match = meth.to_s.match(/^([a-zA-Z\\_]+)(=|$)$/)\n if match\n attribute, setter = match[1], !match[2].blank?\n if setter\n write_attribute(attribute, args.first)\n else\n read_attribute(attribute)\n end\n else\n super(meth, *args, &blk)\n end\n end", "def valid_attributes\n { name: 'do this' }\n end", "def make_attributes_definitions_or_croak(attrArgs, &attrBlok)\n eye = :'m_attrs_defs'\n\n # Work with attribute as strings\n \n $DEBUG && logger_me(eye, logger_fmt_kls(:attrArgs => attrArgs, :attrBlok => attrBlok))\n\n mustbe_attributes_specification_or_croak(attrArgs, eye, \"attrArgs not attributes_specification\")\n \n #STOPATTRARGSINSUPER\n \n #attrAll = mustbe_not_empty_or_croak(mustbe_array_key_or_nil_or_croak(attrArgs, :all, eye, \"all attributes not array\"), eye, \"all attributes is empty\").map(&:to_s)\n attrAll = mustbe_not_empty_or_croak(mustbe_attributes_specification_all_key_or_croak(attrArgs, :all, eye), eye, \"all attributes is empty\").map(&:to_s)\n \n\n #puts(\"\\n\\n\\nATTR ALL >#{attrAll}<\")\n\n #STOPMAKEATTRSPECSENTRY\n\n attrInc = mustbe_attributes_specification_include_key_or_nil_or_croak(attrArgs, :include, eye) # mustbe all strings\n #puts(\"ATTR INC >#{attrInc.class}< >#{attrInc}< >#{is_value_not_empty?(attrInc)}<\")\n attrInc && mustbe_not_empty_or_croak(attrInc, eye, \"include attributes is empty\")\n\n attrExc = mustbe_attributes_specification_exclude_key_or_nil_or_croak(attrArgs, :exclude, eye) || []\n \n attrMapNom = mustbe_attributes_definitions_key_or_nil_or_croak(attrArgs, :definitions, eye) || {}\n attrMap = attrMapNom && potrubi_util_map_hash_kv(attrMapNom) {|k,v| [k.to_s, v]} # keys all strings\n\n # Ensure all consistent\n \n attrInc && mustbe_subset_or_croak(attrInc, attrAll, eye, \"include attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrExc, attrAll, eye, \"exclude attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrMap.keys, attrAll, eye, \"attribute map contains unknown attributes\")\n \n attrUse = ((attrInc || attrAll) - attrExc).uniq # list of unique attributes to report on\n\n # consolidate \"faked up\" attr specs with ones provided to get the composite attrSpecs\n \n attrDefsNom = potrubi_util_array_to_hash(attrUse).merge(attrMap.select {|k,v| attrUse.include?(k)}) # consolidated \"faked up\" attr specs with ones provided\n\n attrDefs = potrubi_util_map_hash_v(attrDefsNom) do | attrName, attrSpecNom|\n\n attrSpec =\n case attrSpecNom\n when NilClass then {}\n when Hash then\n attrSpecNom.each_with_object({}) do | (verbName, verbSpec), h1 |\n case verbName\n when :pass_thru then h1[:pass_thru] = verbSpec # dont touch; just pass through\n when :event_defaults then # add these to pass_thru\n h1[:pass_thru] = (h1[:pass_thru] || {}).merge(verbName => verbSpec)\n when :map, :select, :metric then\n h1[verbName] = {\n :method_name => \"#{verbName}_#{attrName}_#{rand(1000000)}\", # make a unqiue name\n :method_spec => verbSpec # spec must be valid to dynamic_define_methods\n }\n else\n logic_exception(verbName, eye, \"attrName >#{attrName}< verbName >#{verbName}< value should be impossible\")\n end\n end\n \n else\n logic_exception(attrrSpecNom, eye, \"attrSpecNom value should be impossible\")\n end\n\n attrSpec\n \n end\n \n $DEBUG && logger_mx(eye, logger_fmt_kls(:attrDefs => attrDefs))\n\n mustbe_attributes_definitions_or_croak(attrDefs, eye, \"attrDefs failed contract\")\n\n #STOPMAKEATTRSPECS\n \n end", "def create_writer(klass, member)\n # We want to convert these members into attributes just like\n # as if they were declared using attr_accessor.\n new_meth = register MethodObject.new(klass, \"#{member}=\", :instance) do |o|\n o.parameters = [['value', nil]]\n o.signature ||= \"def #{member}=(value)\"\n o.source ||= \"#{o.signature}\\n @#{member} = value\\nend\"\n end\n add_writer_tags(klass, new_meth, member)\n klass.attributes[:instance][member][:write] = new_meth\n end", "def create_setter!\n @target.class_eval <<-EOS\n #{writer_visibility.to_s}\n def #{name}=(value)\n attribute_set(#{name.inspect}, value)\n end\n EOS\n rescue SyntaxError\n raise SyntaxError.new(column)\n end", "def attribute name, type, conditions= DEFAULT_ATTRIBUTE_CONDITIONS\n RMOF.complete_conditions conditions, DEFAULT_ATTRIBUTE_CONDITIONS\n @attributes= {} unless instance_variable_defined? :@attributes\n @attributes[name]= [name, type, conditions]\n unless method_defined? :__attributes then \n define_method( :__attributes) do \n @attributes\n end \n end\n at= \"@#{name}\".to_sym\n getter= \"#{name}\".to_sym\n setter= \"#{name}=\".to_sym\n completion= \"__complete_#{name}\".to_sym\n define_method( getter) do\n if instance_variable_defined? at then instance_variable_get at\n else conditions[:default]\n end\n end\n define_method( setter) do |val|\n instance_variable_set at, val\n end\n define_method( completion) do\n RMOF.validate( self.send(getter), name, type, conditions)\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def create_setter(name, meth)\n define_method(\"#{meth}=\") do |value|\n write_attribute(name, value)\n end\n end", "def sanitized_allowed_attributes=(attributes); end", "def sanitized_allowed_attributes=(attributes); end", "def oattr(name, type)\n case type\n when :custom\n # Do nothing, just register attr below.\n when :writer\n attr_writer name\n else\n raise ArgumentError, \"Unknown type: #{type.inspect}\"\n end\n\n # Register and return.\n name.tap { oattrs << name}\n end", "def valid_attributes\n { name: \"Expert\" }\n end", "def attributes(*method_names, **options)\n add_attributes(method_names, **options, strategy: :write_value_using_method_strategy)\n end", "def []=(attr_name, value)\n writer_method = \"#{attr_name}=\"\n send(writer_method, value) if respond_to?(writer_method)\n end", "def write_extended_attributes(attrs)\n attrs.each do |k, val|\n self.send((k.to_s + \"=\").to_sym, val) if is_flex_attribute?(k)\n end\n self\n end", "def valid_attributes\n { \"username\" => \"MyString\" }\n end", "def cattr_writer(*fields)\n metaclass.send :attr_writer, *fields\n end", "def write_attribute(attr, value)\n if attribute_encrypted?(attr)\n conductor_for(attr).encrypt(value)\n else\n super(attr, value)\n end\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_number_value(\"offsetInDays\", @offset_in_days)\n writer.write_enum_value(\"timeBasedAttribute\", @time_based_attribute)\n end", "def define_attribute_method(attr_name, _owner: generated_attribute_methods)\n CodeGenerator.batch(_owner, __FILE__, __LINE__) do |owner|\n attribute_method_matchers.each do |matcher|\n method_name = matcher.method_name(attr_name)\n\n unless instance_method_already_implemented?(method_name)\n generate_method = \"define_method_#{matcher.target}\"\n\n if respond_to?(generate_method, true)\n send(generate_method, attr_name.to_s, owner: owner)\n else\n define_proxy_call true, owner, method_name, matcher.target, attr_name.to_s\n end\n end\n end\n attribute_method_matchers_cache.clear\n end\n end", "def has_attributes?; end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_boolean_value(\"isExpirationRequired\", @is_expiration_required)\n writer.write_duration_value(\"maximumDuration\", @maximum_duration)\n end", "def add_attributes(item)\n [:class, :instance].each do |attr_loc|\n # Grab attributes for the current location (class or instance)\n attrs = item.attributes[attr_loc]\n attrs.each do |name, attribute|\n reader = attribute[:read]\n writer = attribute[:write]\n\n unless reader || writer\n Logging.warn(\"attribute is not readable or writable somehow, skipping\", attribute)\n next\n end\n\n # Get all given types\n yard_types = []\n if reader\n next if @hide_private && reader.visibility == :private\n yard_types += reader.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n reader.tags('param').flat_map(&:types)\n end\n if writer\n next if @hide_private && writer.visibility == :private\n yard_types += writer.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n writer.tags('param').flat_map(&:types)\n end\n\n # Use untyped if not types specified anywhere, otherwise try to\n # compute Parlour type given all these types\n if yard_types.empty?\n Logging.omit(\"no YARD type given for #{name.inspect}, using untyped\", reader || writer)\n parlour_type = Parlour::Types::Untyped.new\n elsif yard_types.all? { |x| x == 'nil' }\n # Nil attributes are extremely unusual, so just use untyped\n parlour_type = Parlour::Types::Untyped.new\n else\n parlour_type = TypeConverter.yard_to_parlour(\n yard_types, reader || writer, @type_converter_config)\n end\n\n # Generate attribute\n if reader && writer\n kind = :accessor\n elsif reader\n kind = :reader\n elsif writer\n kind = :writer\n end\n\n if @exclude_untyped && parlour_type.is_a?(Parlour::Types::Untyped)\n Logging.omit(\"excluding untyped attribute\", reader || writer, immediate: true)\n next\n end\n\n case @mode\n when :rbi\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n class_attribute: (attr_loc == :class)\n ) do |m|\n add_comments(reader || writer, m)\n end\n when :rbs\n if attr_loc == :class\n # RBS doesn't support class attr_accessors so create individual methods\n\n if reader\n @current_object.create_method(\n name.to_s,\n [Parlour::RbsGenerator::MethodSignature.new([], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(reader, m)\n end\n end\n\n if writer\n @current_object.create_method(\n \"#{name}=\",\n [Parlour::RbsGenerator::MethodSignature.new([Parlour::RbsGenerator::Parameter.new(\n \"value\",\n type: parlour_type,\n required: true\n )], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(writer, m)\n end\n end\n else\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n ) do |m|\n add_comments(reader || writer, m)\n end\n end\n end\n end\n end\n end", "def []=(attr_name, value)\r\n if attr_name.is_a?(String) and attr_name != attr_name.split(ID_SEP).first\r\n attr_name = attr_name.split(ID_SEP)\r\n end\r\n\r\n if attr_name.is_a? Array\r\n value = value.split(ID_SEP) if value.is_a? String\r\n unless value.length == attr_name.length\r\n raise \"Number of attr_names and values do not match\"\r\n end\r\n #breakpoint\r\n [attr_name, value].transpose.map {|name,val| write_attribute(name.to_s, val)}\r\n else\r\n write_attribute(attr_name, value)\r\n end\r\n end", "def attr(symbol, writable=false) end", "def define_writer!(k, definition)\n define_method(\"#{k}=\") do |value|\n # Recursively convert hash and array of hash to schematized objects\n value = ensure_schema value, definition[:schema]\n\n # Initial value\n instance_variable_set \"@#{k}\", value\n\n # Dirty tracking\n self.changed_attributes ||= Set.new\n self.changed_attributes << k\n end\n end", "def validate\n validate_string_attributes\n end", "def write_attribute_with_dynamo(field_name, value)\n if is_dynamo_field?(field_name)\n # Store these guys for now. We don't actually save the field value until the model is saved ( i.e my_supplier.save ).\n # If we were to save the field_value now we wouldn't be able to know the id of the model to link this value to it.\n # @see delay_save\n @all_fields_and_values ||= []\n @all_fields_and_values << {:dynamo_field=>cached_dynamo_field_by_name(field_name), :value=>value}\n end\n # If its a 'normal' attribute let rails write it in the usual way.\n write_attribute_without_dynamo(field_name, value)\n end", "def define_attr_accessor(attr)\n attr_accessor(attr)\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n writer.write_collection_of_object_values(\"attributeMappings\", @attribute_mappings)\n writer.write_boolean_value(\"enabled\", @enabled)\n writer.write_enum_value(\"flowTypes\", @flow_types)\n writer.write_collection_of_object_values(\"metadata\", @metadata)\n writer.write_string_value(\"name\", @name)\n writer.write_string_value(\"@odata.type\", @odata_type)\n writer.write_object_value(\"scope\", @scope)\n writer.write_string_value(\"sourceObjectName\", @source_object_name)\n writer.write_string_value(\"targetObjectName\", @target_object_name)\n writer.write_additional_data(@additional_data)\n end", "def validate_attribute_syntax\n\t\t@values.each do |attribute, values|\n\t\t\t[ values ].flatten.each do |value|\n\t\t\t\tbegin\n\t\t\t\t\tself.get_converted_attribute( attribute.to_sym, value )\n\t\t\t\trescue => err\n\t\t\t\t\tself.log.error \"validation for %p failed: %s: %s\" %\n\t\t\t\t\t\t[ attribute, err.class.name, err.message ]\n\t\t\t\t\tattrtype = self.find_attribute_type( attribute )\n\t\t\t\t\tself.errors.add( attribute, \"isn't a valid %s value\" %\n\t\t\t\t\t\t[ attrtype.syntax ? attrtype.syntax.desc : attrtype.syntax_oid ] )\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def valid_attributes\n { }\n end", "def validatable_attributes(atts, opts)\n am, an, ab, m = opts.values_at(:allow_missing, :allow_nil, :allow_blank, :message)\n Array(atts).each do |a|\n next if am && !values.has_key?(a)\n v = send(a)\n next if an && v.nil?\n next if ab && v.respond_to?(:blank?) && v.blank?\n if message = yield(a, v, m)\n errors.add(a, message)\n end\n end\n end", "def valid_attributes\n { }\n end", "def valid_attributes\n { }\n end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def require_attr(name)\n send(name).tap do |_|\n raise \"Attribute must be set: #{name}\" if _.nil?\n end\n end", "def write_attributes(attributes)\n _attributes = attributes.select do |name, value|\n if self.is_dynamic_field?(name)\n self.dynamic_setter(name, value)\n false\n else\n true\n end\n end\n\n super(_attributes)\n end", "def attribute; end", "def attribute; end" ]
[ "0.6472992", "0.6315012", "0.6315012", "0.62821025", "0.6279224", "0.6211609", "0.61891466", "0.6182247", "0.60683644", "0.6032628", "0.5995443", "0.5988785", "0.5959885", "0.5938289", "0.5931089", "0.58951056", "0.5859927", "0.5851703", "0.58493423", "0.58465594", "0.58328366", "0.5823013", "0.5822229", "0.57850474", "0.5701491", "0.5696689", "0.5682951", "0.5678094", "0.566814", "0.5657499", "0.56555206", "0.5642589", "0.56219065", "0.5615893", "0.56105876", "0.559851", "0.5598089", "0.55940455", "0.5585137", "0.55848545", "0.55796933", "0.5571477", "0.5567006", "0.55667996", "0.55652434", "0.5562926", "0.55600035", "0.55590326", "0.55590326", "0.5554599", "0.5554599", "0.55407417", "0.5534935", "0.5527733", "0.55271375", "0.55238813", "0.5501504", "0.5497003", "0.5496233", "0.54927665", "0.5464706", "0.54617554", "0.5461167", "0.5451583", "0.54498726", "0.54498726", "0.54359984", "0.5430996", "0.5430996", "0.5426488", "0.5418467", "0.54153895", "0.54107565", "0.5407886", "0.5401234", "0.54008496", "0.5400268", "0.53910094", "0.53827274", "0.5377731", "0.5375473", "0.5374833", "0.53720397", "0.5370215", "0.5363264", "0.5361161", "0.5360557", "0.5351706", "0.53514725", "0.53492516", "0.53459316", "0.5341237", "0.5328037", "0.5328037", "0.53230566", "0.53230566", "0.53230566", "0.5319575", "0.531832", "0.5315559", "0.5315559" ]
0.0
-1
Custom attribute writer method with validation
def tcp_opening=(tcp_opening) if tcp_opening.nil? fail ArgumentError, 'tcp_opening cannot be nil' end if tcp_opening > 4320000 fail ArgumentError, 'invalid value for "tcp_opening", must be smaller than or equal to 4320000.' end if tcp_opening < 10 fail ArgumentError, 'invalid value for "tcp_opening", must be greater than or equal to 10.' end @tcp_opening = tcp_opening end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def attr_writer_tag(text); end", "def allowed_attributes=(_arg0); end", "def allowed_attributes=(_arg0); end", "def writer(*args)\n attr_writer(*args)\n args\n end", "def define_write_method(attr_name)\n evaluate_attribute_method attr_name, \"def #{attr_name}=(new_value);write_attribute('#{attr_name}', new_value);end\", \"#{attr_name}=\"\n end", "def attr_writer(*vars)\n # avoid tracking attributes that are added by the class_attribute\n # as these are class attributes and not instance attributes.\n tracked_vars = vars.reject {|var| respond_to? var }\n add_tracked_attrs(false, true, *tracked_vars)\n vars.extract_options!\n super\n end", "def attr_writer(sym, *more) end", "def is_attribute?; end", "def validate_exclusion_of(attr); end", "def register_attributes\n raise \"Not implemented in #{self.class}\"\n end", "def method_missing(method_name, *args)\n return super unless permitted_attributes.include?(method_name)\n begin\n object.send(:\"#{method_name}=\", args.first)\n rescue => e\n if params.has_key?(method_name)\n message = \"Unable to process value for :#{method_name}, no attribute writer. Be sure to override the automatic setters for all params that do not map straight to a model attribute.\"\n Rails.logger.warn({message: message,\n missing_writer: method_name,\n value: args.first,\n error: e})\n self.errors << {status: 422, message: message}\n else\n raise e\n end\n end\n end", "def timeliness_validation_for(attr_names, type)\n super\n attr_names.each { |attr_name| define_timeliness_write_method(attr_name) }\n end", "def create_setter_for(attribute, options)\n setter_method = \"#{attribute}=\"\n\n define_method setter_method do |value|\n if options[:allow_blank] || value != \"\"\n write_attribute(attribute, value)\n end\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each {|attr_name| attr_internal_define(attr_name, :writer)}\n end", "def escape_attr input\n escape input, attr_regexp, attr_mapping\n end", "def make_writer( attrtype )\n\t\tself.log.debug \"Generating an attribute writer for %p\" % [ attrtype ]\n\t\tattrname = attrtype.name\n\t\tif attrtype.single?\n\t\t\tself.log.debug \" attribute is SINGLE, so generating a scalar writer...\"\n\t\t\treturn lambda {|newvalue| self[attrname] = newvalue }\n\t\telse\n\t\t\tself.log.debug \" attribute isn't SINGLE, so generating an array writer...\"\n\t\t\treturn lambda {|*newvalues| self[attrname] = newvalues.flatten }\n\t\tend\n\tend", "def write_attribute(name, value)\n # Simply check if the accessor is allowed to write the field\n # (if so, go to superclass and do it)\n @bypass_auth ||= false\n if allowed_to_write(name) || @bypass_auth\n super(name, value)\n end\n end", "def mattr_writer(*syms, &proc)\n receiver = self\n options = syms.extract_options!\n syms.each do |sym|\n raise NameError.new('invalid attribute name') unless sym =~ /^[_A-Za-z]\\w*$/\n class_exec do\n define_singleton_method \"#{sym}=\" do |obj|\n class_variable_set(\"@@#{sym}\", obj)\n end\n end\n\n unless options[:instance_writer] == false || options[:instance_accessor] == false\n class_exec do\n define_method \"#{sym}=\" do |obj|\n receiver.class_variable_set(\"@@#{sym}\", obj)\n end\n end\n end\n send(\"#{sym}=\", proc.call) if proc\n end\n end", "def write_attribute(attribute, value)\n false\n end", "def add_attribute attribute\n return attribute unless @document_self\n\n # mainly to check for redefinition of an attribute as a method\n # TODO find a policy for 'attr_reader :foo' + 'def foo=()'\n register = false\n\n key = nil\n\n if attribute.rw.index 'R' then\n key = attribute.pretty_name\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name + '='] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if attribute.rw.index 'W' then\n key = attribute.pretty_name + '='\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if register then\n attribute.visibility = @visibility\n add_to @attributes, attribute\n resolve_aliases attribute\n end\n\n attribute\n end", "def define_writer_method(mod)\n writer_method_name = \"#{name}=\"\n attribute = self\n\n mod.send(:define_method, writer_method_name) { |value| attribute.set(self, value) }\n mod.send(writer_visibility, writer_method_name)\n\n self\n end", "def allowed_to_write(name)\n # no point allowing attribute writes if we can't save them?\n if allowed_to_save\n name = name.to_s\n validation_methods = self.class.write_validations(name) \n if validation_methods.nil?\n # We haven't registered any filters on this attribute, so allow the write.\n true\n elsif validation_methods.check :accessor => accessor, :model => self\n # One of the authentication methods worked, so allow the write.\n true\n else\n # We had filters but none of them passed. Disallow write.\n false\n end\n else\n false\n end\n end", "def assert_attr_writer(obj, method)\n assert_respond_to obj, \"#{method}=\"\nend", "def add_attribute(name, &block); end", "def authenticates_writes_to(attr, options={})\n authenticates_access\n @write_validation_map ||= {}\n @write_validation_map[attr.to_s] ||= AuthMethodList.new\n @write_validation_map[attr.to_s].add_method(options)\n end", "def write_attribute_3(param1, param2)\n\twrite_attribute(param1, param2)\n end", "def write_attribute(attr_name, value) #:doc:\n @attributes[attr_name] = empty_string_for_number_column?(attr_name, value) ? nil : value\n end", "def add_writer_tags(klass, new_method, member)\n member_tag = member_tag_for_member(klass, member, :write)\n return_type = return_type_from_tag(member_tag)\n setter_doc_text = member_tag ? member_tag.text : \"Sets the attribute #{member}\"\n new_method.docstring.replace(setter_doc_text)\n new_method.add_tag YARD::Tags::Tag.new(:param, \"the value to set the attribute #{member} to.\", return_type, \"value\")\n new_method.add_tag YARD::Tags::Tag.new(:return, \"the newly set value\", return_type)\n end", "def print_attribute(*) end", "def attribute(name); end", "def add_checked_attribute(clazz, attribute)\r\n eval <<END\r\n class #{clazz}\r\n\r\n def #{attribute}=(value)\r\n raise 'Invalid attribute' unless value\r\n @#{attribute}=value\r\n end\r\n\r\n def #{attribute}\r\n #{attribute}\r\n end\r\n end\r\nEND\r\nend", "def attr(name); end", "def is_attribute?(line)\n (line =~ /(\\s+)attr_(writer|reader|accessor)\\s+:[a-zA-Z_0-9]+/) == 0\n end", "def attribute(name, value)\n\t if !@inStartTag\n\t\traise WriterError.new('attribute outside of tag start')\n\t end\n\t @io << \" #{name}=\\\"#{NQXML.encode(value.to_s)}\\\"\"\n\tend", "def set_attribute(name, value); end", "def dataset_writer(*attributes)\n attributes.flatten.each do |attr_name|\n next if method_defined?(\"#{attr_name}=\")\n\n class_eval <<-RUBY, __FILE__, __LINE__ + 1\n def #{attr_name}=(value)\n dataset_set(:#{attr_name}, value)\n end\n RUBY\n end\n end", "def validated_attribute_names(params); end", "def require_format_of(attribute)\r\n RequireFormatOf.new(attribute)\r\n end", "def attr_writer(*fields)\n check_fields(fields)\n added_fields = jiak.data.writable(*fields)\n added_fields.each do |field|\n class_eval <<-EOM\n def #{field}=(val)\n @jiak.object.data.#{field} = val\n self.class.do_auto_update(self)\n end\n EOM\n end\n nil\n end", "def html_attr(*attrs)\n options = attrs.extract_options!.reverse_merge({\n :level => :super_relaxed\n })\n attrs.each do |att|\n class_eval \"def #{att}=(val); self[:#{att}] = sanitize(val, :#{options[:level]}); end\"\n end\n end", "def validate_attributes=(new_attribute)\n @validate_attributes = new_attribute\n end", "def html_attributes(attr); end", "def instance_write(attr, value)\n setter = :\"#{@name_string}_#{attr}=\"\n instance.send(setter, value) if instance.respond_to?(setter)\n end", "def valid_xml_attribute(name, options={:level => :warning})\n\t\t\t\tvalidate(\"Invalid XML attribute '#{name}'\", options) { name.to_s.match(/^([^[:punct:]0-9<>]|_)[^<>\"']*/) }\n\t\t\tend", "def attr_writer(*args)\n sym_args=args_to_sym(args)\n sym_args.each do |value|\n self.instance_eval(\"def #{value}=(arg); @#{value}=arg;end;\")\n end\n \n end", "def define_writer_method(attribute, method_name, visibility)\n define_method(method_name) { |value| attribute.set(self, value) }\n send(visibility, method_name)\n self\n end", "def write_attribute(name, val)\n if @embedded_models.include? name\n @embedded_models[name].model = val\n elsif @attribute_objects.include? name\n @attribute_objects[name].value = val\n else\n return false\n end\n\n run_callbacks :attribute_change\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def attr; end", "def attribute(*args)\n define_expressions(Attribute, args)\n end", "def write_attribute(name, value)\n name = name.to_s\n\n # The attribute already has an unsaved change.\n if attribute_changed?(name)\n old = changed_attributes[name]\n changed_attributes.delete(name) unless field_changed?(name, old, value)\n else\n attribute_will_change(name) if field_changed?(name, old, value)\n end\n\n # Carry on.\n super(name, value)\n end", "def define_magic_attr(name)\n define_method name do |*attrs|\n raise ArgumentError.new(\"wrong number of arguments\") if attrs.size > 1\n send(\"#{name}=\", attrs.first) if attrs.size == 1\n instance_variable_get(\"@#{name}\")\n end\n\n attr_writer name\n end", "def configurable_writer(attribute, code=nil, &block)\n if block_given? and not code\n Halcyon.class.send(:define_method, :\"#{attribute}=\", block)\n elsif code and not block_given?\n Halcyon.class.send(:eval, <<-\"end;\")\n def #{attribute.to_s}=(value)\n #{code % [attribute.to_sym.inspect]}\n end\n end;\n else\n raise ArgumentError.new(\"Either a block or a code string should be supplied.\")\n end\n end", "def method_missing(name, *args, &block)\n if /\\Ahas_validated_(?<type>\\w*)_attribute\\Z/ =~ name\n has_validated_attribute(type, *args, &block)\n else\n super\n end\n end", "def add_checked_attribute(klass, attribute)\n klass.class_eval do\n define_method attribute do\n instance_variable_get(\"@#{attribute}\")\n end\n\n define_method \"#{attribute}=\" do |value|\n raise 'Invalid attribute' unless value\n \n instance_variable_set(\"@#{attribute}\", value)\n end\n end\nend", "def method_missing(meth, *args, &blk)\n match = meth.to_s.match(/^([a-zA-Z\\_]+)(=|$)$/)\n if match\n attribute, setter = match[1], !match[2].blank?\n if setter\n write_attribute(attribute, args.first)\n else\n read_attribute(attribute)\n end\n else\n super(meth, *args, &blk)\n end\n end", "def valid_attributes\n { name: 'do this' }\n end", "def make_attributes_definitions_or_croak(attrArgs, &attrBlok)\n eye = :'m_attrs_defs'\n\n # Work with attribute as strings\n \n $DEBUG && logger_me(eye, logger_fmt_kls(:attrArgs => attrArgs, :attrBlok => attrBlok))\n\n mustbe_attributes_specification_or_croak(attrArgs, eye, \"attrArgs not attributes_specification\")\n \n #STOPATTRARGSINSUPER\n \n #attrAll = mustbe_not_empty_or_croak(mustbe_array_key_or_nil_or_croak(attrArgs, :all, eye, \"all attributes not array\"), eye, \"all attributes is empty\").map(&:to_s)\n attrAll = mustbe_not_empty_or_croak(mustbe_attributes_specification_all_key_or_croak(attrArgs, :all, eye), eye, \"all attributes is empty\").map(&:to_s)\n \n\n #puts(\"\\n\\n\\nATTR ALL >#{attrAll}<\")\n\n #STOPMAKEATTRSPECSENTRY\n\n attrInc = mustbe_attributes_specification_include_key_or_nil_or_croak(attrArgs, :include, eye) # mustbe all strings\n #puts(\"ATTR INC >#{attrInc.class}< >#{attrInc}< >#{is_value_not_empty?(attrInc)}<\")\n attrInc && mustbe_not_empty_or_croak(attrInc, eye, \"include attributes is empty\")\n\n attrExc = mustbe_attributes_specification_exclude_key_or_nil_or_croak(attrArgs, :exclude, eye) || []\n \n attrMapNom = mustbe_attributes_definitions_key_or_nil_or_croak(attrArgs, :definitions, eye) || {}\n attrMap = attrMapNom && potrubi_util_map_hash_kv(attrMapNom) {|k,v| [k.to_s, v]} # keys all strings\n\n # Ensure all consistent\n \n attrInc && mustbe_subset_or_croak(attrInc, attrAll, eye, \"include attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrExc, attrAll, eye, \"exclude attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrMap.keys, attrAll, eye, \"attribute map contains unknown attributes\")\n \n attrUse = ((attrInc || attrAll) - attrExc).uniq # list of unique attributes to report on\n\n # consolidate \"faked up\" attr specs with ones provided to get the composite attrSpecs\n \n attrDefsNom = potrubi_util_array_to_hash(attrUse).merge(attrMap.select {|k,v| attrUse.include?(k)}) # consolidated \"faked up\" attr specs with ones provided\n\n attrDefs = potrubi_util_map_hash_v(attrDefsNom) do | attrName, attrSpecNom|\n\n attrSpec =\n case attrSpecNom\n when NilClass then {}\n when Hash then\n attrSpecNom.each_with_object({}) do | (verbName, verbSpec), h1 |\n case verbName\n when :pass_thru then h1[:pass_thru] = verbSpec # dont touch; just pass through\n when :event_defaults then # add these to pass_thru\n h1[:pass_thru] = (h1[:pass_thru] || {}).merge(verbName => verbSpec)\n when :map, :select, :metric then\n h1[verbName] = {\n :method_name => \"#{verbName}_#{attrName}_#{rand(1000000)}\", # make a unqiue name\n :method_spec => verbSpec # spec must be valid to dynamic_define_methods\n }\n else\n logic_exception(verbName, eye, \"attrName >#{attrName}< verbName >#{verbName}< value should be impossible\")\n end\n end\n \n else\n logic_exception(attrrSpecNom, eye, \"attrSpecNom value should be impossible\")\n end\n\n attrSpec\n \n end\n \n $DEBUG && logger_mx(eye, logger_fmt_kls(:attrDefs => attrDefs))\n\n mustbe_attributes_definitions_or_croak(attrDefs, eye, \"attrDefs failed contract\")\n\n #STOPMAKEATTRSPECS\n \n end", "def create_writer(klass, member)\n # We want to convert these members into attributes just like\n # as if they were declared using attr_accessor.\n new_meth = register MethodObject.new(klass, \"#{member}=\", :instance) do |o|\n o.parameters = [['value', nil]]\n o.signature ||= \"def #{member}=(value)\"\n o.source ||= \"#{o.signature}\\n @#{member} = value\\nend\"\n end\n add_writer_tags(klass, new_meth, member)\n klass.attributes[:instance][member][:write] = new_meth\n end", "def create_setter!\n @target.class_eval <<-EOS\n #{writer_visibility.to_s}\n def #{name}=(value)\n attribute_set(#{name.inspect}, value)\n end\n EOS\n rescue SyntaxError\n raise SyntaxError.new(column)\n end", "def attribute name, type, conditions= DEFAULT_ATTRIBUTE_CONDITIONS\n RMOF.complete_conditions conditions, DEFAULT_ATTRIBUTE_CONDITIONS\n @attributes= {} unless instance_variable_defined? :@attributes\n @attributes[name]= [name, type, conditions]\n unless method_defined? :__attributes then \n define_method( :__attributes) do \n @attributes\n end \n end\n at= \"@#{name}\".to_sym\n getter= \"#{name}\".to_sym\n setter= \"#{name}=\".to_sym\n completion= \"__complete_#{name}\".to_sym\n define_method( getter) do\n if instance_variable_defined? at then instance_variable_get at\n else conditions[:default]\n end\n end\n define_method( setter) do |val|\n instance_variable_set at, val\n end\n define_method( completion) do\n RMOF.validate( self.send(getter), name, type, conditions)\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def create_setter(name, meth)\n define_method(\"#{meth}=\") do |value|\n write_attribute(name, value)\n end\n end", "def sanitized_allowed_attributes=(attributes); end", "def sanitized_allowed_attributes=(attributes); end", "def oattr(name, type)\n case type\n when :custom\n # Do nothing, just register attr below.\n when :writer\n attr_writer name\n else\n raise ArgumentError, \"Unknown type: #{type.inspect}\"\n end\n\n # Register and return.\n name.tap { oattrs << name}\n end", "def valid_attributes\n { name: \"Expert\" }\n end", "def attributes(*method_names, **options)\n add_attributes(method_names, **options, strategy: :write_value_using_method_strategy)\n end", "def []=(attr_name, value)\n writer_method = \"#{attr_name}=\"\n send(writer_method, value) if respond_to?(writer_method)\n end", "def write_extended_attributes(attrs)\n attrs.each do |k, val|\n self.send((k.to_s + \"=\").to_sym, val) if is_flex_attribute?(k)\n end\n self\n end", "def valid_attributes\n { \"username\" => \"MyString\" }\n end", "def cattr_writer(*fields)\n metaclass.send :attr_writer, *fields\n end", "def write_attribute(attr, value)\n if attribute_encrypted?(attr)\n conductor_for(attr).encrypt(value)\n else\n super(attr, value)\n end\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_number_value(\"offsetInDays\", @offset_in_days)\n writer.write_enum_value(\"timeBasedAttribute\", @time_based_attribute)\n end", "def define_attribute_method(attr_name, _owner: generated_attribute_methods)\n CodeGenerator.batch(_owner, __FILE__, __LINE__) do |owner|\n attribute_method_matchers.each do |matcher|\n method_name = matcher.method_name(attr_name)\n\n unless instance_method_already_implemented?(method_name)\n generate_method = \"define_method_#{matcher.target}\"\n\n if respond_to?(generate_method, true)\n send(generate_method, attr_name.to_s, owner: owner)\n else\n define_proxy_call true, owner, method_name, matcher.target, attr_name.to_s\n end\n end\n end\n attribute_method_matchers_cache.clear\n end\n end", "def has_attributes?; end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_boolean_value(\"isExpirationRequired\", @is_expiration_required)\n writer.write_duration_value(\"maximumDuration\", @maximum_duration)\n end", "def add_attributes(item)\n [:class, :instance].each do |attr_loc|\n # Grab attributes for the current location (class or instance)\n attrs = item.attributes[attr_loc]\n attrs.each do |name, attribute|\n reader = attribute[:read]\n writer = attribute[:write]\n\n unless reader || writer\n Logging.warn(\"attribute is not readable or writable somehow, skipping\", attribute)\n next\n end\n\n # Get all given types\n yard_types = []\n if reader\n next if @hide_private && reader.visibility == :private\n yard_types += reader.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n reader.tags('param').flat_map(&:types)\n end\n if writer\n next if @hide_private && writer.visibility == :private\n yard_types += writer.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n writer.tags('param').flat_map(&:types)\n end\n\n # Use untyped if not types specified anywhere, otherwise try to\n # compute Parlour type given all these types\n if yard_types.empty?\n Logging.omit(\"no YARD type given for #{name.inspect}, using untyped\", reader || writer)\n parlour_type = Parlour::Types::Untyped.new\n elsif yard_types.all? { |x| x == 'nil' }\n # Nil attributes are extremely unusual, so just use untyped\n parlour_type = Parlour::Types::Untyped.new\n else\n parlour_type = TypeConverter.yard_to_parlour(\n yard_types, reader || writer, @type_converter_config)\n end\n\n # Generate attribute\n if reader && writer\n kind = :accessor\n elsif reader\n kind = :reader\n elsif writer\n kind = :writer\n end\n\n if @exclude_untyped && parlour_type.is_a?(Parlour::Types::Untyped)\n Logging.omit(\"excluding untyped attribute\", reader || writer, immediate: true)\n next\n end\n\n case @mode\n when :rbi\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n class_attribute: (attr_loc == :class)\n ) do |m|\n add_comments(reader || writer, m)\n end\n when :rbs\n if attr_loc == :class\n # RBS doesn't support class attr_accessors so create individual methods\n\n if reader\n @current_object.create_method(\n name.to_s,\n [Parlour::RbsGenerator::MethodSignature.new([], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(reader, m)\n end\n end\n\n if writer\n @current_object.create_method(\n \"#{name}=\",\n [Parlour::RbsGenerator::MethodSignature.new([Parlour::RbsGenerator::Parameter.new(\n \"value\",\n type: parlour_type,\n required: true\n )], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(writer, m)\n end\n end\n else\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n ) do |m|\n add_comments(reader || writer, m)\n end\n end\n end\n end\n end\n end", "def []=(attr_name, value)\r\n if attr_name.is_a?(String) and attr_name != attr_name.split(ID_SEP).first\r\n attr_name = attr_name.split(ID_SEP)\r\n end\r\n\r\n if attr_name.is_a? Array\r\n value = value.split(ID_SEP) if value.is_a? String\r\n unless value.length == attr_name.length\r\n raise \"Number of attr_names and values do not match\"\r\n end\r\n #breakpoint\r\n [attr_name, value].transpose.map {|name,val| write_attribute(name.to_s, val)}\r\n else\r\n write_attribute(attr_name, value)\r\n end\r\n end", "def attr(symbol, writable=false) end", "def define_writer!(k, definition)\n define_method(\"#{k}=\") do |value|\n # Recursively convert hash and array of hash to schematized objects\n value = ensure_schema value, definition[:schema]\n\n # Initial value\n instance_variable_set \"@#{k}\", value\n\n # Dirty tracking\n self.changed_attributes ||= Set.new\n self.changed_attributes << k\n end\n end", "def validate\n validate_string_attributes\n end", "def write_attribute_with_dynamo(field_name, value)\n if is_dynamo_field?(field_name)\n # Store these guys for now. We don't actually save the field value until the model is saved ( i.e my_supplier.save ).\n # If we were to save the field_value now we wouldn't be able to know the id of the model to link this value to it.\n # @see delay_save\n @all_fields_and_values ||= []\n @all_fields_and_values << {:dynamo_field=>cached_dynamo_field_by_name(field_name), :value=>value}\n end\n # If its a 'normal' attribute let rails write it in the usual way.\n write_attribute_without_dynamo(field_name, value)\n end", "def define_attr_accessor(attr)\n attr_accessor(attr)\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n writer.write_collection_of_object_values(\"attributeMappings\", @attribute_mappings)\n writer.write_boolean_value(\"enabled\", @enabled)\n writer.write_enum_value(\"flowTypes\", @flow_types)\n writer.write_collection_of_object_values(\"metadata\", @metadata)\n writer.write_string_value(\"name\", @name)\n writer.write_string_value(\"@odata.type\", @odata_type)\n writer.write_object_value(\"scope\", @scope)\n writer.write_string_value(\"sourceObjectName\", @source_object_name)\n writer.write_string_value(\"targetObjectName\", @target_object_name)\n writer.write_additional_data(@additional_data)\n end", "def validate_attribute_syntax\n\t\t@values.each do |attribute, values|\n\t\t\t[ values ].flatten.each do |value|\n\t\t\t\tbegin\n\t\t\t\t\tself.get_converted_attribute( attribute.to_sym, value )\n\t\t\t\trescue => err\n\t\t\t\t\tself.log.error \"validation for %p failed: %s: %s\" %\n\t\t\t\t\t\t[ attribute, err.class.name, err.message ]\n\t\t\t\t\tattrtype = self.find_attribute_type( attribute )\n\t\t\t\t\tself.errors.add( attribute, \"isn't a valid %s value\" %\n\t\t\t\t\t\t[ attrtype.syntax ? attrtype.syntax.desc : attrtype.syntax_oid ] )\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def valid_attributes\n { }\n end", "def validatable_attributes(atts, opts)\n am, an, ab, m = opts.values_at(:allow_missing, :allow_nil, :allow_blank, :message)\n Array(atts).each do |a|\n next if am && !values.has_key?(a)\n v = send(a)\n next if an && v.nil?\n next if ab && v.respond_to?(:blank?) && v.blank?\n if message = yield(a, v, m)\n errors.add(a, message)\n end\n end\n end", "def valid_attributes\n { }\n end", "def valid_attributes\n { }\n end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def require_attr(name)\n send(name).tap do |_|\n raise \"Attribute must be set: #{name}\" if _.nil?\n end\n end", "def write_attributes(attributes)\n _attributes = attributes.select do |name, value|\n if self.is_dynamic_field?(name)\n self.dynamic_setter(name, value)\n false\n else\n true\n end\n end\n\n super(_attributes)\n end", "def attribute; end", "def attribute; end" ]
[ "0.6472992", "0.6315012", "0.6315012", "0.62821025", "0.6279224", "0.6211609", "0.61891466", "0.6182247", "0.60683644", "0.6032628", "0.5995443", "0.5988785", "0.5959885", "0.5938289", "0.5931089", "0.58951056", "0.5859927", "0.5851703", "0.58493423", "0.58465594", "0.58328366", "0.5823013", "0.5822229", "0.57850474", "0.5701491", "0.5696689", "0.5682951", "0.5678094", "0.566814", "0.5657499", "0.56555206", "0.5642589", "0.56219065", "0.5615893", "0.56105876", "0.559851", "0.5598089", "0.55940455", "0.5585137", "0.55848545", "0.55796933", "0.5571477", "0.5567006", "0.55667996", "0.55652434", "0.5562926", "0.55600035", "0.55590326", "0.55590326", "0.5554599", "0.5554599", "0.55407417", "0.5534935", "0.5527733", "0.55271375", "0.55238813", "0.5501504", "0.5497003", "0.5496233", "0.54927665", "0.5464706", "0.54617554", "0.5461167", "0.5451583", "0.54498726", "0.54498726", "0.54359984", "0.5430996", "0.5430996", "0.5426488", "0.5418467", "0.54153895", "0.54107565", "0.5407886", "0.5401234", "0.54008496", "0.5400268", "0.53910094", "0.53827274", "0.5377731", "0.5375473", "0.5374833", "0.53720397", "0.5370215", "0.5363264", "0.5361161", "0.5360557", "0.5351706", "0.53514725", "0.53492516", "0.53459316", "0.5341237", "0.5328037", "0.5328037", "0.53230566", "0.53230566", "0.53230566", "0.5319575", "0.531832", "0.5315559", "0.5315559" ]
0.0
-1
Custom attribute writer method with validation
def udp_single=(udp_single) if udp_single.nil? fail ArgumentError, 'udp_single cannot be nil' end if udp_single > 4320000 fail ArgumentError, 'invalid value for "udp_single", must be smaller than or equal to 4320000.' end if udp_single < 10 fail ArgumentError, 'invalid value for "udp_single", must be greater than or equal to 10.' end @udp_single = udp_single end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def attr_writer_tag(text); end", "def allowed_attributes=(_arg0); end", "def allowed_attributes=(_arg0); end", "def writer(*args)\n attr_writer(*args)\n args\n end", "def define_write_method(attr_name)\n evaluate_attribute_method attr_name, \"def #{attr_name}=(new_value);write_attribute('#{attr_name}', new_value);end\", \"#{attr_name}=\"\n end", "def attr_writer(*vars)\n # avoid tracking attributes that are added by the class_attribute\n # as these are class attributes and not instance attributes.\n tracked_vars = vars.reject {|var| respond_to? var }\n add_tracked_attrs(false, true, *tracked_vars)\n vars.extract_options!\n super\n end", "def attr_writer(sym, *more) end", "def is_attribute?; end", "def validate_exclusion_of(attr); end", "def register_attributes\n raise \"Not implemented in #{self.class}\"\n end", "def method_missing(method_name, *args)\n return super unless permitted_attributes.include?(method_name)\n begin\n object.send(:\"#{method_name}=\", args.first)\n rescue => e\n if params.has_key?(method_name)\n message = \"Unable to process value for :#{method_name}, no attribute writer. Be sure to override the automatic setters for all params that do not map straight to a model attribute.\"\n Rails.logger.warn({message: message,\n missing_writer: method_name,\n value: args.first,\n error: e})\n self.errors << {status: 422, message: message}\n else\n raise e\n end\n end\n end", "def timeliness_validation_for(attr_names, type)\n super\n attr_names.each { |attr_name| define_timeliness_write_method(attr_name) }\n end", "def create_setter_for(attribute, options)\n setter_method = \"#{attribute}=\"\n\n define_method setter_method do |value|\n if options[:allow_blank] || value != \"\"\n write_attribute(attribute, value)\n end\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each {|attr_name| attr_internal_define(attr_name, :writer)}\n end", "def escape_attr input\n escape input, attr_regexp, attr_mapping\n end", "def make_writer( attrtype )\n\t\tself.log.debug \"Generating an attribute writer for %p\" % [ attrtype ]\n\t\tattrname = attrtype.name\n\t\tif attrtype.single?\n\t\t\tself.log.debug \" attribute is SINGLE, so generating a scalar writer...\"\n\t\t\treturn lambda {|newvalue| self[attrname] = newvalue }\n\t\telse\n\t\t\tself.log.debug \" attribute isn't SINGLE, so generating an array writer...\"\n\t\t\treturn lambda {|*newvalues| self[attrname] = newvalues.flatten }\n\t\tend\n\tend", "def write_attribute(name, value)\n # Simply check if the accessor is allowed to write the field\n # (if so, go to superclass and do it)\n @bypass_auth ||= false\n if allowed_to_write(name) || @bypass_auth\n super(name, value)\n end\n end", "def mattr_writer(*syms, &proc)\n receiver = self\n options = syms.extract_options!\n syms.each do |sym|\n raise NameError.new('invalid attribute name') unless sym =~ /^[_A-Za-z]\\w*$/\n class_exec do\n define_singleton_method \"#{sym}=\" do |obj|\n class_variable_set(\"@@#{sym}\", obj)\n end\n end\n\n unless options[:instance_writer] == false || options[:instance_accessor] == false\n class_exec do\n define_method \"#{sym}=\" do |obj|\n receiver.class_variable_set(\"@@#{sym}\", obj)\n end\n end\n end\n send(\"#{sym}=\", proc.call) if proc\n end\n end", "def write_attribute(attribute, value)\n false\n end", "def add_attribute attribute\n return attribute unless @document_self\n\n # mainly to check for redefinition of an attribute as a method\n # TODO find a policy for 'attr_reader :foo' + 'def foo=()'\n register = false\n\n key = nil\n\n if attribute.rw.index 'R' then\n key = attribute.pretty_name\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name + '='] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if attribute.rw.index 'W' then\n key = attribute.pretty_name + '='\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if register then\n attribute.visibility = @visibility\n add_to @attributes, attribute\n resolve_aliases attribute\n end\n\n attribute\n end", "def define_writer_method(mod)\n writer_method_name = \"#{name}=\"\n attribute = self\n\n mod.send(:define_method, writer_method_name) { |value| attribute.set(self, value) }\n mod.send(writer_visibility, writer_method_name)\n\n self\n end", "def allowed_to_write(name)\n # no point allowing attribute writes if we can't save them?\n if allowed_to_save\n name = name.to_s\n validation_methods = self.class.write_validations(name) \n if validation_methods.nil?\n # We haven't registered any filters on this attribute, so allow the write.\n true\n elsif validation_methods.check :accessor => accessor, :model => self\n # One of the authentication methods worked, so allow the write.\n true\n else\n # We had filters but none of them passed. Disallow write.\n false\n end\n else\n false\n end\n end", "def assert_attr_writer(obj, method)\n assert_respond_to obj, \"#{method}=\"\nend", "def add_attribute(name, &block); end", "def authenticates_writes_to(attr, options={})\n authenticates_access\n @write_validation_map ||= {}\n @write_validation_map[attr.to_s] ||= AuthMethodList.new\n @write_validation_map[attr.to_s].add_method(options)\n end", "def write_attribute_3(param1, param2)\n\twrite_attribute(param1, param2)\n end", "def write_attribute(attr_name, value) #:doc:\n @attributes[attr_name] = empty_string_for_number_column?(attr_name, value) ? nil : value\n end", "def add_writer_tags(klass, new_method, member)\n member_tag = member_tag_for_member(klass, member, :write)\n return_type = return_type_from_tag(member_tag)\n setter_doc_text = member_tag ? member_tag.text : \"Sets the attribute #{member}\"\n new_method.docstring.replace(setter_doc_text)\n new_method.add_tag YARD::Tags::Tag.new(:param, \"the value to set the attribute #{member} to.\", return_type, \"value\")\n new_method.add_tag YARD::Tags::Tag.new(:return, \"the newly set value\", return_type)\n end", "def print_attribute(*) end", "def attribute(name); end", "def add_checked_attribute(clazz, attribute)\r\n eval <<END\r\n class #{clazz}\r\n\r\n def #{attribute}=(value)\r\n raise 'Invalid attribute' unless value\r\n @#{attribute}=value\r\n end\r\n\r\n def #{attribute}\r\n #{attribute}\r\n end\r\n end\r\nEND\r\nend", "def attr(name); end", "def is_attribute?(line)\n (line =~ /(\\s+)attr_(writer|reader|accessor)\\s+:[a-zA-Z_0-9]+/) == 0\n end", "def attribute(name, value)\n\t if !@inStartTag\n\t\traise WriterError.new('attribute outside of tag start')\n\t end\n\t @io << \" #{name}=\\\"#{NQXML.encode(value.to_s)}\\\"\"\n\tend", "def set_attribute(name, value); end", "def dataset_writer(*attributes)\n attributes.flatten.each do |attr_name|\n next if method_defined?(\"#{attr_name}=\")\n\n class_eval <<-RUBY, __FILE__, __LINE__ + 1\n def #{attr_name}=(value)\n dataset_set(:#{attr_name}, value)\n end\n RUBY\n end\n end", "def validated_attribute_names(params); end", "def require_format_of(attribute)\r\n RequireFormatOf.new(attribute)\r\n end", "def attr_writer(*fields)\n check_fields(fields)\n added_fields = jiak.data.writable(*fields)\n added_fields.each do |field|\n class_eval <<-EOM\n def #{field}=(val)\n @jiak.object.data.#{field} = val\n self.class.do_auto_update(self)\n end\n EOM\n end\n nil\n end", "def html_attr(*attrs)\n options = attrs.extract_options!.reverse_merge({\n :level => :super_relaxed\n })\n attrs.each do |att|\n class_eval \"def #{att}=(val); self[:#{att}] = sanitize(val, :#{options[:level]}); end\"\n end\n end", "def validate_attributes=(new_attribute)\n @validate_attributes = new_attribute\n end", "def html_attributes(attr); end", "def instance_write(attr, value)\n setter = :\"#{@name_string}_#{attr}=\"\n instance.send(setter, value) if instance.respond_to?(setter)\n end", "def valid_xml_attribute(name, options={:level => :warning})\n\t\t\t\tvalidate(\"Invalid XML attribute '#{name}'\", options) { name.to_s.match(/^([^[:punct:]0-9<>]|_)[^<>\"']*/) }\n\t\t\tend", "def attr_writer(*args)\n sym_args=args_to_sym(args)\n sym_args.each do |value|\n self.instance_eval(\"def #{value}=(arg); @#{value}=arg;end;\")\n end\n \n end", "def define_writer_method(attribute, method_name, visibility)\n define_method(method_name) { |value| attribute.set(self, value) }\n send(visibility, method_name)\n self\n end", "def write_attribute(name, val)\n if @embedded_models.include? name\n @embedded_models[name].model = val\n elsif @attribute_objects.include? name\n @attribute_objects[name].value = val\n else\n return false\n end\n\n run_callbacks :attribute_change\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def attr; end", "def attribute(*args)\n define_expressions(Attribute, args)\n end", "def write_attribute(name, value)\n name = name.to_s\n\n # The attribute already has an unsaved change.\n if attribute_changed?(name)\n old = changed_attributes[name]\n changed_attributes.delete(name) unless field_changed?(name, old, value)\n else\n attribute_will_change(name) if field_changed?(name, old, value)\n end\n\n # Carry on.\n super(name, value)\n end", "def define_magic_attr(name)\n define_method name do |*attrs|\n raise ArgumentError.new(\"wrong number of arguments\") if attrs.size > 1\n send(\"#{name}=\", attrs.first) if attrs.size == 1\n instance_variable_get(\"@#{name}\")\n end\n\n attr_writer name\n end", "def configurable_writer(attribute, code=nil, &block)\n if block_given? and not code\n Halcyon.class.send(:define_method, :\"#{attribute}=\", block)\n elsif code and not block_given?\n Halcyon.class.send(:eval, <<-\"end;\")\n def #{attribute.to_s}=(value)\n #{code % [attribute.to_sym.inspect]}\n end\n end;\n else\n raise ArgumentError.new(\"Either a block or a code string should be supplied.\")\n end\n end", "def method_missing(name, *args, &block)\n if /\\Ahas_validated_(?<type>\\w*)_attribute\\Z/ =~ name\n has_validated_attribute(type, *args, &block)\n else\n super\n end\n end", "def add_checked_attribute(klass, attribute)\n klass.class_eval do\n define_method attribute do\n instance_variable_get(\"@#{attribute}\")\n end\n\n define_method \"#{attribute}=\" do |value|\n raise 'Invalid attribute' unless value\n \n instance_variable_set(\"@#{attribute}\", value)\n end\n end\nend", "def method_missing(meth, *args, &blk)\n match = meth.to_s.match(/^([a-zA-Z\\_]+)(=|$)$/)\n if match\n attribute, setter = match[1], !match[2].blank?\n if setter\n write_attribute(attribute, args.first)\n else\n read_attribute(attribute)\n end\n else\n super(meth, *args, &blk)\n end\n end", "def valid_attributes\n { name: 'do this' }\n end", "def make_attributes_definitions_or_croak(attrArgs, &attrBlok)\n eye = :'m_attrs_defs'\n\n # Work with attribute as strings\n \n $DEBUG && logger_me(eye, logger_fmt_kls(:attrArgs => attrArgs, :attrBlok => attrBlok))\n\n mustbe_attributes_specification_or_croak(attrArgs, eye, \"attrArgs not attributes_specification\")\n \n #STOPATTRARGSINSUPER\n \n #attrAll = mustbe_not_empty_or_croak(mustbe_array_key_or_nil_or_croak(attrArgs, :all, eye, \"all attributes not array\"), eye, \"all attributes is empty\").map(&:to_s)\n attrAll = mustbe_not_empty_or_croak(mustbe_attributes_specification_all_key_or_croak(attrArgs, :all, eye), eye, \"all attributes is empty\").map(&:to_s)\n \n\n #puts(\"\\n\\n\\nATTR ALL >#{attrAll}<\")\n\n #STOPMAKEATTRSPECSENTRY\n\n attrInc = mustbe_attributes_specification_include_key_or_nil_or_croak(attrArgs, :include, eye) # mustbe all strings\n #puts(\"ATTR INC >#{attrInc.class}< >#{attrInc}< >#{is_value_not_empty?(attrInc)}<\")\n attrInc && mustbe_not_empty_or_croak(attrInc, eye, \"include attributes is empty\")\n\n attrExc = mustbe_attributes_specification_exclude_key_or_nil_or_croak(attrArgs, :exclude, eye) || []\n \n attrMapNom = mustbe_attributes_definitions_key_or_nil_or_croak(attrArgs, :definitions, eye) || {}\n attrMap = attrMapNom && potrubi_util_map_hash_kv(attrMapNom) {|k,v| [k.to_s, v]} # keys all strings\n\n # Ensure all consistent\n \n attrInc && mustbe_subset_or_croak(attrInc, attrAll, eye, \"include attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrExc, attrAll, eye, \"exclude attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrMap.keys, attrAll, eye, \"attribute map contains unknown attributes\")\n \n attrUse = ((attrInc || attrAll) - attrExc).uniq # list of unique attributes to report on\n\n # consolidate \"faked up\" attr specs with ones provided to get the composite attrSpecs\n \n attrDefsNom = potrubi_util_array_to_hash(attrUse).merge(attrMap.select {|k,v| attrUse.include?(k)}) # consolidated \"faked up\" attr specs with ones provided\n\n attrDefs = potrubi_util_map_hash_v(attrDefsNom) do | attrName, attrSpecNom|\n\n attrSpec =\n case attrSpecNom\n when NilClass then {}\n when Hash then\n attrSpecNom.each_with_object({}) do | (verbName, verbSpec), h1 |\n case verbName\n when :pass_thru then h1[:pass_thru] = verbSpec # dont touch; just pass through\n when :event_defaults then # add these to pass_thru\n h1[:pass_thru] = (h1[:pass_thru] || {}).merge(verbName => verbSpec)\n when :map, :select, :metric then\n h1[verbName] = {\n :method_name => \"#{verbName}_#{attrName}_#{rand(1000000)}\", # make a unqiue name\n :method_spec => verbSpec # spec must be valid to dynamic_define_methods\n }\n else\n logic_exception(verbName, eye, \"attrName >#{attrName}< verbName >#{verbName}< value should be impossible\")\n end\n end\n \n else\n logic_exception(attrrSpecNom, eye, \"attrSpecNom value should be impossible\")\n end\n\n attrSpec\n \n end\n \n $DEBUG && logger_mx(eye, logger_fmt_kls(:attrDefs => attrDefs))\n\n mustbe_attributes_definitions_or_croak(attrDefs, eye, \"attrDefs failed contract\")\n\n #STOPMAKEATTRSPECS\n \n end", "def create_writer(klass, member)\n # We want to convert these members into attributes just like\n # as if they were declared using attr_accessor.\n new_meth = register MethodObject.new(klass, \"#{member}=\", :instance) do |o|\n o.parameters = [['value', nil]]\n o.signature ||= \"def #{member}=(value)\"\n o.source ||= \"#{o.signature}\\n @#{member} = value\\nend\"\n end\n add_writer_tags(klass, new_meth, member)\n klass.attributes[:instance][member][:write] = new_meth\n end", "def create_setter!\n @target.class_eval <<-EOS\n #{writer_visibility.to_s}\n def #{name}=(value)\n attribute_set(#{name.inspect}, value)\n end\n EOS\n rescue SyntaxError\n raise SyntaxError.new(column)\n end", "def attribute name, type, conditions= DEFAULT_ATTRIBUTE_CONDITIONS\n RMOF.complete_conditions conditions, DEFAULT_ATTRIBUTE_CONDITIONS\n @attributes= {} unless instance_variable_defined? :@attributes\n @attributes[name]= [name, type, conditions]\n unless method_defined? :__attributes then \n define_method( :__attributes) do \n @attributes\n end \n end\n at= \"@#{name}\".to_sym\n getter= \"#{name}\".to_sym\n setter= \"#{name}=\".to_sym\n completion= \"__complete_#{name}\".to_sym\n define_method( getter) do\n if instance_variable_defined? at then instance_variable_get at\n else conditions[:default]\n end\n end\n define_method( setter) do |val|\n instance_variable_set at, val\n end\n define_method( completion) do\n RMOF.validate( self.send(getter), name, type, conditions)\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def create_setter(name, meth)\n define_method(\"#{meth}=\") do |value|\n write_attribute(name, value)\n end\n end", "def sanitized_allowed_attributes=(attributes); end", "def sanitized_allowed_attributes=(attributes); end", "def oattr(name, type)\n case type\n when :custom\n # Do nothing, just register attr below.\n when :writer\n attr_writer name\n else\n raise ArgumentError, \"Unknown type: #{type.inspect}\"\n end\n\n # Register and return.\n name.tap { oattrs << name}\n end", "def valid_attributes\n { name: \"Expert\" }\n end", "def attributes(*method_names, **options)\n add_attributes(method_names, **options, strategy: :write_value_using_method_strategy)\n end", "def []=(attr_name, value)\n writer_method = \"#{attr_name}=\"\n send(writer_method, value) if respond_to?(writer_method)\n end", "def write_extended_attributes(attrs)\n attrs.each do |k, val|\n self.send((k.to_s + \"=\").to_sym, val) if is_flex_attribute?(k)\n end\n self\n end", "def valid_attributes\n { \"username\" => \"MyString\" }\n end", "def cattr_writer(*fields)\n metaclass.send :attr_writer, *fields\n end", "def write_attribute(attr, value)\n if attribute_encrypted?(attr)\n conductor_for(attr).encrypt(value)\n else\n super(attr, value)\n end\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_number_value(\"offsetInDays\", @offset_in_days)\n writer.write_enum_value(\"timeBasedAttribute\", @time_based_attribute)\n end", "def define_attribute_method(attr_name, _owner: generated_attribute_methods)\n CodeGenerator.batch(_owner, __FILE__, __LINE__) do |owner|\n attribute_method_matchers.each do |matcher|\n method_name = matcher.method_name(attr_name)\n\n unless instance_method_already_implemented?(method_name)\n generate_method = \"define_method_#{matcher.target}\"\n\n if respond_to?(generate_method, true)\n send(generate_method, attr_name.to_s, owner: owner)\n else\n define_proxy_call true, owner, method_name, matcher.target, attr_name.to_s\n end\n end\n end\n attribute_method_matchers_cache.clear\n end\n end", "def has_attributes?; end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_boolean_value(\"isExpirationRequired\", @is_expiration_required)\n writer.write_duration_value(\"maximumDuration\", @maximum_duration)\n end", "def add_attributes(item)\n [:class, :instance].each do |attr_loc|\n # Grab attributes for the current location (class or instance)\n attrs = item.attributes[attr_loc]\n attrs.each do |name, attribute|\n reader = attribute[:read]\n writer = attribute[:write]\n\n unless reader || writer\n Logging.warn(\"attribute is not readable or writable somehow, skipping\", attribute)\n next\n end\n\n # Get all given types\n yard_types = []\n if reader\n next if @hide_private && reader.visibility == :private\n yard_types += reader.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n reader.tags('param').flat_map(&:types)\n end\n if writer\n next if @hide_private && writer.visibility == :private\n yard_types += writer.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n writer.tags('param').flat_map(&:types)\n end\n\n # Use untyped if not types specified anywhere, otherwise try to\n # compute Parlour type given all these types\n if yard_types.empty?\n Logging.omit(\"no YARD type given for #{name.inspect}, using untyped\", reader || writer)\n parlour_type = Parlour::Types::Untyped.new\n elsif yard_types.all? { |x| x == 'nil' }\n # Nil attributes are extremely unusual, so just use untyped\n parlour_type = Parlour::Types::Untyped.new\n else\n parlour_type = TypeConverter.yard_to_parlour(\n yard_types, reader || writer, @type_converter_config)\n end\n\n # Generate attribute\n if reader && writer\n kind = :accessor\n elsif reader\n kind = :reader\n elsif writer\n kind = :writer\n end\n\n if @exclude_untyped && parlour_type.is_a?(Parlour::Types::Untyped)\n Logging.omit(\"excluding untyped attribute\", reader || writer, immediate: true)\n next\n end\n\n case @mode\n when :rbi\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n class_attribute: (attr_loc == :class)\n ) do |m|\n add_comments(reader || writer, m)\n end\n when :rbs\n if attr_loc == :class\n # RBS doesn't support class attr_accessors so create individual methods\n\n if reader\n @current_object.create_method(\n name.to_s,\n [Parlour::RbsGenerator::MethodSignature.new([], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(reader, m)\n end\n end\n\n if writer\n @current_object.create_method(\n \"#{name}=\",\n [Parlour::RbsGenerator::MethodSignature.new([Parlour::RbsGenerator::Parameter.new(\n \"value\",\n type: parlour_type,\n required: true\n )], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(writer, m)\n end\n end\n else\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n ) do |m|\n add_comments(reader || writer, m)\n end\n end\n end\n end\n end\n end", "def []=(attr_name, value)\r\n if attr_name.is_a?(String) and attr_name != attr_name.split(ID_SEP).first\r\n attr_name = attr_name.split(ID_SEP)\r\n end\r\n\r\n if attr_name.is_a? Array\r\n value = value.split(ID_SEP) if value.is_a? String\r\n unless value.length == attr_name.length\r\n raise \"Number of attr_names and values do not match\"\r\n end\r\n #breakpoint\r\n [attr_name, value].transpose.map {|name,val| write_attribute(name.to_s, val)}\r\n else\r\n write_attribute(attr_name, value)\r\n end\r\n end", "def attr(symbol, writable=false) end", "def define_writer!(k, definition)\n define_method(\"#{k}=\") do |value|\n # Recursively convert hash and array of hash to schematized objects\n value = ensure_schema value, definition[:schema]\n\n # Initial value\n instance_variable_set \"@#{k}\", value\n\n # Dirty tracking\n self.changed_attributes ||= Set.new\n self.changed_attributes << k\n end\n end", "def validate\n validate_string_attributes\n end", "def write_attribute_with_dynamo(field_name, value)\n if is_dynamo_field?(field_name)\n # Store these guys for now. We don't actually save the field value until the model is saved ( i.e my_supplier.save ).\n # If we were to save the field_value now we wouldn't be able to know the id of the model to link this value to it.\n # @see delay_save\n @all_fields_and_values ||= []\n @all_fields_and_values << {:dynamo_field=>cached_dynamo_field_by_name(field_name), :value=>value}\n end\n # If its a 'normal' attribute let rails write it in the usual way.\n write_attribute_without_dynamo(field_name, value)\n end", "def define_attr_accessor(attr)\n attr_accessor(attr)\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n writer.write_collection_of_object_values(\"attributeMappings\", @attribute_mappings)\n writer.write_boolean_value(\"enabled\", @enabled)\n writer.write_enum_value(\"flowTypes\", @flow_types)\n writer.write_collection_of_object_values(\"metadata\", @metadata)\n writer.write_string_value(\"name\", @name)\n writer.write_string_value(\"@odata.type\", @odata_type)\n writer.write_object_value(\"scope\", @scope)\n writer.write_string_value(\"sourceObjectName\", @source_object_name)\n writer.write_string_value(\"targetObjectName\", @target_object_name)\n writer.write_additional_data(@additional_data)\n end", "def validate_attribute_syntax\n\t\t@values.each do |attribute, values|\n\t\t\t[ values ].flatten.each do |value|\n\t\t\t\tbegin\n\t\t\t\t\tself.get_converted_attribute( attribute.to_sym, value )\n\t\t\t\trescue => err\n\t\t\t\t\tself.log.error \"validation for %p failed: %s: %s\" %\n\t\t\t\t\t\t[ attribute, err.class.name, err.message ]\n\t\t\t\t\tattrtype = self.find_attribute_type( attribute )\n\t\t\t\t\tself.errors.add( attribute, \"isn't a valid %s value\" %\n\t\t\t\t\t\t[ attrtype.syntax ? attrtype.syntax.desc : attrtype.syntax_oid ] )\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def valid_attributes\n { }\n end", "def validatable_attributes(atts, opts)\n am, an, ab, m = opts.values_at(:allow_missing, :allow_nil, :allow_blank, :message)\n Array(atts).each do |a|\n next if am && !values.has_key?(a)\n v = send(a)\n next if an && v.nil?\n next if ab && v.respond_to?(:blank?) && v.blank?\n if message = yield(a, v, m)\n errors.add(a, message)\n end\n end\n end", "def valid_attributes\n { }\n end", "def valid_attributes\n { }\n end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def require_attr(name)\n send(name).tap do |_|\n raise \"Attribute must be set: #{name}\" if _.nil?\n end\n end", "def write_attributes(attributes)\n _attributes = attributes.select do |name, value|\n if self.is_dynamic_field?(name)\n self.dynamic_setter(name, value)\n false\n else\n true\n end\n end\n\n super(_attributes)\n end", "def attribute; end", "def attribute; end" ]
[ "0.6472992", "0.6315012", "0.6315012", "0.62821025", "0.6279224", "0.6211609", "0.61891466", "0.6182247", "0.60683644", "0.6032628", "0.5995443", "0.5988785", "0.5959885", "0.5938289", "0.5931089", "0.58951056", "0.5859927", "0.5851703", "0.58493423", "0.58465594", "0.58328366", "0.5823013", "0.5822229", "0.57850474", "0.5701491", "0.5696689", "0.5682951", "0.5678094", "0.566814", "0.5657499", "0.56555206", "0.5642589", "0.56219065", "0.5615893", "0.56105876", "0.559851", "0.5598089", "0.55940455", "0.5585137", "0.55848545", "0.55796933", "0.5571477", "0.5567006", "0.55667996", "0.55652434", "0.5562926", "0.55600035", "0.55590326", "0.55590326", "0.5554599", "0.5554599", "0.55407417", "0.5534935", "0.5527733", "0.55271375", "0.55238813", "0.5501504", "0.5497003", "0.5496233", "0.54927665", "0.5464706", "0.54617554", "0.5461167", "0.5451583", "0.54498726", "0.54498726", "0.54359984", "0.5430996", "0.5430996", "0.5426488", "0.5418467", "0.54153895", "0.54107565", "0.5407886", "0.5401234", "0.54008496", "0.5400268", "0.53910094", "0.53827274", "0.5377731", "0.5375473", "0.5374833", "0.53720397", "0.5370215", "0.5363264", "0.5361161", "0.5360557", "0.5351706", "0.53514725", "0.53492516", "0.53459316", "0.5341237", "0.5328037", "0.5328037", "0.53230566", "0.53230566", "0.53230566", "0.5319575", "0.531832", "0.5315559", "0.5315559" ]
0.0
-1
Custom attribute writer method with validation
def tcp_finwait=(tcp_finwait) if tcp_finwait.nil? fail ArgumentError, 'tcp_finwait cannot be nil' end if tcp_finwait > 4320000 fail ArgumentError, 'invalid value for "tcp_finwait", must be smaller than or equal to 4320000.' end if tcp_finwait < 10 fail ArgumentError, 'invalid value for "tcp_finwait", must be greater than or equal to 10.' end @tcp_finwait = tcp_finwait end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def attr_writer_tag(text); end", "def allowed_attributes=(_arg0); end", "def allowed_attributes=(_arg0); end", "def writer(*args)\n attr_writer(*args)\n args\n end", "def define_write_method(attr_name)\n evaluate_attribute_method attr_name, \"def #{attr_name}=(new_value);write_attribute('#{attr_name}', new_value);end\", \"#{attr_name}=\"\n end", "def attr_writer(*vars)\n # avoid tracking attributes that are added by the class_attribute\n # as these are class attributes and not instance attributes.\n tracked_vars = vars.reject {|var| respond_to? var }\n add_tracked_attrs(false, true, *tracked_vars)\n vars.extract_options!\n super\n end", "def attr_writer(sym, *more) end", "def is_attribute?; end", "def validate_exclusion_of(attr); end", "def register_attributes\n raise \"Not implemented in #{self.class}\"\n end", "def method_missing(method_name, *args)\n return super unless permitted_attributes.include?(method_name)\n begin\n object.send(:\"#{method_name}=\", args.first)\n rescue => e\n if params.has_key?(method_name)\n message = \"Unable to process value for :#{method_name}, no attribute writer. Be sure to override the automatic setters for all params that do not map straight to a model attribute.\"\n Rails.logger.warn({message: message,\n missing_writer: method_name,\n value: args.first,\n error: e})\n self.errors << {status: 422, message: message}\n else\n raise e\n end\n end\n end", "def timeliness_validation_for(attr_names, type)\n super\n attr_names.each { |attr_name| define_timeliness_write_method(attr_name) }\n end", "def create_setter_for(attribute, options)\n setter_method = \"#{attribute}=\"\n\n define_method setter_method do |value|\n if options[:allow_blank] || value != \"\"\n write_attribute(attribute, value)\n end\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each {|attr_name| attr_internal_define(attr_name, :writer)}\n end", "def escape_attr input\n escape input, attr_regexp, attr_mapping\n end", "def make_writer( attrtype )\n\t\tself.log.debug \"Generating an attribute writer for %p\" % [ attrtype ]\n\t\tattrname = attrtype.name\n\t\tif attrtype.single?\n\t\t\tself.log.debug \" attribute is SINGLE, so generating a scalar writer...\"\n\t\t\treturn lambda {|newvalue| self[attrname] = newvalue }\n\t\telse\n\t\t\tself.log.debug \" attribute isn't SINGLE, so generating an array writer...\"\n\t\t\treturn lambda {|*newvalues| self[attrname] = newvalues.flatten }\n\t\tend\n\tend", "def write_attribute(name, value)\n # Simply check if the accessor is allowed to write the field\n # (if so, go to superclass and do it)\n @bypass_auth ||= false\n if allowed_to_write(name) || @bypass_auth\n super(name, value)\n end\n end", "def mattr_writer(*syms, &proc)\n receiver = self\n options = syms.extract_options!\n syms.each do |sym|\n raise NameError.new('invalid attribute name') unless sym =~ /^[_A-Za-z]\\w*$/\n class_exec do\n define_singleton_method \"#{sym}=\" do |obj|\n class_variable_set(\"@@#{sym}\", obj)\n end\n end\n\n unless options[:instance_writer] == false || options[:instance_accessor] == false\n class_exec do\n define_method \"#{sym}=\" do |obj|\n receiver.class_variable_set(\"@@#{sym}\", obj)\n end\n end\n end\n send(\"#{sym}=\", proc.call) if proc\n end\n end", "def write_attribute(attribute, value)\n false\n end", "def add_attribute attribute\n return attribute unless @document_self\n\n # mainly to check for redefinition of an attribute as a method\n # TODO find a policy for 'attr_reader :foo' + 'def foo=()'\n register = false\n\n key = nil\n\n if attribute.rw.index 'R' then\n key = attribute.pretty_name\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name + '='] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if attribute.rw.index 'W' then\n key = attribute.pretty_name + '='\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if register then\n attribute.visibility = @visibility\n add_to @attributes, attribute\n resolve_aliases attribute\n end\n\n attribute\n end", "def define_writer_method(mod)\n writer_method_name = \"#{name}=\"\n attribute = self\n\n mod.send(:define_method, writer_method_name) { |value| attribute.set(self, value) }\n mod.send(writer_visibility, writer_method_name)\n\n self\n end", "def allowed_to_write(name)\n # no point allowing attribute writes if we can't save them?\n if allowed_to_save\n name = name.to_s\n validation_methods = self.class.write_validations(name) \n if validation_methods.nil?\n # We haven't registered any filters on this attribute, so allow the write.\n true\n elsif validation_methods.check :accessor => accessor, :model => self\n # One of the authentication methods worked, so allow the write.\n true\n else\n # We had filters but none of them passed. Disallow write.\n false\n end\n else\n false\n end\n end", "def assert_attr_writer(obj, method)\n assert_respond_to obj, \"#{method}=\"\nend", "def add_attribute(name, &block); end", "def authenticates_writes_to(attr, options={})\n authenticates_access\n @write_validation_map ||= {}\n @write_validation_map[attr.to_s] ||= AuthMethodList.new\n @write_validation_map[attr.to_s].add_method(options)\n end", "def write_attribute_3(param1, param2)\n\twrite_attribute(param1, param2)\n end", "def write_attribute(attr_name, value) #:doc:\n @attributes[attr_name] = empty_string_for_number_column?(attr_name, value) ? nil : value\n end", "def add_writer_tags(klass, new_method, member)\n member_tag = member_tag_for_member(klass, member, :write)\n return_type = return_type_from_tag(member_tag)\n setter_doc_text = member_tag ? member_tag.text : \"Sets the attribute #{member}\"\n new_method.docstring.replace(setter_doc_text)\n new_method.add_tag YARD::Tags::Tag.new(:param, \"the value to set the attribute #{member} to.\", return_type, \"value\")\n new_method.add_tag YARD::Tags::Tag.new(:return, \"the newly set value\", return_type)\n end", "def print_attribute(*) end", "def attribute(name); end", "def add_checked_attribute(clazz, attribute)\r\n eval <<END\r\n class #{clazz}\r\n\r\n def #{attribute}=(value)\r\n raise 'Invalid attribute' unless value\r\n @#{attribute}=value\r\n end\r\n\r\n def #{attribute}\r\n #{attribute}\r\n end\r\n end\r\nEND\r\nend", "def attr(name); end", "def is_attribute?(line)\n (line =~ /(\\s+)attr_(writer|reader|accessor)\\s+:[a-zA-Z_0-9]+/) == 0\n end", "def attribute(name, value)\n\t if !@inStartTag\n\t\traise WriterError.new('attribute outside of tag start')\n\t end\n\t @io << \" #{name}=\\\"#{NQXML.encode(value.to_s)}\\\"\"\n\tend", "def set_attribute(name, value); end", "def dataset_writer(*attributes)\n attributes.flatten.each do |attr_name|\n next if method_defined?(\"#{attr_name}=\")\n\n class_eval <<-RUBY, __FILE__, __LINE__ + 1\n def #{attr_name}=(value)\n dataset_set(:#{attr_name}, value)\n end\n RUBY\n end\n end", "def validated_attribute_names(params); end", "def require_format_of(attribute)\r\n RequireFormatOf.new(attribute)\r\n end", "def attr_writer(*fields)\n check_fields(fields)\n added_fields = jiak.data.writable(*fields)\n added_fields.each do |field|\n class_eval <<-EOM\n def #{field}=(val)\n @jiak.object.data.#{field} = val\n self.class.do_auto_update(self)\n end\n EOM\n end\n nil\n end", "def html_attr(*attrs)\n options = attrs.extract_options!.reverse_merge({\n :level => :super_relaxed\n })\n attrs.each do |att|\n class_eval \"def #{att}=(val); self[:#{att}] = sanitize(val, :#{options[:level]}); end\"\n end\n end", "def validate_attributes=(new_attribute)\n @validate_attributes = new_attribute\n end", "def html_attributes(attr); end", "def instance_write(attr, value)\n setter = :\"#{@name_string}_#{attr}=\"\n instance.send(setter, value) if instance.respond_to?(setter)\n end", "def valid_xml_attribute(name, options={:level => :warning})\n\t\t\t\tvalidate(\"Invalid XML attribute '#{name}'\", options) { name.to_s.match(/^([^[:punct:]0-9<>]|_)[^<>\"']*/) }\n\t\t\tend", "def attr_writer(*args)\n sym_args=args_to_sym(args)\n sym_args.each do |value|\n self.instance_eval(\"def #{value}=(arg); @#{value}=arg;end;\")\n end\n \n end", "def define_writer_method(attribute, method_name, visibility)\n define_method(method_name) { |value| attribute.set(self, value) }\n send(visibility, method_name)\n self\n end", "def write_attribute(name, val)\n if @embedded_models.include? name\n @embedded_models[name].model = val\n elsif @attribute_objects.include? name\n @attribute_objects[name].value = val\n else\n return false\n end\n\n run_callbacks :attribute_change\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def attr; end", "def attribute(*args)\n define_expressions(Attribute, args)\n end", "def write_attribute(name, value)\n name = name.to_s\n\n # The attribute already has an unsaved change.\n if attribute_changed?(name)\n old = changed_attributes[name]\n changed_attributes.delete(name) unless field_changed?(name, old, value)\n else\n attribute_will_change(name) if field_changed?(name, old, value)\n end\n\n # Carry on.\n super(name, value)\n end", "def define_magic_attr(name)\n define_method name do |*attrs|\n raise ArgumentError.new(\"wrong number of arguments\") if attrs.size > 1\n send(\"#{name}=\", attrs.first) if attrs.size == 1\n instance_variable_get(\"@#{name}\")\n end\n\n attr_writer name\n end", "def configurable_writer(attribute, code=nil, &block)\n if block_given? and not code\n Halcyon.class.send(:define_method, :\"#{attribute}=\", block)\n elsif code and not block_given?\n Halcyon.class.send(:eval, <<-\"end;\")\n def #{attribute.to_s}=(value)\n #{code % [attribute.to_sym.inspect]}\n end\n end;\n else\n raise ArgumentError.new(\"Either a block or a code string should be supplied.\")\n end\n end", "def method_missing(name, *args, &block)\n if /\\Ahas_validated_(?<type>\\w*)_attribute\\Z/ =~ name\n has_validated_attribute(type, *args, &block)\n else\n super\n end\n end", "def add_checked_attribute(klass, attribute)\n klass.class_eval do\n define_method attribute do\n instance_variable_get(\"@#{attribute}\")\n end\n\n define_method \"#{attribute}=\" do |value|\n raise 'Invalid attribute' unless value\n \n instance_variable_set(\"@#{attribute}\", value)\n end\n end\nend", "def method_missing(meth, *args, &blk)\n match = meth.to_s.match(/^([a-zA-Z\\_]+)(=|$)$/)\n if match\n attribute, setter = match[1], !match[2].blank?\n if setter\n write_attribute(attribute, args.first)\n else\n read_attribute(attribute)\n end\n else\n super(meth, *args, &blk)\n end\n end", "def valid_attributes\n { name: 'do this' }\n end", "def make_attributes_definitions_or_croak(attrArgs, &attrBlok)\n eye = :'m_attrs_defs'\n\n # Work with attribute as strings\n \n $DEBUG && logger_me(eye, logger_fmt_kls(:attrArgs => attrArgs, :attrBlok => attrBlok))\n\n mustbe_attributes_specification_or_croak(attrArgs, eye, \"attrArgs not attributes_specification\")\n \n #STOPATTRARGSINSUPER\n \n #attrAll = mustbe_not_empty_or_croak(mustbe_array_key_or_nil_or_croak(attrArgs, :all, eye, \"all attributes not array\"), eye, \"all attributes is empty\").map(&:to_s)\n attrAll = mustbe_not_empty_or_croak(mustbe_attributes_specification_all_key_or_croak(attrArgs, :all, eye), eye, \"all attributes is empty\").map(&:to_s)\n \n\n #puts(\"\\n\\n\\nATTR ALL >#{attrAll}<\")\n\n #STOPMAKEATTRSPECSENTRY\n\n attrInc = mustbe_attributes_specification_include_key_or_nil_or_croak(attrArgs, :include, eye) # mustbe all strings\n #puts(\"ATTR INC >#{attrInc.class}< >#{attrInc}< >#{is_value_not_empty?(attrInc)}<\")\n attrInc && mustbe_not_empty_or_croak(attrInc, eye, \"include attributes is empty\")\n\n attrExc = mustbe_attributes_specification_exclude_key_or_nil_or_croak(attrArgs, :exclude, eye) || []\n \n attrMapNom = mustbe_attributes_definitions_key_or_nil_or_croak(attrArgs, :definitions, eye) || {}\n attrMap = attrMapNom && potrubi_util_map_hash_kv(attrMapNom) {|k,v| [k.to_s, v]} # keys all strings\n\n # Ensure all consistent\n \n attrInc && mustbe_subset_or_croak(attrInc, attrAll, eye, \"include attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrExc, attrAll, eye, \"exclude attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrMap.keys, attrAll, eye, \"attribute map contains unknown attributes\")\n \n attrUse = ((attrInc || attrAll) - attrExc).uniq # list of unique attributes to report on\n\n # consolidate \"faked up\" attr specs with ones provided to get the composite attrSpecs\n \n attrDefsNom = potrubi_util_array_to_hash(attrUse).merge(attrMap.select {|k,v| attrUse.include?(k)}) # consolidated \"faked up\" attr specs with ones provided\n\n attrDefs = potrubi_util_map_hash_v(attrDefsNom) do | attrName, attrSpecNom|\n\n attrSpec =\n case attrSpecNom\n when NilClass then {}\n when Hash then\n attrSpecNom.each_with_object({}) do | (verbName, verbSpec), h1 |\n case verbName\n when :pass_thru then h1[:pass_thru] = verbSpec # dont touch; just pass through\n when :event_defaults then # add these to pass_thru\n h1[:pass_thru] = (h1[:pass_thru] || {}).merge(verbName => verbSpec)\n when :map, :select, :metric then\n h1[verbName] = {\n :method_name => \"#{verbName}_#{attrName}_#{rand(1000000)}\", # make a unqiue name\n :method_spec => verbSpec # spec must be valid to dynamic_define_methods\n }\n else\n logic_exception(verbName, eye, \"attrName >#{attrName}< verbName >#{verbName}< value should be impossible\")\n end\n end\n \n else\n logic_exception(attrrSpecNom, eye, \"attrSpecNom value should be impossible\")\n end\n\n attrSpec\n \n end\n \n $DEBUG && logger_mx(eye, logger_fmt_kls(:attrDefs => attrDefs))\n\n mustbe_attributes_definitions_or_croak(attrDefs, eye, \"attrDefs failed contract\")\n\n #STOPMAKEATTRSPECS\n \n end", "def create_writer(klass, member)\n # We want to convert these members into attributes just like\n # as if they were declared using attr_accessor.\n new_meth = register MethodObject.new(klass, \"#{member}=\", :instance) do |o|\n o.parameters = [['value', nil]]\n o.signature ||= \"def #{member}=(value)\"\n o.source ||= \"#{o.signature}\\n @#{member} = value\\nend\"\n end\n add_writer_tags(klass, new_meth, member)\n klass.attributes[:instance][member][:write] = new_meth\n end", "def create_setter!\n @target.class_eval <<-EOS\n #{writer_visibility.to_s}\n def #{name}=(value)\n attribute_set(#{name.inspect}, value)\n end\n EOS\n rescue SyntaxError\n raise SyntaxError.new(column)\n end", "def attribute name, type, conditions= DEFAULT_ATTRIBUTE_CONDITIONS\n RMOF.complete_conditions conditions, DEFAULT_ATTRIBUTE_CONDITIONS\n @attributes= {} unless instance_variable_defined? :@attributes\n @attributes[name]= [name, type, conditions]\n unless method_defined? :__attributes then \n define_method( :__attributes) do \n @attributes\n end \n end\n at= \"@#{name}\".to_sym\n getter= \"#{name}\".to_sym\n setter= \"#{name}=\".to_sym\n completion= \"__complete_#{name}\".to_sym\n define_method( getter) do\n if instance_variable_defined? at then instance_variable_get at\n else conditions[:default]\n end\n end\n define_method( setter) do |val|\n instance_variable_set at, val\n end\n define_method( completion) do\n RMOF.validate( self.send(getter), name, type, conditions)\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def create_setter(name, meth)\n define_method(\"#{meth}=\") do |value|\n write_attribute(name, value)\n end\n end", "def sanitized_allowed_attributes=(attributes); end", "def sanitized_allowed_attributes=(attributes); end", "def oattr(name, type)\n case type\n when :custom\n # Do nothing, just register attr below.\n when :writer\n attr_writer name\n else\n raise ArgumentError, \"Unknown type: #{type.inspect}\"\n end\n\n # Register and return.\n name.tap { oattrs << name}\n end", "def valid_attributes\n { name: \"Expert\" }\n end", "def attributes(*method_names, **options)\n add_attributes(method_names, **options, strategy: :write_value_using_method_strategy)\n end", "def []=(attr_name, value)\n writer_method = \"#{attr_name}=\"\n send(writer_method, value) if respond_to?(writer_method)\n end", "def write_extended_attributes(attrs)\n attrs.each do |k, val|\n self.send((k.to_s + \"=\").to_sym, val) if is_flex_attribute?(k)\n end\n self\n end", "def valid_attributes\n { \"username\" => \"MyString\" }\n end", "def cattr_writer(*fields)\n metaclass.send :attr_writer, *fields\n end", "def write_attribute(attr, value)\n if attribute_encrypted?(attr)\n conductor_for(attr).encrypt(value)\n else\n super(attr, value)\n end\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_number_value(\"offsetInDays\", @offset_in_days)\n writer.write_enum_value(\"timeBasedAttribute\", @time_based_attribute)\n end", "def define_attribute_method(attr_name, _owner: generated_attribute_methods)\n CodeGenerator.batch(_owner, __FILE__, __LINE__) do |owner|\n attribute_method_matchers.each do |matcher|\n method_name = matcher.method_name(attr_name)\n\n unless instance_method_already_implemented?(method_name)\n generate_method = \"define_method_#{matcher.target}\"\n\n if respond_to?(generate_method, true)\n send(generate_method, attr_name.to_s, owner: owner)\n else\n define_proxy_call true, owner, method_name, matcher.target, attr_name.to_s\n end\n end\n end\n attribute_method_matchers_cache.clear\n end\n end", "def has_attributes?; end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_boolean_value(\"isExpirationRequired\", @is_expiration_required)\n writer.write_duration_value(\"maximumDuration\", @maximum_duration)\n end", "def add_attributes(item)\n [:class, :instance].each do |attr_loc|\n # Grab attributes for the current location (class or instance)\n attrs = item.attributes[attr_loc]\n attrs.each do |name, attribute|\n reader = attribute[:read]\n writer = attribute[:write]\n\n unless reader || writer\n Logging.warn(\"attribute is not readable or writable somehow, skipping\", attribute)\n next\n end\n\n # Get all given types\n yard_types = []\n if reader\n next if @hide_private && reader.visibility == :private\n yard_types += reader.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n reader.tags('param').flat_map(&:types)\n end\n if writer\n next if @hide_private && writer.visibility == :private\n yard_types += writer.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n writer.tags('param').flat_map(&:types)\n end\n\n # Use untyped if not types specified anywhere, otherwise try to\n # compute Parlour type given all these types\n if yard_types.empty?\n Logging.omit(\"no YARD type given for #{name.inspect}, using untyped\", reader || writer)\n parlour_type = Parlour::Types::Untyped.new\n elsif yard_types.all? { |x| x == 'nil' }\n # Nil attributes are extremely unusual, so just use untyped\n parlour_type = Parlour::Types::Untyped.new\n else\n parlour_type = TypeConverter.yard_to_parlour(\n yard_types, reader || writer, @type_converter_config)\n end\n\n # Generate attribute\n if reader && writer\n kind = :accessor\n elsif reader\n kind = :reader\n elsif writer\n kind = :writer\n end\n\n if @exclude_untyped && parlour_type.is_a?(Parlour::Types::Untyped)\n Logging.omit(\"excluding untyped attribute\", reader || writer, immediate: true)\n next\n end\n\n case @mode\n when :rbi\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n class_attribute: (attr_loc == :class)\n ) do |m|\n add_comments(reader || writer, m)\n end\n when :rbs\n if attr_loc == :class\n # RBS doesn't support class attr_accessors so create individual methods\n\n if reader\n @current_object.create_method(\n name.to_s,\n [Parlour::RbsGenerator::MethodSignature.new([], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(reader, m)\n end\n end\n\n if writer\n @current_object.create_method(\n \"#{name}=\",\n [Parlour::RbsGenerator::MethodSignature.new([Parlour::RbsGenerator::Parameter.new(\n \"value\",\n type: parlour_type,\n required: true\n )], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(writer, m)\n end\n end\n else\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n ) do |m|\n add_comments(reader || writer, m)\n end\n end\n end\n end\n end\n end", "def []=(attr_name, value)\r\n if attr_name.is_a?(String) and attr_name != attr_name.split(ID_SEP).first\r\n attr_name = attr_name.split(ID_SEP)\r\n end\r\n\r\n if attr_name.is_a? Array\r\n value = value.split(ID_SEP) if value.is_a? String\r\n unless value.length == attr_name.length\r\n raise \"Number of attr_names and values do not match\"\r\n end\r\n #breakpoint\r\n [attr_name, value].transpose.map {|name,val| write_attribute(name.to_s, val)}\r\n else\r\n write_attribute(attr_name, value)\r\n end\r\n end", "def attr(symbol, writable=false) end", "def define_writer!(k, definition)\n define_method(\"#{k}=\") do |value|\n # Recursively convert hash and array of hash to schematized objects\n value = ensure_schema value, definition[:schema]\n\n # Initial value\n instance_variable_set \"@#{k}\", value\n\n # Dirty tracking\n self.changed_attributes ||= Set.new\n self.changed_attributes << k\n end\n end", "def validate\n validate_string_attributes\n end", "def write_attribute_with_dynamo(field_name, value)\n if is_dynamo_field?(field_name)\n # Store these guys for now. We don't actually save the field value until the model is saved ( i.e my_supplier.save ).\n # If we were to save the field_value now we wouldn't be able to know the id of the model to link this value to it.\n # @see delay_save\n @all_fields_and_values ||= []\n @all_fields_and_values << {:dynamo_field=>cached_dynamo_field_by_name(field_name), :value=>value}\n end\n # If its a 'normal' attribute let rails write it in the usual way.\n write_attribute_without_dynamo(field_name, value)\n end", "def define_attr_accessor(attr)\n attr_accessor(attr)\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n writer.write_collection_of_object_values(\"attributeMappings\", @attribute_mappings)\n writer.write_boolean_value(\"enabled\", @enabled)\n writer.write_enum_value(\"flowTypes\", @flow_types)\n writer.write_collection_of_object_values(\"metadata\", @metadata)\n writer.write_string_value(\"name\", @name)\n writer.write_string_value(\"@odata.type\", @odata_type)\n writer.write_object_value(\"scope\", @scope)\n writer.write_string_value(\"sourceObjectName\", @source_object_name)\n writer.write_string_value(\"targetObjectName\", @target_object_name)\n writer.write_additional_data(@additional_data)\n end", "def validate_attribute_syntax\n\t\t@values.each do |attribute, values|\n\t\t\t[ values ].flatten.each do |value|\n\t\t\t\tbegin\n\t\t\t\t\tself.get_converted_attribute( attribute.to_sym, value )\n\t\t\t\trescue => err\n\t\t\t\t\tself.log.error \"validation for %p failed: %s: %s\" %\n\t\t\t\t\t\t[ attribute, err.class.name, err.message ]\n\t\t\t\t\tattrtype = self.find_attribute_type( attribute )\n\t\t\t\t\tself.errors.add( attribute, \"isn't a valid %s value\" %\n\t\t\t\t\t\t[ attrtype.syntax ? attrtype.syntax.desc : attrtype.syntax_oid ] )\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def valid_attributes\n { }\n end", "def validatable_attributes(atts, opts)\n am, an, ab, m = opts.values_at(:allow_missing, :allow_nil, :allow_blank, :message)\n Array(atts).each do |a|\n next if am && !values.has_key?(a)\n v = send(a)\n next if an && v.nil?\n next if ab && v.respond_to?(:blank?) && v.blank?\n if message = yield(a, v, m)\n errors.add(a, message)\n end\n end\n end", "def valid_attributes\n { }\n end", "def valid_attributes\n { }\n end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def require_attr(name)\n send(name).tap do |_|\n raise \"Attribute must be set: #{name}\" if _.nil?\n end\n end", "def write_attributes(attributes)\n _attributes = attributes.select do |name, value|\n if self.is_dynamic_field?(name)\n self.dynamic_setter(name, value)\n false\n else\n true\n end\n end\n\n super(_attributes)\n end", "def attribute; end", "def attribute; end" ]
[ "0.6472992", "0.6315012", "0.6315012", "0.62821025", "0.6279224", "0.6211609", "0.61891466", "0.6182247", "0.60683644", "0.6032628", "0.5995443", "0.5988785", "0.5959885", "0.5938289", "0.5931089", "0.58951056", "0.5859927", "0.5851703", "0.58493423", "0.58465594", "0.58328366", "0.5823013", "0.5822229", "0.57850474", "0.5701491", "0.5696689", "0.5682951", "0.5678094", "0.566814", "0.5657499", "0.56555206", "0.5642589", "0.56219065", "0.5615893", "0.56105876", "0.559851", "0.5598089", "0.55940455", "0.5585137", "0.55848545", "0.55796933", "0.5571477", "0.5567006", "0.55667996", "0.55652434", "0.5562926", "0.55600035", "0.55590326", "0.55590326", "0.5554599", "0.5554599", "0.55407417", "0.5534935", "0.5527733", "0.55271375", "0.55238813", "0.5501504", "0.5497003", "0.5496233", "0.54927665", "0.5464706", "0.54617554", "0.5461167", "0.5451583", "0.54498726", "0.54498726", "0.54359984", "0.5430996", "0.5430996", "0.5426488", "0.5418467", "0.54153895", "0.54107565", "0.5407886", "0.5401234", "0.54008496", "0.5400268", "0.53910094", "0.53827274", "0.5377731", "0.5375473", "0.5374833", "0.53720397", "0.5370215", "0.5363264", "0.5361161", "0.5360557", "0.5351706", "0.53514725", "0.53492516", "0.53459316", "0.5341237", "0.5328037", "0.5328037", "0.53230566", "0.53230566", "0.53230566", "0.5319575", "0.531832", "0.5315559", "0.5315559" ]
0.0
-1
Custom attribute writer method with validation
def tcp_first_packet=(tcp_first_packet) if tcp_first_packet.nil? fail ArgumentError, 'tcp_first_packet cannot be nil' end if tcp_first_packet > 4320000 fail ArgumentError, 'invalid value for "tcp_first_packet", must be smaller than or equal to 4320000.' end if tcp_first_packet < 10 fail ArgumentError, 'invalid value for "tcp_first_packet", must be greater than or equal to 10.' end @tcp_first_packet = tcp_first_packet end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def attr_writer_tag(text); end", "def allowed_attributes=(_arg0); end", "def allowed_attributes=(_arg0); end", "def writer(*args)\n attr_writer(*args)\n args\n end", "def define_write_method(attr_name)\n evaluate_attribute_method attr_name, \"def #{attr_name}=(new_value);write_attribute('#{attr_name}', new_value);end\", \"#{attr_name}=\"\n end", "def attr_writer(*vars)\n # avoid tracking attributes that are added by the class_attribute\n # as these are class attributes and not instance attributes.\n tracked_vars = vars.reject {|var| respond_to? var }\n add_tracked_attrs(false, true, *tracked_vars)\n vars.extract_options!\n super\n end", "def attr_writer(sym, *more) end", "def is_attribute?; end", "def validate_exclusion_of(attr); end", "def register_attributes\n raise \"Not implemented in #{self.class}\"\n end", "def method_missing(method_name, *args)\n return super unless permitted_attributes.include?(method_name)\n begin\n object.send(:\"#{method_name}=\", args.first)\n rescue => e\n if params.has_key?(method_name)\n message = \"Unable to process value for :#{method_name}, no attribute writer. Be sure to override the automatic setters for all params that do not map straight to a model attribute.\"\n Rails.logger.warn({message: message,\n missing_writer: method_name,\n value: args.first,\n error: e})\n self.errors << {status: 422, message: message}\n else\n raise e\n end\n end\n end", "def timeliness_validation_for(attr_names, type)\n super\n attr_names.each { |attr_name| define_timeliness_write_method(attr_name) }\n end", "def create_setter_for(attribute, options)\n setter_method = \"#{attribute}=\"\n\n define_method setter_method do |value|\n if options[:allow_blank] || value != \"\"\n write_attribute(attribute, value)\n end\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each {|attr_name| attr_internal_define(attr_name, :writer)}\n end", "def escape_attr input\n escape input, attr_regexp, attr_mapping\n end", "def make_writer( attrtype )\n\t\tself.log.debug \"Generating an attribute writer for %p\" % [ attrtype ]\n\t\tattrname = attrtype.name\n\t\tif attrtype.single?\n\t\t\tself.log.debug \" attribute is SINGLE, so generating a scalar writer...\"\n\t\t\treturn lambda {|newvalue| self[attrname] = newvalue }\n\t\telse\n\t\t\tself.log.debug \" attribute isn't SINGLE, so generating an array writer...\"\n\t\t\treturn lambda {|*newvalues| self[attrname] = newvalues.flatten }\n\t\tend\n\tend", "def write_attribute(name, value)\n # Simply check if the accessor is allowed to write the field\n # (if so, go to superclass and do it)\n @bypass_auth ||= false\n if allowed_to_write(name) || @bypass_auth\n super(name, value)\n end\n end", "def mattr_writer(*syms, &proc)\n receiver = self\n options = syms.extract_options!\n syms.each do |sym|\n raise NameError.new('invalid attribute name') unless sym =~ /^[_A-Za-z]\\w*$/\n class_exec do\n define_singleton_method \"#{sym}=\" do |obj|\n class_variable_set(\"@@#{sym}\", obj)\n end\n end\n\n unless options[:instance_writer] == false || options[:instance_accessor] == false\n class_exec do\n define_method \"#{sym}=\" do |obj|\n receiver.class_variable_set(\"@@#{sym}\", obj)\n end\n end\n end\n send(\"#{sym}=\", proc.call) if proc\n end\n end", "def write_attribute(attribute, value)\n false\n end", "def add_attribute attribute\n return attribute unless @document_self\n\n # mainly to check for redefinition of an attribute as a method\n # TODO find a policy for 'attr_reader :foo' + 'def foo=()'\n register = false\n\n key = nil\n\n if attribute.rw.index 'R' then\n key = attribute.pretty_name\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name + '='] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if attribute.rw.index 'W' then\n key = attribute.pretty_name + '='\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if register then\n attribute.visibility = @visibility\n add_to @attributes, attribute\n resolve_aliases attribute\n end\n\n attribute\n end", "def define_writer_method(mod)\n writer_method_name = \"#{name}=\"\n attribute = self\n\n mod.send(:define_method, writer_method_name) { |value| attribute.set(self, value) }\n mod.send(writer_visibility, writer_method_name)\n\n self\n end", "def allowed_to_write(name)\n # no point allowing attribute writes if we can't save them?\n if allowed_to_save\n name = name.to_s\n validation_methods = self.class.write_validations(name) \n if validation_methods.nil?\n # We haven't registered any filters on this attribute, so allow the write.\n true\n elsif validation_methods.check :accessor => accessor, :model => self\n # One of the authentication methods worked, so allow the write.\n true\n else\n # We had filters but none of them passed. Disallow write.\n false\n end\n else\n false\n end\n end", "def assert_attr_writer(obj, method)\n assert_respond_to obj, \"#{method}=\"\nend", "def add_attribute(name, &block); end", "def authenticates_writes_to(attr, options={})\n authenticates_access\n @write_validation_map ||= {}\n @write_validation_map[attr.to_s] ||= AuthMethodList.new\n @write_validation_map[attr.to_s].add_method(options)\n end", "def write_attribute_3(param1, param2)\n\twrite_attribute(param1, param2)\n end", "def write_attribute(attr_name, value) #:doc:\n @attributes[attr_name] = empty_string_for_number_column?(attr_name, value) ? nil : value\n end", "def add_writer_tags(klass, new_method, member)\n member_tag = member_tag_for_member(klass, member, :write)\n return_type = return_type_from_tag(member_tag)\n setter_doc_text = member_tag ? member_tag.text : \"Sets the attribute #{member}\"\n new_method.docstring.replace(setter_doc_text)\n new_method.add_tag YARD::Tags::Tag.new(:param, \"the value to set the attribute #{member} to.\", return_type, \"value\")\n new_method.add_tag YARD::Tags::Tag.new(:return, \"the newly set value\", return_type)\n end", "def print_attribute(*) end", "def attribute(name); end", "def add_checked_attribute(clazz, attribute)\r\n eval <<END\r\n class #{clazz}\r\n\r\n def #{attribute}=(value)\r\n raise 'Invalid attribute' unless value\r\n @#{attribute}=value\r\n end\r\n\r\n def #{attribute}\r\n #{attribute}\r\n end\r\n end\r\nEND\r\nend", "def attr(name); end", "def is_attribute?(line)\n (line =~ /(\\s+)attr_(writer|reader|accessor)\\s+:[a-zA-Z_0-9]+/) == 0\n end", "def attribute(name, value)\n\t if !@inStartTag\n\t\traise WriterError.new('attribute outside of tag start')\n\t end\n\t @io << \" #{name}=\\\"#{NQXML.encode(value.to_s)}\\\"\"\n\tend", "def set_attribute(name, value); end", "def dataset_writer(*attributes)\n attributes.flatten.each do |attr_name|\n next if method_defined?(\"#{attr_name}=\")\n\n class_eval <<-RUBY, __FILE__, __LINE__ + 1\n def #{attr_name}=(value)\n dataset_set(:#{attr_name}, value)\n end\n RUBY\n end\n end", "def validated_attribute_names(params); end", "def require_format_of(attribute)\r\n RequireFormatOf.new(attribute)\r\n end", "def attr_writer(*fields)\n check_fields(fields)\n added_fields = jiak.data.writable(*fields)\n added_fields.each do |field|\n class_eval <<-EOM\n def #{field}=(val)\n @jiak.object.data.#{field} = val\n self.class.do_auto_update(self)\n end\n EOM\n end\n nil\n end", "def html_attr(*attrs)\n options = attrs.extract_options!.reverse_merge({\n :level => :super_relaxed\n })\n attrs.each do |att|\n class_eval \"def #{att}=(val); self[:#{att}] = sanitize(val, :#{options[:level]}); end\"\n end\n end", "def validate_attributes=(new_attribute)\n @validate_attributes = new_attribute\n end", "def html_attributes(attr); end", "def instance_write(attr, value)\n setter = :\"#{@name_string}_#{attr}=\"\n instance.send(setter, value) if instance.respond_to?(setter)\n end", "def valid_xml_attribute(name, options={:level => :warning})\n\t\t\t\tvalidate(\"Invalid XML attribute '#{name}'\", options) { name.to_s.match(/^([^[:punct:]0-9<>]|_)[^<>\"']*/) }\n\t\t\tend", "def attr_writer(*args)\n sym_args=args_to_sym(args)\n sym_args.each do |value|\n self.instance_eval(\"def #{value}=(arg); @#{value}=arg;end;\")\n end\n \n end", "def define_writer_method(attribute, method_name, visibility)\n define_method(method_name) { |value| attribute.set(self, value) }\n send(visibility, method_name)\n self\n end", "def write_attribute(name, val)\n if @embedded_models.include? name\n @embedded_models[name].model = val\n elsif @attribute_objects.include? name\n @attribute_objects[name].value = val\n else\n return false\n end\n\n run_callbacks :attribute_change\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def attr; end", "def attribute(*args)\n define_expressions(Attribute, args)\n end", "def write_attribute(name, value)\n name = name.to_s\n\n # The attribute already has an unsaved change.\n if attribute_changed?(name)\n old = changed_attributes[name]\n changed_attributes.delete(name) unless field_changed?(name, old, value)\n else\n attribute_will_change(name) if field_changed?(name, old, value)\n end\n\n # Carry on.\n super(name, value)\n end", "def define_magic_attr(name)\n define_method name do |*attrs|\n raise ArgumentError.new(\"wrong number of arguments\") if attrs.size > 1\n send(\"#{name}=\", attrs.first) if attrs.size == 1\n instance_variable_get(\"@#{name}\")\n end\n\n attr_writer name\n end", "def configurable_writer(attribute, code=nil, &block)\n if block_given? and not code\n Halcyon.class.send(:define_method, :\"#{attribute}=\", block)\n elsif code and not block_given?\n Halcyon.class.send(:eval, <<-\"end;\")\n def #{attribute.to_s}=(value)\n #{code % [attribute.to_sym.inspect]}\n end\n end;\n else\n raise ArgumentError.new(\"Either a block or a code string should be supplied.\")\n end\n end", "def method_missing(name, *args, &block)\n if /\\Ahas_validated_(?<type>\\w*)_attribute\\Z/ =~ name\n has_validated_attribute(type, *args, &block)\n else\n super\n end\n end", "def add_checked_attribute(klass, attribute)\n klass.class_eval do\n define_method attribute do\n instance_variable_get(\"@#{attribute}\")\n end\n\n define_method \"#{attribute}=\" do |value|\n raise 'Invalid attribute' unless value\n \n instance_variable_set(\"@#{attribute}\", value)\n end\n end\nend", "def method_missing(meth, *args, &blk)\n match = meth.to_s.match(/^([a-zA-Z\\_]+)(=|$)$/)\n if match\n attribute, setter = match[1], !match[2].blank?\n if setter\n write_attribute(attribute, args.first)\n else\n read_attribute(attribute)\n end\n else\n super(meth, *args, &blk)\n end\n end", "def valid_attributes\n { name: 'do this' }\n end", "def make_attributes_definitions_or_croak(attrArgs, &attrBlok)\n eye = :'m_attrs_defs'\n\n # Work with attribute as strings\n \n $DEBUG && logger_me(eye, logger_fmt_kls(:attrArgs => attrArgs, :attrBlok => attrBlok))\n\n mustbe_attributes_specification_or_croak(attrArgs, eye, \"attrArgs not attributes_specification\")\n \n #STOPATTRARGSINSUPER\n \n #attrAll = mustbe_not_empty_or_croak(mustbe_array_key_or_nil_or_croak(attrArgs, :all, eye, \"all attributes not array\"), eye, \"all attributes is empty\").map(&:to_s)\n attrAll = mustbe_not_empty_or_croak(mustbe_attributes_specification_all_key_or_croak(attrArgs, :all, eye), eye, \"all attributes is empty\").map(&:to_s)\n \n\n #puts(\"\\n\\n\\nATTR ALL >#{attrAll}<\")\n\n #STOPMAKEATTRSPECSENTRY\n\n attrInc = mustbe_attributes_specification_include_key_or_nil_or_croak(attrArgs, :include, eye) # mustbe all strings\n #puts(\"ATTR INC >#{attrInc.class}< >#{attrInc}< >#{is_value_not_empty?(attrInc)}<\")\n attrInc && mustbe_not_empty_or_croak(attrInc, eye, \"include attributes is empty\")\n\n attrExc = mustbe_attributes_specification_exclude_key_or_nil_or_croak(attrArgs, :exclude, eye) || []\n \n attrMapNom = mustbe_attributes_definitions_key_or_nil_or_croak(attrArgs, :definitions, eye) || {}\n attrMap = attrMapNom && potrubi_util_map_hash_kv(attrMapNom) {|k,v| [k.to_s, v]} # keys all strings\n\n # Ensure all consistent\n \n attrInc && mustbe_subset_or_croak(attrInc, attrAll, eye, \"include attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrExc, attrAll, eye, \"exclude attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrMap.keys, attrAll, eye, \"attribute map contains unknown attributes\")\n \n attrUse = ((attrInc || attrAll) - attrExc).uniq # list of unique attributes to report on\n\n # consolidate \"faked up\" attr specs with ones provided to get the composite attrSpecs\n \n attrDefsNom = potrubi_util_array_to_hash(attrUse).merge(attrMap.select {|k,v| attrUse.include?(k)}) # consolidated \"faked up\" attr specs with ones provided\n\n attrDefs = potrubi_util_map_hash_v(attrDefsNom) do | attrName, attrSpecNom|\n\n attrSpec =\n case attrSpecNom\n when NilClass then {}\n when Hash then\n attrSpecNom.each_with_object({}) do | (verbName, verbSpec), h1 |\n case verbName\n when :pass_thru then h1[:pass_thru] = verbSpec # dont touch; just pass through\n when :event_defaults then # add these to pass_thru\n h1[:pass_thru] = (h1[:pass_thru] || {}).merge(verbName => verbSpec)\n when :map, :select, :metric then\n h1[verbName] = {\n :method_name => \"#{verbName}_#{attrName}_#{rand(1000000)}\", # make a unqiue name\n :method_spec => verbSpec # spec must be valid to dynamic_define_methods\n }\n else\n logic_exception(verbName, eye, \"attrName >#{attrName}< verbName >#{verbName}< value should be impossible\")\n end\n end\n \n else\n logic_exception(attrrSpecNom, eye, \"attrSpecNom value should be impossible\")\n end\n\n attrSpec\n \n end\n \n $DEBUG && logger_mx(eye, logger_fmt_kls(:attrDefs => attrDefs))\n\n mustbe_attributes_definitions_or_croak(attrDefs, eye, \"attrDefs failed contract\")\n\n #STOPMAKEATTRSPECS\n \n end", "def create_writer(klass, member)\n # We want to convert these members into attributes just like\n # as if they were declared using attr_accessor.\n new_meth = register MethodObject.new(klass, \"#{member}=\", :instance) do |o|\n o.parameters = [['value', nil]]\n o.signature ||= \"def #{member}=(value)\"\n o.source ||= \"#{o.signature}\\n @#{member} = value\\nend\"\n end\n add_writer_tags(klass, new_meth, member)\n klass.attributes[:instance][member][:write] = new_meth\n end", "def create_setter!\n @target.class_eval <<-EOS\n #{writer_visibility.to_s}\n def #{name}=(value)\n attribute_set(#{name.inspect}, value)\n end\n EOS\n rescue SyntaxError\n raise SyntaxError.new(column)\n end", "def attribute name, type, conditions= DEFAULT_ATTRIBUTE_CONDITIONS\n RMOF.complete_conditions conditions, DEFAULT_ATTRIBUTE_CONDITIONS\n @attributes= {} unless instance_variable_defined? :@attributes\n @attributes[name]= [name, type, conditions]\n unless method_defined? :__attributes then \n define_method( :__attributes) do \n @attributes\n end \n end\n at= \"@#{name}\".to_sym\n getter= \"#{name}\".to_sym\n setter= \"#{name}=\".to_sym\n completion= \"__complete_#{name}\".to_sym\n define_method( getter) do\n if instance_variable_defined? at then instance_variable_get at\n else conditions[:default]\n end\n end\n define_method( setter) do |val|\n instance_variable_set at, val\n end\n define_method( completion) do\n RMOF.validate( self.send(getter), name, type, conditions)\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def create_setter(name, meth)\n define_method(\"#{meth}=\") do |value|\n write_attribute(name, value)\n end\n end", "def sanitized_allowed_attributes=(attributes); end", "def sanitized_allowed_attributes=(attributes); end", "def oattr(name, type)\n case type\n when :custom\n # Do nothing, just register attr below.\n when :writer\n attr_writer name\n else\n raise ArgumentError, \"Unknown type: #{type.inspect}\"\n end\n\n # Register and return.\n name.tap { oattrs << name}\n end", "def valid_attributes\n { name: \"Expert\" }\n end", "def attributes(*method_names, **options)\n add_attributes(method_names, **options, strategy: :write_value_using_method_strategy)\n end", "def []=(attr_name, value)\n writer_method = \"#{attr_name}=\"\n send(writer_method, value) if respond_to?(writer_method)\n end", "def write_extended_attributes(attrs)\n attrs.each do |k, val|\n self.send((k.to_s + \"=\").to_sym, val) if is_flex_attribute?(k)\n end\n self\n end", "def valid_attributes\n { \"username\" => \"MyString\" }\n end", "def cattr_writer(*fields)\n metaclass.send :attr_writer, *fields\n end", "def write_attribute(attr, value)\n if attribute_encrypted?(attr)\n conductor_for(attr).encrypt(value)\n else\n super(attr, value)\n end\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_number_value(\"offsetInDays\", @offset_in_days)\n writer.write_enum_value(\"timeBasedAttribute\", @time_based_attribute)\n end", "def define_attribute_method(attr_name, _owner: generated_attribute_methods)\n CodeGenerator.batch(_owner, __FILE__, __LINE__) do |owner|\n attribute_method_matchers.each do |matcher|\n method_name = matcher.method_name(attr_name)\n\n unless instance_method_already_implemented?(method_name)\n generate_method = \"define_method_#{matcher.target}\"\n\n if respond_to?(generate_method, true)\n send(generate_method, attr_name.to_s, owner: owner)\n else\n define_proxy_call true, owner, method_name, matcher.target, attr_name.to_s\n end\n end\n end\n attribute_method_matchers_cache.clear\n end\n end", "def has_attributes?; end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_boolean_value(\"isExpirationRequired\", @is_expiration_required)\n writer.write_duration_value(\"maximumDuration\", @maximum_duration)\n end", "def add_attributes(item)\n [:class, :instance].each do |attr_loc|\n # Grab attributes for the current location (class or instance)\n attrs = item.attributes[attr_loc]\n attrs.each do |name, attribute|\n reader = attribute[:read]\n writer = attribute[:write]\n\n unless reader || writer\n Logging.warn(\"attribute is not readable or writable somehow, skipping\", attribute)\n next\n end\n\n # Get all given types\n yard_types = []\n if reader\n next if @hide_private && reader.visibility == :private\n yard_types += reader.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n reader.tags('param').flat_map(&:types)\n end\n if writer\n next if @hide_private && writer.visibility == :private\n yard_types += writer.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n writer.tags('param').flat_map(&:types)\n end\n\n # Use untyped if not types specified anywhere, otherwise try to\n # compute Parlour type given all these types\n if yard_types.empty?\n Logging.omit(\"no YARD type given for #{name.inspect}, using untyped\", reader || writer)\n parlour_type = Parlour::Types::Untyped.new\n elsif yard_types.all? { |x| x == 'nil' }\n # Nil attributes are extremely unusual, so just use untyped\n parlour_type = Parlour::Types::Untyped.new\n else\n parlour_type = TypeConverter.yard_to_parlour(\n yard_types, reader || writer, @type_converter_config)\n end\n\n # Generate attribute\n if reader && writer\n kind = :accessor\n elsif reader\n kind = :reader\n elsif writer\n kind = :writer\n end\n\n if @exclude_untyped && parlour_type.is_a?(Parlour::Types::Untyped)\n Logging.omit(\"excluding untyped attribute\", reader || writer, immediate: true)\n next\n end\n\n case @mode\n when :rbi\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n class_attribute: (attr_loc == :class)\n ) do |m|\n add_comments(reader || writer, m)\n end\n when :rbs\n if attr_loc == :class\n # RBS doesn't support class attr_accessors so create individual methods\n\n if reader\n @current_object.create_method(\n name.to_s,\n [Parlour::RbsGenerator::MethodSignature.new([], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(reader, m)\n end\n end\n\n if writer\n @current_object.create_method(\n \"#{name}=\",\n [Parlour::RbsGenerator::MethodSignature.new([Parlour::RbsGenerator::Parameter.new(\n \"value\",\n type: parlour_type,\n required: true\n )], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(writer, m)\n end\n end\n else\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n ) do |m|\n add_comments(reader || writer, m)\n end\n end\n end\n end\n end\n end", "def []=(attr_name, value)\r\n if attr_name.is_a?(String) and attr_name != attr_name.split(ID_SEP).first\r\n attr_name = attr_name.split(ID_SEP)\r\n end\r\n\r\n if attr_name.is_a? Array\r\n value = value.split(ID_SEP) if value.is_a? String\r\n unless value.length == attr_name.length\r\n raise \"Number of attr_names and values do not match\"\r\n end\r\n #breakpoint\r\n [attr_name, value].transpose.map {|name,val| write_attribute(name.to_s, val)}\r\n else\r\n write_attribute(attr_name, value)\r\n end\r\n end", "def attr(symbol, writable=false) end", "def define_writer!(k, definition)\n define_method(\"#{k}=\") do |value|\n # Recursively convert hash and array of hash to schematized objects\n value = ensure_schema value, definition[:schema]\n\n # Initial value\n instance_variable_set \"@#{k}\", value\n\n # Dirty tracking\n self.changed_attributes ||= Set.new\n self.changed_attributes << k\n end\n end", "def validate\n validate_string_attributes\n end", "def write_attribute_with_dynamo(field_name, value)\n if is_dynamo_field?(field_name)\n # Store these guys for now. We don't actually save the field value until the model is saved ( i.e my_supplier.save ).\n # If we were to save the field_value now we wouldn't be able to know the id of the model to link this value to it.\n # @see delay_save\n @all_fields_and_values ||= []\n @all_fields_and_values << {:dynamo_field=>cached_dynamo_field_by_name(field_name), :value=>value}\n end\n # If its a 'normal' attribute let rails write it in the usual way.\n write_attribute_without_dynamo(field_name, value)\n end", "def define_attr_accessor(attr)\n attr_accessor(attr)\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n writer.write_collection_of_object_values(\"attributeMappings\", @attribute_mappings)\n writer.write_boolean_value(\"enabled\", @enabled)\n writer.write_enum_value(\"flowTypes\", @flow_types)\n writer.write_collection_of_object_values(\"metadata\", @metadata)\n writer.write_string_value(\"name\", @name)\n writer.write_string_value(\"@odata.type\", @odata_type)\n writer.write_object_value(\"scope\", @scope)\n writer.write_string_value(\"sourceObjectName\", @source_object_name)\n writer.write_string_value(\"targetObjectName\", @target_object_name)\n writer.write_additional_data(@additional_data)\n end", "def validate_attribute_syntax\n\t\t@values.each do |attribute, values|\n\t\t\t[ values ].flatten.each do |value|\n\t\t\t\tbegin\n\t\t\t\t\tself.get_converted_attribute( attribute.to_sym, value )\n\t\t\t\trescue => err\n\t\t\t\t\tself.log.error \"validation for %p failed: %s: %s\" %\n\t\t\t\t\t\t[ attribute, err.class.name, err.message ]\n\t\t\t\t\tattrtype = self.find_attribute_type( attribute )\n\t\t\t\t\tself.errors.add( attribute, \"isn't a valid %s value\" %\n\t\t\t\t\t\t[ attrtype.syntax ? attrtype.syntax.desc : attrtype.syntax_oid ] )\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def valid_attributes\n { }\n end", "def validatable_attributes(atts, opts)\n am, an, ab, m = opts.values_at(:allow_missing, :allow_nil, :allow_blank, :message)\n Array(atts).each do |a|\n next if am && !values.has_key?(a)\n v = send(a)\n next if an && v.nil?\n next if ab && v.respond_to?(:blank?) && v.blank?\n if message = yield(a, v, m)\n errors.add(a, message)\n end\n end\n end", "def valid_attributes\n { }\n end", "def valid_attributes\n { }\n end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def require_attr(name)\n send(name).tap do |_|\n raise \"Attribute must be set: #{name}\" if _.nil?\n end\n end", "def write_attributes(attributes)\n _attributes = attributes.select do |name, value|\n if self.is_dynamic_field?(name)\n self.dynamic_setter(name, value)\n false\n else\n true\n end\n end\n\n super(_attributes)\n end", "def attribute; end", "def attribute; end" ]
[ "0.6472992", "0.6315012", "0.6315012", "0.62821025", "0.6279224", "0.6211609", "0.61891466", "0.6182247", "0.60683644", "0.6032628", "0.5995443", "0.5988785", "0.5959885", "0.5938289", "0.5931089", "0.58951056", "0.5859927", "0.5851703", "0.58493423", "0.58465594", "0.58328366", "0.5823013", "0.5822229", "0.57850474", "0.5701491", "0.5696689", "0.5682951", "0.5678094", "0.566814", "0.5657499", "0.56555206", "0.5642589", "0.56219065", "0.5615893", "0.56105876", "0.559851", "0.5598089", "0.55940455", "0.5585137", "0.55848545", "0.55796933", "0.5571477", "0.5567006", "0.55667996", "0.55652434", "0.5562926", "0.55600035", "0.55590326", "0.55590326", "0.5554599", "0.5554599", "0.55407417", "0.5534935", "0.5527733", "0.55271375", "0.55238813", "0.5501504", "0.5497003", "0.5496233", "0.54927665", "0.5464706", "0.54617554", "0.5461167", "0.5451583", "0.54498726", "0.54498726", "0.54359984", "0.5430996", "0.5430996", "0.5426488", "0.5418467", "0.54153895", "0.54107565", "0.5407886", "0.5401234", "0.54008496", "0.5400268", "0.53910094", "0.53827274", "0.5377731", "0.5375473", "0.5374833", "0.53720397", "0.5370215", "0.5363264", "0.5361161", "0.5360557", "0.5351706", "0.53514725", "0.53492516", "0.53459316", "0.5341237", "0.5328037", "0.5328037", "0.53230566", "0.53230566", "0.53230566", "0.5319575", "0.531832", "0.5315559", "0.5315559" ]
0.0
-1
Custom attribute writer method with validation
def tcp_closing=(tcp_closing) if tcp_closing.nil? fail ArgumentError, 'tcp_closing cannot be nil' end if tcp_closing > 4320000 fail ArgumentError, 'invalid value for "tcp_closing", must be smaller than or equal to 4320000.' end if tcp_closing < 10 fail ArgumentError, 'invalid value for "tcp_closing", must be greater than or equal to 10.' end @tcp_closing = tcp_closing end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def attr_writer_tag(text); end", "def allowed_attributes=(_arg0); end", "def allowed_attributes=(_arg0); end", "def writer(*args)\n attr_writer(*args)\n args\n end", "def define_write_method(attr_name)\n evaluate_attribute_method attr_name, \"def #{attr_name}=(new_value);write_attribute('#{attr_name}', new_value);end\", \"#{attr_name}=\"\n end", "def attr_writer(*vars)\n # avoid tracking attributes that are added by the class_attribute\n # as these are class attributes and not instance attributes.\n tracked_vars = vars.reject {|var| respond_to? var }\n add_tracked_attrs(false, true, *tracked_vars)\n vars.extract_options!\n super\n end", "def attr_writer(sym, *more) end", "def is_attribute?; end", "def validate_exclusion_of(attr); end", "def register_attributes\n raise \"Not implemented in #{self.class}\"\n end", "def method_missing(method_name, *args)\n return super unless permitted_attributes.include?(method_name)\n begin\n object.send(:\"#{method_name}=\", args.first)\n rescue => e\n if params.has_key?(method_name)\n message = \"Unable to process value for :#{method_name}, no attribute writer. Be sure to override the automatic setters for all params that do not map straight to a model attribute.\"\n Rails.logger.warn({message: message,\n missing_writer: method_name,\n value: args.first,\n error: e})\n self.errors << {status: 422, message: message}\n else\n raise e\n end\n end\n end", "def timeliness_validation_for(attr_names, type)\n super\n attr_names.each { |attr_name| define_timeliness_write_method(attr_name) }\n end", "def create_setter_for(attribute, options)\n setter_method = \"#{attribute}=\"\n\n define_method setter_method do |value|\n if options[:allow_blank] || value != \"\"\n write_attribute(attribute, value)\n end\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each {|attr_name| attr_internal_define(attr_name, :writer)}\n end", "def escape_attr input\n escape input, attr_regexp, attr_mapping\n end", "def make_writer( attrtype )\n\t\tself.log.debug \"Generating an attribute writer for %p\" % [ attrtype ]\n\t\tattrname = attrtype.name\n\t\tif attrtype.single?\n\t\t\tself.log.debug \" attribute is SINGLE, so generating a scalar writer...\"\n\t\t\treturn lambda {|newvalue| self[attrname] = newvalue }\n\t\telse\n\t\t\tself.log.debug \" attribute isn't SINGLE, so generating an array writer...\"\n\t\t\treturn lambda {|*newvalues| self[attrname] = newvalues.flatten }\n\t\tend\n\tend", "def write_attribute(name, value)\n # Simply check if the accessor is allowed to write the field\n # (if so, go to superclass and do it)\n @bypass_auth ||= false\n if allowed_to_write(name) || @bypass_auth\n super(name, value)\n end\n end", "def mattr_writer(*syms, &proc)\n receiver = self\n options = syms.extract_options!\n syms.each do |sym|\n raise NameError.new('invalid attribute name') unless sym =~ /^[_A-Za-z]\\w*$/\n class_exec do\n define_singleton_method \"#{sym}=\" do |obj|\n class_variable_set(\"@@#{sym}\", obj)\n end\n end\n\n unless options[:instance_writer] == false || options[:instance_accessor] == false\n class_exec do\n define_method \"#{sym}=\" do |obj|\n receiver.class_variable_set(\"@@#{sym}\", obj)\n end\n end\n end\n send(\"#{sym}=\", proc.call) if proc\n end\n end", "def write_attribute(attribute, value)\n false\n end", "def add_attribute attribute\n return attribute unless @document_self\n\n # mainly to check for redefinition of an attribute as a method\n # TODO find a policy for 'attr_reader :foo' + 'def foo=()'\n register = false\n\n key = nil\n\n if attribute.rw.index 'R' then\n key = attribute.pretty_name\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name + '='] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if attribute.rw.index 'W' then\n key = attribute.pretty_name + '='\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if register then\n attribute.visibility = @visibility\n add_to @attributes, attribute\n resolve_aliases attribute\n end\n\n attribute\n end", "def define_writer_method(mod)\n writer_method_name = \"#{name}=\"\n attribute = self\n\n mod.send(:define_method, writer_method_name) { |value| attribute.set(self, value) }\n mod.send(writer_visibility, writer_method_name)\n\n self\n end", "def allowed_to_write(name)\n # no point allowing attribute writes if we can't save them?\n if allowed_to_save\n name = name.to_s\n validation_methods = self.class.write_validations(name) \n if validation_methods.nil?\n # We haven't registered any filters on this attribute, so allow the write.\n true\n elsif validation_methods.check :accessor => accessor, :model => self\n # One of the authentication methods worked, so allow the write.\n true\n else\n # We had filters but none of them passed. Disallow write.\n false\n end\n else\n false\n end\n end", "def assert_attr_writer(obj, method)\n assert_respond_to obj, \"#{method}=\"\nend", "def add_attribute(name, &block); end", "def authenticates_writes_to(attr, options={})\n authenticates_access\n @write_validation_map ||= {}\n @write_validation_map[attr.to_s] ||= AuthMethodList.new\n @write_validation_map[attr.to_s].add_method(options)\n end", "def write_attribute_3(param1, param2)\n\twrite_attribute(param1, param2)\n end", "def write_attribute(attr_name, value) #:doc:\n @attributes[attr_name] = empty_string_for_number_column?(attr_name, value) ? nil : value\n end", "def add_writer_tags(klass, new_method, member)\n member_tag = member_tag_for_member(klass, member, :write)\n return_type = return_type_from_tag(member_tag)\n setter_doc_text = member_tag ? member_tag.text : \"Sets the attribute #{member}\"\n new_method.docstring.replace(setter_doc_text)\n new_method.add_tag YARD::Tags::Tag.new(:param, \"the value to set the attribute #{member} to.\", return_type, \"value\")\n new_method.add_tag YARD::Tags::Tag.new(:return, \"the newly set value\", return_type)\n end", "def print_attribute(*) end", "def attribute(name); end", "def add_checked_attribute(clazz, attribute)\r\n eval <<END\r\n class #{clazz}\r\n\r\n def #{attribute}=(value)\r\n raise 'Invalid attribute' unless value\r\n @#{attribute}=value\r\n end\r\n\r\n def #{attribute}\r\n #{attribute}\r\n end\r\n end\r\nEND\r\nend", "def attr(name); end", "def is_attribute?(line)\n (line =~ /(\\s+)attr_(writer|reader|accessor)\\s+:[a-zA-Z_0-9]+/) == 0\n end", "def attribute(name, value)\n\t if !@inStartTag\n\t\traise WriterError.new('attribute outside of tag start')\n\t end\n\t @io << \" #{name}=\\\"#{NQXML.encode(value.to_s)}\\\"\"\n\tend", "def set_attribute(name, value); end", "def dataset_writer(*attributes)\n attributes.flatten.each do |attr_name|\n next if method_defined?(\"#{attr_name}=\")\n\n class_eval <<-RUBY, __FILE__, __LINE__ + 1\n def #{attr_name}=(value)\n dataset_set(:#{attr_name}, value)\n end\n RUBY\n end\n end", "def validated_attribute_names(params); end", "def require_format_of(attribute)\r\n RequireFormatOf.new(attribute)\r\n end", "def attr_writer(*fields)\n check_fields(fields)\n added_fields = jiak.data.writable(*fields)\n added_fields.each do |field|\n class_eval <<-EOM\n def #{field}=(val)\n @jiak.object.data.#{field} = val\n self.class.do_auto_update(self)\n end\n EOM\n end\n nil\n end", "def html_attr(*attrs)\n options = attrs.extract_options!.reverse_merge({\n :level => :super_relaxed\n })\n attrs.each do |att|\n class_eval \"def #{att}=(val); self[:#{att}] = sanitize(val, :#{options[:level]}); end\"\n end\n end", "def validate_attributes=(new_attribute)\n @validate_attributes = new_attribute\n end", "def html_attributes(attr); end", "def instance_write(attr, value)\n setter = :\"#{@name_string}_#{attr}=\"\n instance.send(setter, value) if instance.respond_to?(setter)\n end", "def valid_xml_attribute(name, options={:level => :warning})\n\t\t\t\tvalidate(\"Invalid XML attribute '#{name}'\", options) { name.to_s.match(/^([^[:punct:]0-9<>]|_)[^<>\"']*/) }\n\t\t\tend", "def attr_writer(*args)\n sym_args=args_to_sym(args)\n sym_args.each do |value|\n self.instance_eval(\"def #{value}=(arg); @#{value}=arg;end;\")\n end\n \n end", "def define_writer_method(attribute, method_name, visibility)\n define_method(method_name) { |value| attribute.set(self, value) }\n send(visibility, method_name)\n self\n end", "def write_attribute(name, val)\n if @embedded_models.include? name\n @embedded_models[name].model = val\n elsif @attribute_objects.include? name\n @attribute_objects[name].value = val\n else\n return false\n end\n\n run_callbacks :attribute_change\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def attr; end", "def attribute(*args)\n define_expressions(Attribute, args)\n end", "def write_attribute(name, value)\n name = name.to_s\n\n # The attribute already has an unsaved change.\n if attribute_changed?(name)\n old = changed_attributes[name]\n changed_attributes.delete(name) unless field_changed?(name, old, value)\n else\n attribute_will_change(name) if field_changed?(name, old, value)\n end\n\n # Carry on.\n super(name, value)\n end", "def define_magic_attr(name)\n define_method name do |*attrs|\n raise ArgumentError.new(\"wrong number of arguments\") if attrs.size > 1\n send(\"#{name}=\", attrs.first) if attrs.size == 1\n instance_variable_get(\"@#{name}\")\n end\n\n attr_writer name\n end", "def configurable_writer(attribute, code=nil, &block)\n if block_given? and not code\n Halcyon.class.send(:define_method, :\"#{attribute}=\", block)\n elsif code and not block_given?\n Halcyon.class.send(:eval, <<-\"end;\")\n def #{attribute.to_s}=(value)\n #{code % [attribute.to_sym.inspect]}\n end\n end;\n else\n raise ArgumentError.new(\"Either a block or a code string should be supplied.\")\n end\n end", "def method_missing(name, *args, &block)\n if /\\Ahas_validated_(?<type>\\w*)_attribute\\Z/ =~ name\n has_validated_attribute(type, *args, &block)\n else\n super\n end\n end", "def add_checked_attribute(klass, attribute)\n klass.class_eval do\n define_method attribute do\n instance_variable_get(\"@#{attribute}\")\n end\n\n define_method \"#{attribute}=\" do |value|\n raise 'Invalid attribute' unless value\n \n instance_variable_set(\"@#{attribute}\", value)\n end\n end\nend", "def method_missing(meth, *args, &blk)\n match = meth.to_s.match(/^([a-zA-Z\\_]+)(=|$)$/)\n if match\n attribute, setter = match[1], !match[2].blank?\n if setter\n write_attribute(attribute, args.first)\n else\n read_attribute(attribute)\n end\n else\n super(meth, *args, &blk)\n end\n end", "def valid_attributes\n { name: 'do this' }\n end", "def make_attributes_definitions_or_croak(attrArgs, &attrBlok)\n eye = :'m_attrs_defs'\n\n # Work with attribute as strings\n \n $DEBUG && logger_me(eye, logger_fmt_kls(:attrArgs => attrArgs, :attrBlok => attrBlok))\n\n mustbe_attributes_specification_or_croak(attrArgs, eye, \"attrArgs not attributes_specification\")\n \n #STOPATTRARGSINSUPER\n \n #attrAll = mustbe_not_empty_or_croak(mustbe_array_key_or_nil_or_croak(attrArgs, :all, eye, \"all attributes not array\"), eye, \"all attributes is empty\").map(&:to_s)\n attrAll = mustbe_not_empty_or_croak(mustbe_attributes_specification_all_key_or_croak(attrArgs, :all, eye), eye, \"all attributes is empty\").map(&:to_s)\n \n\n #puts(\"\\n\\n\\nATTR ALL >#{attrAll}<\")\n\n #STOPMAKEATTRSPECSENTRY\n\n attrInc = mustbe_attributes_specification_include_key_or_nil_or_croak(attrArgs, :include, eye) # mustbe all strings\n #puts(\"ATTR INC >#{attrInc.class}< >#{attrInc}< >#{is_value_not_empty?(attrInc)}<\")\n attrInc && mustbe_not_empty_or_croak(attrInc, eye, \"include attributes is empty\")\n\n attrExc = mustbe_attributes_specification_exclude_key_or_nil_or_croak(attrArgs, :exclude, eye) || []\n \n attrMapNom = mustbe_attributes_definitions_key_or_nil_or_croak(attrArgs, :definitions, eye) || {}\n attrMap = attrMapNom && potrubi_util_map_hash_kv(attrMapNom) {|k,v| [k.to_s, v]} # keys all strings\n\n # Ensure all consistent\n \n attrInc && mustbe_subset_or_croak(attrInc, attrAll, eye, \"include attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrExc, attrAll, eye, \"exclude attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrMap.keys, attrAll, eye, \"attribute map contains unknown attributes\")\n \n attrUse = ((attrInc || attrAll) - attrExc).uniq # list of unique attributes to report on\n\n # consolidate \"faked up\" attr specs with ones provided to get the composite attrSpecs\n \n attrDefsNom = potrubi_util_array_to_hash(attrUse).merge(attrMap.select {|k,v| attrUse.include?(k)}) # consolidated \"faked up\" attr specs with ones provided\n\n attrDefs = potrubi_util_map_hash_v(attrDefsNom) do | attrName, attrSpecNom|\n\n attrSpec =\n case attrSpecNom\n when NilClass then {}\n when Hash then\n attrSpecNom.each_with_object({}) do | (verbName, verbSpec), h1 |\n case verbName\n when :pass_thru then h1[:pass_thru] = verbSpec # dont touch; just pass through\n when :event_defaults then # add these to pass_thru\n h1[:pass_thru] = (h1[:pass_thru] || {}).merge(verbName => verbSpec)\n when :map, :select, :metric then\n h1[verbName] = {\n :method_name => \"#{verbName}_#{attrName}_#{rand(1000000)}\", # make a unqiue name\n :method_spec => verbSpec # spec must be valid to dynamic_define_methods\n }\n else\n logic_exception(verbName, eye, \"attrName >#{attrName}< verbName >#{verbName}< value should be impossible\")\n end\n end\n \n else\n logic_exception(attrrSpecNom, eye, \"attrSpecNom value should be impossible\")\n end\n\n attrSpec\n \n end\n \n $DEBUG && logger_mx(eye, logger_fmt_kls(:attrDefs => attrDefs))\n\n mustbe_attributes_definitions_or_croak(attrDefs, eye, \"attrDefs failed contract\")\n\n #STOPMAKEATTRSPECS\n \n end", "def create_writer(klass, member)\n # We want to convert these members into attributes just like\n # as if they were declared using attr_accessor.\n new_meth = register MethodObject.new(klass, \"#{member}=\", :instance) do |o|\n o.parameters = [['value', nil]]\n o.signature ||= \"def #{member}=(value)\"\n o.source ||= \"#{o.signature}\\n @#{member} = value\\nend\"\n end\n add_writer_tags(klass, new_meth, member)\n klass.attributes[:instance][member][:write] = new_meth\n end", "def create_setter!\n @target.class_eval <<-EOS\n #{writer_visibility.to_s}\n def #{name}=(value)\n attribute_set(#{name.inspect}, value)\n end\n EOS\n rescue SyntaxError\n raise SyntaxError.new(column)\n end", "def attribute name, type, conditions= DEFAULT_ATTRIBUTE_CONDITIONS\n RMOF.complete_conditions conditions, DEFAULT_ATTRIBUTE_CONDITIONS\n @attributes= {} unless instance_variable_defined? :@attributes\n @attributes[name]= [name, type, conditions]\n unless method_defined? :__attributes then \n define_method( :__attributes) do \n @attributes\n end \n end\n at= \"@#{name}\".to_sym\n getter= \"#{name}\".to_sym\n setter= \"#{name}=\".to_sym\n completion= \"__complete_#{name}\".to_sym\n define_method( getter) do\n if instance_variable_defined? at then instance_variable_get at\n else conditions[:default]\n end\n end\n define_method( setter) do |val|\n instance_variable_set at, val\n end\n define_method( completion) do\n RMOF.validate( self.send(getter), name, type, conditions)\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def create_setter(name, meth)\n define_method(\"#{meth}=\") do |value|\n write_attribute(name, value)\n end\n end", "def sanitized_allowed_attributes=(attributes); end", "def sanitized_allowed_attributes=(attributes); end", "def oattr(name, type)\n case type\n when :custom\n # Do nothing, just register attr below.\n when :writer\n attr_writer name\n else\n raise ArgumentError, \"Unknown type: #{type.inspect}\"\n end\n\n # Register and return.\n name.tap { oattrs << name}\n end", "def valid_attributes\n { name: \"Expert\" }\n end", "def attributes(*method_names, **options)\n add_attributes(method_names, **options, strategy: :write_value_using_method_strategy)\n end", "def []=(attr_name, value)\n writer_method = \"#{attr_name}=\"\n send(writer_method, value) if respond_to?(writer_method)\n end", "def write_extended_attributes(attrs)\n attrs.each do |k, val|\n self.send((k.to_s + \"=\").to_sym, val) if is_flex_attribute?(k)\n end\n self\n end", "def valid_attributes\n { \"username\" => \"MyString\" }\n end", "def cattr_writer(*fields)\n metaclass.send :attr_writer, *fields\n end", "def write_attribute(attr, value)\n if attribute_encrypted?(attr)\n conductor_for(attr).encrypt(value)\n else\n super(attr, value)\n end\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_number_value(\"offsetInDays\", @offset_in_days)\n writer.write_enum_value(\"timeBasedAttribute\", @time_based_attribute)\n end", "def define_attribute_method(attr_name, _owner: generated_attribute_methods)\n CodeGenerator.batch(_owner, __FILE__, __LINE__) do |owner|\n attribute_method_matchers.each do |matcher|\n method_name = matcher.method_name(attr_name)\n\n unless instance_method_already_implemented?(method_name)\n generate_method = \"define_method_#{matcher.target}\"\n\n if respond_to?(generate_method, true)\n send(generate_method, attr_name.to_s, owner: owner)\n else\n define_proxy_call true, owner, method_name, matcher.target, attr_name.to_s\n end\n end\n end\n attribute_method_matchers_cache.clear\n end\n end", "def has_attributes?; end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_boolean_value(\"isExpirationRequired\", @is_expiration_required)\n writer.write_duration_value(\"maximumDuration\", @maximum_duration)\n end", "def add_attributes(item)\n [:class, :instance].each do |attr_loc|\n # Grab attributes for the current location (class or instance)\n attrs = item.attributes[attr_loc]\n attrs.each do |name, attribute|\n reader = attribute[:read]\n writer = attribute[:write]\n\n unless reader || writer\n Logging.warn(\"attribute is not readable or writable somehow, skipping\", attribute)\n next\n end\n\n # Get all given types\n yard_types = []\n if reader\n next if @hide_private && reader.visibility == :private\n yard_types += reader.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n reader.tags('param').flat_map(&:types)\n end\n if writer\n next if @hide_private && writer.visibility == :private\n yard_types += writer.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n writer.tags('param').flat_map(&:types)\n end\n\n # Use untyped if not types specified anywhere, otherwise try to\n # compute Parlour type given all these types\n if yard_types.empty?\n Logging.omit(\"no YARD type given for #{name.inspect}, using untyped\", reader || writer)\n parlour_type = Parlour::Types::Untyped.new\n elsif yard_types.all? { |x| x == 'nil' }\n # Nil attributes are extremely unusual, so just use untyped\n parlour_type = Parlour::Types::Untyped.new\n else\n parlour_type = TypeConverter.yard_to_parlour(\n yard_types, reader || writer, @type_converter_config)\n end\n\n # Generate attribute\n if reader && writer\n kind = :accessor\n elsif reader\n kind = :reader\n elsif writer\n kind = :writer\n end\n\n if @exclude_untyped && parlour_type.is_a?(Parlour::Types::Untyped)\n Logging.omit(\"excluding untyped attribute\", reader || writer, immediate: true)\n next\n end\n\n case @mode\n when :rbi\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n class_attribute: (attr_loc == :class)\n ) do |m|\n add_comments(reader || writer, m)\n end\n when :rbs\n if attr_loc == :class\n # RBS doesn't support class attr_accessors so create individual methods\n\n if reader\n @current_object.create_method(\n name.to_s,\n [Parlour::RbsGenerator::MethodSignature.new([], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(reader, m)\n end\n end\n\n if writer\n @current_object.create_method(\n \"#{name}=\",\n [Parlour::RbsGenerator::MethodSignature.new([Parlour::RbsGenerator::Parameter.new(\n \"value\",\n type: parlour_type,\n required: true\n )], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(writer, m)\n end\n end\n else\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n ) do |m|\n add_comments(reader || writer, m)\n end\n end\n end\n end\n end\n end", "def []=(attr_name, value)\r\n if attr_name.is_a?(String) and attr_name != attr_name.split(ID_SEP).first\r\n attr_name = attr_name.split(ID_SEP)\r\n end\r\n\r\n if attr_name.is_a? Array\r\n value = value.split(ID_SEP) if value.is_a? String\r\n unless value.length == attr_name.length\r\n raise \"Number of attr_names and values do not match\"\r\n end\r\n #breakpoint\r\n [attr_name, value].transpose.map {|name,val| write_attribute(name.to_s, val)}\r\n else\r\n write_attribute(attr_name, value)\r\n end\r\n end", "def attr(symbol, writable=false) end", "def define_writer!(k, definition)\n define_method(\"#{k}=\") do |value|\n # Recursively convert hash and array of hash to schematized objects\n value = ensure_schema value, definition[:schema]\n\n # Initial value\n instance_variable_set \"@#{k}\", value\n\n # Dirty tracking\n self.changed_attributes ||= Set.new\n self.changed_attributes << k\n end\n end", "def validate\n validate_string_attributes\n end", "def write_attribute_with_dynamo(field_name, value)\n if is_dynamo_field?(field_name)\n # Store these guys for now. We don't actually save the field value until the model is saved ( i.e my_supplier.save ).\n # If we were to save the field_value now we wouldn't be able to know the id of the model to link this value to it.\n # @see delay_save\n @all_fields_and_values ||= []\n @all_fields_and_values << {:dynamo_field=>cached_dynamo_field_by_name(field_name), :value=>value}\n end\n # If its a 'normal' attribute let rails write it in the usual way.\n write_attribute_without_dynamo(field_name, value)\n end", "def define_attr_accessor(attr)\n attr_accessor(attr)\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n writer.write_collection_of_object_values(\"attributeMappings\", @attribute_mappings)\n writer.write_boolean_value(\"enabled\", @enabled)\n writer.write_enum_value(\"flowTypes\", @flow_types)\n writer.write_collection_of_object_values(\"metadata\", @metadata)\n writer.write_string_value(\"name\", @name)\n writer.write_string_value(\"@odata.type\", @odata_type)\n writer.write_object_value(\"scope\", @scope)\n writer.write_string_value(\"sourceObjectName\", @source_object_name)\n writer.write_string_value(\"targetObjectName\", @target_object_name)\n writer.write_additional_data(@additional_data)\n end", "def validate_attribute_syntax\n\t\t@values.each do |attribute, values|\n\t\t\t[ values ].flatten.each do |value|\n\t\t\t\tbegin\n\t\t\t\t\tself.get_converted_attribute( attribute.to_sym, value )\n\t\t\t\trescue => err\n\t\t\t\t\tself.log.error \"validation for %p failed: %s: %s\" %\n\t\t\t\t\t\t[ attribute, err.class.name, err.message ]\n\t\t\t\t\tattrtype = self.find_attribute_type( attribute )\n\t\t\t\t\tself.errors.add( attribute, \"isn't a valid %s value\" %\n\t\t\t\t\t\t[ attrtype.syntax ? attrtype.syntax.desc : attrtype.syntax_oid ] )\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def valid_attributes\n { }\n end", "def validatable_attributes(atts, opts)\n am, an, ab, m = opts.values_at(:allow_missing, :allow_nil, :allow_blank, :message)\n Array(atts).each do |a|\n next if am && !values.has_key?(a)\n v = send(a)\n next if an && v.nil?\n next if ab && v.respond_to?(:blank?) && v.blank?\n if message = yield(a, v, m)\n errors.add(a, message)\n end\n end\n end", "def valid_attributes\n { }\n end", "def valid_attributes\n { }\n end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def require_attr(name)\n send(name).tap do |_|\n raise \"Attribute must be set: #{name}\" if _.nil?\n end\n end", "def write_attributes(attributes)\n _attributes = attributes.select do |name, value|\n if self.is_dynamic_field?(name)\n self.dynamic_setter(name, value)\n false\n else\n true\n end\n end\n\n super(_attributes)\n end", "def attribute; end", "def attribute; end" ]
[ "0.6472992", "0.6315012", "0.6315012", "0.62821025", "0.6279224", "0.6211609", "0.61891466", "0.6182247", "0.60683644", "0.6032628", "0.5995443", "0.5988785", "0.5959885", "0.5938289", "0.5931089", "0.58951056", "0.5859927", "0.5851703", "0.58493423", "0.58465594", "0.58328366", "0.5823013", "0.5822229", "0.57850474", "0.5701491", "0.5696689", "0.5682951", "0.5678094", "0.566814", "0.5657499", "0.56555206", "0.5642589", "0.56219065", "0.5615893", "0.56105876", "0.559851", "0.5598089", "0.55940455", "0.5585137", "0.55848545", "0.55796933", "0.5571477", "0.5567006", "0.55667996", "0.55652434", "0.5562926", "0.55600035", "0.55590326", "0.55590326", "0.5554599", "0.5554599", "0.55407417", "0.5534935", "0.5527733", "0.55271375", "0.55238813", "0.5501504", "0.5497003", "0.5496233", "0.54927665", "0.5464706", "0.54617554", "0.5461167", "0.5451583", "0.54498726", "0.54498726", "0.54359984", "0.5430996", "0.5430996", "0.5426488", "0.5418467", "0.54153895", "0.54107565", "0.5407886", "0.5401234", "0.54008496", "0.5400268", "0.53910094", "0.53827274", "0.5377731", "0.5375473", "0.5374833", "0.53720397", "0.5370215", "0.5363264", "0.5361161", "0.5360557", "0.5351706", "0.53514725", "0.53492516", "0.53459316", "0.5341237", "0.5328037", "0.5328037", "0.53230566", "0.53230566", "0.53230566", "0.5319575", "0.531832", "0.5315559", "0.5315559" ]
0.0
-1
Custom attribute writer method with validation
def tcp_established=(tcp_established) if tcp_established.nil? fail ArgumentError, 'tcp_established cannot be nil' end if tcp_established > 4320000 fail ArgumentError, 'invalid value for "tcp_established", must be smaller than or equal to 4320000.' end if tcp_established < 120 fail ArgumentError, 'invalid value for "tcp_established", must be greater than or equal to 120.' end @tcp_established = tcp_established end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def attr_writer_tag(text); end", "def allowed_attributes=(_arg0); end", "def allowed_attributes=(_arg0); end", "def writer(*args)\n attr_writer(*args)\n args\n end", "def define_write_method(attr_name)\n evaluate_attribute_method attr_name, \"def #{attr_name}=(new_value);write_attribute('#{attr_name}', new_value);end\", \"#{attr_name}=\"\n end", "def attr_writer(*vars)\n # avoid tracking attributes that are added by the class_attribute\n # as these are class attributes and not instance attributes.\n tracked_vars = vars.reject {|var| respond_to? var }\n add_tracked_attrs(false, true, *tracked_vars)\n vars.extract_options!\n super\n end", "def attr_writer(sym, *more) end", "def is_attribute?; end", "def validate_exclusion_of(attr); end", "def register_attributes\n raise \"Not implemented in #{self.class}\"\n end", "def method_missing(method_name, *args)\n return super unless permitted_attributes.include?(method_name)\n begin\n object.send(:\"#{method_name}=\", args.first)\n rescue => e\n if params.has_key?(method_name)\n message = \"Unable to process value for :#{method_name}, no attribute writer. Be sure to override the automatic setters for all params that do not map straight to a model attribute.\"\n Rails.logger.warn({message: message,\n missing_writer: method_name,\n value: args.first,\n error: e})\n self.errors << {status: 422, message: message}\n else\n raise e\n end\n end\n end", "def timeliness_validation_for(attr_names, type)\n super\n attr_names.each { |attr_name| define_timeliness_write_method(attr_name) }\n end", "def create_setter_for(attribute, options)\n setter_method = \"#{attribute}=\"\n\n define_method setter_method do |value|\n if options[:allow_blank] || value != \"\"\n write_attribute(attribute, value)\n end\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each {|attr_name| attr_internal_define(attr_name, :writer)}\n end", "def escape_attr input\n escape input, attr_regexp, attr_mapping\n end", "def make_writer( attrtype )\n\t\tself.log.debug \"Generating an attribute writer for %p\" % [ attrtype ]\n\t\tattrname = attrtype.name\n\t\tif attrtype.single?\n\t\t\tself.log.debug \" attribute is SINGLE, so generating a scalar writer...\"\n\t\t\treturn lambda {|newvalue| self[attrname] = newvalue }\n\t\telse\n\t\t\tself.log.debug \" attribute isn't SINGLE, so generating an array writer...\"\n\t\t\treturn lambda {|*newvalues| self[attrname] = newvalues.flatten }\n\t\tend\n\tend", "def write_attribute(name, value)\n # Simply check if the accessor is allowed to write the field\n # (if so, go to superclass and do it)\n @bypass_auth ||= false\n if allowed_to_write(name) || @bypass_auth\n super(name, value)\n end\n end", "def mattr_writer(*syms, &proc)\n receiver = self\n options = syms.extract_options!\n syms.each do |sym|\n raise NameError.new('invalid attribute name') unless sym =~ /^[_A-Za-z]\\w*$/\n class_exec do\n define_singleton_method \"#{sym}=\" do |obj|\n class_variable_set(\"@@#{sym}\", obj)\n end\n end\n\n unless options[:instance_writer] == false || options[:instance_accessor] == false\n class_exec do\n define_method \"#{sym}=\" do |obj|\n receiver.class_variable_set(\"@@#{sym}\", obj)\n end\n end\n end\n send(\"#{sym}=\", proc.call) if proc\n end\n end", "def write_attribute(attribute, value)\n false\n end", "def add_attribute attribute\n return attribute unless @document_self\n\n # mainly to check for redefinition of an attribute as a method\n # TODO find a policy for 'attr_reader :foo' + 'def foo=()'\n register = false\n\n key = nil\n\n if attribute.rw.index 'R' then\n key = attribute.pretty_name\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name + '='] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if attribute.rw.index 'W' then\n key = attribute.pretty_name + '='\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if register then\n attribute.visibility = @visibility\n add_to @attributes, attribute\n resolve_aliases attribute\n end\n\n attribute\n end", "def define_writer_method(mod)\n writer_method_name = \"#{name}=\"\n attribute = self\n\n mod.send(:define_method, writer_method_name) { |value| attribute.set(self, value) }\n mod.send(writer_visibility, writer_method_name)\n\n self\n end", "def allowed_to_write(name)\n # no point allowing attribute writes if we can't save them?\n if allowed_to_save\n name = name.to_s\n validation_methods = self.class.write_validations(name) \n if validation_methods.nil?\n # We haven't registered any filters on this attribute, so allow the write.\n true\n elsif validation_methods.check :accessor => accessor, :model => self\n # One of the authentication methods worked, so allow the write.\n true\n else\n # We had filters but none of them passed. Disallow write.\n false\n end\n else\n false\n end\n end", "def assert_attr_writer(obj, method)\n assert_respond_to obj, \"#{method}=\"\nend", "def add_attribute(name, &block); end", "def authenticates_writes_to(attr, options={})\n authenticates_access\n @write_validation_map ||= {}\n @write_validation_map[attr.to_s] ||= AuthMethodList.new\n @write_validation_map[attr.to_s].add_method(options)\n end", "def write_attribute_3(param1, param2)\n\twrite_attribute(param1, param2)\n end", "def write_attribute(attr_name, value) #:doc:\n @attributes[attr_name] = empty_string_for_number_column?(attr_name, value) ? nil : value\n end", "def add_writer_tags(klass, new_method, member)\n member_tag = member_tag_for_member(klass, member, :write)\n return_type = return_type_from_tag(member_tag)\n setter_doc_text = member_tag ? member_tag.text : \"Sets the attribute #{member}\"\n new_method.docstring.replace(setter_doc_text)\n new_method.add_tag YARD::Tags::Tag.new(:param, \"the value to set the attribute #{member} to.\", return_type, \"value\")\n new_method.add_tag YARD::Tags::Tag.new(:return, \"the newly set value\", return_type)\n end", "def print_attribute(*) end", "def attribute(name); end", "def add_checked_attribute(clazz, attribute)\r\n eval <<END\r\n class #{clazz}\r\n\r\n def #{attribute}=(value)\r\n raise 'Invalid attribute' unless value\r\n @#{attribute}=value\r\n end\r\n\r\n def #{attribute}\r\n #{attribute}\r\n end\r\n end\r\nEND\r\nend", "def attr(name); end", "def is_attribute?(line)\n (line =~ /(\\s+)attr_(writer|reader|accessor)\\s+:[a-zA-Z_0-9]+/) == 0\n end", "def attribute(name, value)\n\t if !@inStartTag\n\t\traise WriterError.new('attribute outside of tag start')\n\t end\n\t @io << \" #{name}=\\\"#{NQXML.encode(value.to_s)}\\\"\"\n\tend", "def set_attribute(name, value); end", "def dataset_writer(*attributes)\n attributes.flatten.each do |attr_name|\n next if method_defined?(\"#{attr_name}=\")\n\n class_eval <<-RUBY, __FILE__, __LINE__ + 1\n def #{attr_name}=(value)\n dataset_set(:#{attr_name}, value)\n end\n RUBY\n end\n end", "def validated_attribute_names(params); end", "def require_format_of(attribute)\r\n RequireFormatOf.new(attribute)\r\n end", "def attr_writer(*fields)\n check_fields(fields)\n added_fields = jiak.data.writable(*fields)\n added_fields.each do |field|\n class_eval <<-EOM\n def #{field}=(val)\n @jiak.object.data.#{field} = val\n self.class.do_auto_update(self)\n end\n EOM\n end\n nil\n end", "def html_attr(*attrs)\n options = attrs.extract_options!.reverse_merge({\n :level => :super_relaxed\n })\n attrs.each do |att|\n class_eval \"def #{att}=(val); self[:#{att}] = sanitize(val, :#{options[:level]}); end\"\n end\n end", "def validate_attributes=(new_attribute)\n @validate_attributes = new_attribute\n end", "def html_attributes(attr); end", "def instance_write(attr, value)\n setter = :\"#{@name_string}_#{attr}=\"\n instance.send(setter, value) if instance.respond_to?(setter)\n end", "def valid_xml_attribute(name, options={:level => :warning})\n\t\t\t\tvalidate(\"Invalid XML attribute '#{name}'\", options) { name.to_s.match(/^([^[:punct:]0-9<>]|_)[^<>\"']*/) }\n\t\t\tend", "def attr_writer(*args)\n sym_args=args_to_sym(args)\n sym_args.each do |value|\n self.instance_eval(\"def #{value}=(arg); @#{value}=arg;end;\")\n end\n \n end", "def define_writer_method(attribute, method_name, visibility)\n define_method(method_name) { |value| attribute.set(self, value) }\n send(visibility, method_name)\n self\n end", "def write_attribute(name, val)\n if @embedded_models.include? name\n @embedded_models[name].model = val\n elsif @attribute_objects.include? name\n @attribute_objects[name].value = val\n else\n return false\n end\n\n run_callbacks :attribute_change\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def attr; end", "def attribute(*args)\n define_expressions(Attribute, args)\n end", "def write_attribute(name, value)\n name = name.to_s\n\n # The attribute already has an unsaved change.\n if attribute_changed?(name)\n old = changed_attributes[name]\n changed_attributes.delete(name) unless field_changed?(name, old, value)\n else\n attribute_will_change(name) if field_changed?(name, old, value)\n end\n\n # Carry on.\n super(name, value)\n end", "def define_magic_attr(name)\n define_method name do |*attrs|\n raise ArgumentError.new(\"wrong number of arguments\") if attrs.size > 1\n send(\"#{name}=\", attrs.first) if attrs.size == 1\n instance_variable_get(\"@#{name}\")\n end\n\n attr_writer name\n end", "def configurable_writer(attribute, code=nil, &block)\n if block_given? and not code\n Halcyon.class.send(:define_method, :\"#{attribute}=\", block)\n elsif code and not block_given?\n Halcyon.class.send(:eval, <<-\"end;\")\n def #{attribute.to_s}=(value)\n #{code % [attribute.to_sym.inspect]}\n end\n end;\n else\n raise ArgumentError.new(\"Either a block or a code string should be supplied.\")\n end\n end", "def method_missing(name, *args, &block)\n if /\\Ahas_validated_(?<type>\\w*)_attribute\\Z/ =~ name\n has_validated_attribute(type, *args, &block)\n else\n super\n end\n end", "def add_checked_attribute(klass, attribute)\n klass.class_eval do\n define_method attribute do\n instance_variable_get(\"@#{attribute}\")\n end\n\n define_method \"#{attribute}=\" do |value|\n raise 'Invalid attribute' unless value\n \n instance_variable_set(\"@#{attribute}\", value)\n end\n end\nend", "def method_missing(meth, *args, &blk)\n match = meth.to_s.match(/^([a-zA-Z\\_]+)(=|$)$/)\n if match\n attribute, setter = match[1], !match[2].blank?\n if setter\n write_attribute(attribute, args.first)\n else\n read_attribute(attribute)\n end\n else\n super(meth, *args, &blk)\n end\n end", "def valid_attributes\n { name: 'do this' }\n end", "def make_attributes_definitions_or_croak(attrArgs, &attrBlok)\n eye = :'m_attrs_defs'\n\n # Work with attribute as strings\n \n $DEBUG && logger_me(eye, logger_fmt_kls(:attrArgs => attrArgs, :attrBlok => attrBlok))\n\n mustbe_attributes_specification_or_croak(attrArgs, eye, \"attrArgs not attributes_specification\")\n \n #STOPATTRARGSINSUPER\n \n #attrAll = mustbe_not_empty_or_croak(mustbe_array_key_or_nil_or_croak(attrArgs, :all, eye, \"all attributes not array\"), eye, \"all attributes is empty\").map(&:to_s)\n attrAll = mustbe_not_empty_or_croak(mustbe_attributes_specification_all_key_or_croak(attrArgs, :all, eye), eye, \"all attributes is empty\").map(&:to_s)\n \n\n #puts(\"\\n\\n\\nATTR ALL >#{attrAll}<\")\n\n #STOPMAKEATTRSPECSENTRY\n\n attrInc = mustbe_attributes_specification_include_key_or_nil_or_croak(attrArgs, :include, eye) # mustbe all strings\n #puts(\"ATTR INC >#{attrInc.class}< >#{attrInc}< >#{is_value_not_empty?(attrInc)}<\")\n attrInc && mustbe_not_empty_or_croak(attrInc, eye, \"include attributes is empty\")\n\n attrExc = mustbe_attributes_specification_exclude_key_or_nil_or_croak(attrArgs, :exclude, eye) || []\n \n attrMapNom = mustbe_attributes_definitions_key_or_nil_or_croak(attrArgs, :definitions, eye) || {}\n attrMap = attrMapNom && potrubi_util_map_hash_kv(attrMapNom) {|k,v| [k.to_s, v]} # keys all strings\n\n # Ensure all consistent\n \n attrInc && mustbe_subset_or_croak(attrInc, attrAll, eye, \"include attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrExc, attrAll, eye, \"exclude attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrMap.keys, attrAll, eye, \"attribute map contains unknown attributes\")\n \n attrUse = ((attrInc || attrAll) - attrExc).uniq # list of unique attributes to report on\n\n # consolidate \"faked up\" attr specs with ones provided to get the composite attrSpecs\n \n attrDefsNom = potrubi_util_array_to_hash(attrUse).merge(attrMap.select {|k,v| attrUse.include?(k)}) # consolidated \"faked up\" attr specs with ones provided\n\n attrDefs = potrubi_util_map_hash_v(attrDefsNom) do | attrName, attrSpecNom|\n\n attrSpec =\n case attrSpecNom\n when NilClass then {}\n when Hash then\n attrSpecNom.each_with_object({}) do | (verbName, verbSpec), h1 |\n case verbName\n when :pass_thru then h1[:pass_thru] = verbSpec # dont touch; just pass through\n when :event_defaults then # add these to pass_thru\n h1[:pass_thru] = (h1[:pass_thru] || {}).merge(verbName => verbSpec)\n when :map, :select, :metric then\n h1[verbName] = {\n :method_name => \"#{verbName}_#{attrName}_#{rand(1000000)}\", # make a unqiue name\n :method_spec => verbSpec # spec must be valid to dynamic_define_methods\n }\n else\n logic_exception(verbName, eye, \"attrName >#{attrName}< verbName >#{verbName}< value should be impossible\")\n end\n end\n \n else\n logic_exception(attrrSpecNom, eye, \"attrSpecNom value should be impossible\")\n end\n\n attrSpec\n \n end\n \n $DEBUG && logger_mx(eye, logger_fmt_kls(:attrDefs => attrDefs))\n\n mustbe_attributes_definitions_or_croak(attrDefs, eye, \"attrDefs failed contract\")\n\n #STOPMAKEATTRSPECS\n \n end", "def create_writer(klass, member)\n # We want to convert these members into attributes just like\n # as if they were declared using attr_accessor.\n new_meth = register MethodObject.new(klass, \"#{member}=\", :instance) do |o|\n o.parameters = [['value', nil]]\n o.signature ||= \"def #{member}=(value)\"\n o.source ||= \"#{o.signature}\\n @#{member} = value\\nend\"\n end\n add_writer_tags(klass, new_meth, member)\n klass.attributes[:instance][member][:write] = new_meth\n end", "def create_setter!\n @target.class_eval <<-EOS\n #{writer_visibility.to_s}\n def #{name}=(value)\n attribute_set(#{name.inspect}, value)\n end\n EOS\n rescue SyntaxError\n raise SyntaxError.new(column)\n end", "def attribute name, type, conditions= DEFAULT_ATTRIBUTE_CONDITIONS\n RMOF.complete_conditions conditions, DEFAULT_ATTRIBUTE_CONDITIONS\n @attributes= {} unless instance_variable_defined? :@attributes\n @attributes[name]= [name, type, conditions]\n unless method_defined? :__attributes then \n define_method( :__attributes) do \n @attributes\n end \n end\n at= \"@#{name}\".to_sym\n getter= \"#{name}\".to_sym\n setter= \"#{name}=\".to_sym\n completion= \"__complete_#{name}\".to_sym\n define_method( getter) do\n if instance_variable_defined? at then instance_variable_get at\n else conditions[:default]\n end\n end\n define_method( setter) do |val|\n instance_variable_set at, val\n end\n define_method( completion) do\n RMOF.validate( self.send(getter), name, type, conditions)\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def create_setter(name, meth)\n define_method(\"#{meth}=\") do |value|\n write_attribute(name, value)\n end\n end", "def sanitized_allowed_attributes=(attributes); end", "def sanitized_allowed_attributes=(attributes); end", "def oattr(name, type)\n case type\n when :custom\n # Do nothing, just register attr below.\n when :writer\n attr_writer name\n else\n raise ArgumentError, \"Unknown type: #{type.inspect}\"\n end\n\n # Register and return.\n name.tap { oattrs << name}\n end", "def valid_attributes\n { name: \"Expert\" }\n end", "def attributes(*method_names, **options)\n add_attributes(method_names, **options, strategy: :write_value_using_method_strategy)\n end", "def []=(attr_name, value)\n writer_method = \"#{attr_name}=\"\n send(writer_method, value) if respond_to?(writer_method)\n end", "def write_extended_attributes(attrs)\n attrs.each do |k, val|\n self.send((k.to_s + \"=\").to_sym, val) if is_flex_attribute?(k)\n end\n self\n end", "def valid_attributes\n { \"username\" => \"MyString\" }\n end", "def cattr_writer(*fields)\n metaclass.send :attr_writer, *fields\n end", "def write_attribute(attr, value)\n if attribute_encrypted?(attr)\n conductor_for(attr).encrypt(value)\n else\n super(attr, value)\n end\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_number_value(\"offsetInDays\", @offset_in_days)\n writer.write_enum_value(\"timeBasedAttribute\", @time_based_attribute)\n end", "def define_attribute_method(attr_name, _owner: generated_attribute_methods)\n CodeGenerator.batch(_owner, __FILE__, __LINE__) do |owner|\n attribute_method_matchers.each do |matcher|\n method_name = matcher.method_name(attr_name)\n\n unless instance_method_already_implemented?(method_name)\n generate_method = \"define_method_#{matcher.target}\"\n\n if respond_to?(generate_method, true)\n send(generate_method, attr_name.to_s, owner: owner)\n else\n define_proxy_call true, owner, method_name, matcher.target, attr_name.to_s\n end\n end\n end\n attribute_method_matchers_cache.clear\n end\n end", "def has_attributes?; end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_boolean_value(\"isExpirationRequired\", @is_expiration_required)\n writer.write_duration_value(\"maximumDuration\", @maximum_duration)\n end", "def add_attributes(item)\n [:class, :instance].each do |attr_loc|\n # Grab attributes for the current location (class or instance)\n attrs = item.attributes[attr_loc]\n attrs.each do |name, attribute|\n reader = attribute[:read]\n writer = attribute[:write]\n\n unless reader || writer\n Logging.warn(\"attribute is not readable or writable somehow, skipping\", attribute)\n next\n end\n\n # Get all given types\n yard_types = []\n if reader\n next if @hide_private && reader.visibility == :private\n yard_types += reader.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n reader.tags('param').flat_map(&:types)\n end\n if writer\n next if @hide_private && writer.visibility == :private\n yard_types += writer.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n writer.tags('param').flat_map(&:types)\n end\n\n # Use untyped if not types specified anywhere, otherwise try to\n # compute Parlour type given all these types\n if yard_types.empty?\n Logging.omit(\"no YARD type given for #{name.inspect}, using untyped\", reader || writer)\n parlour_type = Parlour::Types::Untyped.new\n elsif yard_types.all? { |x| x == 'nil' }\n # Nil attributes are extremely unusual, so just use untyped\n parlour_type = Parlour::Types::Untyped.new\n else\n parlour_type = TypeConverter.yard_to_parlour(\n yard_types, reader || writer, @type_converter_config)\n end\n\n # Generate attribute\n if reader && writer\n kind = :accessor\n elsif reader\n kind = :reader\n elsif writer\n kind = :writer\n end\n\n if @exclude_untyped && parlour_type.is_a?(Parlour::Types::Untyped)\n Logging.omit(\"excluding untyped attribute\", reader || writer, immediate: true)\n next\n end\n\n case @mode\n when :rbi\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n class_attribute: (attr_loc == :class)\n ) do |m|\n add_comments(reader || writer, m)\n end\n when :rbs\n if attr_loc == :class\n # RBS doesn't support class attr_accessors so create individual methods\n\n if reader\n @current_object.create_method(\n name.to_s,\n [Parlour::RbsGenerator::MethodSignature.new([], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(reader, m)\n end\n end\n\n if writer\n @current_object.create_method(\n \"#{name}=\",\n [Parlour::RbsGenerator::MethodSignature.new([Parlour::RbsGenerator::Parameter.new(\n \"value\",\n type: parlour_type,\n required: true\n )], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(writer, m)\n end\n end\n else\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n ) do |m|\n add_comments(reader || writer, m)\n end\n end\n end\n end\n end\n end", "def []=(attr_name, value)\r\n if attr_name.is_a?(String) and attr_name != attr_name.split(ID_SEP).first\r\n attr_name = attr_name.split(ID_SEP)\r\n end\r\n\r\n if attr_name.is_a? Array\r\n value = value.split(ID_SEP) if value.is_a? String\r\n unless value.length == attr_name.length\r\n raise \"Number of attr_names and values do not match\"\r\n end\r\n #breakpoint\r\n [attr_name, value].transpose.map {|name,val| write_attribute(name.to_s, val)}\r\n else\r\n write_attribute(attr_name, value)\r\n end\r\n end", "def attr(symbol, writable=false) end", "def define_writer!(k, definition)\n define_method(\"#{k}=\") do |value|\n # Recursively convert hash and array of hash to schematized objects\n value = ensure_schema value, definition[:schema]\n\n # Initial value\n instance_variable_set \"@#{k}\", value\n\n # Dirty tracking\n self.changed_attributes ||= Set.new\n self.changed_attributes << k\n end\n end", "def validate\n validate_string_attributes\n end", "def write_attribute_with_dynamo(field_name, value)\n if is_dynamo_field?(field_name)\n # Store these guys for now. We don't actually save the field value until the model is saved ( i.e my_supplier.save ).\n # If we were to save the field_value now we wouldn't be able to know the id of the model to link this value to it.\n # @see delay_save\n @all_fields_and_values ||= []\n @all_fields_and_values << {:dynamo_field=>cached_dynamo_field_by_name(field_name), :value=>value}\n end\n # If its a 'normal' attribute let rails write it in the usual way.\n write_attribute_without_dynamo(field_name, value)\n end", "def define_attr_accessor(attr)\n attr_accessor(attr)\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n writer.write_collection_of_object_values(\"attributeMappings\", @attribute_mappings)\n writer.write_boolean_value(\"enabled\", @enabled)\n writer.write_enum_value(\"flowTypes\", @flow_types)\n writer.write_collection_of_object_values(\"metadata\", @metadata)\n writer.write_string_value(\"name\", @name)\n writer.write_string_value(\"@odata.type\", @odata_type)\n writer.write_object_value(\"scope\", @scope)\n writer.write_string_value(\"sourceObjectName\", @source_object_name)\n writer.write_string_value(\"targetObjectName\", @target_object_name)\n writer.write_additional_data(@additional_data)\n end", "def validate_attribute_syntax\n\t\t@values.each do |attribute, values|\n\t\t\t[ values ].flatten.each do |value|\n\t\t\t\tbegin\n\t\t\t\t\tself.get_converted_attribute( attribute.to_sym, value )\n\t\t\t\trescue => err\n\t\t\t\t\tself.log.error \"validation for %p failed: %s: %s\" %\n\t\t\t\t\t\t[ attribute, err.class.name, err.message ]\n\t\t\t\t\tattrtype = self.find_attribute_type( attribute )\n\t\t\t\t\tself.errors.add( attribute, \"isn't a valid %s value\" %\n\t\t\t\t\t\t[ attrtype.syntax ? attrtype.syntax.desc : attrtype.syntax_oid ] )\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def valid_attributes\n { }\n end", "def validatable_attributes(atts, opts)\n am, an, ab, m = opts.values_at(:allow_missing, :allow_nil, :allow_blank, :message)\n Array(atts).each do |a|\n next if am && !values.has_key?(a)\n v = send(a)\n next if an && v.nil?\n next if ab && v.respond_to?(:blank?) && v.blank?\n if message = yield(a, v, m)\n errors.add(a, message)\n end\n end\n end", "def valid_attributes\n { }\n end", "def valid_attributes\n { }\n end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def require_attr(name)\n send(name).tap do |_|\n raise \"Attribute must be set: #{name}\" if _.nil?\n end\n end", "def write_attributes(attributes)\n _attributes = attributes.select do |name, value|\n if self.is_dynamic_field?(name)\n self.dynamic_setter(name, value)\n false\n else\n true\n end\n end\n\n super(_attributes)\n end", "def attribute; end", "def attribute; end" ]
[ "0.6472992", "0.6315012", "0.6315012", "0.62821025", "0.6279224", "0.6211609", "0.61891466", "0.6182247", "0.60683644", "0.6032628", "0.5995443", "0.5988785", "0.5959885", "0.5938289", "0.5931089", "0.58951056", "0.5859927", "0.5851703", "0.58493423", "0.58465594", "0.58328366", "0.5823013", "0.5822229", "0.57850474", "0.5701491", "0.5696689", "0.5682951", "0.5678094", "0.566814", "0.5657499", "0.56555206", "0.5642589", "0.56219065", "0.5615893", "0.56105876", "0.559851", "0.5598089", "0.55940455", "0.5585137", "0.55848545", "0.55796933", "0.5571477", "0.5567006", "0.55667996", "0.55652434", "0.5562926", "0.55600035", "0.55590326", "0.55590326", "0.5554599", "0.5554599", "0.55407417", "0.5534935", "0.5527733", "0.55271375", "0.55238813", "0.5501504", "0.5497003", "0.5496233", "0.54927665", "0.5464706", "0.54617554", "0.5461167", "0.5451583", "0.54498726", "0.54498726", "0.54359984", "0.5430996", "0.5430996", "0.5426488", "0.5418467", "0.54153895", "0.54107565", "0.5407886", "0.5401234", "0.54008496", "0.5400268", "0.53910094", "0.53827274", "0.5377731", "0.5375473", "0.5374833", "0.53720397", "0.5370215", "0.5363264", "0.5361161", "0.5360557", "0.5351706", "0.53514725", "0.53492516", "0.53459316", "0.5341237", "0.5328037", "0.5328037", "0.53230566", "0.53230566", "0.53230566", "0.5319575", "0.531832", "0.5315559", "0.5315559" ]
0.0
-1
Custom attribute writer method with validation
def udp_multiple=(udp_multiple) if udp_multiple.nil? fail ArgumentError, 'udp_multiple cannot be nil' end if udp_multiple > 4320000 fail ArgumentError, 'invalid value for "udp_multiple", must be smaller than or equal to 4320000.' end if udp_multiple < 10 fail ArgumentError, 'invalid value for "udp_multiple", must be greater than or equal to 10.' end @udp_multiple = udp_multiple end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def attr_writer_tag(text); end", "def allowed_attributes=(_arg0); end", "def allowed_attributes=(_arg0); end", "def writer(*args)\n attr_writer(*args)\n args\n end", "def define_write_method(attr_name)\n evaluate_attribute_method attr_name, \"def #{attr_name}=(new_value);write_attribute('#{attr_name}', new_value);end\", \"#{attr_name}=\"\n end", "def attr_writer(*vars)\n # avoid tracking attributes that are added by the class_attribute\n # as these are class attributes and not instance attributes.\n tracked_vars = vars.reject {|var| respond_to? var }\n add_tracked_attrs(false, true, *tracked_vars)\n vars.extract_options!\n super\n end", "def attr_writer(sym, *more) end", "def is_attribute?; end", "def validate_exclusion_of(attr); end", "def register_attributes\n raise \"Not implemented in #{self.class}\"\n end", "def method_missing(method_name, *args)\n return super unless permitted_attributes.include?(method_name)\n begin\n object.send(:\"#{method_name}=\", args.first)\n rescue => e\n if params.has_key?(method_name)\n message = \"Unable to process value for :#{method_name}, no attribute writer. Be sure to override the automatic setters for all params that do not map straight to a model attribute.\"\n Rails.logger.warn({message: message,\n missing_writer: method_name,\n value: args.first,\n error: e})\n self.errors << {status: 422, message: message}\n else\n raise e\n end\n end\n end", "def timeliness_validation_for(attr_names, type)\n super\n attr_names.each { |attr_name| define_timeliness_write_method(attr_name) }\n end", "def create_setter_for(attribute, options)\n setter_method = \"#{attribute}=\"\n\n define_method setter_method do |value|\n if options[:allow_blank] || value != \"\"\n write_attribute(attribute, value)\n end\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each {|attr_name| attr_internal_define(attr_name, :writer)}\n end", "def escape_attr input\n escape input, attr_regexp, attr_mapping\n end", "def make_writer( attrtype )\n\t\tself.log.debug \"Generating an attribute writer for %p\" % [ attrtype ]\n\t\tattrname = attrtype.name\n\t\tif attrtype.single?\n\t\t\tself.log.debug \" attribute is SINGLE, so generating a scalar writer...\"\n\t\t\treturn lambda {|newvalue| self[attrname] = newvalue }\n\t\telse\n\t\t\tself.log.debug \" attribute isn't SINGLE, so generating an array writer...\"\n\t\t\treturn lambda {|*newvalues| self[attrname] = newvalues.flatten }\n\t\tend\n\tend", "def write_attribute(name, value)\n # Simply check if the accessor is allowed to write the field\n # (if so, go to superclass and do it)\n @bypass_auth ||= false\n if allowed_to_write(name) || @bypass_auth\n super(name, value)\n end\n end", "def mattr_writer(*syms, &proc)\n receiver = self\n options = syms.extract_options!\n syms.each do |sym|\n raise NameError.new('invalid attribute name') unless sym =~ /^[_A-Za-z]\\w*$/\n class_exec do\n define_singleton_method \"#{sym}=\" do |obj|\n class_variable_set(\"@@#{sym}\", obj)\n end\n end\n\n unless options[:instance_writer] == false || options[:instance_accessor] == false\n class_exec do\n define_method \"#{sym}=\" do |obj|\n receiver.class_variable_set(\"@@#{sym}\", obj)\n end\n end\n end\n send(\"#{sym}=\", proc.call) if proc\n end\n end", "def write_attribute(attribute, value)\n false\n end", "def add_attribute attribute\n return attribute unless @document_self\n\n # mainly to check for redefinition of an attribute as a method\n # TODO find a policy for 'attr_reader :foo' + 'def foo=()'\n register = false\n\n key = nil\n\n if attribute.rw.index 'R' then\n key = attribute.pretty_name\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name + '='] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if attribute.rw.index 'W' then\n key = attribute.pretty_name + '='\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if register then\n attribute.visibility = @visibility\n add_to @attributes, attribute\n resolve_aliases attribute\n end\n\n attribute\n end", "def define_writer_method(mod)\n writer_method_name = \"#{name}=\"\n attribute = self\n\n mod.send(:define_method, writer_method_name) { |value| attribute.set(self, value) }\n mod.send(writer_visibility, writer_method_name)\n\n self\n end", "def allowed_to_write(name)\n # no point allowing attribute writes if we can't save them?\n if allowed_to_save\n name = name.to_s\n validation_methods = self.class.write_validations(name) \n if validation_methods.nil?\n # We haven't registered any filters on this attribute, so allow the write.\n true\n elsif validation_methods.check :accessor => accessor, :model => self\n # One of the authentication methods worked, so allow the write.\n true\n else\n # We had filters but none of them passed. Disallow write.\n false\n end\n else\n false\n end\n end", "def assert_attr_writer(obj, method)\n assert_respond_to obj, \"#{method}=\"\nend", "def add_attribute(name, &block); end", "def authenticates_writes_to(attr, options={})\n authenticates_access\n @write_validation_map ||= {}\n @write_validation_map[attr.to_s] ||= AuthMethodList.new\n @write_validation_map[attr.to_s].add_method(options)\n end", "def write_attribute_3(param1, param2)\n\twrite_attribute(param1, param2)\n end", "def write_attribute(attr_name, value) #:doc:\n @attributes[attr_name] = empty_string_for_number_column?(attr_name, value) ? nil : value\n end", "def add_writer_tags(klass, new_method, member)\n member_tag = member_tag_for_member(klass, member, :write)\n return_type = return_type_from_tag(member_tag)\n setter_doc_text = member_tag ? member_tag.text : \"Sets the attribute #{member}\"\n new_method.docstring.replace(setter_doc_text)\n new_method.add_tag YARD::Tags::Tag.new(:param, \"the value to set the attribute #{member} to.\", return_type, \"value\")\n new_method.add_tag YARD::Tags::Tag.new(:return, \"the newly set value\", return_type)\n end", "def print_attribute(*) end", "def attribute(name); end", "def add_checked_attribute(clazz, attribute)\r\n eval <<END\r\n class #{clazz}\r\n\r\n def #{attribute}=(value)\r\n raise 'Invalid attribute' unless value\r\n @#{attribute}=value\r\n end\r\n\r\n def #{attribute}\r\n #{attribute}\r\n end\r\n end\r\nEND\r\nend", "def attr(name); end", "def is_attribute?(line)\n (line =~ /(\\s+)attr_(writer|reader|accessor)\\s+:[a-zA-Z_0-9]+/) == 0\n end", "def attribute(name, value)\n\t if !@inStartTag\n\t\traise WriterError.new('attribute outside of tag start')\n\t end\n\t @io << \" #{name}=\\\"#{NQXML.encode(value.to_s)}\\\"\"\n\tend", "def set_attribute(name, value); end", "def dataset_writer(*attributes)\n attributes.flatten.each do |attr_name|\n next if method_defined?(\"#{attr_name}=\")\n\n class_eval <<-RUBY, __FILE__, __LINE__ + 1\n def #{attr_name}=(value)\n dataset_set(:#{attr_name}, value)\n end\n RUBY\n end\n end", "def validated_attribute_names(params); end", "def require_format_of(attribute)\r\n RequireFormatOf.new(attribute)\r\n end", "def attr_writer(*fields)\n check_fields(fields)\n added_fields = jiak.data.writable(*fields)\n added_fields.each do |field|\n class_eval <<-EOM\n def #{field}=(val)\n @jiak.object.data.#{field} = val\n self.class.do_auto_update(self)\n end\n EOM\n end\n nil\n end", "def html_attr(*attrs)\n options = attrs.extract_options!.reverse_merge({\n :level => :super_relaxed\n })\n attrs.each do |att|\n class_eval \"def #{att}=(val); self[:#{att}] = sanitize(val, :#{options[:level]}); end\"\n end\n end", "def validate_attributes=(new_attribute)\n @validate_attributes = new_attribute\n end", "def html_attributes(attr); end", "def instance_write(attr, value)\n setter = :\"#{@name_string}_#{attr}=\"\n instance.send(setter, value) if instance.respond_to?(setter)\n end", "def valid_xml_attribute(name, options={:level => :warning})\n\t\t\t\tvalidate(\"Invalid XML attribute '#{name}'\", options) { name.to_s.match(/^([^[:punct:]0-9<>]|_)[^<>\"']*/) }\n\t\t\tend", "def attr_writer(*args)\n sym_args=args_to_sym(args)\n sym_args.each do |value|\n self.instance_eval(\"def #{value}=(arg); @#{value}=arg;end;\")\n end\n \n end", "def define_writer_method(attribute, method_name, visibility)\n define_method(method_name) { |value| attribute.set(self, value) }\n send(visibility, method_name)\n self\n end", "def write_attribute(name, val)\n if @embedded_models.include? name\n @embedded_models[name].model = val\n elsif @attribute_objects.include? name\n @attribute_objects[name].value = val\n else\n return false\n end\n\n run_callbacks :attribute_change\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def attr; end", "def attribute(*args)\n define_expressions(Attribute, args)\n end", "def write_attribute(name, value)\n name = name.to_s\n\n # The attribute already has an unsaved change.\n if attribute_changed?(name)\n old = changed_attributes[name]\n changed_attributes.delete(name) unless field_changed?(name, old, value)\n else\n attribute_will_change(name) if field_changed?(name, old, value)\n end\n\n # Carry on.\n super(name, value)\n end", "def define_magic_attr(name)\n define_method name do |*attrs|\n raise ArgumentError.new(\"wrong number of arguments\") if attrs.size > 1\n send(\"#{name}=\", attrs.first) if attrs.size == 1\n instance_variable_get(\"@#{name}\")\n end\n\n attr_writer name\n end", "def configurable_writer(attribute, code=nil, &block)\n if block_given? and not code\n Halcyon.class.send(:define_method, :\"#{attribute}=\", block)\n elsif code and not block_given?\n Halcyon.class.send(:eval, <<-\"end;\")\n def #{attribute.to_s}=(value)\n #{code % [attribute.to_sym.inspect]}\n end\n end;\n else\n raise ArgumentError.new(\"Either a block or a code string should be supplied.\")\n end\n end", "def method_missing(name, *args, &block)\n if /\\Ahas_validated_(?<type>\\w*)_attribute\\Z/ =~ name\n has_validated_attribute(type, *args, &block)\n else\n super\n end\n end", "def add_checked_attribute(klass, attribute)\n klass.class_eval do\n define_method attribute do\n instance_variable_get(\"@#{attribute}\")\n end\n\n define_method \"#{attribute}=\" do |value|\n raise 'Invalid attribute' unless value\n \n instance_variable_set(\"@#{attribute}\", value)\n end\n end\nend", "def method_missing(meth, *args, &blk)\n match = meth.to_s.match(/^([a-zA-Z\\_]+)(=|$)$/)\n if match\n attribute, setter = match[1], !match[2].blank?\n if setter\n write_attribute(attribute, args.first)\n else\n read_attribute(attribute)\n end\n else\n super(meth, *args, &blk)\n end\n end", "def valid_attributes\n { name: 'do this' }\n end", "def make_attributes_definitions_or_croak(attrArgs, &attrBlok)\n eye = :'m_attrs_defs'\n\n # Work with attribute as strings\n \n $DEBUG && logger_me(eye, logger_fmt_kls(:attrArgs => attrArgs, :attrBlok => attrBlok))\n\n mustbe_attributes_specification_or_croak(attrArgs, eye, \"attrArgs not attributes_specification\")\n \n #STOPATTRARGSINSUPER\n \n #attrAll = mustbe_not_empty_or_croak(mustbe_array_key_or_nil_or_croak(attrArgs, :all, eye, \"all attributes not array\"), eye, \"all attributes is empty\").map(&:to_s)\n attrAll = mustbe_not_empty_or_croak(mustbe_attributes_specification_all_key_or_croak(attrArgs, :all, eye), eye, \"all attributes is empty\").map(&:to_s)\n \n\n #puts(\"\\n\\n\\nATTR ALL >#{attrAll}<\")\n\n #STOPMAKEATTRSPECSENTRY\n\n attrInc = mustbe_attributes_specification_include_key_or_nil_or_croak(attrArgs, :include, eye) # mustbe all strings\n #puts(\"ATTR INC >#{attrInc.class}< >#{attrInc}< >#{is_value_not_empty?(attrInc)}<\")\n attrInc && mustbe_not_empty_or_croak(attrInc, eye, \"include attributes is empty\")\n\n attrExc = mustbe_attributes_specification_exclude_key_or_nil_or_croak(attrArgs, :exclude, eye) || []\n \n attrMapNom = mustbe_attributes_definitions_key_or_nil_or_croak(attrArgs, :definitions, eye) || {}\n attrMap = attrMapNom && potrubi_util_map_hash_kv(attrMapNom) {|k,v| [k.to_s, v]} # keys all strings\n\n # Ensure all consistent\n \n attrInc && mustbe_subset_or_croak(attrInc, attrAll, eye, \"include attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrExc, attrAll, eye, \"exclude attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrMap.keys, attrAll, eye, \"attribute map contains unknown attributes\")\n \n attrUse = ((attrInc || attrAll) - attrExc).uniq # list of unique attributes to report on\n\n # consolidate \"faked up\" attr specs with ones provided to get the composite attrSpecs\n \n attrDefsNom = potrubi_util_array_to_hash(attrUse).merge(attrMap.select {|k,v| attrUse.include?(k)}) # consolidated \"faked up\" attr specs with ones provided\n\n attrDefs = potrubi_util_map_hash_v(attrDefsNom) do | attrName, attrSpecNom|\n\n attrSpec =\n case attrSpecNom\n when NilClass then {}\n when Hash then\n attrSpecNom.each_with_object({}) do | (verbName, verbSpec), h1 |\n case verbName\n when :pass_thru then h1[:pass_thru] = verbSpec # dont touch; just pass through\n when :event_defaults then # add these to pass_thru\n h1[:pass_thru] = (h1[:pass_thru] || {}).merge(verbName => verbSpec)\n when :map, :select, :metric then\n h1[verbName] = {\n :method_name => \"#{verbName}_#{attrName}_#{rand(1000000)}\", # make a unqiue name\n :method_spec => verbSpec # spec must be valid to dynamic_define_methods\n }\n else\n logic_exception(verbName, eye, \"attrName >#{attrName}< verbName >#{verbName}< value should be impossible\")\n end\n end\n \n else\n logic_exception(attrrSpecNom, eye, \"attrSpecNom value should be impossible\")\n end\n\n attrSpec\n \n end\n \n $DEBUG && logger_mx(eye, logger_fmt_kls(:attrDefs => attrDefs))\n\n mustbe_attributes_definitions_or_croak(attrDefs, eye, \"attrDefs failed contract\")\n\n #STOPMAKEATTRSPECS\n \n end", "def create_writer(klass, member)\n # We want to convert these members into attributes just like\n # as if they were declared using attr_accessor.\n new_meth = register MethodObject.new(klass, \"#{member}=\", :instance) do |o|\n o.parameters = [['value', nil]]\n o.signature ||= \"def #{member}=(value)\"\n o.source ||= \"#{o.signature}\\n @#{member} = value\\nend\"\n end\n add_writer_tags(klass, new_meth, member)\n klass.attributes[:instance][member][:write] = new_meth\n end", "def create_setter!\n @target.class_eval <<-EOS\n #{writer_visibility.to_s}\n def #{name}=(value)\n attribute_set(#{name.inspect}, value)\n end\n EOS\n rescue SyntaxError\n raise SyntaxError.new(column)\n end", "def attribute name, type, conditions= DEFAULT_ATTRIBUTE_CONDITIONS\n RMOF.complete_conditions conditions, DEFAULT_ATTRIBUTE_CONDITIONS\n @attributes= {} unless instance_variable_defined? :@attributes\n @attributes[name]= [name, type, conditions]\n unless method_defined? :__attributes then \n define_method( :__attributes) do \n @attributes\n end \n end\n at= \"@#{name}\".to_sym\n getter= \"#{name}\".to_sym\n setter= \"#{name}=\".to_sym\n completion= \"__complete_#{name}\".to_sym\n define_method( getter) do\n if instance_variable_defined? at then instance_variable_get at\n else conditions[:default]\n end\n end\n define_method( setter) do |val|\n instance_variable_set at, val\n end\n define_method( completion) do\n RMOF.validate( self.send(getter), name, type, conditions)\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def create_setter(name, meth)\n define_method(\"#{meth}=\") do |value|\n write_attribute(name, value)\n end\n end", "def sanitized_allowed_attributes=(attributes); end", "def sanitized_allowed_attributes=(attributes); end", "def oattr(name, type)\n case type\n when :custom\n # Do nothing, just register attr below.\n when :writer\n attr_writer name\n else\n raise ArgumentError, \"Unknown type: #{type.inspect}\"\n end\n\n # Register and return.\n name.tap { oattrs << name}\n end", "def valid_attributes\n { name: \"Expert\" }\n end", "def attributes(*method_names, **options)\n add_attributes(method_names, **options, strategy: :write_value_using_method_strategy)\n end", "def []=(attr_name, value)\n writer_method = \"#{attr_name}=\"\n send(writer_method, value) if respond_to?(writer_method)\n end", "def write_extended_attributes(attrs)\n attrs.each do |k, val|\n self.send((k.to_s + \"=\").to_sym, val) if is_flex_attribute?(k)\n end\n self\n end", "def valid_attributes\n { \"username\" => \"MyString\" }\n end", "def cattr_writer(*fields)\n metaclass.send :attr_writer, *fields\n end", "def write_attribute(attr, value)\n if attribute_encrypted?(attr)\n conductor_for(attr).encrypt(value)\n else\n super(attr, value)\n end\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_number_value(\"offsetInDays\", @offset_in_days)\n writer.write_enum_value(\"timeBasedAttribute\", @time_based_attribute)\n end", "def define_attribute_method(attr_name, _owner: generated_attribute_methods)\n CodeGenerator.batch(_owner, __FILE__, __LINE__) do |owner|\n attribute_method_matchers.each do |matcher|\n method_name = matcher.method_name(attr_name)\n\n unless instance_method_already_implemented?(method_name)\n generate_method = \"define_method_#{matcher.target}\"\n\n if respond_to?(generate_method, true)\n send(generate_method, attr_name.to_s, owner: owner)\n else\n define_proxy_call true, owner, method_name, matcher.target, attr_name.to_s\n end\n end\n end\n attribute_method_matchers_cache.clear\n end\n end", "def has_attributes?; end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_boolean_value(\"isExpirationRequired\", @is_expiration_required)\n writer.write_duration_value(\"maximumDuration\", @maximum_duration)\n end", "def add_attributes(item)\n [:class, :instance].each do |attr_loc|\n # Grab attributes for the current location (class or instance)\n attrs = item.attributes[attr_loc]\n attrs.each do |name, attribute|\n reader = attribute[:read]\n writer = attribute[:write]\n\n unless reader || writer\n Logging.warn(\"attribute is not readable or writable somehow, skipping\", attribute)\n next\n end\n\n # Get all given types\n yard_types = []\n if reader\n next if @hide_private && reader.visibility == :private\n yard_types += reader.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n reader.tags('param').flat_map(&:types)\n end\n if writer\n next if @hide_private && writer.visibility == :private\n yard_types += writer.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n writer.tags('param').flat_map(&:types)\n end\n\n # Use untyped if not types specified anywhere, otherwise try to\n # compute Parlour type given all these types\n if yard_types.empty?\n Logging.omit(\"no YARD type given for #{name.inspect}, using untyped\", reader || writer)\n parlour_type = Parlour::Types::Untyped.new\n elsif yard_types.all? { |x| x == 'nil' }\n # Nil attributes are extremely unusual, so just use untyped\n parlour_type = Parlour::Types::Untyped.new\n else\n parlour_type = TypeConverter.yard_to_parlour(\n yard_types, reader || writer, @type_converter_config)\n end\n\n # Generate attribute\n if reader && writer\n kind = :accessor\n elsif reader\n kind = :reader\n elsif writer\n kind = :writer\n end\n\n if @exclude_untyped && parlour_type.is_a?(Parlour::Types::Untyped)\n Logging.omit(\"excluding untyped attribute\", reader || writer, immediate: true)\n next\n end\n\n case @mode\n when :rbi\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n class_attribute: (attr_loc == :class)\n ) do |m|\n add_comments(reader || writer, m)\n end\n when :rbs\n if attr_loc == :class\n # RBS doesn't support class attr_accessors so create individual methods\n\n if reader\n @current_object.create_method(\n name.to_s,\n [Parlour::RbsGenerator::MethodSignature.new([], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(reader, m)\n end\n end\n\n if writer\n @current_object.create_method(\n \"#{name}=\",\n [Parlour::RbsGenerator::MethodSignature.new([Parlour::RbsGenerator::Parameter.new(\n \"value\",\n type: parlour_type,\n required: true\n )], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(writer, m)\n end\n end\n else\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n ) do |m|\n add_comments(reader || writer, m)\n end\n end\n end\n end\n end\n end", "def []=(attr_name, value)\r\n if attr_name.is_a?(String) and attr_name != attr_name.split(ID_SEP).first\r\n attr_name = attr_name.split(ID_SEP)\r\n end\r\n\r\n if attr_name.is_a? Array\r\n value = value.split(ID_SEP) if value.is_a? String\r\n unless value.length == attr_name.length\r\n raise \"Number of attr_names and values do not match\"\r\n end\r\n #breakpoint\r\n [attr_name, value].transpose.map {|name,val| write_attribute(name.to_s, val)}\r\n else\r\n write_attribute(attr_name, value)\r\n end\r\n end", "def attr(symbol, writable=false) end", "def define_writer!(k, definition)\n define_method(\"#{k}=\") do |value|\n # Recursively convert hash and array of hash to schematized objects\n value = ensure_schema value, definition[:schema]\n\n # Initial value\n instance_variable_set \"@#{k}\", value\n\n # Dirty tracking\n self.changed_attributes ||= Set.new\n self.changed_attributes << k\n end\n end", "def validate\n validate_string_attributes\n end", "def write_attribute_with_dynamo(field_name, value)\n if is_dynamo_field?(field_name)\n # Store these guys for now. We don't actually save the field value until the model is saved ( i.e my_supplier.save ).\n # If we were to save the field_value now we wouldn't be able to know the id of the model to link this value to it.\n # @see delay_save\n @all_fields_and_values ||= []\n @all_fields_and_values << {:dynamo_field=>cached_dynamo_field_by_name(field_name), :value=>value}\n end\n # If its a 'normal' attribute let rails write it in the usual way.\n write_attribute_without_dynamo(field_name, value)\n end", "def define_attr_accessor(attr)\n attr_accessor(attr)\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n writer.write_collection_of_object_values(\"attributeMappings\", @attribute_mappings)\n writer.write_boolean_value(\"enabled\", @enabled)\n writer.write_enum_value(\"flowTypes\", @flow_types)\n writer.write_collection_of_object_values(\"metadata\", @metadata)\n writer.write_string_value(\"name\", @name)\n writer.write_string_value(\"@odata.type\", @odata_type)\n writer.write_object_value(\"scope\", @scope)\n writer.write_string_value(\"sourceObjectName\", @source_object_name)\n writer.write_string_value(\"targetObjectName\", @target_object_name)\n writer.write_additional_data(@additional_data)\n end", "def validate_attribute_syntax\n\t\t@values.each do |attribute, values|\n\t\t\t[ values ].flatten.each do |value|\n\t\t\t\tbegin\n\t\t\t\t\tself.get_converted_attribute( attribute.to_sym, value )\n\t\t\t\trescue => err\n\t\t\t\t\tself.log.error \"validation for %p failed: %s: %s\" %\n\t\t\t\t\t\t[ attribute, err.class.name, err.message ]\n\t\t\t\t\tattrtype = self.find_attribute_type( attribute )\n\t\t\t\t\tself.errors.add( attribute, \"isn't a valid %s value\" %\n\t\t\t\t\t\t[ attrtype.syntax ? attrtype.syntax.desc : attrtype.syntax_oid ] )\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def valid_attributes\n { }\n end", "def validatable_attributes(atts, opts)\n am, an, ab, m = opts.values_at(:allow_missing, :allow_nil, :allow_blank, :message)\n Array(atts).each do |a|\n next if am && !values.has_key?(a)\n v = send(a)\n next if an && v.nil?\n next if ab && v.respond_to?(:blank?) && v.blank?\n if message = yield(a, v, m)\n errors.add(a, message)\n end\n end\n end", "def valid_attributes\n { }\n end", "def valid_attributes\n { }\n end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def require_attr(name)\n send(name).tap do |_|\n raise \"Attribute must be set: #{name}\" if _.nil?\n end\n end", "def write_attributes(attributes)\n _attributes = attributes.select do |name, value|\n if self.is_dynamic_field?(name)\n self.dynamic_setter(name, value)\n false\n else\n true\n end\n end\n\n super(_attributes)\n end", "def attribute; end", "def attribute; end" ]
[ "0.6472992", "0.6315012", "0.6315012", "0.62821025", "0.6279224", "0.6211609", "0.61891466", "0.6182247", "0.60683644", "0.6032628", "0.5995443", "0.5988785", "0.5959885", "0.5938289", "0.5931089", "0.58951056", "0.5859927", "0.5851703", "0.58493423", "0.58465594", "0.58328366", "0.5823013", "0.5822229", "0.57850474", "0.5701491", "0.5696689", "0.5682951", "0.5678094", "0.566814", "0.5657499", "0.56555206", "0.5642589", "0.56219065", "0.5615893", "0.56105876", "0.559851", "0.5598089", "0.55940455", "0.5585137", "0.55848545", "0.55796933", "0.5571477", "0.5567006", "0.55667996", "0.55652434", "0.5562926", "0.55600035", "0.55590326", "0.55590326", "0.5554599", "0.5554599", "0.55407417", "0.5534935", "0.5527733", "0.55271375", "0.55238813", "0.5501504", "0.5497003", "0.5496233", "0.54927665", "0.5464706", "0.54617554", "0.5461167", "0.5451583", "0.54498726", "0.54498726", "0.54359984", "0.5430996", "0.5430996", "0.5426488", "0.5418467", "0.54153895", "0.54107565", "0.5407886", "0.5401234", "0.54008496", "0.5400268", "0.53910094", "0.53827274", "0.5377731", "0.5375473", "0.5374833", "0.53720397", "0.5370215", "0.5363264", "0.5361161", "0.5360557", "0.5351706", "0.53514725", "0.53492516", "0.53459316", "0.5341237", "0.5328037", "0.5328037", "0.53230566", "0.53230566", "0.53230566", "0.5319575", "0.531832", "0.5315559", "0.5315559" ]
0.0
-1
Custom attribute writer method with validation
def icmp_error_reply=(icmp_error_reply) if icmp_error_reply.nil? fail ArgumentError, 'icmp_error_reply cannot be nil' end if icmp_error_reply > 4320000 fail ArgumentError, 'invalid value for "icmp_error_reply", must be smaller than or equal to 4320000.' end if icmp_error_reply < 10 fail ArgumentError, 'invalid value for "icmp_error_reply", must be greater than or equal to 10.' end @icmp_error_reply = icmp_error_reply end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def attr_writer_tag(text); end", "def allowed_attributes=(_arg0); end", "def allowed_attributes=(_arg0); end", "def writer(*args)\n attr_writer(*args)\n args\n end", "def define_write_method(attr_name)\n evaluate_attribute_method attr_name, \"def #{attr_name}=(new_value);write_attribute('#{attr_name}', new_value);end\", \"#{attr_name}=\"\n end", "def attr_writer(*vars)\n # avoid tracking attributes that are added by the class_attribute\n # as these are class attributes and not instance attributes.\n tracked_vars = vars.reject {|var| respond_to? var }\n add_tracked_attrs(false, true, *tracked_vars)\n vars.extract_options!\n super\n end", "def attr_writer(sym, *more) end", "def is_attribute?; end", "def validate_exclusion_of(attr); end", "def register_attributes\n raise \"Not implemented in #{self.class}\"\n end", "def method_missing(method_name, *args)\n return super unless permitted_attributes.include?(method_name)\n begin\n object.send(:\"#{method_name}=\", args.first)\n rescue => e\n if params.has_key?(method_name)\n message = \"Unable to process value for :#{method_name}, no attribute writer. Be sure to override the automatic setters for all params that do not map straight to a model attribute.\"\n Rails.logger.warn({message: message,\n missing_writer: method_name,\n value: args.first,\n error: e})\n self.errors << {status: 422, message: message}\n else\n raise e\n end\n end\n end", "def timeliness_validation_for(attr_names, type)\n super\n attr_names.each { |attr_name| define_timeliness_write_method(attr_name) }\n end", "def create_setter_for(attribute, options)\n setter_method = \"#{attribute}=\"\n\n define_method setter_method do |value|\n if options[:allow_blank] || value != \"\"\n write_attribute(attribute, value)\n end\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each {|attr_name| attr_internal_define(attr_name, :writer)}\n end", "def escape_attr input\n escape input, attr_regexp, attr_mapping\n end", "def make_writer( attrtype )\n\t\tself.log.debug \"Generating an attribute writer for %p\" % [ attrtype ]\n\t\tattrname = attrtype.name\n\t\tif attrtype.single?\n\t\t\tself.log.debug \" attribute is SINGLE, so generating a scalar writer...\"\n\t\t\treturn lambda {|newvalue| self[attrname] = newvalue }\n\t\telse\n\t\t\tself.log.debug \" attribute isn't SINGLE, so generating an array writer...\"\n\t\t\treturn lambda {|*newvalues| self[attrname] = newvalues.flatten }\n\t\tend\n\tend", "def write_attribute(name, value)\n # Simply check if the accessor is allowed to write the field\n # (if so, go to superclass and do it)\n @bypass_auth ||= false\n if allowed_to_write(name) || @bypass_auth\n super(name, value)\n end\n end", "def mattr_writer(*syms, &proc)\n receiver = self\n options = syms.extract_options!\n syms.each do |sym|\n raise NameError.new('invalid attribute name') unless sym =~ /^[_A-Za-z]\\w*$/\n class_exec do\n define_singleton_method \"#{sym}=\" do |obj|\n class_variable_set(\"@@#{sym}\", obj)\n end\n end\n\n unless options[:instance_writer] == false || options[:instance_accessor] == false\n class_exec do\n define_method \"#{sym}=\" do |obj|\n receiver.class_variable_set(\"@@#{sym}\", obj)\n end\n end\n end\n send(\"#{sym}=\", proc.call) if proc\n end\n end", "def write_attribute(attribute, value)\n false\n end", "def add_attribute attribute\n return attribute unless @document_self\n\n # mainly to check for redefinition of an attribute as a method\n # TODO find a policy for 'attr_reader :foo' + 'def foo=()'\n register = false\n\n key = nil\n\n if attribute.rw.index 'R' then\n key = attribute.pretty_name\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name + '='] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if attribute.rw.index 'W' then\n key = attribute.pretty_name + '='\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if register then\n attribute.visibility = @visibility\n add_to @attributes, attribute\n resolve_aliases attribute\n end\n\n attribute\n end", "def define_writer_method(mod)\n writer_method_name = \"#{name}=\"\n attribute = self\n\n mod.send(:define_method, writer_method_name) { |value| attribute.set(self, value) }\n mod.send(writer_visibility, writer_method_name)\n\n self\n end", "def allowed_to_write(name)\n # no point allowing attribute writes if we can't save them?\n if allowed_to_save\n name = name.to_s\n validation_methods = self.class.write_validations(name) \n if validation_methods.nil?\n # We haven't registered any filters on this attribute, so allow the write.\n true\n elsif validation_methods.check :accessor => accessor, :model => self\n # One of the authentication methods worked, so allow the write.\n true\n else\n # We had filters but none of them passed. Disallow write.\n false\n end\n else\n false\n end\n end", "def assert_attr_writer(obj, method)\n assert_respond_to obj, \"#{method}=\"\nend", "def add_attribute(name, &block); end", "def authenticates_writes_to(attr, options={})\n authenticates_access\n @write_validation_map ||= {}\n @write_validation_map[attr.to_s] ||= AuthMethodList.new\n @write_validation_map[attr.to_s].add_method(options)\n end", "def write_attribute_3(param1, param2)\n\twrite_attribute(param1, param2)\n end", "def write_attribute(attr_name, value) #:doc:\n @attributes[attr_name] = empty_string_for_number_column?(attr_name, value) ? nil : value\n end", "def add_writer_tags(klass, new_method, member)\n member_tag = member_tag_for_member(klass, member, :write)\n return_type = return_type_from_tag(member_tag)\n setter_doc_text = member_tag ? member_tag.text : \"Sets the attribute #{member}\"\n new_method.docstring.replace(setter_doc_text)\n new_method.add_tag YARD::Tags::Tag.new(:param, \"the value to set the attribute #{member} to.\", return_type, \"value\")\n new_method.add_tag YARD::Tags::Tag.new(:return, \"the newly set value\", return_type)\n end", "def print_attribute(*) end", "def attribute(name); end", "def add_checked_attribute(clazz, attribute)\r\n eval <<END\r\n class #{clazz}\r\n\r\n def #{attribute}=(value)\r\n raise 'Invalid attribute' unless value\r\n @#{attribute}=value\r\n end\r\n\r\n def #{attribute}\r\n #{attribute}\r\n end\r\n end\r\nEND\r\nend", "def attr(name); end", "def is_attribute?(line)\n (line =~ /(\\s+)attr_(writer|reader|accessor)\\s+:[a-zA-Z_0-9]+/) == 0\n end", "def attribute(name, value)\n\t if !@inStartTag\n\t\traise WriterError.new('attribute outside of tag start')\n\t end\n\t @io << \" #{name}=\\\"#{NQXML.encode(value.to_s)}\\\"\"\n\tend", "def set_attribute(name, value); end", "def dataset_writer(*attributes)\n attributes.flatten.each do |attr_name|\n next if method_defined?(\"#{attr_name}=\")\n\n class_eval <<-RUBY, __FILE__, __LINE__ + 1\n def #{attr_name}=(value)\n dataset_set(:#{attr_name}, value)\n end\n RUBY\n end\n end", "def validated_attribute_names(params); end", "def require_format_of(attribute)\r\n RequireFormatOf.new(attribute)\r\n end", "def attr_writer(*fields)\n check_fields(fields)\n added_fields = jiak.data.writable(*fields)\n added_fields.each do |field|\n class_eval <<-EOM\n def #{field}=(val)\n @jiak.object.data.#{field} = val\n self.class.do_auto_update(self)\n end\n EOM\n end\n nil\n end", "def html_attr(*attrs)\n options = attrs.extract_options!.reverse_merge({\n :level => :super_relaxed\n })\n attrs.each do |att|\n class_eval \"def #{att}=(val); self[:#{att}] = sanitize(val, :#{options[:level]}); end\"\n end\n end", "def validate_attributes=(new_attribute)\n @validate_attributes = new_attribute\n end", "def html_attributes(attr); end", "def instance_write(attr, value)\n setter = :\"#{@name_string}_#{attr}=\"\n instance.send(setter, value) if instance.respond_to?(setter)\n end", "def valid_xml_attribute(name, options={:level => :warning})\n\t\t\t\tvalidate(\"Invalid XML attribute '#{name}'\", options) { name.to_s.match(/^([^[:punct:]0-9<>]|_)[^<>\"']*/) }\n\t\t\tend", "def attr_writer(*args)\n sym_args=args_to_sym(args)\n sym_args.each do |value|\n self.instance_eval(\"def #{value}=(arg); @#{value}=arg;end;\")\n end\n \n end", "def define_writer_method(attribute, method_name, visibility)\n define_method(method_name) { |value| attribute.set(self, value) }\n send(visibility, method_name)\n self\n end", "def write_attribute(name, val)\n if @embedded_models.include? name\n @embedded_models[name].model = val\n elsif @attribute_objects.include? name\n @attribute_objects[name].value = val\n else\n return false\n end\n\n run_callbacks :attribute_change\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def attr; end", "def attribute(*args)\n define_expressions(Attribute, args)\n end", "def write_attribute(name, value)\n name = name.to_s\n\n # The attribute already has an unsaved change.\n if attribute_changed?(name)\n old = changed_attributes[name]\n changed_attributes.delete(name) unless field_changed?(name, old, value)\n else\n attribute_will_change(name) if field_changed?(name, old, value)\n end\n\n # Carry on.\n super(name, value)\n end", "def define_magic_attr(name)\n define_method name do |*attrs|\n raise ArgumentError.new(\"wrong number of arguments\") if attrs.size > 1\n send(\"#{name}=\", attrs.first) if attrs.size == 1\n instance_variable_get(\"@#{name}\")\n end\n\n attr_writer name\n end", "def configurable_writer(attribute, code=nil, &block)\n if block_given? and not code\n Halcyon.class.send(:define_method, :\"#{attribute}=\", block)\n elsif code and not block_given?\n Halcyon.class.send(:eval, <<-\"end;\")\n def #{attribute.to_s}=(value)\n #{code % [attribute.to_sym.inspect]}\n end\n end;\n else\n raise ArgumentError.new(\"Either a block or a code string should be supplied.\")\n end\n end", "def method_missing(name, *args, &block)\n if /\\Ahas_validated_(?<type>\\w*)_attribute\\Z/ =~ name\n has_validated_attribute(type, *args, &block)\n else\n super\n end\n end", "def add_checked_attribute(klass, attribute)\n klass.class_eval do\n define_method attribute do\n instance_variable_get(\"@#{attribute}\")\n end\n\n define_method \"#{attribute}=\" do |value|\n raise 'Invalid attribute' unless value\n \n instance_variable_set(\"@#{attribute}\", value)\n end\n end\nend", "def method_missing(meth, *args, &blk)\n match = meth.to_s.match(/^([a-zA-Z\\_]+)(=|$)$/)\n if match\n attribute, setter = match[1], !match[2].blank?\n if setter\n write_attribute(attribute, args.first)\n else\n read_attribute(attribute)\n end\n else\n super(meth, *args, &blk)\n end\n end", "def valid_attributes\n { name: 'do this' }\n end", "def make_attributes_definitions_or_croak(attrArgs, &attrBlok)\n eye = :'m_attrs_defs'\n\n # Work with attribute as strings\n \n $DEBUG && logger_me(eye, logger_fmt_kls(:attrArgs => attrArgs, :attrBlok => attrBlok))\n\n mustbe_attributes_specification_or_croak(attrArgs, eye, \"attrArgs not attributes_specification\")\n \n #STOPATTRARGSINSUPER\n \n #attrAll = mustbe_not_empty_or_croak(mustbe_array_key_or_nil_or_croak(attrArgs, :all, eye, \"all attributes not array\"), eye, \"all attributes is empty\").map(&:to_s)\n attrAll = mustbe_not_empty_or_croak(mustbe_attributes_specification_all_key_or_croak(attrArgs, :all, eye), eye, \"all attributes is empty\").map(&:to_s)\n \n\n #puts(\"\\n\\n\\nATTR ALL >#{attrAll}<\")\n\n #STOPMAKEATTRSPECSENTRY\n\n attrInc = mustbe_attributes_specification_include_key_or_nil_or_croak(attrArgs, :include, eye) # mustbe all strings\n #puts(\"ATTR INC >#{attrInc.class}< >#{attrInc}< >#{is_value_not_empty?(attrInc)}<\")\n attrInc && mustbe_not_empty_or_croak(attrInc, eye, \"include attributes is empty\")\n\n attrExc = mustbe_attributes_specification_exclude_key_or_nil_or_croak(attrArgs, :exclude, eye) || []\n \n attrMapNom = mustbe_attributes_definitions_key_or_nil_or_croak(attrArgs, :definitions, eye) || {}\n attrMap = attrMapNom && potrubi_util_map_hash_kv(attrMapNom) {|k,v| [k.to_s, v]} # keys all strings\n\n # Ensure all consistent\n \n attrInc && mustbe_subset_or_croak(attrInc, attrAll, eye, \"include attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrExc, attrAll, eye, \"exclude attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrMap.keys, attrAll, eye, \"attribute map contains unknown attributes\")\n \n attrUse = ((attrInc || attrAll) - attrExc).uniq # list of unique attributes to report on\n\n # consolidate \"faked up\" attr specs with ones provided to get the composite attrSpecs\n \n attrDefsNom = potrubi_util_array_to_hash(attrUse).merge(attrMap.select {|k,v| attrUse.include?(k)}) # consolidated \"faked up\" attr specs with ones provided\n\n attrDefs = potrubi_util_map_hash_v(attrDefsNom) do | attrName, attrSpecNom|\n\n attrSpec =\n case attrSpecNom\n when NilClass then {}\n when Hash then\n attrSpecNom.each_with_object({}) do | (verbName, verbSpec), h1 |\n case verbName\n when :pass_thru then h1[:pass_thru] = verbSpec # dont touch; just pass through\n when :event_defaults then # add these to pass_thru\n h1[:pass_thru] = (h1[:pass_thru] || {}).merge(verbName => verbSpec)\n when :map, :select, :metric then\n h1[verbName] = {\n :method_name => \"#{verbName}_#{attrName}_#{rand(1000000)}\", # make a unqiue name\n :method_spec => verbSpec # spec must be valid to dynamic_define_methods\n }\n else\n logic_exception(verbName, eye, \"attrName >#{attrName}< verbName >#{verbName}< value should be impossible\")\n end\n end\n \n else\n logic_exception(attrrSpecNom, eye, \"attrSpecNom value should be impossible\")\n end\n\n attrSpec\n \n end\n \n $DEBUG && logger_mx(eye, logger_fmt_kls(:attrDefs => attrDefs))\n\n mustbe_attributes_definitions_or_croak(attrDefs, eye, \"attrDefs failed contract\")\n\n #STOPMAKEATTRSPECS\n \n end", "def create_writer(klass, member)\n # We want to convert these members into attributes just like\n # as if they were declared using attr_accessor.\n new_meth = register MethodObject.new(klass, \"#{member}=\", :instance) do |o|\n o.parameters = [['value', nil]]\n o.signature ||= \"def #{member}=(value)\"\n o.source ||= \"#{o.signature}\\n @#{member} = value\\nend\"\n end\n add_writer_tags(klass, new_meth, member)\n klass.attributes[:instance][member][:write] = new_meth\n end", "def create_setter!\n @target.class_eval <<-EOS\n #{writer_visibility.to_s}\n def #{name}=(value)\n attribute_set(#{name.inspect}, value)\n end\n EOS\n rescue SyntaxError\n raise SyntaxError.new(column)\n end", "def attribute name, type, conditions= DEFAULT_ATTRIBUTE_CONDITIONS\n RMOF.complete_conditions conditions, DEFAULT_ATTRIBUTE_CONDITIONS\n @attributes= {} unless instance_variable_defined? :@attributes\n @attributes[name]= [name, type, conditions]\n unless method_defined? :__attributes then \n define_method( :__attributes) do \n @attributes\n end \n end\n at= \"@#{name}\".to_sym\n getter= \"#{name}\".to_sym\n setter= \"#{name}=\".to_sym\n completion= \"__complete_#{name}\".to_sym\n define_method( getter) do\n if instance_variable_defined? at then instance_variable_get at\n else conditions[:default]\n end\n end\n define_method( setter) do |val|\n instance_variable_set at, val\n end\n define_method( completion) do\n RMOF.validate( self.send(getter), name, type, conditions)\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def create_setter(name, meth)\n define_method(\"#{meth}=\") do |value|\n write_attribute(name, value)\n end\n end", "def sanitized_allowed_attributes=(attributes); end", "def sanitized_allowed_attributes=(attributes); end", "def oattr(name, type)\n case type\n when :custom\n # Do nothing, just register attr below.\n when :writer\n attr_writer name\n else\n raise ArgumentError, \"Unknown type: #{type.inspect}\"\n end\n\n # Register and return.\n name.tap { oattrs << name}\n end", "def valid_attributes\n { name: \"Expert\" }\n end", "def attributes(*method_names, **options)\n add_attributes(method_names, **options, strategy: :write_value_using_method_strategy)\n end", "def []=(attr_name, value)\n writer_method = \"#{attr_name}=\"\n send(writer_method, value) if respond_to?(writer_method)\n end", "def write_extended_attributes(attrs)\n attrs.each do |k, val|\n self.send((k.to_s + \"=\").to_sym, val) if is_flex_attribute?(k)\n end\n self\n end", "def valid_attributes\n { \"username\" => \"MyString\" }\n end", "def cattr_writer(*fields)\n metaclass.send :attr_writer, *fields\n end", "def write_attribute(attr, value)\n if attribute_encrypted?(attr)\n conductor_for(attr).encrypt(value)\n else\n super(attr, value)\n end\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_number_value(\"offsetInDays\", @offset_in_days)\n writer.write_enum_value(\"timeBasedAttribute\", @time_based_attribute)\n end", "def define_attribute_method(attr_name, _owner: generated_attribute_methods)\n CodeGenerator.batch(_owner, __FILE__, __LINE__) do |owner|\n attribute_method_matchers.each do |matcher|\n method_name = matcher.method_name(attr_name)\n\n unless instance_method_already_implemented?(method_name)\n generate_method = \"define_method_#{matcher.target}\"\n\n if respond_to?(generate_method, true)\n send(generate_method, attr_name.to_s, owner: owner)\n else\n define_proxy_call true, owner, method_name, matcher.target, attr_name.to_s\n end\n end\n end\n attribute_method_matchers_cache.clear\n end\n end", "def has_attributes?; end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_boolean_value(\"isExpirationRequired\", @is_expiration_required)\n writer.write_duration_value(\"maximumDuration\", @maximum_duration)\n end", "def add_attributes(item)\n [:class, :instance].each do |attr_loc|\n # Grab attributes for the current location (class or instance)\n attrs = item.attributes[attr_loc]\n attrs.each do |name, attribute|\n reader = attribute[:read]\n writer = attribute[:write]\n\n unless reader || writer\n Logging.warn(\"attribute is not readable or writable somehow, skipping\", attribute)\n next\n end\n\n # Get all given types\n yard_types = []\n if reader\n next if @hide_private && reader.visibility == :private\n yard_types += reader.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n reader.tags('param').flat_map(&:types)\n end\n if writer\n next if @hide_private && writer.visibility == :private\n yard_types += writer.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n writer.tags('param').flat_map(&:types)\n end\n\n # Use untyped if not types specified anywhere, otherwise try to\n # compute Parlour type given all these types\n if yard_types.empty?\n Logging.omit(\"no YARD type given for #{name.inspect}, using untyped\", reader || writer)\n parlour_type = Parlour::Types::Untyped.new\n elsif yard_types.all? { |x| x == 'nil' }\n # Nil attributes are extremely unusual, so just use untyped\n parlour_type = Parlour::Types::Untyped.new\n else\n parlour_type = TypeConverter.yard_to_parlour(\n yard_types, reader || writer, @type_converter_config)\n end\n\n # Generate attribute\n if reader && writer\n kind = :accessor\n elsif reader\n kind = :reader\n elsif writer\n kind = :writer\n end\n\n if @exclude_untyped && parlour_type.is_a?(Parlour::Types::Untyped)\n Logging.omit(\"excluding untyped attribute\", reader || writer, immediate: true)\n next\n end\n\n case @mode\n when :rbi\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n class_attribute: (attr_loc == :class)\n ) do |m|\n add_comments(reader || writer, m)\n end\n when :rbs\n if attr_loc == :class\n # RBS doesn't support class attr_accessors so create individual methods\n\n if reader\n @current_object.create_method(\n name.to_s,\n [Parlour::RbsGenerator::MethodSignature.new([], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(reader, m)\n end\n end\n\n if writer\n @current_object.create_method(\n \"#{name}=\",\n [Parlour::RbsGenerator::MethodSignature.new([Parlour::RbsGenerator::Parameter.new(\n \"value\",\n type: parlour_type,\n required: true\n )], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(writer, m)\n end\n end\n else\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n ) do |m|\n add_comments(reader || writer, m)\n end\n end\n end\n end\n end\n end", "def []=(attr_name, value)\r\n if attr_name.is_a?(String) and attr_name != attr_name.split(ID_SEP).first\r\n attr_name = attr_name.split(ID_SEP)\r\n end\r\n\r\n if attr_name.is_a? Array\r\n value = value.split(ID_SEP) if value.is_a? String\r\n unless value.length == attr_name.length\r\n raise \"Number of attr_names and values do not match\"\r\n end\r\n #breakpoint\r\n [attr_name, value].transpose.map {|name,val| write_attribute(name.to_s, val)}\r\n else\r\n write_attribute(attr_name, value)\r\n end\r\n end", "def attr(symbol, writable=false) end", "def define_writer!(k, definition)\n define_method(\"#{k}=\") do |value|\n # Recursively convert hash and array of hash to schematized objects\n value = ensure_schema value, definition[:schema]\n\n # Initial value\n instance_variable_set \"@#{k}\", value\n\n # Dirty tracking\n self.changed_attributes ||= Set.new\n self.changed_attributes << k\n end\n end", "def validate\n validate_string_attributes\n end", "def write_attribute_with_dynamo(field_name, value)\n if is_dynamo_field?(field_name)\n # Store these guys for now. We don't actually save the field value until the model is saved ( i.e my_supplier.save ).\n # If we were to save the field_value now we wouldn't be able to know the id of the model to link this value to it.\n # @see delay_save\n @all_fields_and_values ||= []\n @all_fields_and_values << {:dynamo_field=>cached_dynamo_field_by_name(field_name), :value=>value}\n end\n # If its a 'normal' attribute let rails write it in the usual way.\n write_attribute_without_dynamo(field_name, value)\n end", "def define_attr_accessor(attr)\n attr_accessor(attr)\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n writer.write_collection_of_object_values(\"attributeMappings\", @attribute_mappings)\n writer.write_boolean_value(\"enabled\", @enabled)\n writer.write_enum_value(\"flowTypes\", @flow_types)\n writer.write_collection_of_object_values(\"metadata\", @metadata)\n writer.write_string_value(\"name\", @name)\n writer.write_string_value(\"@odata.type\", @odata_type)\n writer.write_object_value(\"scope\", @scope)\n writer.write_string_value(\"sourceObjectName\", @source_object_name)\n writer.write_string_value(\"targetObjectName\", @target_object_name)\n writer.write_additional_data(@additional_data)\n end", "def validate_attribute_syntax\n\t\t@values.each do |attribute, values|\n\t\t\t[ values ].flatten.each do |value|\n\t\t\t\tbegin\n\t\t\t\t\tself.get_converted_attribute( attribute.to_sym, value )\n\t\t\t\trescue => err\n\t\t\t\t\tself.log.error \"validation for %p failed: %s: %s\" %\n\t\t\t\t\t\t[ attribute, err.class.name, err.message ]\n\t\t\t\t\tattrtype = self.find_attribute_type( attribute )\n\t\t\t\t\tself.errors.add( attribute, \"isn't a valid %s value\" %\n\t\t\t\t\t\t[ attrtype.syntax ? attrtype.syntax.desc : attrtype.syntax_oid ] )\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def valid_attributes\n { }\n end", "def validatable_attributes(atts, opts)\n am, an, ab, m = opts.values_at(:allow_missing, :allow_nil, :allow_blank, :message)\n Array(atts).each do |a|\n next if am && !values.has_key?(a)\n v = send(a)\n next if an && v.nil?\n next if ab && v.respond_to?(:blank?) && v.blank?\n if message = yield(a, v, m)\n errors.add(a, message)\n end\n end\n end", "def valid_attributes\n { }\n end", "def valid_attributes\n { }\n end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def require_attr(name)\n send(name).tap do |_|\n raise \"Attribute must be set: #{name}\" if _.nil?\n end\n end", "def write_attributes(attributes)\n _attributes = attributes.select do |name, value|\n if self.is_dynamic_field?(name)\n self.dynamic_setter(name, value)\n false\n else\n true\n end\n end\n\n super(_attributes)\n end", "def attribute; end", "def attribute; end" ]
[ "0.6472992", "0.6315012", "0.6315012", "0.62821025", "0.6279224", "0.6211609", "0.61891466", "0.6182247", "0.60683644", "0.6032628", "0.5995443", "0.5988785", "0.5959885", "0.5938289", "0.5931089", "0.58951056", "0.5859927", "0.5851703", "0.58493423", "0.58465594", "0.58328366", "0.5823013", "0.5822229", "0.57850474", "0.5701491", "0.5696689", "0.5682951", "0.5678094", "0.566814", "0.5657499", "0.56555206", "0.5642589", "0.56219065", "0.5615893", "0.56105876", "0.559851", "0.5598089", "0.55940455", "0.5585137", "0.55848545", "0.55796933", "0.5571477", "0.5567006", "0.55667996", "0.55652434", "0.5562926", "0.55600035", "0.55590326", "0.55590326", "0.5554599", "0.5554599", "0.55407417", "0.5534935", "0.5527733", "0.55271375", "0.55238813", "0.5501504", "0.5497003", "0.5496233", "0.54927665", "0.5464706", "0.54617554", "0.5461167", "0.5451583", "0.54498726", "0.54498726", "0.54359984", "0.5430996", "0.5430996", "0.5426488", "0.5418467", "0.54153895", "0.54107565", "0.5407886", "0.5401234", "0.54008496", "0.5400268", "0.53910094", "0.53827274", "0.5377731", "0.5375473", "0.5374833", "0.53720397", "0.5370215", "0.5363264", "0.5361161", "0.5360557", "0.5351706", "0.53514725", "0.53492516", "0.53459316", "0.5341237", "0.5328037", "0.5328037", "0.53230566", "0.53230566", "0.53230566", "0.5319575", "0.531832", "0.5315559", "0.5315559" ]
0.0
-1
Custom attribute writer method with validation
def udp_first_packet=(udp_first_packet) if udp_first_packet.nil? fail ArgumentError, 'udp_first_packet cannot be nil' end if udp_first_packet > 4320000 fail ArgumentError, 'invalid value for "udp_first_packet", must be smaller than or equal to 4320000.' end if udp_first_packet < 10 fail ArgumentError, 'invalid value for "udp_first_packet", must be greater than or equal to 10.' end @udp_first_packet = udp_first_packet end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def attr_writer_tag(text); end", "def allowed_attributes=(_arg0); end", "def allowed_attributes=(_arg0); end", "def writer(*args)\n attr_writer(*args)\n args\n end", "def define_write_method(attr_name)\n evaluate_attribute_method attr_name, \"def #{attr_name}=(new_value);write_attribute('#{attr_name}', new_value);end\", \"#{attr_name}=\"\n end", "def attr_writer(*vars)\n # avoid tracking attributes that are added by the class_attribute\n # as these are class attributes and not instance attributes.\n tracked_vars = vars.reject {|var| respond_to? var }\n add_tracked_attrs(false, true, *tracked_vars)\n vars.extract_options!\n super\n end", "def attr_writer(sym, *more) end", "def is_attribute?; end", "def validate_exclusion_of(attr); end", "def register_attributes\n raise \"Not implemented in #{self.class}\"\n end", "def method_missing(method_name, *args)\n return super unless permitted_attributes.include?(method_name)\n begin\n object.send(:\"#{method_name}=\", args.first)\n rescue => e\n if params.has_key?(method_name)\n message = \"Unable to process value for :#{method_name}, no attribute writer. Be sure to override the automatic setters for all params that do not map straight to a model attribute.\"\n Rails.logger.warn({message: message,\n missing_writer: method_name,\n value: args.first,\n error: e})\n self.errors << {status: 422, message: message}\n else\n raise e\n end\n end\n end", "def timeliness_validation_for(attr_names, type)\n super\n attr_names.each { |attr_name| define_timeliness_write_method(attr_name) }\n end", "def create_setter_for(attribute, options)\n setter_method = \"#{attribute}=\"\n\n define_method setter_method do |value|\n if options[:allow_blank] || value != \"\"\n write_attribute(attribute, value)\n end\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each {|attr_name| attr_internal_define(attr_name, :writer)}\n end", "def escape_attr input\n escape input, attr_regexp, attr_mapping\n end", "def make_writer( attrtype )\n\t\tself.log.debug \"Generating an attribute writer for %p\" % [ attrtype ]\n\t\tattrname = attrtype.name\n\t\tif attrtype.single?\n\t\t\tself.log.debug \" attribute is SINGLE, so generating a scalar writer...\"\n\t\t\treturn lambda {|newvalue| self[attrname] = newvalue }\n\t\telse\n\t\t\tself.log.debug \" attribute isn't SINGLE, so generating an array writer...\"\n\t\t\treturn lambda {|*newvalues| self[attrname] = newvalues.flatten }\n\t\tend\n\tend", "def write_attribute(name, value)\n # Simply check if the accessor is allowed to write the field\n # (if so, go to superclass and do it)\n @bypass_auth ||= false\n if allowed_to_write(name) || @bypass_auth\n super(name, value)\n end\n end", "def mattr_writer(*syms, &proc)\n receiver = self\n options = syms.extract_options!\n syms.each do |sym|\n raise NameError.new('invalid attribute name') unless sym =~ /^[_A-Za-z]\\w*$/\n class_exec do\n define_singleton_method \"#{sym}=\" do |obj|\n class_variable_set(\"@@#{sym}\", obj)\n end\n end\n\n unless options[:instance_writer] == false || options[:instance_accessor] == false\n class_exec do\n define_method \"#{sym}=\" do |obj|\n receiver.class_variable_set(\"@@#{sym}\", obj)\n end\n end\n end\n send(\"#{sym}=\", proc.call) if proc\n end\n end", "def write_attribute(attribute, value)\n false\n end", "def add_attribute attribute\n return attribute unless @document_self\n\n # mainly to check for redefinition of an attribute as a method\n # TODO find a policy for 'attr_reader :foo' + 'def foo=()'\n register = false\n\n key = nil\n\n if attribute.rw.index 'R' then\n key = attribute.pretty_name\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name + '='] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if attribute.rw.index 'W' then\n key = attribute.pretty_name + '='\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if register then\n attribute.visibility = @visibility\n add_to @attributes, attribute\n resolve_aliases attribute\n end\n\n attribute\n end", "def define_writer_method(mod)\n writer_method_name = \"#{name}=\"\n attribute = self\n\n mod.send(:define_method, writer_method_name) { |value| attribute.set(self, value) }\n mod.send(writer_visibility, writer_method_name)\n\n self\n end", "def allowed_to_write(name)\n # no point allowing attribute writes if we can't save them?\n if allowed_to_save\n name = name.to_s\n validation_methods = self.class.write_validations(name) \n if validation_methods.nil?\n # We haven't registered any filters on this attribute, so allow the write.\n true\n elsif validation_methods.check :accessor => accessor, :model => self\n # One of the authentication methods worked, so allow the write.\n true\n else\n # We had filters but none of them passed. Disallow write.\n false\n end\n else\n false\n end\n end", "def assert_attr_writer(obj, method)\n assert_respond_to obj, \"#{method}=\"\nend", "def add_attribute(name, &block); end", "def authenticates_writes_to(attr, options={})\n authenticates_access\n @write_validation_map ||= {}\n @write_validation_map[attr.to_s] ||= AuthMethodList.new\n @write_validation_map[attr.to_s].add_method(options)\n end", "def write_attribute_3(param1, param2)\n\twrite_attribute(param1, param2)\n end", "def write_attribute(attr_name, value) #:doc:\n @attributes[attr_name] = empty_string_for_number_column?(attr_name, value) ? nil : value\n end", "def add_writer_tags(klass, new_method, member)\n member_tag = member_tag_for_member(klass, member, :write)\n return_type = return_type_from_tag(member_tag)\n setter_doc_text = member_tag ? member_tag.text : \"Sets the attribute #{member}\"\n new_method.docstring.replace(setter_doc_text)\n new_method.add_tag YARD::Tags::Tag.new(:param, \"the value to set the attribute #{member} to.\", return_type, \"value\")\n new_method.add_tag YARD::Tags::Tag.new(:return, \"the newly set value\", return_type)\n end", "def print_attribute(*) end", "def attribute(name); end", "def add_checked_attribute(clazz, attribute)\r\n eval <<END\r\n class #{clazz}\r\n\r\n def #{attribute}=(value)\r\n raise 'Invalid attribute' unless value\r\n @#{attribute}=value\r\n end\r\n\r\n def #{attribute}\r\n #{attribute}\r\n end\r\n end\r\nEND\r\nend", "def attr(name); end", "def is_attribute?(line)\n (line =~ /(\\s+)attr_(writer|reader|accessor)\\s+:[a-zA-Z_0-9]+/) == 0\n end", "def attribute(name, value)\n\t if !@inStartTag\n\t\traise WriterError.new('attribute outside of tag start')\n\t end\n\t @io << \" #{name}=\\\"#{NQXML.encode(value.to_s)}\\\"\"\n\tend", "def set_attribute(name, value); end", "def dataset_writer(*attributes)\n attributes.flatten.each do |attr_name|\n next if method_defined?(\"#{attr_name}=\")\n\n class_eval <<-RUBY, __FILE__, __LINE__ + 1\n def #{attr_name}=(value)\n dataset_set(:#{attr_name}, value)\n end\n RUBY\n end\n end", "def validated_attribute_names(params); end", "def require_format_of(attribute)\r\n RequireFormatOf.new(attribute)\r\n end", "def attr_writer(*fields)\n check_fields(fields)\n added_fields = jiak.data.writable(*fields)\n added_fields.each do |field|\n class_eval <<-EOM\n def #{field}=(val)\n @jiak.object.data.#{field} = val\n self.class.do_auto_update(self)\n end\n EOM\n end\n nil\n end", "def html_attr(*attrs)\n options = attrs.extract_options!.reverse_merge({\n :level => :super_relaxed\n })\n attrs.each do |att|\n class_eval \"def #{att}=(val); self[:#{att}] = sanitize(val, :#{options[:level]}); end\"\n end\n end", "def validate_attributes=(new_attribute)\n @validate_attributes = new_attribute\n end", "def html_attributes(attr); end", "def instance_write(attr, value)\n setter = :\"#{@name_string}_#{attr}=\"\n instance.send(setter, value) if instance.respond_to?(setter)\n end", "def valid_xml_attribute(name, options={:level => :warning})\n\t\t\t\tvalidate(\"Invalid XML attribute '#{name}'\", options) { name.to_s.match(/^([^[:punct:]0-9<>]|_)[^<>\"']*/) }\n\t\t\tend", "def attr_writer(*args)\n sym_args=args_to_sym(args)\n sym_args.each do |value|\n self.instance_eval(\"def #{value}=(arg); @#{value}=arg;end;\")\n end\n \n end", "def define_writer_method(attribute, method_name, visibility)\n define_method(method_name) { |value| attribute.set(self, value) }\n send(visibility, method_name)\n self\n end", "def write_attribute(name, val)\n if @embedded_models.include? name\n @embedded_models[name].model = val\n elsif @attribute_objects.include? name\n @attribute_objects[name].value = val\n else\n return false\n end\n\n run_callbacks :attribute_change\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def attr; end", "def attribute(*args)\n define_expressions(Attribute, args)\n end", "def write_attribute(name, value)\n name = name.to_s\n\n # The attribute already has an unsaved change.\n if attribute_changed?(name)\n old = changed_attributes[name]\n changed_attributes.delete(name) unless field_changed?(name, old, value)\n else\n attribute_will_change(name) if field_changed?(name, old, value)\n end\n\n # Carry on.\n super(name, value)\n end", "def define_magic_attr(name)\n define_method name do |*attrs|\n raise ArgumentError.new(\"wrong number of arguments\") if attrs.size > 1\n send(\"#{name}=\", attrs.first) if attrs.size == 1\n instance_variable_get(\"@#{name}\")\n end\n\n attr_writer name\n end", "def configurable_writer(attribute, code=nil, &block)\n if block_given? and not code\n Halcyon.class.send(:define_method, :\"#{attribute}=\", block)\n elsif code and not block_given?\n Halcyon.class.send(:eval, <<-\"end;\")\n def #{attribute.to_s}=(value)\n #{code % [attribute.to_sym.inspect]}\n end\n end;\n else\n raise ArgumentError.new(\"Either a block or a code string should be supplied.\")\n end\n end", "def method_missing(name, *args, &block)\n if /\\Ahas_validated_(?<type>\\w*)_attribute\\Z/ =~ name\n has_validated_attribute(type, *args, &block)\n else\n super\n end\n end", "def add_checked_attribute(klass, attribute)\n klass.class_eval do\n define_method attribute do\n instance_variable_get(\"@#{attribute}\")\n end\n\n define_method \"#{attribute}=\" do |value|\n raise 'Invalid attribute' unless value\n \n instance_variable_set(\"@#{attribute}\", value)\n end\n end\nend", "def method_missing(meth, *args, &blk)\n match = meth.to_s.match(/^([a-zA-Z\\_]+)(=|$)$/)\n if match\n attribute, setter = match[1], !match[2].blank?\n if setter\n write_attribute(attribute, args.first)\n else\n read_attribute(attribute)\n end\n else\n super(meth, *args, &blk)\n end\n end", "def valid_attributes\n { name: 'do this' }\n end", "def make_attributes_definitions_or_croak(attrArgs, &attrBlok)\n eye = :'m_attrs_defs'\n\n # Work with attribute as strings\n \n $DEBUG && logger_me(eye, logger_fmt_kls(:attrArgs => attrArgs, :attrBlok => attrBlok))\n\n mustbe_attributes_specification_or_croak(attrArgs, eye, \"attrArgs not attributes_specification\")\n \n #STOPATTRARGSINSUPER\n \n #attrAll = mustbe_not_empty_or_croak(mustbe_array_key_or_nil_or_croak(attrArgs, :all, eye, \"all attributes not array\"), eye, \"all attributes is empty\").map(&:to_s)\n attrAll = mustbe_not_empty_or_croak(mustbe_attributes_specification_all_key_or_croak(attrArgs, :all, eye), eye, \"all attributes is empty\").map(&:to_s)\n \n\n #puts(\"\\n\\n\\nATTR ALL >#{attrAll}<\")\n\n #STOPMAKEATTRSPECSENTRY\n\n attrInc = mustbe_attributes_specification_include_key_or_nil_or_croak(attrArgs, :include, eye) # mustbe all strings\n #puts(\"ATTR INC >#{attrInc.class}< >#{attrInc}< >#{is_value_not_empty?(attrInc)}<\")\n attrInc && mustbe_not_empty_or_croak(attrInc, eye, \"include attributes is empty\")\n\n attrExc = mustbe_attributes_specification_exclude_key_or_nil_or_croak(attrArgs, :exclude, eye) || []\n \n attrMapNom = mustbe_attributes_definitions_key_or_nil_or_croak(attrArgs, :definitions, eye) || {}\n attrMap = attrMapNom && potrubi_util_map_hash_kv(attrMapNom) {|k,v| [k.to_s, v]} # keys all strings\n\n # Ensure all consistent\n \n attrInc && mustbe_subset_or_croak(attrInc, attrAll, eye, \"include attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrExc, attrAll, eye, \"exclude attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrMap.keys, attrAll, eye, \"attribute map contains unknown attributes\")\n \n attrUse = ((attrInc || attrAll) - attrExc).uniq # list of unique attributes to report on\n\n # consolidate \"faked up\" attr specs with ones provided to get the composite attrSpecs\n \n attrDefsNom = potrubi_util_array_to_hash(attrUse).merge(attrMap.select {|k,v| attrUse.include?(k)}) # consolidated \"faked up\" attr specs with ones provided\n\n attrDefs = potrubi_util_map_hash_v(attrDefsNom) do | attrName, attrSpecNom|\n\n attrSpec =\n case attrSpecNom\n when NilClass then {}\n when Hash then\n attrSpecNom.each_with_object({}) do | (verbName, verbSpec), h1 |\n case verbName\n when :pass_thru then h1[:pass_thru] = verbSpec # dont touch; just pass through\n when :event_defaults then # add these to pass_thru\n h1[:pass_thru] = (h1[:pass_thru] || {}).merge(verbName => verbSpec)\n when :map, :select, :metric then\n h1[verbName] = {\n :method_name => \"#{verbName}_#{attrName}_#{rand(1000000)}\", # make a unqiue name\n :method_spec => verbSpec # spec must be valid to dynamic_define_methods\n }\n else\n logic_exception(verbName, eye, \"attrName >#{attrName}< verbName >#{verbName}< value should be impossible\")\n end\n end\n \n else\n logic_exception(attrrSpecNom, eye, \"attrSpecNom value should be impossible\")\n end\n\n attrSpec\n \n end\n \n $DEBUG && logger_mx(eye, logger_fmt_kls(:attrDefs => attrDefs))\n\n mustbe_attributes_definitions_or_croak(attrDefs, eye, \"attrDefs failed contract\")\n\n #STOPMAKEATTRSPECS\n \n end", "def create_writer(klass, member)\n # We want to convert these members into attributes just like\n # as if they were declared using attr_accessor.\n new_meth = register MethodObject.new(klass, \"#{member}=\", :instance) do |o|\n o.parameters = [['value', nil]]\n o.signature ||= \"def #{member}=(value)\"\n o.source ||= \"#{o.signature}\\n @#{member} = value\\nend\"\n end\n add_writer_tags(klass, new_meth, member)\n klass.attributes[:instance][member][:write] = new_meth\n end", "def create_setter!\n @target.class_eval <<-EOS\n #{writer_visibility.to_s}\n def #{name}=(value)\n attribute_set(#{name.inspect}, value)\n end\n EOS\n rescue SyntaxError\n raise SyntaxError.new(column)\n end", "def attribute name, type, conditions= DEFAULT_ATTRIBUTE_CONDITIONS\n RMOF.complete_conditions conditions, DEFAULT_ATTRIBUTE_CONDITIONS\n @attributes= {} unless instance_variable_defined? :@attributes\n @attributes[name]= [name, type, conditions]\n unless method_defined? :__attributes then \n define_method( :__attributes) do \n @attributes\n end \n end\n at= \"@#{name}\".to_sym\n getter= \"#{name}\".to_sym\n setter= \"#{name}=\".to_sym\n completion= \"__complete_#{name}\".to_sym\n define_method( getter) do\n if instance_variable_defined? at then instance_variable_get at\n else conditions[:default]\n end\n end\n define_method( setter) do |val|\n instance_variable_set at, val\n end\n define_method( completion) do\n RMOF.validate( self.send(getter), name, type, conditions)\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def create_setter(name, meth)\n define_method(\"#{meth}=\") do |value|\n write_attribute(name, value)\n end\n end", "def sanitized_allowed_attributes=(attributes); end", "def sanitized_allowed_attributes=(attributes); end", "def oattr(name, type)\n case type\n when :custom\n # Do nothing, just register attr below.\n when :writer\n attr_writer name\n else\n raise ArgumentError, \"Unknown type: #{type.inspect}\"\n end\n\n # Register and return.\n name.tap { oattrs << name}\n end", "def valid_attributes\n { name: \"Expert\" }\n end", "def attributes(*method_names, **options)\n add_attributes(method_names, **options, strategy: :write_value_using_method_strategy)\n end", "def []=(attr_name, value)\n writer_method = \"#{attr_name}=\"\n send(writer_method, value) if respond_to?(writer_method)\n end", "def write_extended_attributes(attrs)\n attrs.each do |k, val|\n self.send((k.to_s + \"=\").to_sym, val) if is_flex_attribute?(k)\n end\n self\n end", "def valid_attributes\n { \"username\" => \"MyString\" }\n end", "def cattr_writer(*fields)\n metaclass.send :attr_writer, *fields\n end", "def write_attribute(attr, value)\n if attribute_encrypted?(attr)\n conductor_for(attr).encrypt(value)\n else\n super(attr, value)\n end\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_number_value(\"offsetInDays\", @offset_in_days)\n writer.write_enum_value(\"timeBasedAttribute\", @time_based_attribute)\n end", "def define_attribute_method(attr_name, _owner: generated_attribute_methods)\n CodeGenerator.batch(_owner, __FILE__, __LINE__) do |owner|\n attribute_method_matchers.each do |matcher|\n method_name = matcher.method_name(attr_name)\n\n unless instance_method_already_implemented?(method_name)\n generate_method = \"define_method_#{matcher.target}\"\n\n if respond_to?(generate_method, true)\n send(generate_method, attr_name.to_s, owner: owner)\n else\n define_proxy_call true, owner, method_name, matcher.target, attr_name.to_s\n end\n end\n end\n attribute_method_matchers_cache.clear\n end\n end", "def has_attributes?; end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_boolean_value(\"isExpirationRequired\", @is_expiration_required)\n writer.write_duration_value(\"maximumDuration\", @maximum_duration)\n end", "def add_attributes(item)\n [:class, :instance].each do |attr_loc|\n # Grab attributes for the current location (class or instance)\n attrs = item.attributes[attr_loc]\n attrs.each do |name, attribute|\n reader = attribute[:read]\n writer = attribute[:write]\n\n unless reader || writer\n Logging.warn(\"attribute is not readable or writable somehow, skipping\", attribute)\n next\n end\n\n # Get all given types\n yard_types = []\n if reader\n next if @hide_private && reader.visibility == :private\n yard_types += reader.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n reader.tags('param').flat_map(&:types)\n end\n if writer\n next if @hide_private && writer.visibility == :private\n yard_types += writer.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n writer.tags('param').flat_map(&:types)\n end\n\n # Use untyped if not types specified anywhere, otherwise try to\n # compute Parlour type given all these types\n if yard_types.empty?\n Logging.omit(\"no YARD type given for #{name.inspect}, using untyped\", reader || writer)\n parlour_type = Parlour::Types::Untyped.new\n elsif yard_types.all? { |x| x == 'nil' }\n # Nil attributes are extremely unusual, so just use untyped\n parlour_type = Parlour::Types::Untyped.new\n else\n parlour_type = TypeConverter.yard_to_parlour(\n yard_types, reader || writer, @type_converter_config)\n end\n\n # Generate attribute\n if reader && writer\n kind = :accessor\n elsif reader\n kind = :reader\n elsif writer\n kind = :writer\n end\n\n if @exclude_untyped && parlour_type.is_a?(Parlour::Types::Untyped)\n Logging.omit(\"excluding untyped attribute\", reader || writer, immediate: true)\n next\n end\n\n case @mode\n when :rbi\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n class_attribute: (attr_loc == :class)\n ) do |m|\n add_comments(reader || writer, m)\n end\n when :rbs\n if attr_loc == :class\n # RBS doesn't support class attr_accessors so create individual methods\n\n if reader\n @current_object.create_method(\n name.to_s,\n [Parlour::RbsGenerator::MethodSignature.new([], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(reader, m)\n end\n end\n\n if writer\n @current_object.create_method(\n \"#{name}=\",\n [Parlour::RbsGenerator::MethodSignature.new([Parlour::RbsGenerator::Parameter.new(\n \"value\",\n type: parlour_type,\n required: true\n )], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(writer, m)\n end\n end\n else\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n ) do |m|\n add_comments(reader || writer, m)\n end\n end\n end\n end\n end\n end", "def []=(attr_name, value)\r\n if attr_name.is_a?(String) and attr_name != attr_name.split(ID_SEP).first\r\n attr_name = attr_name.split(ID_SEP)\r\n end\r\n\r\n if attr_name.is_a? Array\r\n value = value.split(ID_SEP) if value.is_a? String\r\n unless value.length == attr_name.length\r\n raise \"Number of attr_names and values do not match\"\r\n end\r\n #breakpoint\r\n [attr_name, value].transpose.map {|name,val| write_attribute(name.to_s, val)}\r\n else\r\n write_attribute(attr_name, value)\r\n end\r\n end", "def attr(symbol, writable=false) end", "def define_writer!(k, definition)\n define_method(\"#{k}=\") do |value|\n # Recursively convert hash and array of hash to schematized objects\n value = ensure_schema value, definition[:schema]\n\n # Initial value\n instance_variable_set \"@#{k}\", value\n\n # Dirty tracking\n self.changed_attributes ||= Set.new\n self.changed_attributes << k\n end\n end", "def validate\n validate_string_attributes\n end", "def write_attribute_with_dynamo(field_name, value)\n if is_dynamo_field?(field_name)\n # Store these guys for now. We don't actually save the field value until the model is saved ( i.e my_supplier.save ).\n # If we were to save the field_value now we wouldn't be able to know the id of the model to link this value to it.\n # @see delay_save\n @all_fields_and_values ||= []\n @all_fields_and_values << {:dynamo_field=>cached_dynamo_field_by_name(field_name), :value=>value}\n end\n # If its a 'normal' attribute let rails write it in the usual way.\n write_attribute_without_dynamo(field_name, value)\n end", "def define_attr_accessor(attr)\n attr_accessor(attr)\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n writer.write_collection_of_object_values(\"attributeMappings\", @attribute_mappings)\n writer.write_boolean_value(\"enabled\", @enabled)\n writer.write_enum_value(\"flowTypes\", @flow_types)\n writer.write_collection_of_object_values(\"metadata\", @metadata)\n writer.write_string_value(\"name\", @name)\n writer.write_string_value(\"@odata.type\", @odata_type)\n writer.write_object_value(\"scope\", @scope)\n writer.write_string_value(\"sourceObjectName\", @source_object_name)\n writer.write_string_value(\"targetObjectName\", @target_object_name)\n writer.write_additional_data(@additional_data)\n end", "def validate_attribute_syntax\n\t\t@values.each do |attribute, values|\n\t\t\t[ values ].flatten.each do |value|\n\t\t\t\tbegin\n\t\t\t\t\tself.get_converted_attribute( attribute.to_sym, value )\n\t\t\t\trescue => err\n\t\t\t\t\tself.log.error \"validation for %p failed: %s: %s\" %\n\t\t\t\t\t\t[ attribute, err.class.name, err.message ]\n\t\t\t\t\tattrtype = self.find_attribute_type( attribute )\n\t\t\t\t\tself.errors.add( attribute, \"isn't a valid %s value\" %\n\t\t\t\t\t\t[ attrtype.syntax ? attrtype.syntax.desc : attrtype.syntax_oid ] )\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def valid_attributes\n { }\n end", "def validatable_attributes(atts, opts)\n am, an, ab, m = opts.values_at(:allow_missing, :allow_nil, :allow_blank, :message)\n Array(atts).each do |a|\n next if am && !values.has_key?(a)\n v = send(a)\n next if an && v.nil?\n next if ab && v.respond_to?(:blank?) && v.blank?\n if message = yield(a, v, m)\n errors.add(a, message)\n end\n end\n end", "def valid_attributes\n { }\n end", "def valid_attributes\n { }\n end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def require_attr(name)\n send(name).tap do |_|\n raise \"Attribute must be set: #{name}\" if _.nil?\n end\n end", "def write_attributes(attributes)\n _attributes = attributes.select do |name, value|\n if self.is_dynamic_field?(name)\n self.dynamic_setter(name, value)\n false\n else\n true\n end\n end\n\n super(_attributes)\n end", "def attribute; end", "def attribute; end" ]
[ "0.6472992", "0.6315012", "0.6315012", "0.62821025", "0.6279224", "0.6211609", "0.61891466", "0.6182247", "0.60683644", "0.6032628", "0.5995443", "0.5988785", "0.5959885", "0.5938289", "0.5931089", "0.58951056", "0.5859927", "0.5851703", "0.58493423", "0.58465594", "0.58328366", "0.5823013", "0.5822229", "0.57850474", "0.5701491", "0.5696689", "0.5682951", "0.5678094", "0.566814", "0.5657499", "0.56555206", "0.5642589", "0.56219065", "0.5615893", "0.56105876", "0.559851", "0.5598089", "0.55940455", "0.5585137", "0.55848545", "0.55796933", "0.5571477", "0.5567006", "0.55667996", "0.55652434", "0.5562926", "0.55600035", "0.55590326", "0.55590326", "0.5554599", "0.5554599", "0.55407417", "0.5534935", "0.5527733", "0.55271375", "0.55238813", "0.5501504", "0.5497003", "0.5496233", "0.54927665", "0.5464706", "0.54617554", "0.5461167", "0.5451583", "0.54498726", "0.54498726", "0.54359984", "0.5430996", "0.5430996", "0.5426488", "0.5418467", "0.54153895", "0.54107565", "0.5407886", "0.5401234", "0.54008496", "0.5400268", "0.53910094", "0.53827274", "0.5377731", "0.5375473", "0.5374833", "0.53720397", "0.5370215", "0.5363264", "0.5361161", "0.5360557", "0.5351706", "0.53514725", "0.53492516", "0.53459316", "0.5341237", "0.5328037", "0.5328037", "0.53230566", "0.53230566", "0.53230566", "0.5319575", "0.531832", "0.5315559", "0.5315559" ]
0.0
-1
Custom attribute writer method with validation
def icmp_first_packet=(icmp_first_packet) if icmp_first_packet.nil? fail ArgumentError, 'icmp_first_packet cannot be nil' end if icmp_first_packet > 4320000 fail ArgumentError, 'invalid value for "icmp_first_packet", must be smaller than or equal to 4320000.' end if icmp_first_packet < 10 fail ArgumentError, 'invalid value for "icmp_first_packet", must be greater than or equal to 10.' end @icmp_first_packet = icmp_first_packet end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def attr_writer_tag(text); end", "def allowed_attributes=(_arg0); end", "def allowed_attributes=(_arg0); end", "def writer(*args)\n attr_writer(*args)\n args\n end", "def define_write_method(attr_name)\n evaluate_attribute_method attr_name, \"def #{attr_name}=(new_value);write_attribute('#{attr_name}', new_value);end\", \"#{attr_name}=\"\n end", "def attr_writer(*vars)\n # avoid tracking attributes that are added by the class_attribute\n # as these are class attributes and not instance attributes.\n tracked_vars = vars.reject {|var| respond_to? var }\n add_tracked_attrs(false, true, *tracked_vars)\n vars.extract_options!\n super\n end", "def attr_writer(sym, *more) end", "def is_attribute?; end", "def validate_exclusion_of(attr); end", "def register_attributes\n raise \"Not implemented in #{self.class}\"\n end", "def method_missing(method_name, *args)\n return super unless permitted_attributes.include?(method_name)\n begin\n object.send(:\"#{method_name}=\", args.first)\n rescue => e\n if params.has_key?(method_name)\n message = \"Unable to process value for :#{method_name}, no attribute writer. Be sure to override the automatic setters for all params that do not map straight to a model attribute.\"\n Rails.logger.warn({message: message,\n missing_writer: method_name,\n value: args.first,\n error: e})\n self.errors << {status: 422, message: message}\n else\n raise e\n end\n end\n end", "def timeliness_validation_for(attr_names, type)\n super\n attr_names.each { |attr_name| define_timeliness_write_method(attr_name) }\n end", "def create_setter_for(attribute, options)\n setter_method = \"#{attribute}=\"\n\n define_method setter_method do |value|\n if options[:allow_blank] || value != \"\"\n write_attribute(attribute, value)\n end\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each {|attr_name| attr_internal_define(attr_name, :writer)}\n end", "def escape_attr input\n escape input, attr_regexp, attr_mapping\n end", "def make_writer( attrtype )\n\t\tself.log.debug \"Generating an attribute writer for %p\" % [ attrtype ]\n\t\tattrname = attrtype.name\n\t\tif attrtype.single?\n\t\t\tself.log.debug \" attribute is SINGLE, so generating a scalar writer...\"\n\t\t\treturn lambda {|newvalue| self[attrname] = newvalue }\n\t\telse\n\t\t\tself.log.debug \" attribute isn't SINGLE, so generating an array writer...\"\n\t\t\treturn lambda {|*newvalues| self[attrname] = newvalues.flatten }\n\t\tend\n\tend", "def write_attribute(name, value)\n # Simply check if the accessor is allowed to write the field\n # (if so, go to superclass and do it)\n @bypass_auth ||= false\n if allowed_to_write(name) || @bypass_auth\n super(name, value)\n end\n end", "def mattr_writer(*syms, &proc)\n receiver = self\n options = syms.extract_options!\n syms.each do |sym|\n raise NameError.new('invalid attribute name') unless sym =~ /^[_A-Za-z]\\w*$/\n class_exec do\n define_singleton_method \"#{sym}=\" do |obj|\n class_variable_set(\"@@#{sym}\", obj)\n end\n end\n\n unless options[:instance_writer] == false || options[:instance_accessor] == false\n class_exec do\n define_method \"#{sym}=\" do |obj|\n receiver.class_variable_set(\"@@#{sym}\", obj)\n end\n end\n end\n send(\"#{sym}=\", proc.call) if proc\n end\n end", "def write_attribute(attribute, value)\n false\n end", "def add_attribute attribute\n return attribute unless @document_self\n\n # mainly to check for redefinition of an attribute as a method\n # TODO find a policy for 'attr_reader :foo' + 'def foo=()'\n register = false\n\n key = nil\n\n if attribute.rw.index 'R' then\n key = attribute.pretty_name\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name + '='] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if attribute.rw.index 'W' then\n key = attribute.pretty_name + '='\n known = @methods_hash[key]\n\n if known then\n known.comment = attribute.comment if known.comment.empty?\n elsif registered = @methods_hash[attribute.pretty_name] and\n RDoc::Attr === registered then\n registered.rw = 'RW'\n else\n @methods_hash[key] = attribute\n register = true\n end\n end\n\n if register then\n attribute.visibility = @visibility\n add_to @attributes, attribute\n resolve_aliases attribute\n end\n\n attribute\n end", "def define_writer_method(mod)\n writer_method_name = \"#{name}=\"\n attribute = self\n\n mod.send(:define_method, writer_method_name) { |value| attribute.set(self, value) }\n mod.send(writer_visibility, writer_method_name)\n\n self\n end", "def allowed_to_write(name)\n # no point allowing attribute writes if we can't save them?\n if allowed_to_save\n name = name.to_s\n validation_methods = self.class.write_validations(name) \n if validation_methods.nil?\n # We haven't registered any filters on this attribute, so allow the write.\n true\n elsif validation_methods.check :accessor => accessor, :model => self\n # One of the authentication methods worked, so allow the write.\n true\n else\n # We had filters but none of them passed. Disallow write.\n false\n end\n else\n false\n end\n end", "def assert_attr_writer(obj, method)\n assert_respond_to obj, \"#{method}=\"\nend", "def add_attribute(name, &block); end", "def authenticates_writes_to(attr, options={})\n authenticates_access\n @write_validation_map ||= {}\n @write_validation_map[attr.to_s] ||= AuthMethodList.new\n @write_validation_map[attr.to_s].add_method(options)\n end", "def write_attribute_3(param1, param2)\n\twrite_attribute(param1, param2)\n end", "def write_attribute(attr_name, value) #:doc:\n @attributes[attr_name] = empty_string_for_number_column?(attr_name, value) ? nil : value\n end", "def add_writer_tags(klass, new_method, member)\n member_tag = member_tag_for_member(klass, member, :write)\n return_type = return_type_from_tag(member_tag)\n setter_doc_text = member_tag ? member_tag.text : \"Sets the attribute #{member}\"\n new_method.docstring.replace(setter_doc_text)\n new_method.add_tag YARD::Tags::Tag.new(:param, \"the value to set the attribute #{member} to.\", return_type, \"value\")\n new_method.add_tag YARD::Tags::Tag.new(:return, \"the newly set value\", return_type)\n end", "def print_attribute(*) end", "def attribute(name); end", "def add_checked_attribute(clazz, attribute)\r\n eval <<END\r\n class #{clazz}\r\n\r\n def #{attribute}=(value)\r\n raise 'Invalid attribute' unless value\r\n @#{attribute}=value\r\n end\r\n\r\n def #{attribute}\r\n #{attribute}\r\n end\r\n end\r\nEND\r\nend", "def attr(name); end", "def is_attribute?(line)\n (line =~ /(\\s+)attr_(writer|reader|accessor)\\s+:[a-zA-Z_0-9]+/) == 0\n end", "def attribute(name, value)\n\t if !@inStartTag\n\t\traise WriterError.new('attribute outside of tag start')\n\t end\n\t @io << \" #{name}=\\\"#{NQXML.encode(value.to_s)}\\\"\"\n\tend", "def set_attribute(name, value); end", "def dataset_writer(*attributes)\n attributes.flatten.each do |attr_name|\n next if method_defined?(\"#{attr_name}=\")\n\n class_eval <<-RUBY, __FILE__, __LINE__ + 1\n def #{attr_name}=(value)\n dataset_set(:#{attr_name}, value)\n end\n RUBY\n end\n end", "def validated_attribute_names(params); end", "def require_format_of(attribute)\r\n RequireFormatOf.new(attribute)\r\n end", "def attr_writer(*fields)\n check_fields(fields)\n added_fields = jiak.data.writable(*fields)\n added_fields.each do |field|\n class_eval <<-EOM\n def #{field}=(val)\n @jiak.object.data.#{field} = val\n self.class.do_auto_update(self)\n end\n EOM\n end\n nil\n end", "def html_attr(*attrs)\n options = attrs.extract_options!.reverse_merge({\n :level => :super_relaxed\n })\n attrs.each do |att|\n class_eval \"def #{att}=(val); self[:#{att}] = sanitize(val, :#{options[:level]}); end\"\n end\n end", "def validate_attributes=(new_attribute)\n @validate_attributes = new_attribute\n end", "def html_attributes(attr); end", "def instance_write(attr, value)\n setter = :\"#{@name_string}_#{attr}=\"\n instance.send(setter, value) if instance.respond_to?(setter)\n end", "def valid_xml_attribute(name, options={:level => :warning})\n\t\t\t\tvalidate(\"Invalid XML attribute '#{name}'\", options) { name.to_s.match(/^([^[:punct:]0-9<>]|_)[^<>\"']*/) }\n\t\t\tend", "def attr_writer(*args)\n sym_args=args_to_sym(args)\n sym_args.each do |value|\n self.instance_eval(\"def #{value}=(arg); @#{value}=arg;end;\")\n end\n \n end", "def define_writer_method(attribute, method_name, visibility)\n define_method(method_name) { |value| attribute.set(self, value) }\n send(visibility, method_name)\n self\n end", "def write_attribute(name, val)\n if @embedded_models.include? name\n @embedded_models[name].model = val\n elsif @attribute_objects.include? name\n @attribute_objects[name].value = val\n else\n return false\n end\n\n run_callbacks :attribute_change\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { \"name\" => \"MyString\" }\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def valid_attributes\n { body: \"blah\",\n rule_text: 'Something',\n change_description: \"blaa\"}\n end", "def attr; end", "def attribute(*args)\n define_expressions(Attribute, args)\n end", "def write_attribute(name, value)\n name = name.to_s\n\n # The attribute already has an unsaved change.\n if attribute_changed?(name)\n old = changed_attributes[name]\n changed_attributes.delete(name) unless field_changed?(name, old, value)\n else\n attribute_will_change(name) if field_changed?(name, old, value)\n end\n\n # Carry on.\n super(name, value)\n end", "def define_magic_attr(name)\n define_method name do |*attrs|\n raise ArgumentError.new(\"wrong number of arguments\") if attrs.size > 1\n send(\"#{name}=\", attrs.first) if attrs.size == 1\n instance_variable_get(\"@#{name}\")\n end\n\n attr_writer name\n end", "def configurable_writer(attribute, code=nil, &block)\n if block_given? and not code\n Halcyon.class.send(:define_method, :\"#{attribute}=\", block)\n elsif code and not block_given?\n Halcyon.class.send(:eval, <<-\"end;\")\n def #{attribute.to_s}=(value)\n #{code % [attribute.to_sym.inspect]}\n end\n end;\n else\n raise ArgumentError.new(\"Either a block or a code string should be supplied.\")\n end\n end", "def method_missing(name, *args, &block)\n if /\\Ahas_validated_(?<type>\\w*)_attribute\\Z/ =~ name\n has_validated_attribute(type, *args, &block)\n else\n super\n end\n end", "def add_checked_attribute(klass, attribute)\n klass.class_eval do\n define_method attribute do\n instance_variable_get(\"@#{attribute}\")\n end\n\n define_method \"#{attribute}=\" do |value|\n raise 'Invalid attribute' unless value\n \n instance_variable_set(\"@#{attribute}\", value)\n end\n end\nend", "def method_missing(meth, *args, &blk)\n match = meth.to_s.match(/^([a-zA-Z\\_]+)(=|$)$/)\n if match\n attribute, setter = match[1], !match[2].blank?\n if setter\n write_attribute(attribute, args.first)\n else\n read_attribute(attribute)\n end\n else\n super(meth, *args, &blk)\n end\n end", "def valid_attributes\n { name: 'do this' }\n end", "def make_attributes_definitions_or_croak(attrArgs, &attrBlok)\n eye = :'m_attrs_defs'\n\n # Work with attribute as strings\n \n $DEBUG && logger_me(eye, logger_fmt_kls(:attrArgs => attrArgs, :attrBlok => attrBlok))\n\n mustbe_attributes_specification_or_croak(attrArgs, eye, \"attrArgs not attributes_specification\")\n \n #STOPATTRARGSINSUPER\n \n #attrAll = mustbe_not_empty_or_croak(mustbe_array_key_or_nil_or_croak(attrArgs, :all, eye, \"all attributes not array\"), eye, \"all attributes is empty\").map(&:to_s)\n attrAll = mustbe_not_empty_or_croak(mustbe_attributes_specification_all_key_or_croak(attrArgs, :all, eye), eye, \"all attributes is empty\").map(&:to_s)\n \n\n #puts(\"\\n\\n\\nATTR ALL >#{attrAll}<\")\n\n #STOPMAKEATTRSPECSENTRY\n\n attrInc = mustbe_attributes_specification_include_key_or_nil_or_croak(attrArgs, :include, eye) # mustbe all strings\n #puts(\"ATTR INC >#{attrInc.class}< >#{attrInc}< >#{is_value_not_empty?(attrInc)}<\")\n attrInc && mustbe_not_empty_or_croak(attrInc, eye, \"include attributes is empty\")\n\n attrExc = mustbe_attributes_specification_exclude_key_or_nil_or_croak(attrArgs, :exclude, eye) || []\n \n attrMapNom = mustbe_attributes_definitions_key_or_nil_or_croak(attrArgs, :definitions, eye) || {}\n attrMap = attrMapNom && potrubi_util_map_hash_kv(attrMapNom) {|k,v| [k.to_s, v]} # keys all strings\n\n # Ensure all consistent\n \n attrInc && mustbe_subset_or_croak(attrInc, attrAll, eye, \"include attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrExc, attrAll, eye, \"exclude attributes contains unknown attributes\")\n mustbe_subset_or_croak(attrMap.keys, attrAll, eye, \"attribute map contains unknown attributes\")\n \n attrUse = ((attrInc || attrAll) - attrExc).uniq # list of unique attributes to report on\n\n # consolidate \"faked up\" attr specs with ones provided to get the composite attrSpecs\n \n attrDefsNom = potrubi_util_array_to_hash(attrUse).merge(attrMap.select {|k,v| attrUse.include?(k)}) # consolidated \"faked up\" attr specs with ones provided\n\n attrDefs = potrubi_util_map_hash_v(attrDefsNom) do | attrName, attrSpecNom|\n\n attrSpec =\n case attrSpecNom\n when NilClass then {}\n when Hash then\n attrSpecNom.each_with_object({}) do | (verbName, verbSpec), h1 |\n case verbName\n when :pass_thru then h1[:pass_thru] = verbSpec # dont touch; just pass through\n when :event_defaults then # add these to pass_thru\n h1[:pass_thru] = (h1[:pass_thru] || {}).merge(verbName => verbSpec)\n when :map, :select, :metric then\n h1[verbName] = {\n :method_name => \"#{verbName}_#{attrName}_#{rand(1000000)}\", # make a unqiue name\n :method_spec => verbSpec # spec must be valid to dynamic_define_methods\n }\n else\n logic_exception(verbName, eye, \"attrName >#{attrName}< verbName >#{verbName}< value should be impossible\")\n end\n end\n \n else\n logic_exception(attrrSpecNom, eye, \"attrSpecNom value should be impossible\")\n end\n\n attrSpec\n \n end\n \n $DEBUG && logger_mx(eye, logger_fmt_kls(:attrDefs => attrDefs))\n\n mustbe_attributes_definitions_or_croak(attrDefs, eye, \"attrDefs failed contract\")\n\n #STOPMAKEATTRSPECS\n \n end", "def create_writer(klass, member)\n # We want to convert these members into attributes just like\n # as if they were declared using attr_accessor.\n new_meth = register MethodObject.new(klass, \"#{member}=\", :instance) do |o|\n o.parameters = [['value', nil]]\n o.signature ||= \"def #{member}=(value)\"\n o.source ||= \"#{o.signature}\\n @#{member} = value\\nend\"\n end\n add_writer_tags(klass, new_meth, member)\n klass.attributes[:instance][member][:write] = new_meth\n end", "def create_setter!\n @target.class_eval <<-EOS\n #{writer_visibility.to_s}\n def #{name}=(value)\n attribute_set(#{name.inspect}, value)\n end\n EOS\n rescue SyntaxError\n raise SyntaxError.new(column)\n end", "def attribute name, type, conditions= DEFAULT_ATTRIBUTE_CONDITIONS\n RMOF.complete_conditions conditions, DEFAULT_ATTRIBUTE_CONDITIONS\n @attributes= {} unless instance_variable_defined? :@attributes\n @attributes[name]= [name, type, conditions]\n unless method_defined? :__attributes then \n define_method( :__attributes) do \n @attributes\n end \n end\n at= \"@#{name}\".to_sym\n getter= \"#{name}\".to_sym\n setter= \"#{name}=\".to_sym\n completion= \"__complete_#{name}\".to_sym\n define_method( getter) do\n if instance_variable_defined? at then instance_variable_get at\n else conditions[:default]\n end\n end\n define_method( setter) do |val|\n instance_variable_set at, val\n end\n define_method( completion) do\n RMOF.validate( self.send(getter), name, type, conditions)\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def attr_internal_writer(*attrs)\n attrs.each do |attr|\n module_eval \"def #{attr}=(v) #{attr_internal_ivar_name(attr)} = v end\"\n end\n end", "def create_setter(name, meth)\n define_method(\"#{meth}=\") do |value|\n write_attribute(name, value)\n end\n end", "def sanitized_allowed_attributes=(attributes); end", "def sanitized_allowed_attributes=(attributes); end", "def oattr(name, type)\n case type\n when :custom\n # Do nothing, just register attr below.\n when :writer\n attr_writer name\n else\n raise ArgumentError, \"Unknown type: #{type.inspect}\"\n end\n\n # Register and return.\n name.tap { oattrs << name}\n end", "def valid_attributes\n { name: \"Expert\" }\n end", "def attributes(*method_names, **options)\n add_attributes(method_names, **options, strategy: :write_value_using_method_strategy)\n end", "def []=(attr_name, value)\n writer_method = \"#{attr_name}=\"\n send(writer_method, value) if respond_to?(writer_method)\n end", "def write_extended_attributes(attrs)\n attrs.each do |k, val|\n self.send((k.to_s + \"=\").to_sym, val) if is_flex_attribute?(k)\n end\n self\n end", "def valid_attributes\n { \"username\" => \"MyString\" }\n end", "def cattr_writer(*fields)\n metaclass.send :attr_writer, *fields\n end", "def write_attribute(attr, value)\n if attribute_encrypted?(attr)\n conductor_for(attr).encrypt(value)\n else\n super(attr, value)\n end\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_number_value(\"offsetInDays\", @offset_in_days)\n writer.write_enum_value(\"timeBasedAttribute\", @time_based_attribute)\n end", "def define_attribute_method(attr_name, _owner: generated_attribute_methods)\n CodeGenerator.batch(_owner, __FILE__, __LINE__) do |owner|\n attribute_method_matchers.each do |matcher|\n method_name = matcher.method_name(attr_name)\n\n unless instance_method_already_implemented?(method_name)\n generate_method = \"define_method_#{matcher.target}\"\n\n if respond_to?(generate_method, true)\n send(generate_method, attr_name.to_s, owner: owner)\n else\n define_proxy_call true, owner, method_name, matcher.target, attr_name.to_s\n end\n end\n end\n attribute_method_matchers_cache.clear\n end\n end", "def has_attributes?; end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n super\n writer.write_boolean_value(\"isExpirationRequired\", @is_expiration_required)\n writer.write_duration_value(\"maximumDuration\", @maximum_duration)\n end", "def add_attributes(item)\n [:class, :instance].each do |attr_loc|\n # Grab attributes for the current location (class or instance)\n attrs = item.attributes[attr_loc]\n attrs.each do |name, attribute|\n reader = attribute[:read]\n writer = attribute[:write]\n\n unless reader || writer\n Logging.warn(\"attribute is not readable or writable somehow, skipping\", attribute)\n next\n end\n\n # Get all given types\n yard_types = []\n if reader\n next if @hide_private && reader.visibility == :private\n yard_types += reader.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n reader.tags('param').flat_map(&:types)\n end\n if writer\n next if @hide_private && writer.visibility == :private\n yard_types += writer.tags('return').flat_map(&:types).compact.reject { |x| x.downcase == 'void' } +\n writer.tags('param').flat_map(&:types)\n end\n\n # Use untyped if not types specified anywhere, otherwise try to\n # compute Parlour type given all these types\n if yard_types.empty?\n Logging.omit(\"no YARD type given for #{name.inspect}, using untyped\", reader || writer)\n parlour_type = Parlour::Types::Untyped.new\n elsif yard_types.all? { |x| x == 'nil' }\n # Nil attributes are extremely unusual, so just use untyped\n parlour_type = Parlour::Types::Untyped.new\n else\n parlour_type = TypeConverter.yard_to_parlour(\n yard_types, reader || writer, @type_converter_config)\n end\n\n # Generate attribute\n if reader && writer\n kind = :accessor\n elsif reader\n kind = :reader\n elsif writer\n kind = :writer\n end\n\n if @exclude_untyped && parlour_type.is_a?(Parlour::Types::Untyped)\n Logging.omit(\"excluding untyped attribute\", reader || writer, immediate: true)\n next\n end\n\n case @mode\n when :rbi\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n class_attribute: (attr_loc == :class)\n ) do |m|\n add_comments(reader || writer, m)\n end\n when :rbs\n if attr_loc == :class\n # RBS doesn't support class attr_accessors so create individual methods\n\n if reader\n @current_object.create_method(\n name.to_s,\n [Parlour::RbsGenerator::MethodSignature.new([], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(reader, m)\n end\n end\n\n if writer\n @current_object.create_method(\n \"#{name}=\",\n [Parlour::RbsGenerator::MethodSignature.new([Parlour::RbsGenerator::Parameter.new(\n \"value\",\n type: parlour_type,\n required: true\n )], parlour_type)],\n class_method: true\n ) do |m|\n add_comments(writer, m)\n end\n end\n else\n @current_object.create_attribute(\n name.to_s,\n kind: kind,\n type: parlour_type,\n ) do |m|\n add_comments(reader || writer, m)\n end\n end\n end\n end\n end\n end", "def []=(attr_name, value)\r\n if attr_name.is_a?(String) and attr_name != attr_name.split(ID_SEP).first\r\n attr_name = attr_name.split(ID_SEP)\r\n end\r\n\r\n if attr_name.is_a? Array\r\n value = value.split(ID_SEP) if value.is_a? String\r\n unless value.length == attr_name.length\r\n raise \"Number of attr_names and values do not match\"\r\n end\r\n #breakpoint\r\n [attr_name, value].transpose.map {|name,val| write_attribute(name.to_s, val)}\r\n else\r\n write_attribute(attr_name, value)\r\n end\r\n end", "def attr(symbol, writable=false) end", "def define_writer!(k, definition)\n define_method(\"#{k}=\") do |value|\n # Recursively convert hash and array of hash to schematized objects\n value = ensure_schema value, definition[:schema]\n\n # Initial value\n instance_variable_set \"@#{k}\", value\n\n # Dirty tracking\n self.changed_attributes ||= Set.new\n self.changed_attributes << k\n end\n end", "def validate\n validate_string_attributes\n end", "def write_attribute_with_dynamo(field_name, value)\n if is_dynamo_field?(field_name)\n # Store these guys for now. We don't actually save the field value until the model is saved ( i.e my_supplier.save ).\n # If we were to save the field_value now we wouldn't be able to know the id of the model to link this value to it.\n # @see delay_save\n @all_fields_and_values ||= []\n @all_fields_and_values << {:dynamo_field=>cached_dynamo_field_by_name(field_name), :value=>value}\n end\n # If its a 'normal' attribute let rails write it in the usual way.\n write_attribute_without_dynamo(field_name, value)\n end", "def define_attr_accessor(attr)\n attr_accessor(attr)\n end", "def serialize(writer)\n raise StandardError, 'writer cannot be null' if writer.nil?\n writer.write_collection_of_object_values(\"attributeMappings\", @attribute_mappings)\n writer.write_boolean_value(\"enabled\", @enabled)\n writer.write_enum_value(\"flowTypes\", @flow_types)\n writer.write_collection_of_object_values(\"metadata\", @metadata)\n writer.write_string_value(\"name\", @name)\n writer.write_string_value(\"@odata.type\", @odata_type)\n writer.write_object_value(\"scope\", @scope)\n writer.write_string_value(\"sourceObjectName\", @source_object_name)\n writer.write_string_value(\"targetObjectName\", @target_object_name)\n writer.write_additional_data(@additional_data)\n end", "def validate_attribute_syntax\n\t\t@values.each do |attribute, values|\n\t\t\t[ values ].flatten.each do |value|\n\t\t\t\tbegin\n\t\t\t\t\tself.get_converted_attribute( attribute.to_sym, value )\n\t\t\t\trescue => err\n\t\t\t\t\tself.log.error \"validation for %p failed: %s: %s\" %\n\t\t\t\t\t\t[ attribute, err.class.name, err.message ]\n\t\t\t\t\tattrtype = self.find_attribute_type( attribute )\n\t\t\t\t\tself.errors.add( attribute, \"isn't a valid %s value\" %\n\t\t\t\t\t\t[ attrtype.syntax ? attrtype.syntax.desc : attrtype.syntax_oid ] )\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def valid_attributes\n { }\n end", "def validatable_attributes(atts, opts)\n am, an, ab, m = opts.values_at(:allow_missing, :allow_nil, :allow_blank, :message)\n Array(atts).each do |a|\n next if am && !values.has_key?(a)\n v = send(a)\n next if an && v.nil?\n next if ab && v.respond_to?(:blank?) && v.blank?\n if message = yield(a, v, m)\n errors.add(a, message)\n end\n end\n end", "def valid_attributes\n { }\n end", "def valid_attributes\n { }\n end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def attribute_name=(_arg0); end", "def require_attr(name)\n send(name).tap do |_|\n raise \"Attribute must be set: #{name}\" if _.nil?\n end\n end", "def write_attributes(attributes)\n _attributes = attributes.select do |name, value|\n if self.is_dynamic_field?(name)\n self.dynamic_setter(name, value)\n false\n else\n true\n end\n end\n\n super(_attributes)\n end", "def attribute; end", "def attribute; end" ]
[ "0.6472992", "0.6315012", "0.6315012", "0.62821025", "0.6279224", "0.6211609", "0.61891466", "0.6182247", "0.60683644", "0.6032628", "0.5995443", "0.5988785", "0.5959885", "0.5938289", "0.5931089", "0.58951056", "0.5859927", "0.5851703", "0.58493423", "0.58465594", "0.58328366", "0.5823013", "0.5822229", "0.57850474", "0.5701491", "0.5696689", "0.5682951", "0.5678094", "0.566814", "0.5657499", "0.56555206", "0.5642589", "0.56219065", "0.5615893", "0.56105876", "0.559851", "0.5598089", "0.55940455", "0.5585137", "0.55848545", "0.55796933", "0.5571477", "0.5567006", "0.55667996", "0.55652434", "0.5562926", "0.55600035", "0.55590326", "0.55590326", "0.5554599", "0.5554599", "0.55407417", "0.5534935", "0.5527733", "0.55271375", "0.55238813", "0.5501504", "0.5497003", "0.5496233", "0.54927665", "0.5464706", "0.54617554", "0.5461167", "0.5451583", "0.54498726", "0.54498726", "0.54359984", "0.5430996", "0.5430996", "0.5426488", "0.5418467", "0.54153895", "0.54107565", "0.5407886", "0.5401234", "0.54008496", "0.5400268", "0.53910094", "0.53827274", "0.5377731", "0.5375473", "0.5374833", "0.53720397", "0.5370215", "0.5363264", "0.5361161", "0.5360557", "0.5351706", "0.53514725", "0.53492516", "0.53459316", "0.5341237", "0.5328037", "0.5328037", "0.53230566", "0.53230566", "0.53230566", "0.5319575", "0.531832", "0.5315559", "0.5315559" ]
0.0
-1
Checks equality by comparing each attribute.
def ==(o) return true if self.equal?(o) self.class == o.class && _self == o._self && _links == o._links && _schema == o._schema && _revision == o._revision && _system_owned == o._system_owned && display_name == o.display_name && description == o.description && tags == o.tags && _create_user == o._create_user && _protection == o._protection && _create_time == o._create_time && _last_modified_time == o._last_modified_time && _last_modified_user == o._last_modified_user && id == o.id && resource_type == o.resource_type && path == o.path && parent_path == o.parent_path && unique_id == o.unique_id && relative_path == o.relative_path && children == o.children && overridden == o.overridden && marked_for_delete == o.marked_for_delete && tcp_closed == o.tcp_closed && tcp_opening == o.tcp_opening && udp_single == o.udp_single && tcp_finwait == o.tcp_finwait && tcp_first_packet == o.tcp_first_packet && tcp_closing == o.tcp_closing && tcp_established == o.tcp_established && udp_multiple == o.udp_multiple && icmp_error_reply == o.icmp_error_reply && udp_first_packet == o.udp_first_packet && icmp_first_packet == o.icmp_first_packet end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ==(other)\n attributes == other.attributes\n end", "def ==(other) # :nodoc:\n @attrs == other.attrs\n end", "def eql?(other)\n return true if self == other\n @@ATTRIBUTES.each do |att|\n return false unless self.send(att).eql?(other.send(att))\n end\n true\n end", "def assert_equal_attributes(object, expected_attributes)\n expected_attributes.each do |index, value|\n assert_equal value, object[index], \"#{index}\"\n end\n end", "def attr_equal?(o)\n self == o and\n self.instance_variables_compare(o).empty? and\n self.attributes == o.attributes\n end", "def same_attributes?(spec)\n @@attributes.all? {|name, default| self.send(name) == spec.send(name) }\n end", "def ==(other)\n self.class.valid_attrs.each do |attr|\n return false if read(attr) != other.read(attr)\n end\n true\n end", "def ==(other)\n self.attributes == (other.respond(:attributes) || {} )\n end", "def ==(other)\n other.present? && self.attributes == other.attributes\n end", "def ==(other)\n return false if other.nil? || !other.respond_to?(:attributes)\n attributes == other.attributes\n end", "def match?(attributes)\n attributes.each do |attr, val|\n return false if send(attr).to_s != val.to_s\n end\n true\n end", "def ==(other)\n self.class == other.class &&\n self.attributes == other.attributes\n end", "def ==(other)\n self.class == other.class &&\n attributes == other.attributes\n end", "def ==(other)\n return super unless other.is_a?(self.class)\n\n attributes.all? { |name, value| value == other.send(name) }\n end", "def changed?(comparison)\n attributes.any? do |attribute, value|\n next unless comparison.key?(attribute)\n comparison[attribute] != value\n end\n end", "def ==(other)\n return false unless self.class == other.class\n self.attributes == other.attributes\n end", "def ==(other)\n if other.kind_of? Details::Attribute\n self.name == other.name && self.value == other.value\n else\n self.value == other\n end\n end", "def ==(other)\n return false unless other.instance_of? self.class\n attributes == other.attributes\n end", "def ==(other)\n return super unless other.is_a?(self.class)\n\n attributes.all? { |name, value| value == other.attributes[name] }\n end", "def ==(other)\n return super unless other.is_a?(self.class)\n\n attributes.all? { |name, value| value == other.attributes[name] }\n end", "def ==(other)\n return super unless other.is_a?(self.class)\n\n attributes.all? { |name, value| value == other.attributes[name] }\n end", "def ==(other)\n Attribute === other && \n !(Expression === other) &&\n relation == other.relation && \n name == other.name && \n self.alias == other.alias && \n original_relation == other.original_relation\n end", "def ==(obj)\n if obj.instance_of?(self.class)\n compare_attributes = [\"category_id\", \"combo_item_id\", \"quantity\", \"sequence\"]\n compare_attributes.each do |field|\n if self.send(field) != obj.send(field)\n return false\n end\n end\n return true\n end\n return false\n end", "def ==(other)\n return false if other.class != self.class\n attr_hash == other.attr_hash\n end", "def ==(other)\n case other\n when Chair::Row\n @attributes == other.instance_variable_get('@attributes')\n when Array\n @attributes.values == other\n else false\n end\n end", "def == other\n return false unless other.kind_of? self.class\n attribute_of.all? do |key, val|\n val.get == other.__send__(key)\n end\n end", "def correct_combination?(attr1, attr2, attr3)\n result = false\n if attr1 == attr2 && attr2 == attr3\n result = true\n elsif attr1 != attr2 && attr2 != attr3 && attr1 != attr3\n result = true\n end\n return result\n end", "def ==(other)\n return false if self.class != other.class\n return super if @_lazer_model.required_properties.empty?\n @_lazer_model.required_properties.each do |key_name|\n return false if read_attribute(key_name) != other.read_attribute(key_name)\n end\n true\n end", "def eql?(other)\n other.is_a?(self.class) && !self.class.comparison_attrs.find{|a| send(a) != other.send(a)}\n end", "def verify_attributes(hash, expected)\n return [] unless expected.attributes\n expected.attributes.map{ |a| verify_attribute_value(hash[a.name.to_s], a) }\n end", "def assert_attributes obj, attr_hash\n default_attr_hash = {}\n if obj.respond_to? :default_attr_hash\n default_attr_hash = obj.default_attr_hash\n end\n default_attr_hash.merge(attr_hash).each_pair do |key, value|\n assert_equal value, obj.__send__(key), \"Attribute #{key} of #{obj}\"\n end\n end", "def match_attributes(attrs)\n attrs = Saxxy::Helpers.stringify_keys(attrs)\n attributes.reduce(true) do |b, (k, v)|\n value = attrs[k]\n b && ((!value.nil? && match(v, value)) || (v.nil? && value.nil?))\n end\n end", "def equal_set(expected)\n message = \"#{Helpers.inspect_records(@object)} has the same records as #{Helpers.inspect_records(expected)}\"\n \n left = @object.map(&:id).sort\n right = expected.map(&:id).sort\n \n test_case.assert(left != right, message)\n end", "def ===(other)\n required = self.class.required_attributes\n\n other.respond_to?(:keys) && (common = other.keys & required) &&\n common.size == other.keys.size && common.size == required.size\n end", "def bt_same_value?(other)\n bt_value_attributes == other.bt_value_attributes\n end", "def ==(x)\n return true if object_id == x.object_id\n return false unless x.kind_of?(AttrArray)\n each_with_index do |a, n|\n return false unless a == x[n]\n end\n true\n end", "def equal_set(expected)\n message = \"#{Helpers.inspect_records(@object)} does not have the same records as #{Helpers.inspect_records(expected)}\"\n \n left = @object.map(&:id).sort\n right = expected.map(&:id).sort\n \n test_case.assert(left == right, message)\n end", "def compare_attributes(data_criteria, criteria)\n return false unless data_criteria['dataElementAttributes']&.any?\n\n data_criteria['dataElementAttributes'].map { |dc| dc.except('_id') }.include? criteria['dataElementAttributes'][attribute_index].except('_id')\n end", "def ==(other)\n @klass == other.class && @attributes == strip_active_record(other)\n end", "def ==(other)\n other.is_a?(self.class) &&\n other.attribute == attribute &&\n other.validation == validation &&\n other.expected == expected &&\n other.actual == actual\n end", "def == other\n return false unless self.class == other.class\n [:unit, :frequency, :anchor, :weeks, :monthdays, :weekdays, :times].all? do |attribute|\n self.send(attribute) == other.send(attribute)\n end\n end", "def compare_equal?(item, line_item)\n ![\n :ax_account_number,\n :ax_account_id,\n :ax_order_number,\n :ax_order_id,\n :email_address,\n :first_name,\n :last_name,\n :serial_number,\n :purch_order_form_num\n ].detect { |attr| item.send(attr) != line_item.send(attr) }\n end", "def ==(b) # :nodoc:\n ( b.respond_to?(:result_attributes) &&\n result_attributes == b.result_attributes && \n @result_attributes.all?{ |k| send(k) == b.send(k) } )\n end", "def validates_different(*attr_names)\n validates_with ValidatesAll::DifferenceValidator, _merge_attributes(attr_names)\n end", "def identical?\n #Song.first.attributes.each { |v,k| Song.find(:all, :conditions => [\" #{v} like ?\", \"%blah%\"])}\n Song.find(:all, :conditions => [\"name = ? or length = ?\", \"#{self.name}\", self.length]) do |x| \n x.hash == self.hash\n end\n end", "def diff?(model = self.class.find(id))\n self.class.diffable_attributes.each do |attribute|\n return true if send(attribute) != model.send(attribute)\n end\n return false\n end", "def filter_attributes_match?(hash_one, hash_two)\n hash_one.all? do |key, value_one|\n value_two = hash_two[key]\n case\n when value_one == value_two\n true\n when value_one.is_a?(Hash) && value_two.is_a?(Hash)\n filter_attributes_match?(value_one, value_two)\n when hash_one[key].to_s == hash_two[key].to_s\n true\n when value_one.is_a?(String) && value_one.start_with?(\"eval:\")\n eval_attribute_value(value_one, value_two)\n else\n false\n end\n end\n end", "def comparable_attributes\n#\t\tHashWithIndifferentAccess[attributes.select {|k,v| \n#\t\t\t!Abstract.incomparable_attribute_names.include?(k)}]\n\t\tHashWithIndifferentAccess[attributes.select {|k,v| db_fields.include?(k)}]\n\tend", "def all_equal?\n a = self.first\n all? { |b| a == b }\n end", "def check_attrs(attr_list)\r\n attrs = []\r\n attr_list.each do |attr_sym|\r\n attr = assigns(attr_sym.to_sym)\r\n assert_not_nil attr, \"Attribute @#{attr_sym} should not be nil\"\r\n assert !attr.new_record?, \"Should have saved the @#{attr_sym} obj\" if attr.class == ActiveRecord\r\n attrs << attr\r\n end\r\n attrs.length > 1 ? attrs : attrs[0]\r\n end", "def check_attrs(attr_list)\r\n attrs = []\r\n attr_list.each do |attr_sym|\r\n attr = assigns(attr_sym.to_sym)\r\n assert_not_nil attr, \"Attribute @#{attr_sym} should not be nil\"\r\n assert !attr.new_record?, \"Should have saved the @#{attr_sym} obj\" if attr.class == ActiveRecord\r\n attrs << attr\r\n end\r\n attrs.length > 1 ? attrs : attrs[0]\r\n end", "def attr_set?(cards, attr)\n array = []\n cards.each do |card|\n # evalutes the string 'attr' and returns the value\n array << card.send(attr)\n end\n\n # only return true if it's all the same or totally different\n return true if array.uniq.count == 1\n return true if array.uniq.count == 3\n return false\n end", "def attribute_changed?(attribute_name)\n (self.diff['attributes']['new']||{})[attribute] != (self.diff['attributes']['old']||{})[attribute]\n end", "def eql?(other)\n return false if (other.nil? or self.class != other.class)\n return false unless super(other)\n return false unless self.attributes == other.attributes\n return false unless self.nodes == other.nodes\n true\n end", "def eql?(other)\n return false unless self.class == other.class\n self.key_attributes == other.key_attributes\n end", "def uniquify_attributes(attributes)\n attributes.each do |ka|\n oldval = send(ka)\n next unless String === oldval\n newval = UniquifierCache.instance.get(self, oldval)\n set_property_value(ka, newval)\n logger.debug { \"Reset #{qp} #{ka} from #{oldval} to unique value #{newval}.\" }\n end\n end", "def eql?(object)\n self.class.equal?(object.class) && attributes == object.attributes\n end", "def multi_element_attr_check( elements )\n wanted = Array.new\n found = Array.new\n elements.each do |element|\n print \".\"\n e = $driver.find_element(element[0].to_sym, element[1])\n wanted << [ element[1], element[2], element[3] ]\n found << [ element[1], element[2], e.attribute(element[2]) ]\n end\n\n found.should == wanted\n end", "def equals(rule)\n element == rule.element && attributes == rule.attributes\n end", "def attr_reader(*args)\n super\n comparison_attrs.concat(args)\n end", "def xml_nodes_match_attrs(xml_nodes, attrs, mismatches = [])\n attrs.each_with_index.each { |attr_set, idx|\n xn = xml_nodes[idx]\n attr_set.each { |(attr_key, attr_val)|\n # Either call method, or hash key, or recurse on children\n # p.name vs. p[:name]\n if :children == attr_key\n # recurse over children\n xml_nodes_match_attrs(xn.children, attr_val, mismatches)\n else\n # compare attrs\n xn_val = xn.methods.include?(attr_key) ? xn.send(attr_key) : xn[attr_key]\n if xn_val != attr_val\n mismatches << { node: xn.name_and_class_path, attr: \"#{ attr_key }: expected #{ attr_val.inspect }, got #{ xn_val.inspect }\" }\n end\n end\n }\n }\n mismatches\n end", "def matches_state_attrs?\n @expected_attrs == state_attrs\n end", "def equal_list(expected)\n message = \"#{Helpers.inspect_records(@object)} has the same records as #{Helpers.inspect_records(expected)}\"\n \n left = @object.map(&:id)\n right = expected.map(&:id)\n \n test_case.assert(left != right, message)\n end", "def eql?(other)\n return false unless super(other)\n return false unless attributes == other.attributes\n return false unless content == other.content\n\n true\n end", "def ==(other)\n return true if other.equal?(self)\n return false unless other.instance_of?(self.class)\n\n self.class.attributes.inject(true) do |memo, attribute|\n attribute_name = attribute.first\n attribute_type = attribute.last[:type]\n\n # Skip associations\n if attribute_type.include?(LazyResource::Resource) || (attribute_type.is_a?(::Array) && attribute_type.first.include?(LazyResource::Resource))\n memo\n else\n memo && self.send(:\"#{attribute_name}\") == other.send(:\"#{attribute_name}\")\n end\n end\n end", "def matches? item, attributes\n\n attributes.map { |attribute, value|\n\n item.send(attribute) == value\n\n }.flatten == [true]\n\n end", "def ==( other ) \n\t\t\tcomparison_attributes = lambda{ |area| [ area.area_desc, area.altitude, area.ceiling, area.circles, area.geocodes, area.polygons ]}\n\t\t\tcomparison_attributes.call( self ) == comparison_attributes.call( other )\n\t\tend", "def all_obs_same_attr?(observations, attr)\n exemplar = observations.first.send(attr)\n observations.all? { |o| o.send(attr) == exemplar }\n end", "def eql?(*) end", "def eql?(other)\n return true if equal?(other)\n return false unless self == other\n [:id, :fide_id, :rating, :fide_rating, :title, :gender].each do |m|\n return false if self.send(m) && other.send(m) && self.send(m) != other.send(m)\n end\n true\n end", "def match\n @matches = attributes_enumerator.map do |(type, value), index|\n attribute_name = self.class.names[index]\n attributes.store(\n attribute_name, type.match(value, context: @context.dup)\n )\n end\n return if (failures = @matches.select(&:invalid?)).empty?\n failures.unshift(failure).reduce(:merge!)\n end", "def ==(val)\n if val.is_a?(Model)\n # Use normal comparison for a model\n super\n else\n # Compare to attributes otherwise\n attributes == val\n end\n end", "def ==(o)\n return true if self.equal?(o)\n self.class == o.class &&\n attribute == o.attribute &&\n statistics == o.statistics &&\n other == o.other &&\n total == o.total &&\n missing == o.missing &&\n term_count == o.term_count &&\n term_type == o.term_type &&\n terms == o.terms\n end", "def ==(*several_variants)\n #This is a stub, used for indexing\n end", "def is_equal?(a)\n @amount == a.amount && @code == a.code\n end", "def equal_list(expected)\n message = \"#{Helpers.inspect_records(@object)} does not have the same records as #{Helpers.inspect_records(expected)}\"\n \n left = @object.map(&:id)\n right = expected.map(&:id)\n \n test_case.assert(left == right, message)\n end", "def comparison_attributes\n except_list = ['id', 'updated_at', 'created_at', 'verified_at']\n except_list << 'alternative_phone' unless Spree::Config[:alternative_shipping_phone]\n except_list << 'company' unless Spree::Config[:company]\n\n a = attributes.except(*except_list)\n a.each{|k, v|\n if v.is_a?(String)\n v = v.downcase.strip.gsub(/\\s+/, ' ')\n a[k] = v.present? ? v : nil\n end\n }\n a['state_name'] = nil if a['state_name'].blank?\n a\n end", "def multi_element_attr_match( elements )\n elements.each do |element|\n print \".\"\n wait_for_element(element[0].to_sym, element[1])\n check_attribute_match(element[0].to_sym, element[1], element[2], element[3])\n end\n end", "def xml_should_eql(actual, expected)\n same = xml_cmp(actual, expected)\n actual.should.== expected unless same \nend", "def test_equality_simple\n value1_ = ::Versionomy.create(:major => 2, :minor => 0, :release_type => :alpha, :alpha_version => 5)\n value2_ = ::Versionomy.create(:major => 2, :release_type => :alpha, :alpha_version => 5)\n assert_equal(value2_, value1_)\n assert_equal(value2_.hash, value1_.hash)\n end", "def ==(other)\n other.is_a?(self.class) &&\n name == other.name &&\n attributes == other.attributes\n end", "def changes(attrs1, attrs2)\n old_attrs = attrs1.slice(*GENERATED_ATTRS)\n new_attrs = attrs2.slice(*GENERATED_ATTRS)\n\n return if old_attrs == new_attrs\n old_attrs.each do |k, v|\n next if new_attrs[k] == v\n @changes << Change.new(nil, k, v, new_attrs[k]) \n end\n end", "def tdiff_equal(node)\n if (self.class == node.class)\n case node\n when Nokogiri::XML::Attr\n (self.name == node.name && self.value == node.value)\n when Nokogiri::XML::Element, Nokogiri::XML::DTD\n self.name == node.name\n when Nokogiri::XML::Text, Nokogiri::XML::Comment\n self.text == node.text\n when Nokogiri::XML::ProcessingInstruction\n (self.name == node.name && self.content = self.content)\n else\n false\n end\n else\n false\n end\n end", "def ==(other)\n name == other.name &&\n color == other.color &&\n age == other.age\n end", "def more_desirable?(attribute_id1, attribute_id2)\n attribute_id1 < attribute_id2\n end", "def isSame(tab)\n for x in 0..3\n for y in 0..3\n return(false) if (self.val(x,y) != tab.val(x,y)) ;\n end\n end\n return true ;\n end", "def ==(other)\n # If the classes don't match, they cannot possibly be equal.\n if self.class != other.class\n return false\n end\n\n # If the persisted state doesn't match, they also can never be equal.\n if persisted? != other.persisted?\n return false\n end\n\n # When persisted, check the other's id to see if it's the same,\n # cannot possible be equals if they have different ids.\n if persisted? && id != other.id\n return false\n end\n\n # Finally, compare the attributes hash. If all key/values match,\n # they are considered equal.\n attributes == other.attributes\n end", "def ==(other)\n self.class == other.class &&\n attributes[\"_id\"] == other.attributes[\"_id\"]\n end", "def assert_same_values(expected, actual)\n actual.each_pair do |k,v|\n next unless expected[k]\n assert_equal expected[k], v, \"Values for #{k} are not matching\"\n end\n end", "def assert_equivalent_xml(expected, actual)\n expected_xml = Nokogiri::XML(\"<test-xml>\\n#{expected}\\n</test-xml>\")\n actual_xml = Nokogiri::XML(\"<test-xml>\\n#{actual}\\n</test-xml>\")\n ignored_attributes = %w(style data-disable-with)\n\n equivalent = EquivalentXml.equivalent?(expected_xml, actual_xml, {\n ignore_attr_values: ignored_attributes\n }) do |a, b, result|\n if result === false && b.is_a?(Nokogiri::XML::Element)\n if b.attr('name') == 'utf8'\n # Handle wrapped utf8 hidden field for Rails 4.2+\n result = EquivalentXml.equivalent?(a.child, b)\n end\n if b.delete('data-disable-with')\n # Remove data-disable-with for Rails 5+\n # Workaround because ignoring in EquivalentXml doesn't work\n result = EquivalentXml.equivalent?(a, b)\n end\n if a.attr('type') == 'datetime' && b.attr('type') == 'datetime-local'\n a.delete('type')\n b.delete('type')\n # Handle new datetime type for Rails 5+\n result = EquivalentXml.equivalent?(a, b)\n end\n end\n result\n end\n\n assert equivalent, lambda {\n # using a lambda because diffing is expensive\n Diffy::Diff.new(\n sort_attributes(expected_xml.root),\n sort_attributes(actual_xml.root)\n ).to_s(:color)\n }\n end", "def sync_duplicate_obj_attributes(obj1, obj2)\n duplicate_keys.each do |key|\n unless obj1[key].blank? && obj2[key].blank?\n if obj1[key].blank?\n obj1.send(\"#{key}=\", obj2[key])\n elsif obj2[key].blank?\n obj2.send(\"#{key}=\", obj1[key])\n else # Each obj has a value\n if obj1[key] != obj2[key]\n raise ArgumentError, \"#{key} attribute values on the two objects don't match: #{obj1[key]} vs #{obj2[key]}\"\n end\n end\n end\n end\n end", "def eql?(other)\n return true if equal?(other)\n\n # two instances for different models cannot be equivalent\n return false unless other.kind_of?(model)\n\n # two instances with different keys cannot be equivalent\n return false if key != other.key\n\n # neither object has changed since loaded, so they are equivalent\n return true if repository == other.repository && !dirty? && !other.dirty?\n\n # get all the loaded and non-loaded properties that are not keys,\n # since the key comparison was performed earlier\n loaded, not_loaded = properties.select { |p| !p.key? }.partition do |property|\n attribute_loaded?(property.name) && other.attribute_loaded?(property.name)\n end\n\n # check all loaded properties, and then all unloaded properties\n (loaded + not_loaded).all? { |p| p.get(self) == p.get(other) }\n end", "def assert_event_are_light_equal e1, e2\n return false if e1.class != e2.class\n\n [:subject, :event, :moodid,\n :mood, :music, :location, :taglist, :pickeyword,\n :preformatted, :backdated, :comments, :security, :allowmask,\n :screening,].each do |attr|\n return false if e1.send(attr) != e2.send(attr)\n end\n\n e1.compare_time(e2)\n end", "def eql(expected)\n set_relativity(:eql, expected)\n end", "def modified?( original )\n DATA_ATTRIBUTES.any? { |e| send( e ) != original.send( e )}\n end", "def ==(other)\n @name == other.name && @amount == other.amount\n end", "def ==(other)\n other.kind_of?(self.class) &&\n @name == other.name && @columns == other.columns && @unique == other.unique?\n end", "def match_same_name_attributes(*options)\n\n options = options.extract_options!\n same_name_attributes = @from_table.columns.map(&:name) & @to_table.columns.map(&:name)\n\n if same_name_attributes\n same_name_attributes = columns_from_options(same_name_attributes, options)\n same_name_attributes.each do |same_name_attribute|\n from same_name_attribute, :to => same_name_attribute\n end\n end\n end", "def equal_pair(key, request)\n if @event[\"required\"][key] == request[\"object_attributes\"][key] || event[\"required\"][key] == \"\"\n true\n else\n false\n end\n end", "def assert_equal(att, value, error = [att, :not_equal])\n assert value === send(att), error\n end", "def validate\n matched = {}\n duplicated_attributes = []\n attributes.each do |attribute|\n if matched.has_key?(attribute.name) && matched[attribute.name] == attribute.name_format\n duplicated_attributes << attribute.name unless duplicated_attributes.include?(attribute.name)\n else\n matched[attribute.name] = attribute.name_format\n end\n end\n if !duplicated_attributes.empty?\n raise ValidationError, \"An attribute with the same name and name format may only be specified once. The following attributes were specified multiple times: #{duplicated_attributes.join(',')}\"\n end\n end" ]
[ "0.7291717", "0.7188103", "0.70395297", "0.7007927", "0.68874705", "0.6861532", "0.6707156", "0.6660597", "0.66147524", "0.658478", "0.6584619", "0.6580019", "0.65543133", "0.6543933", "0.65068495", "0.6479513", "0.6456241", "0.6415999", "0.6412208", "0.6412208", "0.6412208", "0.6411266", "0.6380575", "0.63775986", "0.6260147", "0.6246534", "0.6240681", "0.62150854", "0.62014365", "0.6186426", "0.61837834", "0.6164858", "0.61304426", "0.61149454", "0.6097789", "0.6083095", "0.6078927", "0.6067201", "0.60053444", "0.59974694", "0.5994989", "0.5991373", "0.59856457", "0.5985243", "0.5977118", "0.59521115", "0.59428704", "0.59311265", "0.59247756", "0.5921222", "0.5921222", "0.59095234", "0.58795947", "0.58789194", "0.5870439", "0.58598673", "0.58571184", "0.5856412", "0.5855177", "0.58480394", "0.5847516", "0.58370507", "0.5799985", "0.5795313", "0.57880926", "0.57823527", "0.57788265", "0.5776185", "0.57670164", "0.5759791", "0.5758563", "0.5753949", "0.57518554", "0.5750137", "0.57385117", "0.57309806", "0.5729126", "0.572618", "0.57250285", "0.57210624", "0.5712646", "0.5710082", "0.57059866", "0.57036847", "0.5702592", "0.5690256", "0.5674193", "0.56433815", "0.5641553", "0.56216776", "0.56148046", "0.5591313", "0.5587681", "0.55836356", "0.5569298", "0.5550885", "0.5546161", "0.5545665", "0.55422115", "0.5539372", "0.5529004" ]
0.0
-1
Calculates hash code according to all attributes.
def hash [_self, _links, _schema, _revision, _system_owned, display_name, description, tags, _create_user, _protection, _create_time, _last_modified_time, _last_modified_user, id, resource_type, path, parent_path, unique_id, relative_path, children, overridden, marked_for_delete, tcp_closed, tcp_opening, udp_single, tcp_finwait, tcp_first_packet, tcp_closing, tcp_established, udp_multiple, icmp_error_reply, udp_first_packet, icmp_first_packet].hash end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def attr_hash\n Digest::MD5.hexdigest(\"#{@name}:#{@ruby_type}\")\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\n code = 17\n code = 37*code + @x.hash\n code = 37*code + @y.hash\n # Add lines like this for each significant instance variable\n code # Return the resulting code\n end", "def hash(*) end", "def hash\n code = 17\n code = 37 * code\n self.instance_variables.each do |v|\n code += self.instance_variable_get(v).hash\n end\n code\n end", "def hash_code; 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 hash() #:nodoc:\n prime = 31;\n result = 1;\n result = prime * result + @amount.to_i\n result = prime * result + @new_balance.to_i\n result = prime * result + (@date.nil? ? 0 : Bankjob.date_time_to_ofx(@date).hash);\n result = prime * result + (@raw_description.nil? ? 0 : @raw_description.hash);\n result = prime * result + (@type.nil? ? 0 : @type.hash);\n # don't use value date\n return result;\n end", "def hash\n prime = 31\n result = 1\n result = result * prime + (@decision_target == nil ? 0 : @decision_target.hash)\n result = prime * result + (@string_id == nil ? 0 : @string_id.hash)\n result\n end", "def hash\n @hash ||= begin\n result = 17\n result = 31 * result + self.class.hash\n result = 31 * result + ord\n result.is_a?(Fixnum) ? result : result.hash\n end\n end", "def hash\n @hash ||= begin\n result = 17\n result = 31 * result + self.class.hash\n result = 31 * result + ord\n result.is_a?(Fixnum) ? result : result.hash\n end\n end", "def hash; map{|el| \"#{el.name} @ #{el.hash}\"}; map(&:hash).reduce(:+) % 2**32; end", "def hash\r\n a = 0\r\n @id.each_byte {|c| a += c.to_i}\r\n (a + @paired.to_i) * HASH_PRIME\r\n end", "def hash\n raw = [name, type, values.join('/')].join(' ')\n Digest::MD5.hexdigest(raw)\n end", "def hash\n size.hash ^ rank.hash\n end", "def hash\n \"#{self.class.name}-#{self.id}-#{@__metadata__.cas}-#{@__attributes__.hash}\".hash\n end", "def hash\n @hash || calculate_hash!\n end", "def hash\n return name.hash ^ direction.hash ^ lhs.hash ^ rhs.hash\n end", "def hash\n value = 0\n my_rows = @rows\n r_size = my_rows.size\n for i in 0..r_size-1 do\n a_row = my_rows[i]\n a_size = a_row.size\n for j in 0..a_size-1 do\n value ^= a_row[j].hash\n end\n end\n return value\n end", "def hash\n id.hash + 32 * bs_request.hash\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 hash\n type.hash ^ (id.hash >> 1)\n end", "def hash\n [self.class, self.val, self.attribute].hash\n end", "def hash\n 0\n end", "def hash # :nodoc:\n identifier.hash ^ requirement.hash\n end", "def hash\n self.class.hash ^ key_attributes.hash\n end", "def hash\n return super unless has_size?\n\n res = 0\n each do |el|\n res += el.hash\n end\n return res\n end", "def hash\n h = @e.nil? ? 0 : @e\n h = (h << 1) ^ @r.hash\n h = (h << 1) ^ @v.hash\n end", "def hash() source.hash ^ (target.hash+1); end", "def hash() source.hash ^ (target.hash+1); end", "def hash\n\t\t\"#{@x}#{@y}\".hash\n\tend", "def hash #:nodoc:\n __getobj__.hash ^ self.class.hash\n end", "def hash\n Zlib.crc32(to_a.map(&:to_s).sort.to_s)\n end", "def hash_code\n prime = 31\n result = 1\n result = prime * result + x\n result = prime * result + y\n return result;\n end", "def hash\n self.class.hash ^ operand.hash\n end", "def hash!\n\t\t@@email.downcase!\n\t\thash = Digest::MD5.hexdigest(@@email)\n\t\treturn hash\n\tend", "def hash\n [anchor, cv, nullifier, proof, rk, spend_auth_sig].hash\n end", "def hash\n ([self.class] + self.class.comparison_attrs.map{|x| send(x)}).hash\n end", "def hash\n @symbols.hash + 37*positive?.hash\n end", "def calculate_unique_hash\n unique = ''\n unique += self.content if self.content.present?\n unique += self.summary if self.summary.present?\n unique += self.title if self.title.present?\n self.unique_hash = Digest::MD5.hexdigest unique\n end", "def hash()\n #This is a stub, used for indexing\n end", "def hash\n # Memoizing such a simple hash value seems silly, however the\n # profiler showed the Card#hash method as having 22% of the runtime. My\n # memoizing the hash value that was reduced to 12%.\n return @hash unless @hash.nil?\n @hash = @value.hash ^ @suit.hash\n end", "def hash=(_arg0); end", "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 hash\n num = 0\n self.each do |k,v|\n if k.is_a?(Integer) && v.is_a?(Integer)\n num += k * 26 + v\n elsif k.is_a?(Integer) && !v.is_a?(Integer)\n num += k * 26 + ALPHA_NUMBERS[v.to_s.downcase]\n elsif v.is_a?(Integer) && !k.is_a?(Integer)\n num += v * 26 + ALPHA_NUMBERS[k.to_s.downcase]\n elsif !k.nil? && !v.nil?\n num += ALPHA_NUMBERS[k.to_s.downcase] * ALPHA_NUMBERS[v.to_s.downcase]\n end\n end\n num\n end", "def hash\r\n\t\treturn @name.hash() + @type.hash()\r\n\tend", "def hash\n return @hash_code if defined? @hash_code\n @hash_code = usual_equal_object.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 hash; end", "def hash; end", "def hash; end", "def hash\n [oct, pc].hash\n end", "def hash\n excl = @excl ? 1 : 0\n hash = excl\n hash ^= @begin.hash << 1\n hash ^= @end.hash << 9\n hash ^= excl << 24;\n # Are we throwing away too much here for a good hash value distribution?\n return hash & Fixnum::MAX\n end", "def hash\n code.hash\n end", "def hash # :nodoc:\n name.hash ^ type.hash ^ requirement.hash\n end", "def hash\n @vbits.hash\n end", "def hash\n Digest::SHA256.hexdigest( \"#{nonce}#{time}#{difficulty}#{prev}#{data}\" )\n end", "def hash\n if @sha512hash != nil\n return @sha512hash.to_i(16)\n else\n super\n end\n end", "def calc_hash(pass)\n salt_cost = SCrypt::Engine.autodetect_cost(self[:salt])\n SCrypt::Engine.scrypt(pass, self[:salt], salt_cost, 32).unpack('H*').first\n end", "def hash\n [lac, cid, radio, mcc, mnc, signal, psc, asu, ta].hash\n end", "def calculate_checksum\n last_checksum = previous_event&.checksum\n attrs = attributes.except(\"checksum\", \"id\", \"updated_at\").merge(last_checksum: last_checksum)\n cs = Digest::SHA256.hexdigest(attrs.to_s)\n puts \"#{id} calculate_checksum: #{cs} <- #{attrs} \" if Rails.env.development?\n Rails.logger.info(\"#{id} calculate_checksum: #{cs} <- #{attrs} \")\n return cs\n end", "def hash\n code.hash\n end", "def hash\n\t\t[@a, @b, self.class::D].hash\n\tend", "def consistent_hash\n Zlib.crc32(self.to_yaml, 0)\n end", "def hash\n @hash[:perm_type].hash ^\n @hash[:perms].hash ^\n @hash[:inheritance].hash ^\n @hash[:target].hash\n end", "def hash( *strs )\n return Digest::MD5.hexdigest( strs.join )\n end", "def hash\n @rank.hash ^ @suit.hash\n end", "def hash\n return Digest::MD5.hexdigest(self.describe(' '))\n end", "def hash\n @real.hash ^ @image.hash\n end", "def to_hash() end", "def hash_length\n super\n end", "def hash_hash(h)\n require 'digest/md5'\n Digest::MD5.hexdigest(Marshal::dump(h.sort))\n end", "def hash() source.hash ^ target.hash; end", "def hash\n [first_name, last_name, address_one, address_two, city, state, zip, phone, email, country_code].hash\n end", "def calculate_hash(input, prep_hashes)\n result = 0\n input.unpack('U*').each do |x|\n result += prep_hashes.hash(x)\n end\n (result % MOD_VALUE).to_s(HEX)\nend", "def c_hash\n sha256 = Digest::SHA256.new\n token = @code.token.token\n hashed_token = sha256.digest(token)\n first_half = hashed_token[0...hashed_token.length / 2]\n Base64.urlsafe_encode64(first_half).tr('=', '')\n end", "def hash(block)\n Digest::SHA256.hexdigest(block.to_s.encode)\n end", "def calculate_hash\n\t\toptions = {:firstname => firstname, :email => email, :phone => phone, :txnid => txnid, :surl => surl, :furl => furl, :productinfo => productinfo, :amount => amount}\n\t\tservice = PayuIndia::Helper.new(payment_gateway_key, payment_gateway_salt, options)\n\t\tself.hast = service.generate_checksum\n\tend", "def hash\n [rank, suit].hash\n end", "def hash\n self.class.hash ^ left.hash ^ right.hash\n end", "def generate_hash(*args)\n Digest::SHA3.hexdigest(args.join(''))\n end", "def hash_code\n hash_code = {}\n self.seq.each do |letter|\n hash_code.keys.include?(letter) ? hash_code[letter] += 1 : hash_code[letter] = 1\n end\n hash_code\n end", "def hashify_attributes(attrs)\n Hash.new.tap{ |h| attrs.each{|a| h[a] = self.send(a)} }\n end", "def hash\n\n self.h.fei.hash\n end", "def hash\n shasum.hash\n end", "def hash\n shasum.hash\n end", "def hash\n shasum.hash\n end", "def hash\n attributes.hash\n end", "def hash\n attributes.hash\n end" ]
[ "0.7118691", "0.70400536", "0.70400536", "0.70400536", "0.70400536", "0.70400536", "0.70400536", "0.70400536", "0.68960655", "0.67847186", "0.6707762", "0.670052", "0.6688737", "0.66705376", "0.6489735", "0.6462376", "0.6462376", "0.64444333", "0.6413127", "0.6395483", "0.63898623", "0.6372129", "0.635671", "0.63370055", "0.62682766", "0.62533766", "0.6246914", "0.6230963", "0.62173444", "0.6214272", "0.6214131", "0.61962456", "0.619165", "0.61866295", "0.6185355", "0.6185355", "0.6153702", "0.6145376", "0.6144877", "0.6139152", "0.6128312", "0.61224943", "0.61217207", "0.61205214", "0.61041045", "0.61000645", "0.60937095", "0.60931146", "0.60818595", "0.60811466", "0.60500103", "0.60322344", "0.6022704", "0.6020012", "0.6020012", "0.6020012", "0.6020012", "0.6020012", "0.6020012", "0.6020012", "0.6020012", "0.6020012", "0.6020012", "0.60178953", "0.6014942", "0.5997442", "0.59880185", "0.598736", "0.59799886", "0.5972682", "0.5969595", "0.5969411", "0.59594935", "0.5957466", "0.59423596", "0.5942144", "0.59245354", "0.5924357", "0.5904946", "0.59025365", "0.58536685", "0.5847055", "0.58454466", "0.5845053", "0.58447546", "0.5844059", "0.5842638", "0.5840575", "0.58391696", "0.5825819", "0.5824118", "0.5823615", "0.58184344", "0.5815284", "0.58124787", "0.5810309", "0.5808056", "0.5808056", "0.5808056", "0.5806852", "0.5806852" ]
0.0
-1
Builds the object from hash
def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def build(hash)\n obj = new\n hash.each_pair do |k,v|\n obj[k] = v if variables[k]\n end\n return obj\n end", "def build_from_hash(attributes)\n\n end", "def build_from_hash(hash)\n instance = self.new\n\n # Add the instance attributes dynamically from the hash. If the attribute\n # does not already exist, then don't re-add the attribute class and\n # variable, just set it with the value from the hash\n hash.keys.each do |key|\n class_eval { attr_accessor key } unless instance.methods.include?(key.to_sym)\n instance.instance_variable_set \"@#{key}\", hash[key]\n end\n\n instance\n end", "def build(hash, track_changes = true)\n resource = fields.each_with_object(new) do |field, r|\n value = hash.fetch(field.to_s, hash[field.to_sym])\n r.send(\"#{field}=\", value)\n end\n resource.clear_changes! unless track_changes\n resource\n end", "def initialize hash\n @hash = hash\n end", "def build(params)\n return new(params) if params.is_a?(Hash)\n raise(\"unexpected parameter, expected Hash, received #{params.class}\")\n end", "def initialize( hash )\n\t\t\t@hash = hash.dup\n\t\t\t@dirty = false\n\t\tend", "def initialize(a_hash)\n from_h(a_hash)\n end", "def initialize\n\t\t\t@hash = {}\n\t\tend", "def initialize(hash)\n @hash = hash\n @converted = {}\n end", "def initialize(hash)\n @short_code = hash[\"short_code\"]\n @name = hash[\"name\"]\n @id = hash[\"id\"]\n end", "def initialize(hash)\n super(hash)\n end", "def initialize\n @h = new_hash\n end", "def new_from_hash(hash)\n if hash == nil\n self.class.new.assign(self)\n else\n hash_obj = hash\n if hash.instance_of?(Hash)\n hash_obj = self.class.new\n merge_hash_into_object(hash, hash_obj)\n end\n instance = self.class.new\n object_assign(instance, hash_obj)\n end\n end", "def initialize(hash={})\n @hash = hash\n end", "def initialize\n @hash = {}\n end", "def initialize\n @hash = {}\n end", "def initialize(hash)\r\n hash.each { |k, v|\r\n # Create getters and setters\r\n self.class.attr_accessor(k)\r\n # Set value for created variable\r\n self.send(\"#{k}=\", v)\r\n }\r\n self.class.all.push(self)\r\n end", "def build!(hash)\n hash.must(::Hash) { raise ArgumentError, \"#{self} expects Hash, but got #{hash.class}\" }\n\n if hash.size != variables.size\n keys1 = variables.keys\n keys2 = hash.keys.map(&:to_s)\n minus = (keys1 - keys2).map{|i| \"-#{i}\"}\n plus = (keys2 - keys1).map{|i| \"+#{i}\"}\n \n msg = \"#{self} expects #{variables.size}, but got #{hash.size} (%s)\" % (minus + plus).join(\",\")\n raise Typed::SizeMismatch, msg\n end\n\n # 'build' just ignore unknown fields, but 'build!' raise errors\n obj = new\n hash.each_pair do |k,v|\n obj[k] = v\n end\n return obj\n end", "def initialize(hash)\n @cw_id = hash[\"cw_id\"]\n @cik = hash[\"cik\"]\n @name = hash[\"company_name\"]\n @irs_number = hash[\"irs_number\"]\n @sic_code = hash[\"sic_code\"]\n @industry = hash[\"industry_name\"]\n @sic_sector = hash[\"sic_sector\"]\n @sector_name = hash[\"sector_name\"]\n @source_type = hash[\"source_type\"]\n @address = hash[\"raw_address\"]\n @country = hash[\"country_code\"]\n @state = hash[\"subdiv_code\"]\n @top_parent_id = hash[\"top_parent_id\"]\n @num_parents = hash[\"num_parents\"]\n @num_children = hash[\"num_children\"]\n @max_year = hash[\"max_year\"]\n @min_year = hash[\"min_year\"]\n end", "def from_hash(hash)\n instance = allocate\n instance.instance_variable_set :@attributes, hash.freeze\n instance\n end", "def from_hash(hash)\n hash = DEFAULTS.merge(hash)\n hash['spdx_id'] = hash.delete('spdx-id')\n ordered_array = hash.values_at(*members.map(&:to_s))\n new(*ordered_array)\n end", "def initialize(hash=nil)\n @table = HashWithIndifferentAccess.new\n\n for k,v in hash\n @table[k] = v\n new_ostruct_member(k)\n end if hash\n end", "def from_hash(hash)\n hash.each_pair do |key, value|\n\n # We need to catch hashes representing child objects\n # If the hash key:value is a of a Hash/BSON:Ordered hash\n if hash[key].class == Hash || hash[key].class == BSON::OrderedHash\n # If we have a classname we know we need to return to an object\n if hash[key][\"@classname\"]\n self.instance_variable_set(key, ::Object::full_const_get(hash[key][\"@classname\"]).new(hash[key])) unless key.to_s.start_with?(\"_\")\n else\n self.instance_variable_set(key, value) unless key.to_s.start_with?(\"_\")\n end\n else\n self.instance_variable_set(key, value) unless key.to_s.start_with?(\"_\")\n end\n end\n end", "def from_hash(hash)\n hash.each_pair do |key, value|\n\n # We need to catch hashes representing child objects\n # If the hash key:value is a of a Hash/BSON:Ordered hash\n if hash[key].class == Hash || hash[key].class == BSON::OrderedHash\n # If we have a classname we know we need to return to an object\n if hash[key][\"@classname\"]\n self.instance_variable_set(key, ::Object::full_const_get(hash[key][\"@classname\"]).new(hash[key])) unless key.to_s.start_with?(\"_\")\n else\n self.instance_variable_set(key, value) unless key.to_s.start_with?(\"_\")\n end\n else\n self.instance_variable_set(key, value) unless key.to_s.start_with?(\"_\")\n end\n end\n end", "def initialize(hash)\n @hash = hash\n @data = resourcify_data\n end", "def from_hash hash\n @id= hash['id']\n\n @admin= hash['admin']\n @username= hash['username']\n @timezone= hash['timezone']\n @email_address= hash['email_address']\n\n @password = nil\n\n @created_at= DateTime.parse(hash['created_at'])\n @updated_at= DateTime.parse(hash['updated_at'])\n end", "def hash_to_obj hash\n OpenStruct.new(hash) rescue raise ConfigError, \"Can't convert setup to object\"\n end", "def initialize(hash)\n load_hash(hash)\n end", "def from_hash( h)\n\t\th.each { |name,attributes|\n\t\t\tklass = Klass.new\n\t\t\tklass.from_hash( { name => attributes } )\n\t\t\tself.add_class( klass)\n\t\t}\n\n\t\t# this is an experiment in handling \"through\" attributes\n\t\t# i.e. enriching the model with the join classes\n\tend", "def initialize(*args)\n super\n # hash = {}\n end", "def build_object(resp)\n return resp unless resp.respond_to?(:merge)\n @build_object ||= final_object_class.new(resp.merge(additional_hash_to_serialize_after_response))\n end", "def from_hash(hash)\n ordered_array = hash.values_at(*members.map(&:to_s))\n new(*ordered_array)\n end", "def __convert hash #:nodoc:\n instance = self.class.new\n hash.each do |k, v|\n k = k.to_s if !k.respond_to?(:to_sym) && k.respond_to?(:to_s)\n instance.new_ostruct_member k\n if v.is_a?(Hash)\n v = v[\"type\"] == \"hash\" ? v[\"contents\"] : __convert(v)\n elsif v.is_a?(Array)\n v = v.map{|e| e.instance_of?(Hash) ? __convert(e) : e}\n end\n instance.send \"#{k}=\".to_sym, v\n end\n instance\n end", "def initialize(hash)\n\t\t@id = hash['id']\n\t\t@first_name = hash['first_name']\n\t\t@last_name = hash['last_name']\n\t\t@mentor = hash['mentor']\n\tend", "def initialize(hash={})\n @name = validate_name(hash[:name])\n @description = hash[:description]\n @snmp_opts = hash[:snmp_opts]\n\n save # Save a copy of self to Redis on creation\n end", "def initialize\n @hash_dict = {}\n end", "def initialize(hash=nil)\n @attributes = hash\n @attributes ||= {}\n end", "def initialize(hash={})\n self.init_attrs_from_hash(hash)\n end", "def from_hash(hash)\n apply_nested_hash(hash)\n end", "def initialize(hash)\n # @id = hash[\"id\"]\n # @street_address = hash[\"street_address\"]\n # @city = hash[\"city\"]\n # @state = hash[\"state\"]\n # @zipcode = hash[\"zipcode\"]\n # @country = hash[\"country\"]\n\n #add in correct details\n end", "def from_hash(hash)\n @data_object.user_acc_name = hash['user_acc_name']\n @data_object.user_affiliate = hash['user_affiliate']\n @user_over_13 = hash['user_over_13']\n\n contact.from_hash(hash)\n end", "def initialize(hash)\n @name = hash[\"campaign\"] #decided to change it to \"name\" since this is the campaign class\n date_elements = hash[\"date\"].split(\"/\") #date is being passed in as a string, need this array to create the Date object in the next line\n @date = Date.new(date_elements[2].to_i + 2000, date_elements[0].to_i, date_elements[1].to_i) #added 2000 to year since the program was considering it as the year 15; this creates the date object\n @spend = hash[\"spend\"].to_f #use .to_f to make sure spend comes in as a float instead of a string\n @impressions = hash[\"impressions\"].to_i #need it as an integer for counting purposes later\n @actions = JSON.parse(hash[\"actions\"])#ensures that each action comes in as an array instead of a string\n @@all << self #shovels it into the all array\n end", "def initialize(hash)\n hash.each do |k, v|\n self.send(\"#{k}=\", v) if self.respond_to?(\"#{k}=\")\n end\n @id = hash[\"id\"]\n end", "def initialize (hash)\n hash.each {|key, value|\n self.class.attr_accessor(key)\n self.send((\"#{key}=\"), value)\n }\n @@all << self\n end", "def initialize(hash={})\n @data = Hash.new\n hash.each do |key, value|\n self[key] = value\n end\n end", "def create_from_hash(hash, opts={})\n create_opts = update_or_create_options(hash, opts)\n create { |instance| instance.set(create_opts) }\n end", "def initialize(hash={})\n # assign the attributes here (???)\n hash.each do |k, v| # name = id, name, etc.\n self.send(\"#{k}=\", v)\n # self.k = v # there's no '.k' method\n #binding.pry\n end\n end", "def initialize(hash) #.new\n @name = hash[:name][0]\n @region = hash[:region]\n @population = hash[:population]\n @capital = hash[:capital]\n @flag_link = hash[:flag_link]\n @@all << self\n #binding.pry\n end", "def initialize(hash = {})\n super(hash)\n\n @action = extract_value(hash, :action)\n @clientId = extract_value(hash, :clientId)\n @clientIdAlias = extract_value(hash, :clientIdAlias)\n @clientIdAliasUsed = extract_boolean_value(hash, :clientIdAliasUsed)\n @expiresAt = extract_integer_value(hash, :expiresAt)\n @subject = extract_value(hash, :subject)\n @scopes = extract_value(hash, :scopes)\n @existent = extract_boolean_value(hash, :existent)\n @usable = extract_boolean_value(hash, :usable)\n @sufficient = extract_boolean_value(hash, :sufficient)\n @refreshable = extract_boolean_value(hash, :refreshable)\n @responseContent = extract_value(hash, :responseContent)\n @properties = extract_array_value(hash, :scopes) do |element|\n Authlete::Model::Property.parse(element)\n end\n end", "def initialize( hash )\n\t\t@object_classes = self.parse_objectclasses( hash['objectClasses'] || [] )\n\t\t@attribute_types = self.parse_attribute_types( hash['attributeTypes'] || [] )\n\t\t@ldap_syntaxes = self.parse_ldap_syntaxes( hash['ldapSyntaxes'] || [] )\n\t\t@matching_rules = self.parse_matching_rules( hash['matchingRules'] || [] )\n\t\t@matching_rule_uses = self.parse_matching_rule_uses( hash['matchingRuleUse'] || [] )\n\tend", "def from_hash(hash)\n super(hash)\n verify\n end", "def objects_from_serialized_hash(hash) # :nodoc:\n klass, attributes = Helpers.to_class_and_attributes(hash)\n klass.from_seedable_attributes(attributes)\n end", "def initialize (hash)\n @name = hash [:name]\n @color = hash [:color]\n @robots = hash [:robots]\n @moon_count = hash [:moon_count]\n @cats = hash [:cats]\n #@solar_rotation = solar_rotation .....I dont really understand what a solar rotation is.... it's confusing.....\n @distance_from_the_sun = hash [:distance_from_the_sun]\n end", "def initialize(hash = nil)\n @arguments = 0\n return if hash.nil?\n @name = hash['name']\n @arguments = hash['arguments']\n end", "def _from_hash(hsh)\n hsh.each do |k, v|\n v = restore_hash(v)\n v = v.map { |iv| restore_hash(iv) } if v.is_a?(Array)\n send(:\"#{k}=\", v)\n end\n self\n end", "def from_hash(hash)\n struct = SparkleStruct.new\n struct._camel_keys_set(:auto_discovery)\n struct._load(hash)\n struct._camel_keys_set(nil)\n struct\n end", "def from_hash(hash)\n struct = SparkleStruct.new\n struct._camel_keys_set(:auto_discovery)\n struct._load(hash)\n struct._camel_keys_set(nil)\n struct\n end", "def initialize(hash={})\n self.attributes = hash\n end", "def initialize(raw_hash)\n if valid_hash?(raw_hash)\n self.replace(raw_hash)\n @version, @cost, @salt, @checksum = split_hash(self)\n else\n raise Errors::InvalidHash.new(\"invalid hash\")\n end\n end", "def initialize(raw_hash)\n if valid_hash?(raw_hash)\n self.replace(raw_hash)\n @version, @cost, @salt, @checksum = split_hash(self)\n else\n raise Errors::InvalidHash.new(\"invalid hash\")\n end\n end", "def build(base, object, type = nil, selected_fields = nil)\n return object unless object.is_a?(Hash)\n if _loading?\n Factory.from_db(klass, object, nil, selected_fields)\n else\n Factory.build(klass, object)\n end\n end", "def initialize(hash)\n super(hash)\n @size = hash[\"size\"]\n end", "def initialize(raw_hash)\n if valid_hash?(raw_hash)\n self.replace(raw_hash)\n @cost, @salt, @digest = split_hash(self.to_s)\n else\n raise Errors::InvalidHash.new(\"invalid hash\")\n end\n end", "def instantiate hash, extra_attributes={}\n return hash unless hash.kind_of? Hash\n# init = hash.values_at(*@singulars).compact.first\n init = hash[@singular]\n inits = hash[@plural]\n if init\n new init.merge extra_attributes\n elsif inits\n inits.map {|each| new each.merge extra_attributes}\n else\n hash\n end\n end", "def from_hash(values)\n @data_object.team_challenge = values['team_challenge']\n @data_object.team_level = values['team_level']\n @data_object.team_name = values['team_name']\n\n# @mgr_email = values['mgr_email']\n\n names = values['tm_name']\n\n TeamMember::MEMBERS_PER_TEAM.times do |i|\n if names[i].empty?\n @members[i].clear\n else\n @members[i].tm_name = names[i]\n @members[i].tm_grade = values['tm_grade'][i].to_i\n @members[i].tm_dob_mon = values['tm_dob_mon'][i]\n @members[i].tm_dob_day = values['tm_dob_day'][i]\n @members[i].tm_dob_year = values['tm_dob_year'][i]\n @members[i].tm_sex = values['tm_sex'][i]\n end\n end\n end", "def hash\n { hash: @hash, hashType: @hash_type }\n end", "def initialize(raw_hash)\n raise Errors::InvalidHash, 'invalid hash' unless valid_hash?(raw_hash)\n\n replace(raw_hash)\n\n @cost, @salt, @digest = split_hash(to_s)\n end", "def initialize( confighash={} )\n\t\tihash = internify_keys( untaint_values(confighash) )\n\t\tmergedhash = DEFAULTS.merge( ihash, &HashMergeFunction )\n\n\t\t@struct = ConfigStruct.new( mergedhash )\n\t\t@create_time = Time.now\n\t\t@name = nil\n\t\t@loader = nil\n\n\t\tsuper()\n\tend", "def initialize(*args)\n @hash = HashWithIndifferentAccess.new(*args)\n end", "def create(hash={})\n model = self.new(hash)\n model.save\n model\n end", "def from_hash(hash:, klass:)\n validate_class_kit(klass)\n\n @hash_helper.indifferent!(hash)\n entity = klass.new\n attributes = @attribute_helper.get_attributes(klass)\n attributes.each do |attribute|\n key = attribute[:name]\n type = attribute[:type]\n\n #if the hash value is nil skip it\n next if hash[key].nil?\n\n value = if is_class_kit?(type)\n from_hash(hash: hash[key], klass: type)\n elsif type == Array\n hash[key].map do |array_element|\n if attribute[:collection_type].nil?\n array_element\n else\n if is_class_kit?(attribute[:collection_type])\n from_hash(hash: array_element, klass: attribute[:collection_type])\n else\n @value_helper.parse(type: attribute[:collection_type], value: array_element)\n end\n end\n end\n else\n hash[key]\n end\n\n entity.public_send(:\"#{key}=\", value)\n end\n\n entity\n end", "def from_h(hash, converter = nil)\n instance = new\n\n hash.each do |k, v|\n v = convert(v, k, converter) if converter\n instance.instance_variable_set(:\"@#{k}\", v)\n end\n\n instance\n end", "def initialize(hash_that_represents_json)\n\t\t@data = hash_that_represents_json\n\tend", "def hash_for_merging(hash)\n new_hash = { id: hash['message_id'].to_i,\n date: Time.at(hash['date'].to_i),\n from: User.new(hash['from'], @bot),\n chat: Chat.new(hash['chat'], @bot) }\n\n type = TYPES.find { |t| hash[t.to_s] }\n new_hash[type] = hash[type.to_s] # TODO: fail if type not found\n\n new_hash\n end", "def initialize(hash)\n @header = Msg::Header.new(hash)\n @body = Msg::Body.new(content_is_json?, hash)\n end", "def build_resource(hash = {})\n self.resource = resource_class.new(hash)\n end", "def initialize()\n @hash = {}\n @values = []\n end", "def build\n fail \"Please provide a value for key, currently: #{key}\" if key.nil?\n\n if in_key\n { in_key.to_sym => { key => data } }\n else\n process_data\n transform_to_hash\n end\n end", "def initialize(build)\n @build = build\n @hash = {}\n @already_run = []\n end", "def new_from_hash_marketplace(h)\n self.url = h\n h=h.split('/')\n h=h[h.size-2]\n self.original_id = h\n return self\n end", "def initialize(hash, type, dump)\n self.hash = hash\n self.type = type.to_sym\n self.dump = dump\n end", "def initialize(hash_data, opts: {})\n @hsh = hash_data\n @opts = opts\n\n @title = @hsh[:title]\n @body = @hsh[:body_hash]\n end", "def initialize(hash)\n @color = hash[:color]\n @scent = hash[:scent]\n end", "def initialize(hash = nil)\n hash.each { |key, value| self[key] = value } if !hash.nil? && hash.is_a?(Hash)\n end", "def create(hash)\n NotImplementedError\n end", "def from_h(hash, converter = nil)\n instance = new\n\n hash.each do |k, v|\n v = instance.convert(v, k, converter) if converter\n instance.send(:\"#{k}=\", v)\n end\n\n instance\n end", "def init_jaxb_json_hash(_o)\n super _o\n @id = String.from_json(_o['id']) unless _o['id'].nil?\n @version = String.from_json(_o['version']) unless _o['version'].nil?\n @description = String.from_json(_o['description']) unless _o['description'].nil?\n @url = String.from_json(_o['url']) unless _o['url'].nil?\n @name = String.from_json(_o['name']) unless _o['name'].nil?\n @organization = Org::Apache::Archiva::Metadata::Model::Organization.from_json(_o['organization']) unless _o['organization'].nil?\n @issueManagement = Org::Apache::Archiva::Metadata::Model::IssueManagement.from_json(_o['issueManagement']) unless _o['issueManagement'].nil?\n @scm = Org::Apache::Archiva::Metadata::Model::Scm.from_json(_o['scm']) unless _o['scm'].nil?\n @ciManagement = Org::Apache::Archiva::Metadata::Model::CiManagement.from_json(_o['ciManagement']) unless _o['ciManagement'].nil?\n if !_o['licenses'].nil?\n @licenses = Array.new\n _oa = _o['licenses']\n _oa.each { | _item | @licenses.push Org::Apache::Archiva::Metadata::Model::License.from_json(_item) }\n end\n if !_o['mailingLists'].nil?\n @mailingLists = Array.new\n _oa = _o['mailingLists']\n _oa.each { | _item | @mailingLists.push Org::Apache::Archiva::Metadata::Model::MailingList.from_json(_item) }\n end\n if !_o['dependencies'].nil?\n @dependencies = Array.new\n _oa = _o['dependencies']\n _oa.each { | _item | @dependencies.push Org::Apache::Archiva::Metadata::Model::Dependency.from_json(_item) }\n end\n @incomplete = Boolean.from_json(_o['incomplete']) unless _o['incomplete'].nil?\n end", "def create_version_hash\n new_version = {}\n new_version['created'] = ''\n new_version['message'] = ''\n new_version['user'] = {}\n # user is #name, # address.\n new_version['user']['name'] = ''\n new_version['user']['address'] = ''\n new_version['state'] = {}\n new_version\n end", "def create_from_hash hash\n values = values_from_hash hash\n unless obj = find(:first, :conditions => values)\n return nil if values[:id]\n obj = create!(values)\n raise ArgumentError, \"#{obj.errors.to_s}\" unless obj.errors.empty?\n end\n obj\n end", "def initialize result_hash={}\n @result_hash = result_hash\n end", "def create_hash(&block); end", "def create_hash(&block); end", "def initialize(attrs={})\n from_hash(attrs)\n end", "def build_request_data(hash)\n {\n :attributes! => {\n addressinfo: { \"xsi:type\" => \"ns2:Map\" },\n },\n username: @username,\n password: @password,\n addressinfo: {\n item: [\n { key: 'name', value: hash[:name] },\n { key: 'address1', value: hash[:address1] },\n { key: 'address2', value: hash[:address2] },\n { key: 'city', value: hash[:city] },\n { key: 'state', value: hash[:state] },\n { key: 'zip', value: hash[:zip] },\n { key: 'fflno', value: hash[:fflno] },\n { key: 'fflexp', value: hash[:fflexp] }\n ]\n },\n testing: @testing\n }\n end", "def init_jaxb_json_hash(_o)\n @groupId = String.from_json(_o['groupId']) unless _o['groupId'].nil?\n @artifactId = String.from_json(_o['artifactId']) unless _o['artifactId'].nil?\n @version = String.from_json(_o['version']) unless _o['version'].nil?\n @packaging = String.from_json(_o['packaging']) unless _o['packaging'].nil?\n @className = String.from_json(_o['className']) unless _o['className'].nil?\n if !_o['repositories'].nil?\n @repositories = Array.new\n _oa = _o['repositories']\n _oa.each { | _item | @repositories.push String.from_json(_item) }\n end\n @bundleVersion = String.from_json(_o['bundleVersion']) unless _o['bundleVersion'].nil?\n @bundleSymbolicName = String.from_json(_o['bundleSymbolicName']) unless _o['bundleSymbolicName'].nil?\n @bundleExportPackage = String.from_json(_o['bundleExportPackage']) unless _o['bundleExportPackage'].nil?\n @bundleExportService = String.from_json(_o['bundleExportService']) unless _o['bundleExportService'].nil?\n @classifier = String.from_json(_o['classifier']) unless _o['classifier'].nil?\n @includePomArtifacts = Boolean.from_json(_o['includePomArtifacts']) unless _o['includePomArtifacts'].nil?\n @queryTerms = String.from_json(_o['queryTerms']) unless _o['queryTerms'].nil?\n @bundleImportPackage = String.from_json(_o['bundleImportPackage']) unless _o['bundleImportPackage'].nil?\n @bundleRequireBundle = String.from_json(_o['bundleRequireBundle']) unless _o['bundleRequireBundle'].nil?\n @pageSize = Fixnum.from_json(_o['pageSize']) unless _o['pageSize'].nil?\n @selectedPage = Fixnum.from_json(_o['selectedPage']) unless _o['selectedPage'].nil?\n end", "def initialize(order_hash)\n @id = order_hash['id']\n @number = order_hash['number']\n @special_instructions = order_hash['special_instructions']\n @total = order_hash['total']\n @total_quantity = order_hash['total_quantity']\n @created_at = order_hash['created_at']\n @updated_at = order_hash['updated_at']\n end", "def from_db_hash *args\n from_hash *args\n end", "def build_from_hash(attributes)\n return nil unless attributes.is_a?(Hash)\n self.class.swagger_types.each_pair do |key, type|\n if type =~ /^Array<(.*)>/i\n if attributes[self.class.attribute_map[key]].is_a?(Array)\n self.send(\"#{key}=\", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } )\n else\n #TODO show warning in debug mode\n end\n elsif !attributes[self.class.attribute_map[key]].nil?\n self.send(\"#{key}=\", _deserialize(type, attributes[self.class.attribute_map[key]]))\n else\n # data not found in attributes(hash), not an issue as the data can be optional\n end\n end\n\n self\n end", "def build_from_hash(attributes)\n return nil unless attributes.is_a?(Hash)\n self.class.swagger_types.each_pair do |key, type|\n if type =~ /^Array<(.*)>/i\n if attributes[self.class.attribute_map[key]].is_a?(Array)\n self.send(\"#{key}=\", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } )\n else\n #TODO show warning in debug mode\n end\n elsif !attributes[self.class.attribute_map[key]].nil?\n self.send(\"#{key}=\", _deserialize(type, attributes[self.class.attribute_map[key]]))\n else\n # data not found in attributes(hash), not an issue as the data can be optional\n end\n end\n\n self\n end", "def build_from_hash(attributes)\n return nil unless attributes.is_a?(Hash)\n self.class.swagger_types.each_pair do |key, type|\n if type =~ /^Array<(.*)>/i\n if attributes[self.class.attribute_map[key]].is_a?(Array)\n self.send(\"#{key}=\", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } )\n else\n #TODO show warning in debug mode\n end\n elsif !attributes[self.class.attribute_map[key]].nil?\n self.send(\"#{key}=\", _deserialize(type, attributes[self.class.attribute_map[key]]))\n else\n # data not found in attributes(hash), not an issue as the data can be optional\n end\n end\n\n self\n end" ]
[ "0.8011074", "0.7470833", "0.7457607", "0.7256629", "0.72455454", "0.70060325", "0.6973257", "0.6955014", "0.69459796", "0.69398683", "0.69363195", "0.6917627", "0.6872358", "0.6796184", "0.6783521", "0.67575246", "0.67575246", "0.67560464", "0.67514306", "0.67136854", "0.66667664", "0.6623634", "0.661206", "0.66098964", "0.66098964", "0.6591922", "0.65713006", "0.6547411", "0.6524743", "0.6524143", "0.6513636", "0.650189", "0.6498057", "0.6485853", "0.6483371", "0.6475685", "0.6459916", "0.6454491", "0.6440182", "0.6434778", "0.6401363", "0.63977015", "0.6396885", "0.63910425", "0.63720834", "0.6363958", "0.63597506", "0.6313429", "0.6295958", "0.62923384", "0.62915224", "0.62704456", "0.62703115", "0.62622243", "0.62515473", "0.6249854", "0.6242987", "0.6242987", "0.62426233", "0.62408733", "0.62407595", "0.62321323", "0.62298346", "0.622897", "0.622756", "0.62245685", "0.62217826", "0.6218501", "0.6210329", "0.62091905", "0.620342", "0.6201614", "0.6178616", "0.6166234", "0.61611027", "0.6140086", "0.6126761", "0.61154264", "0.61059844", "0.60980254", "0.60971874", "0.6090533", "0.6064119", "0.6061236", "0.6060324", "0.60599816", "0.60420287", "0.6039776", "0.603712", "0.6033585", "0.6030829", "0.6023582", "0.6023582", "0.6016123", "0.60155296", "0.6014705", "0.6008574", "0.60031897", "0.60024095", "0.60024095", "0.60024095" ]
0.0
-1
Deserializes the data based on type
def _deserialize(type, value) case type.to_sym when :DateTime DateTime.parse(value) when :Date Date.parse(value) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :BOOLEAN if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model temp_model = NSXTPolicy.const_get(type).new temp_model.build_from_hash(value) end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Telstra_Messaging.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = FattureInCloud.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = IFClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = WineShipping.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = UltracartClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = UltracartClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = UltracartClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = UltracartClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = UltracartClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = UltracartClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = UltracartClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = UltracartClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = UltracartClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = UltracartClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = UltracartClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = UltracartClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = UltracartClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = UltracartClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = UltracartClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = UltracartClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :Boolean\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n DearInventoryRuby.const_get(type).build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Mooncard.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Aimastering.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Harbor1Client.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Intrinio.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Intrinio.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Intrinio.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Intrinio.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Intrinio.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Intrinio.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Intrinio.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /^(true|t|yes|y|1)$/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Pier.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /^(true|t|yes|y|1)$/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Pier.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /^(true|t|yes|y|1)$/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Pier.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /^(true|t|yes|y|1)$/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Pier.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /^(true|t|yes|y|1)$/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Pier.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /^(true|t|yes|y|1)$/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Pier.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /^(true|t|yes|y|1)$/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Pier.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /^(true|t|yes|y|1)$/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Pier.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /^(true|t|yes|y|1)$/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Pier.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /^(true|t|yes|y|1)$/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Pier.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = CrelateClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = CrelateClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = CrelateClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = CrelateClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = CrelateClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = WellsFargoAchClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = ArtikCloud.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Dkron.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :Boolean\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n MailSlurpClient.const_get(type).build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :Boolean\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n MailSlurpClient.const_get(type).build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Esi.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Esi.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Esi.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :Time\n Time.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :Boolean\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n # models (e.g. Pet) or oneOf\n klass = Fastly.const_get(type)\n klass.respond_to?(:fastly_one_of) ? klass.build(value) : klass.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :Time\n Time.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :Boolean\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n # models (e.g. Pet) or oneOf\n klass = Fastly.const_get(type)\n klass.respond_to?(:fastly_one_of) ? klass.build(value) : klass.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :Time\n Time.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :Boolean\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n # models (e.g. Pet) or oneOf\n klass = Fastly.const_get(type)\n klass.respond_to?(:fastly_one_of) ? klass.build(value) : klass.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :Time\n Time.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :Boolean\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n # models (e.g. Pet) or oneOf\n klass = Fastly.const_get(type)\n klass.respond_to?(:fastly_one_of) ? klass.build(value) : klass.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n ::DateTime.parse(value)\n when :Date\n ::Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Models.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n ::DateTime.parse(value)\n when :Date\n ::Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Models.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :Time\n Time.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :Boolean\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n # models (e.g. Pet) or oneOf\n klass = Hubspot::Cms::Performance.const_get(type)\n klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = SmoochApi.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Tradenity.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Tradenity.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = SamplifyAPIClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = OpsgenieClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = LemonWayClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = BudgeaClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = BudgeaClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :Boolean\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n Nodeum.const_get(type).build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = TextMagic.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = TextMagic.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = TextMagic.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n Date.parse value\n when :Date\n Date.parse value\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else\n # model\n temp_model = GroupDocsViewerCloud.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n Date.parse value\n when :Date\n Date.parse value\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else\n # model\n temp_model = GroupDocsViewerCloud.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n Date.parse value\n when :Date\n Date.parse value\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else\n # model\n temp_model = GroupDocsViewerCloud.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = ConnectWise.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = ConnectWise.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = ConnectWise.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = ConnectWise.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = ConnectWise.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = ConnectWise.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = ConnectWise.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = ConnectWise.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = ConnectWise.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = ConnectWise.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = ConnectWise.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = ConnectWise.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = ConnectWise.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = ConnectWise.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = NSXT.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = NSXT.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = NSXT.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = TreezorClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = TreezorClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = TreezorClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = SwiftApi.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = SwiftApi.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = TripletexApi.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = unwiredClient.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end", "def _deserialize(type, value)\n case type.to_sym\n when :DateTime\n DateTime.parse(value)\n when :Date\n Date.parse(value)\n when :String\n value.to_s\n when :Integer\n value.to_i\n when :Float\n value.to_f\n when :BOOLEAN\n if value.to_s =~ /\\A(true|t|yes|y|1)\\z/i\n true\n else\n false\n end\n when :Object\n # generic object (usually a Hash), return directly\n value\n when /\\AArray<(?<inner_type>.+)>\\z/\n inner_type = Regexp.last_match[:inner_type]\n value.map { |v| _deserialize(inner_type, v) }\n when /\\AHash<(?<k_type>.+?), (?<v_type>.+)>\\z/\n k_type = Regexp.last_match[:k_type]\n v_type = Regexp.last_match[:v_type]\n {}.tap do |hash|\n value.each do |k, v|\n hash[_deserialize(k_type, k)] = _deserialize(v_type, v)\n end\n end\n else # model\n temp_model = Quandoo.const_get(type).new\n temp_model.build_from_hash(value)\n end\n end" ]
[ "0.7330926", "0.7274019", "0.72504056", "0.7245751", "0.72291344", "0.72291344", "0.72291344", "0.72291344", "0.72291344", "0.72291344", "0.72291344", "0.72291344", "0.72291344", "0.72291344", "0.72291344", "0.72291344", "0.72291344", "0.72291344", "0.72291344", "0.72291344", "0.7218884", "0.7213926", "0.71909", "0.7183136", "0.71796805", "0.71796805", "0.71796805", "0.71796805", "0.71796805", "0.71796805", "0.71796805", "0.71791923", "0.71791923", "0.71791923", "0.71791923", "0.71791923", "0.71791923", "0.71791923", "0.71791923", "0.71791923", "0.71791923", "0.71712995", "0.71712995", "0.71712995", "0.71712995", "0.71712995", "0.71632504", "0.71549904", "0.71473306", "0.71413666", "0.71413666", "0.7141116", "0.7141116", "0.7141116", "0.7133874", "0.7133874", "0.7133874", "0.7133874", "0.71333444", "0.71333444", "0.7127688", "0.7125744", "0.71210617", "0.71210617", "0.71190786", "0.71184087", "0.711393", "0.7113519", "0.7113519", "0.7113516", "0.71119875", "0.71119875", "0.71119875", "0.7105169", "0.7105169", "0.7105169", "0.7104928", "0.7104928", "0.7104928", "0.7104928", "0.7104928", "0.7104928", "0.7104928", "0.7104928", "0.7104928", "0.7104928", "0.7104928", "0.7104928", "0.7104928", "0.7104928", "0.7102596", "0.7102596", "0.7102596", "0.7101596", "0.7101596", "0.7101596", "0.70996517", "0.70996517", "0.7097952", "0.7097185", "0.70965225" ]
0.0
-1
Returns the string representation of the object
def to_s to_hash.to_s end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def to_s\n @object.to_s\n end", "def to_s\n object.to_s\n end", "def serialize(object)\n object.to_s\n end", "def to_s\n self.inspect\n end", "def to_s\n @string || @object.to_s('F')\n end", "def to_s\n @string || @object.to_s('F')\n end", "def to_s\n \"#<#{self.class.name}:#{object_id} #{info}>\"\n end", "def to_s\n \"#<#{self.class.name}:#{object_id}> @names=#{names}>\"\n end", "def to_s\n self.inspect\n end", "def to_s\n toString()\n end", "def to_s\r\n dump\r\n end", "def to_s\n inspect\n end", "def to_s\n toString\n end", "def toString\n #Not sure if we want this or just use the getters for more\n #selective formatting\n end", "def to_s\n\t\t\t@string\n\t\tend", "def to_s\n stringify\n end", "def to_s\n to_h.to_s\n end", "def to_s\n @string\n end", "def to_s\n @string\n end", "def to_s\n @string\n end", "def to_s\n @string\n end", "def to_s\n @string\n end", "def to_s\n @string\n end", "def to_s\n @string\n end", "def to_s\n @string\n end", "def inspect\n serialize.to_s\n end", "def inspect\n to_s\n end", "def to_s\n @string ||= Builder::ToString.new(self).string\n end", "def to_s\n self\n end", "def to_s()\n serialize.to_s()\n end", "def to_s()\n serialize.to_s()\n end", "def to_s\n string\n end", "def to_s\n inspect\n end", "def to_s\n inspect\n end", "def inspect\n to_s\n end", "def inspect\n to_s\n end", "def inspect\n to_s\n end", "def inspect\n to_s\n end", "def inspect\n to_s\n end", "def inspect\n to_s\n end", "def inspect\n to_s\n end", "def inspect\n self.to_s\n end", "def inspect\n self.to_s\n end", "def inspect\n to_s\n end", "def inspect\n to_s\n end", "def to_s\n end", "def to_s\n end", "def to_s\n end", "def to_s\n end", "def inspect\n to_s.inspect\n end", "def inspect()\n serialize.to_s()\n end", "def inspect()\n serialize.to_s()\n end", "def inspect\n return self.to_s\n end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end", "def to_s; end" ]
[ "0.901024", "0.89506465", "0.84703195", "0.83409667", "0.8337169", "0.8337169", "0.8332247", "0.82546586", "0.8145818", "0.8144667", "0.81357557", "0.812714", "0.8093436", "0.8086725", "0.8073356", "0.8039774", "0.80308646", "0.80064154", "0.80064154", "0.80064154", "0.80064154", "0.7962831", "0.7962831", "0.7962831", "0.7962831", "0.7954296", "0.79446983", "0.7919419", "0.7909274", "0.78848016", "0.78848016", "0.78841925", "0.788328", "0.788328", "0.78758216", "0.78758216", "0.78758216", "0.78758216", "0.78758216", "0.78758216", "0.78758216", "0.7866813", "0.7866813", "0.7865939", "0.7865939", "0.7850519", "0.7850519", "0.7850519", "0.7850519", "0.7808076", "0.7784745", "0.7784745", "0.7767656", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824", "0.77608824" ]
0.0
-1
to_body is an alias to to_hash (backward compatibility)
def to_body to_hash end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def to_body\r\n to_hash\r\n end", "def to_body\n to_hash\nend", "def to_body\n to_hash\nend" ]
[ "0.84283537", "0.8347048", "0.8347048" ]
0.0
-1
Returns the object in the form of hash
def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) next if value.nil? hash[param] = _to_hash(value) end hash end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def to_hash\n object\n end", "def hash\r\n return to_s.hash\r\n end", "def hash\n to_a.hash\n end", "def hash\n [_hash, name, owner].hash\n end", "def hash\n return to_s.hash\n end", "def hash\n @hash\n end", "def hash\n @hash.hash\n end", "def hash\n @hash ||= self.to_a.hash\n end", "def to_hash\n @hash\n end", "def to_hash\n @hash\n end", "def hash\n to_s.hash\n end", "def to_hash\n @hash\n end", "def to_h\n @object\n end", "def to_h\n @object\n end", "def to_h\n @object\n end", "def to_h\n @object\n end", "def to_h\n @object\n end", "def to_h\n @object\n end", "def to_h\n @object\n end", "def to_h\n @object\n end", "def to_h\n @object\n end", "def to_h\n @object\n end", "def to_h\n @object\n end", "def to_h\n @object\n end", "def to_h\n @object\n end", "def to_h\n @object\n end", "def to_h\n @hash\n end", "def to_h\n @hash\n end", "def hash\n to_h.hash ^ self.class.hash\n end", "def as_hash\n @hash\n end", "def __getobj__\n @hashobj\n end", "def to_hash() end", "def hash\n to_s.hash\n end", "def hash\n to_s.hash\n end", "def hash\n object_id\n end", "def to_hash\n @_hash_\n end", "def hash\n\t\treturn self.name.to_s.hash\n\tend", "def to_hash\n to_a.hash\n end", "def hash\n { hash: @hash, hashType: @hash_type }\n end", "def hash\n data.hash\n end", "def hash\n [self.class, to_h].hash\n end", "def hash\n [self.class, to_h].hash\n end", "def hash\n [self.class, to_h].hash\n end", "def hash\r\n id.hash\r\n end", "def hash\n \"#{self.class.name}-#{self.id}-#{@__metadata__.cas}-#{@__attributes__.hash}\".hash\n end", "def hash\n attributes.hash\n end", "def hash\n attributes.hash\n end", "def hash\n attributes.hash\n end", "def hash #:nodoc:\n __getobj__.hash ^ self.class.hash\n end", "def hash\n self.to_f.hash\n end", "def hash\n end", "def hash\n end", "def hash\n end", "def to_hash\n return self\n end", "def to_hash(object)\n validate_class_kit(object.class)\n\n @hash_helper.to_hash(object)\n end", "def hash\n return @id.hash\n end", "def to_h\n Hash[ self ]\n end", "def to_hash\n Hash[self]\n end", "def to_h\n @hash.dup\n end", "def hash\n id.hash\n end", "def hash\n id.hash\n end", "def hash\n id.hash\n end", "def hash\n id.hash\n end", "def hash\n id.hash\n end", "def hash\n id.hash\n end", "def hash\n id.hash\n end", "def hash\n id.hash\n end", "def hash\n id.hash\n end", "def hash\n id.hash\n end", "def to_h\n @hash.dup\n end", "def hash\n model.hash + key.hash\n end", "def to_hash; end", "def to_hash; end", "def to_hash; end", "def to_hash; end", "def to_hash; end", "def to_hash; end", "def hash\n [self.class, to_s].hash\n end", "def hash\n id.hash\n end", "def hash\n id.hash\n end", "def hash\n self.atoms.hash\n end", "def to_h\n Hash[self]\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 hash\n\t\tvalue.hash\n\tend", "def hash\n [description, routing_number, account_number, account_type, signatory, metadata, id, signature_url, bank_name, verified, date_created, date_modified, deleted, object].hash\n end", "def hash\n @id.hash\n end", "def hash\n id.hash\n end", "def hash\n self.class.name.hash\n end", "def to_h\n @_hash.dup\n end", "def hash\n\t\t[@id].hash\n\tend", "def hash\n [self.class, to_s].hash\n end", "def __hash\n @hash\n end" ]
[ "0.8270299", "0.78767854", "0.78726953", "0.7802364", "0.7789188", "0.77806795", "0.7775915", "0.7767511", "0.7760525", "0.7760525", "0.77559966", "0.7731286", "0.7713916", "0.7713916", "0.7713916", "0.7713916", "0.7713916", "0.7713916", "0.7713916", "0.7713916", "0.7713916", "0.7713916", "0.7713916", "0.7713916", "0.7713916", "0.7713916", "0.7647042", "0.7647042", "0.7626769", "0.760354", "0.7595938", "0.7582562", "0.7579971", "0.7579971", "0.7535553", "0.7495252", "0.7433835", "0.7411177", "0.73843014", "0.73661345", "0.73658615", "0.73658615", "0.73658615", "0.73600674", "0.7359121", "0.73590857", "0.73590857", "0.73590857", "0.7340058", "0.73356754", "0.7329828", "0.7329828", "0.7329828", "0.73170114", "0.730566", "0.73028016", "0.7294603", "0.72854036", "0.72643596", "0.72637254", "0.72620076", "0.72620076", "0.72620076", "0.72620076", "0.72620076", "0.72620076", "0.72620076", "0.72620076", "0.72620076", "0.726188", "0.72524244", "0.72511965", "0.72511965", "0.72511965", "0.72511965", "0.72511965", "0.72511965", "0.72479564", "0.72474235", "0.72474235", "0.7241066", "0.7229342", "0.7228758", "0.7228758", "0.7228758", "0.7228758", "0.7228758", "0.7228758", "0.7228758", "0.7228758", "0.7228758", "0.7228758", "0.7224175", "0.72185695", "0.72126305", "0.72116995", "0.71945405", "0.71828544", "0.7181684", "0.7171822", "0.71657544" ]
0.0
-1
Outputs nonarray value in the form of hash For object, use to_hash. Otherwise, just return the value
def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def hash\n [value].hash\n end", "def hash\n [value].hash\n end", "def hash\n\t\tvalue.hash\n\tend", "def hash\n value.hash\n end", "def hash\n @value.hash\n end", "def hash\r\n return to_s.hash\r\n end", "def to_hash\n @value\n end", "def to_hash\n @value\n end", "def hash\n @hash || @hash = (value.hash * -1)\n end", "def output_hash; end", "def to_hash() end", "def hash\n return to_s.hash\n end", "def hash\n value_id.hash\n end", "def to_hash\n call\n @hash = @value\n @hash\n end", "def hash\n to_s.hash\n end", "def hash\n to_s.hash\n end", "def hash\n self.to_f.hash\n end", "def hash\n to_s.hash\n end", "def to_hash(obj = T.unsafe(nil)); end", "def to_h\n @value\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map { |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map { |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map { |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map { |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def value_to_hash(value, options = T.unsafe(nil)); end", "def to_s\r\n to_hash.to_s\r\n end", "def _to_hash(value)\r\n if value.is_a?(Array)\r\n value.compact.map{ |v| _to_hash(v) }\r\n elsif value.is_a?(Hash)\r\n {}.tap do |hash|\r\n value.each { |k, v| hash[k] = _to_hash(v) }\r\n end\r\n elsif value.respond_to? :to_hash\r\n value.to_hash\r\n else\r\n value\r\n end\r\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 to_s\n to_hash.to_s\nend", "def to_s\n to_hash.to_s\nend", "def to_h(value)\n return value unless @to_h\n @to_h.call value\n end", "def to_hash\n Hash[to_a]\n end", "def to_hash; end", "def to_hash; end", "def to_hash; end", "def to_hash; end", "def to_hash; end", "def to_hash; end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end", "def _to_hash(value)\n if value.is_a?(Array)\n value.compact.map{ |v| _to_hash(v) }\n elsif value.is_a?(Hash)\n {}.tap do |hash|\n value.each { |k, v| hash[k] = _to_hash(v) }\n end\n elsif value.respond_to? :to_hash\n value.to_hash\n else\n value\n end\n end" ]
[ "0.6719518", "0.6719518", "0.666832", "0.66565555", "0.6586841", "0.6452931", "0.6414911", "0.6414911", "0.6382046", "0.6346188", "0.6302933", "0.62237245", "0.6151989", "0.6101756", "0.60795677", "0.60795677", "0.60717124", "0.6035991", "0.6021168", "0.5936472", "0.5903488", "0.5903488", "0.5903488", "0.5903488", "0.5903488", "0.5890367", "0.5890367", "0.5884459", "0.5884459", "0.58669275", "0.58533067", "0.58355993", "0.58215266", "0.58215266", "0.58215266", "0.58215266", "0.58215266", "0.58215266", "0.58215266", "0.58215266", "0.58215266", "0.58215266", "0.5803003", "0.5803003", "0.57983655", "0.578115", "0.577359", "0.577359", "0.577359", "0.577359", "0.577359", "0.577359", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771", "0.5769771" ]
0.0
-1
vim: ts=2 sts=2 sw=2 expandtab
def hex(s) s.nil? ? 'nil' : "[#{s.bytesize}]:#{s.bytes.map{|b|'%02X' % b}.join '.'}" end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def with_repl_like_sigint; end", "def terpene; end", "def autofinish; end", "def my955; end", "def source_line=(_); end", "def start_re=(_); end", "def expanded; end", "def code_point=(_); end", "def lines_of_code; end", "def lines_of_code; end", "def leading=(_); end", "def tt; end", "def probers; end", "def beautify; end", "def beautify; end", "def verdi; end", "def auto_analyze=(_arg0); end", "def macro; end", "def macro; end", "def vim_mappings\n { \n \"VI_SELECTED_TEXT\" => \"getreg()\",\n \"VI_FILENAME\" => \"@%\",\n \"VI_CURRENT_LINE\" => \"getline(\\\".\\\")\",\n \"VI_SOFT_TABS\" => \"&expandtab\"\n }\n end", "def private; end", "def slop!; end", "def slop!; end", "def begin_pos=(_); end", "def tiny; end", "def yyerrok; end", "def yyerrok; end", "def autofinish=(_arg0); end", "def anchored; end", "def as_you_like_it_quote; end", "def line_range=(_arg0); end", "def loc; end", "def loc; end", "def loc; end", "def line=(_); end", "def line=(_); end", "def source_line; end", "def flags; end", "def tokens=(_arg0); end", "def tokens=(_arg0); end", "def tokens=(_arg0); end", "def buzzword; end", "def buzzword; end", "def motto; end", "def leading; end", "def rossini; end", "def flag; end", "def before_lint; end", "def parslet; end", "def parslet; end", "def parslet; end", "def parslet; end", "def bellini; end", "def unexpected_indent_offset; end", "def preamble\n \"// BEGIN METARUBY PREAMBLE\n#include <ruby.h>\n#define RB_COMPARE(x, y) (x) == (y) ? 0 : (x) < (y) ? -1 : 1\ntypedef char * str;\n#define case_equal_long(x, y) ((x) == (y))\n// END METARUBY PREAMBLE\n\" + self.prototypes.join('')\n end", "def full_source=(_arg0); end", "def suivre; end", "def ignores; end", "def trd; end", "def tld; end", "def tld; end", "def line=(_arg0); end", "def gounod; end", "def lsi; end", "def berlioz; end", "def source_lines; end", "def source_lines; end", "def source_lines; end", "def source_lines; end", "def blg; end", "def cmd; end", "def auto_analyze; end", "def sourcemap_option; end", "def alt; end", "def tagline; end", "def source_decls; end", "def reserved_words=(_arg0); end", "def up(spaces = T.unsafe(nil)); end", "def up(spaces = T.unsafe(nil)); end", "def result_of_executing_the_commands\n @commands = \":set ft=ruby\r\" + @commands\n RobotVim::Runner.new.run(:input_file => @input, :commands => @commands)\nend", "def change_indent plus\n # nothing here\n end", "def PO114=(arg)", "def end_pos=(_); end", "def vix\n Object.class_eval `cat ~/.scratchvim.rb`\nend", "def lex_start; end", "def lex_start; end", "def lex_start; end", "def lex_start; end", "def stderrs; end", "def pre_match() end", "def ibu; end", "def line; end", "def line; end", "def line; end", "def line; end", "def line; end", "def line; end", "def line; end", "def line; end", "def line; end", "def line; end" ]
[ "0.6003154", "0.5932986", "0.5823631", "0.57155794", "0.56689525", "0.5657982", "0.56509584", "0.5605258", "0.5604854", "0.5604854", "0.5564482", "0.55569184", "0.5554731", "0.55493504", "0.55493504", "0.5541388", "0.55095273", "0.5505661", "0.5505661", "0.54965097", "0.5453158", "0.54395455", "0.54395455", "0.543793", "0.5427937", "0.54238075", "0.54238075", "0.541103", "0.539142", "0.53596085", "0.5342008", "0.532702", "0.532702", "0.532702", "0.53264", "0.53264", "0.5323206", "0.5317991", "0.53144217", "0.53144217", "0.53144217", "0.53127116", "0.53127116", "0.5305281", "0.53035384", "0.5287308", "0.52836305", "0.5282196", "0.5274951", "0.5274951", "0.5274951", "0.5274951", "0.52721643", "0.52582693", "0.5256248", "0.52551657", "0.523149", "0.5219814", "0.52074766", "0.52032566", "0.52032566", "0.519887", "0.51984286", "0.5188072", "0.51809", "0.517995", "0.517995", "0.517995", "0.517995", "0.5160578", "0.51523006", "0.51472956", "0.5138328", "0.51356685", "0.5132636", "0.5124818", "0.51209104", "0.512027", "0.512027", "0.5117801", "0.50947607", "0.50942093", "0.50884527", "0.50835556", "0.5083503", "0.5083503", "0.5083503", "0.5083503", "0.50770175", "0.5073111", "0.50690025", "0.506601", "0.506601", "0.506601", "0.506601", "0.506601", "0.506601", "0.506601", "0.506601", "0.506601", "0.506601" ]
0.0
-1
True if we've sent or received a GOAWAY frame.
def shutdown? @shutdown_lock.synchronize { @shutting_down } end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def framed?\n return @peer.framed?\n end", "def sent?\n status.sent? || status.received? || status.read?\n end", "def received?\r\n self['trans_status']=='99'\r\n end", "def response_received?\n !! @status\n end", "def response_received?\n !! @status\n end", "def received?\n !!self.received_at?\n end", "def well_formated_response?\n all_expected_fields_received? && validate_bank_response_signature\n end", "def msg_sent?\n true\n end", "def done_request_line?\n [:headers, :body_identity, :body_chunked, :body_chunked_tail, :done].include?(@state)\n end", "def message_sent?\n message.state == 'sent'\n end", "def message_sent?\n message.state == 'sent'\n end", "def received?\n status.received? || status.read?\n end", "def ok?\n first[OK] == 1 || reply.nil?\n end", "def semantic_frame? f\n f.type == FrameTypes::DATA || f.type == FrameTypes::HEADERS || f.type == FrameTypes::CONTINUATION || f.type == FrameTypes::GZIPPED_DATA\n end", "def bodiless?\n\t\treturn self.extended_reply? ||\n\t\t\tself.body.nil? ||\n\t\t\tHTTP::BODILESS_HTTP_RESPONSE_CODES.include?( self.status )\n\tend", "def response?\n\t\treturn ((self.type == PACKET_TYPE_RESPONSE) ||\n\t\t (self.type == PACKET_TYPE_PLAIN_RESPONSE))\n\tend", "def response?\n\t\treturn ((self.type == PACKET_TYPE_RESPONSE) ||\n\t\t (self.type == PACKET_TYPE_PLAIN_RESPONSE))\n\tend", "def sent?\n !@sent_at.nil?\n end", "def received?\n received_event_parameters\n end", "def needs_sending?\n !sent? && !flagged?\n end", "def ok? \n @response.is_a? Net::HTTPOK\n end", "def send?\n type == 'send'\n end", "def alive?\n return true if ws && ts\n return false\n end", "def payment_received?\n payment_state == PAYMENT_RECEIVED\n end", "def handshake_approved?\n return false if params[:token] != ENV[\"SLACK_TOKEN\"]\n return false unless !event_type_supported?\n\n return true\n end", "def control_frame?(frame_type)\n !%i(text binary continuation).include?(frame_type)\n end", "def can_send?\n !sent?\n end", "def alive?\n !client_security_token.nil? && !x_security_token.nil?\n end", "def keepalive?\n\t\tka_header = self.headers[:connection]\n\t\treturn !ka_header.nil? && ka_header =~ /keep-alive/i\n\t\treturn false\n\tend", "def is_request_status_ok\n get_request_status == MA500Functions::MA500::ILV_OK.hex\n end", "def btc_arrived?\n item = read\n item['active'] && item['active'] == 2\n end", "def in_transit?\n status.sent?\n end", "def alive?\n unless(@recvthread.instance_of?(Thread))\n return false\n end\n \n ret=@recvthread.alive?\n @sendthreads.each_value{|t|\n ret&=t\n }\n ret&=(!@socket.closed?)\n \n return ret\n end", "def alive?\n @alive && @mailbox.alive?\n end", "def delivered?\n processed? && !held? && !bounced? && message.present?\n end", "def send_gzip?\n return if !@ext__peer_gzip\n @ext__send_gzip\n end", "def receive_po\n is_received?\n end", "def can_receive?\n if (self.state == 'C' or self.state == 'F')\n return true\n end\n return false\n end", "def alive?\n state == :open\n end", "def sent?\n status == \"sent\"\n end", "def response?\n done? ? @grpc_op.result == :response : false\n end", "def open?\n @handshake&.finished? && !@closed\n end", "def done_headers?\n [:body_identity, :body_chunked, :body_chunked_tail, :done].include?(@state)\n end", "def have_transmission_header?\n @have_transmission_header\n end", "def is_receiving_data\n if defined? TsPoint\n return IsTsInstrumentAlive.call(TsPoint, \"value\", self.id, self.sample_rate_seconds+5)\n else\n return false\n end\n end", "def ack?\n Capp::TCP_ACK == flags & Capp::TCP_ACK\n end", "def sendable?\n at?(:active)\n end", "def caught_by_player?\n return flags.anybits?(FLAG_CAUGHT_BY_PLAYER)\n end", "def sent?\n @sent\n end", "def request_sent?\n !response.nil?\n end", "def alive?\n !cst.nil? && !x_security_token.nil?\n end", "def isMyMessage(message)\r\n return message[:type] == :Sent\r\n end", "def body?\n HTTY::Request::METHODS_SENDING_BODY.include? method\n end", "def valid?\n @method == \"GET\" &&\n !@request_uri.empty? &&\n @http_version >= 1.1 &&\n @header[\"Upgrade\"] == \"websocket\" &&\n @header[\"Connection\"].include?(\"Upgrade\") &&\n Base64.decode64(@header[\"Sec-WebSocket-Key\"]).length == 16 &&\n @header[\"Sec-WebSocket-Version\"].to_i == 13\n end", "def response?\n done? && !error?\n end", "def has_accepted_response?\n self.responses.accepted.any? {|response| response.accepted?}\n end", "def responds_on?(buffy_context)\n return true unless event_action\n buffy_context.event_action == event_action ? true : false\n end", "def verify\n if (buffer.offset + @_model.fbe_offset) > buffer.size\n return false\n end\n\n fbe_struct_size = read_uint32(@_model.fbe_offset - 8)\n fbe_struct_type = read_uint32(@_model.fbe_offset - 4)\n if (fbe_struct_size <= 0) or (fbe_struct_type != fbe_type)\n return false\n end\n\n (8 + @_model.verify) == fbe_struct_size\n end", "def verify\n if (buffer.offset + @_model.fbe_offset) > buffer.size\n return false\n end\n\n fbe_struct_size = read_uint32(@_model.fbe_offset - 8)\n fbe_struct_type = read_uint32(@_model.fbe_offset - 4)\n if (fbe_struct_size <= 0) or (fbe_struct_type != fbe_type)\n return false\n end\n\n (8 + @_model.verify) == fbe_struct_size\n end", "def verify\n if (buffer.offset + @_model.fbe_offset) > buffer.size\n return false\n end\n\n fbe_struct_size = read_uint32(@_model.fbe_offset - 8)\n fbe_struct_type = read_uint32(@_model.fbe_offset - 4)\n if (fbe_struct_size <= 0) or (fbe_struct_type != fbe_type)\n return false\n end\n\n (8 + @_model.verify) == fbe_struct_size\n end", "def verify\n if (buffer.offset + @_model.fbe_offset) > buffer.size\n return false\n end\n\n fbe_struct_size = read_uint32(@_model.fbe_offset - 8)\n fbe_struct_type = read_uint32(@_model.fbe_offset - 4)\n if (fbe_struct_size <= 0) or (fbe_struct_type != fbe_type)\n return false\n end\n\n (8 + @_model.verify) == fbe_struct_size\n end", "def closed?\n\t\t\t\t@state == :closed || @framer.nil?\n\t\t\tend", "def response?\n qr?\n end", "def done?\n @next_frame == @total_frames\n end", "def bitbucket_server_webhook?\n # https://confluence.atlassian.com/bitbucketserver/event-payload-938025882.html\n @headers.key?('HTTP_X_EVENT_KEY') && @headers.key?('HTTP_X_REQUEST_ID')\n end", "def valid_oxum?\n bag_info[\"Payload-Oxum\"] == payload_oxum\n end", "def gtp_session_complete?(sequence_number) \n (@gtp_session[sequence_number][:REQUEST].key?(:req_res) && @gtp_session[sequence_number][:RESPONSE].key?(:req_res))\n end", "def has_outgoing_headers?\n !!(raw_headers =~ /^X\\-Postal\\-MsgID\\:/i)\n end", "def has_outgoing_headers?\n !!(raw_headers =~ /^X\\-Postal\\-MsgID\\:/i)\n end", "def payment_received?\n status == Enums::PaymentStatus::PAYMENT_RECEIVED\n end", "def receive?\n type == 'receive'\n end", "def bot_agent?\r\n BotAgents.bot_agent?(useragent) || JunkAgents.junk_agent?(useragent)\r\n end", "def finished?\n\t\t\t\t@finished && @body.length >= @headers['CONTENT_LENGTH']\n\t\t\tend", "def successful?(response)\n (response[\"GatewayRspCode\"] == \"0\") && ((response[\"RspCode\"] || \"0\") == \"0\")\n end", "def sent?\n self.status == 'sent'\n end", "def can_capture?(payment)\n (payment.pending? || payment.checkout?) && !payment.response_code.blank?\n end", "def can_capture?(payment)\n (payment.pending? || payment.checkout?) && !payment.response_code.blank?\n end", "def push?\n Capp::TCP_PUSH == flags & Capp::TCP_PUSH\n end", "def should_keep_alive\n # Explicit:\n return true if 'keep-alive'.eql_igncase? connection_type\n return false if 'close'.eql_igncase? connection_type\n \n # Otherwise, we have to guess:\n # (the UFO operator does lexical array comparison, positive if @ht_v > 1.1)\n (@http_version <=> [1,1]) >= 0\n end", "def mfa?\n @response.is_a?(Net::HTTPCreated)\n end", "def final_frame_complete?\n if roll_final_frame_first_strike? || roll_final_frame_second_strike? ||\n final_frame_spare?\n current_frame.length == 3\n else\n current_frame == 2\n end\n end", "def ok?\n @status == OK\n end", "def delivered?\n (!current_stage.nil? &&\n current_stage.stage.eql?('delivered') &&\n current_stage.status.eql?('passed') &&\n !AutomateSoup.url.nil? &&\n !AutomateSoup.credentials.nil?)\n end", "def urg?\n Capp::TCP_URG == flags & Capp::TCP_URG\n end", "def response?\n @type == :response\n end", "def skipping_frame?\n return @frame_to_skip > 0\n end", "def framed?\n dim_type.outer_target == \"frame\"\n end", "def can_capture?(payment)\n ['pending'].include?(payment.state)\n end", "def response_code_is_ok?\n return true if %w(00 24).include? response_code\n\n false\n end", "def can_capture?(payment)\n ['checkout', 'pending'].include?(payment.state)\n end", "def can_capture?(payment)\n ['checkout', 'pending'].include?(payment.state)\n end", "def can_capture?(payment)\n ['pending'].include?(payment.state)\n end", "def accept_gzip?\n return if @ext__veto_gzip\n @ext__recv_gzip\n end", "def can_capture?(payment)\n payment.state == 'pending' || payment.state == 'checkout'\n end", "def link_alive?\n !!socket && !socket.closed? && !@dead && @disabled_tx == 0\n end", "def can_capture?(payment)\n ['checkout', 'pending'].include?(payment.state)\n end", "def response?\n !response.nil?\n end", "def verify_accept\n raise WebSocket::Error::Handshake::InvalidAuthentication unless @handshake.headers['sec-websocket-accept'] == accept\n true\n end", "def wan_up?\n `ping -c 1 8.8.8.8 -W 1`.include? \"1 received\"\n end", "def eof\n\t\trequest = Packet.create_request('core_channel_eof')\n\n\t\trequest.add_tlv(TLV_TYPE_CHANNEL_ID, self.cid)\n\n\t\tbegin\n\t\t\tresponse = self.client.send_request(request)\n\t\trescue\n\t\t\treturn true\n\t\tend\n\n\t\tif (response.has_tlv?(TLV_TYPE_BOOL))\n\t\t\treturn response.get_tlv_value(TLV_TYPE_BOOL)\n\t\tend\n\n\t\treturn false\n\tend", "def valid?\n mandatory_keys = %w[message stacktrace]\n return false unless mandatory_keys.all? { |key| @payload.key?(key) }\n return false if @payload['stacktrace'].empty?\n\n true\n end" ]
[ "0.6952977", "0.6361301", "0.63327146", "0.6249398", "0.6249398", "0.62153685", "0.6182273", "0.61802363", "0.61600554", "0.61289746", "0.61289746", "0.6128398", "0.61024445", "0.609877", "0.60802794", "0.60538113", "0.60538113", "0.6029418", "0.5988028", "0.59795785", "0.59772706", "0.5966684", "0.59642637", "0.5950529", "0.5932895", "0.58932084", "0.5876217", "0.58306557", "0.58261013", "0.5814536", "0.58080953", "0.5791708", "0.57863283", "0.5786253", "0.5772792", "0.5766447", "0.5764969", "0.5759179", "0.5756909", "0.5745871", "0.57445294", "0.57438785", "0.5743218", "0.5731803", "0.5724351", "0.5718082", "0.57144505", "0.5708807", "0.5703959", "0.57015556", "0.56995565", "0.56948626", "0.56528914", "0.56500626", "0.5649674", "0.5647804", "0.5629306", "0.5625427", "0.5625427", "0.5625427", "0.5625427", "0.56200314", "0.5616473", "0.5613282", "0.56074905", "0.5587287", "0.5586592", "0.5585103", "0.5585103", "0.55810225", "0.5580808", "0.5579344", "0.5577915", "0.5571333", "0.55707115", "0.5567515", "0.5567515", "0.555793", "0.55551136", "0.55549455", "0.55510855", "0.55501825", "0.554947", "0.5548902", "0.5545852", "0.5544809", "0.5543965", "0.55399007", "0.5538573", "0.5535695", "0.5535695", "0.5531208", "0.55306333", "0.55272895", "0.55267173", "0.5525985", "0.55156493", "0.5515447", "0.55088884", "0.55088747", "0.5507126" ]
0.0
-1
Set the callback to be invoked when a stream is cancelled.
def on_cancel &b @cancel_proc = b self end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def cancel()\n @callback = nil\n @cancelled = true\n end", "def cancel!\n @callback = nil\n end", "def cancel!\n # The simplest way to keep track of cancelled status is to nullify the\n # callback. This should also be optimal for garbage collection.\n @callback = nil\n end", "def cancel!\n\t\t\t\t# The simplest way to keep track of cancelled status is to nullify the\n\t\t\t\t# callback. This should also be optimal for garbage collection.\n\t\t\t\t@callback = nil\n\t\t\tend", "def cancel_callback\n Interface::midiin_cancel_callback(@midiin)\n end", "def cancellation_handler\n lambda do\n if not @_cancelled\n on_cancellation.call\n connection.close\n @_cancelled = true\n end\n end\n end", "def cancel_event(msg = nil)\n raise CallbackError.new(msg)\n end", "def on_cancelled(&block)\n @handlers[:cancelled] = block\n self\n end", "def emit_cancel sid, error\n @cancel_proc.call sid, error if @cancel_proc\n end", "def cancelled?\n @callback.nil?\n end", "def cancelled?\n @callback.nil?\n end", "def call_cancel_handler; call_handler(:cancel); end", "def cancelled?\n\t\t\t\t@callback.nil?\n\t\t\tend", "def cancelled!\n @cancelled = true\n end", "def on_close(&callback)\n @close_cb = callback\n end", "def onCancel(flag, view)\n self.reset(view)\n end", "def on_disconnect(&callback)\n @disconnect_cb = callback\n end", "def setCB(callback)\n @callbackfn = callback\n end", "def cancel\n @error = :cancelled\n end", "def cancel stream_id, code\n # TODO: @streams[stream_id].close_local!\n g = Frame.new FrameTypes::RST_STREAM, 0x00, stream_id, [code].pack('N')\n send_frame g\n end", "def stream_close\n self[STREAM_CLOSE].call\n end", "def cancel!\n state_guard { modify_call 'Status' => 'cancelled' }\n end", "def on_abort &proc\n @abort_hadnler = proc\n end", "def on_exit_status(&callback)\n @stream_callbacks[:exit_status] = callback\n end", "def onCancel flag, view\n ## puts \"onCancel called\"\n\t\tself.reset(view)\n\tend", "def unbind\n if not @callback.nil?\n @callback.call(@buffer)\n end\n end", "def cancel\r\n # @todo Emit a warning for attempts to cancel an action after it's been\r\n # executed\r\n @cancelled = true\r\n end", "def shutdown(callback)\n @shutdown_callback = callback\n return self\n\tend", "def callback=(proc)\n # Save proc to instance variable so that GC doesn't free\n # the proc object before the transfer.\n @callback_proc = proc do |pTrans|\n proc.call(self)\n end\n @transfer[:callback] = @callback_proc\n end", "def onCancel(flag, view)\n self.reset(view)\nend", "def callback_handler_remove\n rl_callback_handler_remove\n @rl_callback_handler = nil\n end", "def cancel!; end", "def cancelled?; end", "def cancel\n @procedure&.cancel\n @cancel = true\n self\n end", "def cancellation_handler(&block)\n @cancellation_task = lambda { |cause| block.call(@handle, cause) }\n end", "def on_error(&callback)\n @err_cb, @err_cb_overridden = callback, true\n end", "def _on_cancel(fei, flavour)\n Ruote.participant_send(\n self, [ :on_cancel, :cancel ], 'fei' => fei, 'flavour' => flavour)\n end", "def cancel\n if not @complete\n @complete = ::Libuv::Ext.cancel(@pointer) >= 0\n end\n @complete\n end", "def cancel\n super\n end", "def cancel\n super\n end", "def cancel\n super\n end", "def cancel\n # Define this later\n end", "def cancel\n super\nend", "def on_error(&callback)\n @err_cb, @err_cb_overridden = callback, true\n end", "def cancel\n super\n end", "def cancel\n super\n end", "def cancel\n super\n end", "def cancel\n super\n end", "def cancel\n super\n end", "def cancel\n super\n end", "def cancel\n super\n end", "def cancel\n super\n end", "def cancel\n super\n end", "def cancel\n super\n end", "def cancel\n super\n end", "def cancel\n super\n end", "def cancel\n super\n end", "def cancel\n super\n end", "def cancel\n super\n end", "def cancel\n super\n end", "def cancel\n super\n end", "def cancel\n super\n end", "def cancel\n # TODO: That thing I'm claiming to do in the comments\n super\n end", "def cancel; end", "def cancel; end", "def cancel\n super\n end", "def on_start=(callback)\n weak = WeakRef.new(self)\n\n Dispatch::Queue.main.async do\n if weak\n callback.call unless weak.isCancelled\n end\n end\n end", "def on_disconnect(&callback)\n @disconnect_cb = callback\n @client.on_disconnect(&callback) unless @client.nil?\n end", "def disconnected_callback(callback, &block)\n\t\t\t@disconnected = callback || block\n\t\tend", "def on_timeout=(callback)\n @timeout_callback = callback\n end", "def cancel\n self.class.cancel(self)\n end", "def restore_failure_callback\n @failure_callback = DEFAULT_FAILURE_CALLBACK\n end", "def remove_callback(callback_name)\n connection.remove_callback(callback_name)\n end", "def on_close(&callback)\n @close_cb = callback\n @client.on_close(&callback) unless @client.nil?\n end", "def off(callback_name)\n raise(ArgumentError, \"Argument 'callback_name' must be a String.\") unless callback_name.is_a?(String)\n @procs_callback.delete(callback_name)\n return self\nend", "def cancel_when_closed\n\n [] # by default, no effect\n end", "def cancelondisconnect(state, &blk)\n raise 'This API endpoint cannot be used over HTTP.' unless block_given?\n\n websocket.subscribe :cancelondisconnect, params: { state: state, auth: true }, &blk\n end", "def cancel\n end", "def cancel\n end", "def cancel_enabled?; handle?(:cancel); end", "def process_cancel\n Sound.play_cancel\n Input.update\n deactivate if @symbol.nil?\n @symbol = nil\n call_cancel_handler\n end", "def callback\n EM.Callback do\n if @readers.none?(&:running?)\n EM.stop_event_loop\n end\n end\n end", "def cancel!\n self.type = :unsubscribed\n reply_if_needed!\n end", "def on_end(&callback)\n @end_callback = callback\n end", "def initialize(callback)\n @callback = callback\n @buffer = \"\"\n super()\n reset\n end", "def stop_all_streams; end", "def callback\n @callback ||= :value.to_proc\n end", "def unbind\n if @current_state == 'streaming'\n @parser.parse_unflushed_data\n end\n\n if !@intentionally_closed\n setup_reconnect\n end\n\n execute_callback(@connection_close_callback)\n @current_state = 'init'\n end", "def on_closed(&block)\n define_callback :disconnect, &block\n end", "def on_error(&callback)\n @on_error = callback\n end", "def cancel\n throw(:abort)\n end", "def cancel\n self.update_status :cancelled\n end", "def cancel ; @finished = true ; @buff = '' ; end", "def cancel!\n update(request_cancelled: true)\n end", "def on_cancel\n\n doc = fetch(fei)\n\n return unless doc\n\n r = @context.storage.delete(doc)\n\n on_cancel(fei, flavour) if r != nil\n end", "def set_Callback(value)\n set_input(\"Callback\", value)\n end", "def on_finish=(callback)\n @finish_callback = callback\n end", "def close_on_exec=(value)\n # Do nothing.\n end", "def cancelled?\n !@call.status.nil? && @call.status.code == Core::StatusCodes::CANCELLED\n end", "def on_no_data_received &block\n @no_data_received_callback = block\n end" ]
[ "0.78955865", "0.76355064", "0.76210225", "0.7489106", "0.67421764", "0.66237724", "0.6587204", "0.6572214", "0.6509801", "0.6430958", "0.63600487", "0.6304011", "0.62445414", "0.6043354", "0.60068184", "0.58935237", "0.5841838", "0.58389264", "0.5814512", "0.5808875", "0.5803096", "0.57628", "0.5754049", "0.57433546", "0.5742805", "0.57290035", "0.57074255", "0.5701525", "0.56888837", "0.5688526", "0.5677851", "0.5671471", "0.5664978", "0.5637346", "0.5586189", "0.55831486", "0.5573212", "0.5557889", "0.55490637", "0.55490637", "0.55490637", "0.55486107", "0.5528853", "0.5511154", "0.5501499", "0.5501499", "0.5501499", "0.5501499", "0.5501499", "0.5501499", "0.5501499", "0.5501499", "0.5501499", "0.5501499", "0.5501499", "0.5501499", "0.5501499", "0.5501499", "0.5501499", "0.5501499", "0.5501499", "0.54947746", "0.54664636", "0.5458899", "0.5458899", "0.54318035", "0.5415023", "0.54092354", "0.5408739", "0.5375097", "0.5360834", "0.535862", "0.53582764", "0.5357212", "0.5353902", "0.53355193", "0.52951837", "0.5277364", "0.5277364", "0.52675235", "0.52663034", "0.5252327", "0.5249783", "0.5246632", "0.5232546", "0.5228866", "0.5221383", "0.5196254", "0.51892346", "0.51888174", "0.517497", "0.51518124", "0.5144758", "0.5137946", "0.5135836", "0.5130094", "0.51156265", "0.51096433", "0.5097066", "0.5085609" ]
0.7140782
4
wrap a TCPSocket e.g.: require 'socket' server = TCPServer.new 4567 http_client.wrap server.accept
def wrap s raise "already wrapped a socket!" if @socket @socket = s if defined? OpenSSL::SSL::SSLSocket and s.is_a? OpenSSL::SSL::SSLSocket @descr = s.io.remote_address.inspect_sockaddr else @descr = s.remote_address.inspect_sockaddr end @sil = FrameSerialiser.new {|b| cyan "@sil: _write #{hex b}" _write s, b rescue nil } @dsil = FrameDeserialiser.new do |f| begin brown "dsil: received #{frm f}" @hook << f rescue ConnectionError => e @logger.info "connection error [#{e.code}:#{e}] in client #{@descr} {1}" die e.code end end handle_prefaces s send_frame Settings.frame_from(initial_settings), true loop do bytes = begin s.readpartial(4*1024*1024) rescue EOFError nil rescue IOError, Errno::ECONNRESET raise unless s.closed? end if bytes.nil? or bytes.empty? @logger.info "client disconnected from #{@descr}" break end red "read #{hex bytes}" @dsil << bytes Thread.pass end rescue ConnectionError => e @logger.info "connection error [#{e.code}:#{e}] in client #{@descr} {2}" die e.code ensure _close_socket end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def accept\n while true\n s = @socket.accept\n break if (@acl ? @acl.allow_socket?(s) : true)\n s.close\n end\n if @config[:tcp_original_host].to_s.size == 0\n uri = \"druby://#{s.addr[3]}:#{@config[:tcp_port]}\"\n else\n uri = @uri\n end\n self.class.new(uri, s, @config)\n end", "def cork_socket(socket); end", "def set_socket\r\n @socket = TCPSocket.new(@server, @port) \r\n end", "def accept_client_connection\n Thread.start(socket_server.accept) do |client_socket|\n if client_socket.is_a?(OpenSSL::SSL::SSLSocket)\n begin\n client_socket.accept\n rescue OpenSSL::SSL::SSLError => e\n logger.warn e.message\n client_socket.close rescue true\n Thread.exit\n end\n end\n process_request(client_socket)\n end\n end", "def socket_accept\n Error.translate do\n socket = to_io.accept_nonblock\n\n ssl_socket = OpenSSL::SSL::SSLSocket.new(\n socket,\n @ssl_context\n )\n ssl_socket.sync_close = true\n ssl.accept if @start_immediately\n ssl_socket\n end\n rescue IO::WaitReadable, IO::WaitWritable\n rescue Error => e\n close e\n end", "def sockopen(host, port)\n socket = nil\n msg = nil\n timeout = 5.0\n socket = turbina_timeout(timeout, proc {TCPSocket.open(host, port)})\n return socket\n end", "def with_socket\n set_client_id unless @set_client_id.nil?\n\n yield(socket)\n end", "def accept\n\tsocket = @server.accept\n\tsend_handshake(socket) && Connection.new(socket)\n end", "def socket\n @socket ||= TCPSocket.new(host, port)\n end", "def tls_socket socket\n socket = OpenSSL::SSL::SSLSocket.new socket, create_ssl_context\n socket.sync_close = true\n socket.hostname = @host unless RE_IP_ADDR.match(@host)\n socket.connect\n socket\n end", "def talk_to_server(host, port, request)\n socket = TCPSocket.open(host, port)\n socket.print(request)\n response = socket.read\n socket.close\n\n response\nend", "def accept_connection(tcp)\n counter = counter ? counter + 1 : 1\n\n sock = BasicSocket.for_fd(tcp.sysaccept)\n sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_NOSIGPIPE, true) if Socket.const_defined? :SO_NOSIGPIPE\n sock\n rescue RuntimeError => e\n counter == 1 ? retry : raise(e)\n end", "def client(&block)\n if options[:socket]\n UNIXSocket.open(options[:socket], &block)\n else\n TCPSocket.open(options[:host], options[:port], &block)\n end\n rescue Errno::EACCES\n sock = options[:socket] || \"#{options[:host]}:#{options[:port]}\"\n raise ServiceError, \"unable to open socket: #{sock} (check permissions)\"\n end", "def connect_to_server\n @socket = TCPSocket.open(@serverip, @serverport)\n end", "def connect_using_proxy(socket); end", "def connect()\n @sock = TCPSocket.open(@server, @port)\n end", "def open_socket(host, domain = nil, timeout = 5, port = 22, &_block)\n Timeout.timeout(timeout) do\n target_host = host\n target_host = \"#{host}.#{domain}\" if domain\n sock = TCPSocket.new target_host, port\n begin\n yield sock if block_given?\n ensure\n sock.close\n end\n end\n end", "def accept_socket(server, options)\n waiting = accept_nonblock server\n if [:r, :w].include? waiting\n logger.warn \"Expected to receive new connection, but the server is not quite ready\"\n return\n end\n logger.debug \"Receiving new connection #{waiting} on port #{options[:port]}\"\n if options[:ssl_context]\n logger.debug \"Upgrading Connection #{waiting} to ssl\"\n ssl = upgrade_to_ssl(waiting, options)\n try_accept_nonblock ssl do\n logger.info \"Incoming connection #{waiting} upgraded to #{ssl}\"\n yield ssl\n end\n else\n yield waiting\n end\n end", "def open_socket()\n socket = nil\n if @socket\n socket = @socket\n else\n Timeout::timeout(@sock_timeout) { socket = TCPSocket.new(@server, @port) }\n BasicSocket.do_not_reverse_lookup = true\n end\n\n return(socket)\n end", "def connect\n sock = TCPSocket.new(@host, @port)\n if @ssl\n sock = OpenSSL::SSL::SSLSocket.new(sock)\n sock.sync_close = true\n sock.connect\n sock.post_connection_check(@host) if @verify_ssl\n end\n sock\n end", "def connect\n socket = TCPSocket.new(@server, @port.to_i)\n if @options[:ssl] == nil\n return socket\n end\n ssl_context = @options[:ssl]\n ssl_context = OpenSSL::SSL::SSLContext.new()\n unless ssl_context.verify_mode\n warn \"warning: peer certificate won't be verified this session.\"\n ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE\n end\n ssl_socket = OpenSSL::SSL::SSLSocket.new(socket, ssl_context)\n ssl_socket.sync_close = true\n ssl_socket.connect\n return ssl_socket\n end", "def open_socket\n loop {\n listen_for_client\n\n # read first input line only\n request = @client.gets\n\n resp = process_client_request(request)\n headers = generate_headers(resp)\n\n @client.puts headers\n @client.puts resp\n\n @client.puts \"Disconnecting client...\"\n @client.close # close connection to client\n }\n end", "def create_outbound_tcp_socket\n label = \"#{@remote_host}:#{@remote_port}\"\n if @proxy_url\n log.info(\"Connecting to #{label} through proxy #{@proxy_url}\")\n\n popts = {}\n popts[:user_agent] = ENV['HTTP_USER_AGENT'] if ENV['HTTP_USER_AGENT']\n\n if popts[:user_agent]\n log.debug('Passing User-Agent: ' + popts[:user_agent].inspect)\n end\n\n @proxy = Proxifier::Proxy(@proxy_url, popts)\n tcp_socket = @proxy.open(@remote_host, @remote_port)\n else\n log.info(\"Connecting to #{label}\")\n tcp_socket = TCPSocket.new(@remote_host, @remote_port)\n end\n\n if @use_ssl\n create_ssl_socket(tcp_socket, @ssl_opts)\n else\n tcp_socket\n end\n end", "def socket\n return @socket if @socket\n s = TCPSocket.new(host || '127.0.0.1', port || 2003) # CORRECT DEFAULT PORT?\n @socket = s\n @socket\n rescue ::SystemExit, ::Interrupt, ::SignalException\n raise\n rescue ::Exception => exc\n STDERR.puts \"#{self} socket: failed #{exc.inspect}\\n #{exc.backtrace * \"\\n \"}\"\n sleep 10\n retry\n end", "def connect(socket_class, host, port, nodelay = T.unsafe(nil)); end", "def accept_client\n client = self.accept\n @sockets << client\n end", "def open( host, port )\n sock = TCPSocket.new( @proxy_host, @proxy_port )\n\n ip_addr = IPAddr.new( Resolv.getaddress( host ) )\n \n packet = [ SOCKS_VERSION, SOCKS_CMD_CONNECT,\n port.to_i, ip_addr.to_i,\n proxy_user, 0 ].pack( \"CCnNA*C\" )\n sock.send packet, 0\n\n version, status, port, ip = sock.recv( 8 ).unpack( \"CCnN\" )\n if status != SOCKS_GRANTED\n sock.close\n raise ConnectError, \"error connecting to proxy (#{status})\"\n end\n\n return sock\n end", "def handler(sock)\n end", "def accept_nonblock\n return if closed?\n\n fcntl(Fcntl::F_SETFL, Fcntl::O_NONBLOCK)\n\n fd = nil\n sockaddr = nil\n\n FFI::MemoryPointer.new 1024 do |sockaddr_p| # HACK from MRI\n FFI::MemoryPointer.new :int do |size_p|\n fd = Socket::Foreign.accept descriptor, sockaddr_p, size_p\n end\n end\n\n Errno.handle 'accept(2)' if fd < 0\n\n # TCPServer -> TCPSocket etc. *sigh*\n socket = self.class.superclass.allocate\n IO.setup socket, fd, nil, true\n socket\n end", "def socket_loop\n @socket.listen\n loop do\n client_socket, client_addr = @socket.accept\n Thread.new(client_socket) { |client_socket| serve_client client_socket } \n end\n @manager.tem_ports\n end", "def accept_client_connection\n Thread.start(socket_server.accept_nonblock) do |client_socket|\n logger.debug \"Accepted connection from #{client_socket.peeraddr.last}\"\n process_request(client_socket)\n end\n end", "def socket_setup()\n ctx = { 'Msf' => self.options['Msf'], 'MsfExploit' => self.options['MsfExploit'] }\n self.socket = case self.handle.protocol\n\n when 'ncacn_ip_tcp'\n Rex::Socket.create_tcp(\n 'PeerHost' => self.handle.address,\n 'PeerPort' => self.handle.options[0],\n 'Context' => ctx,\n 'Timeout' => self.options['connect_timeout']\n )\n\n when 'ncacn_np'\n begin\n socket = Rex::Socket.create_tcp(\n 'PeerHost' => self.handle.address,\n 'PeerPort' => 445,\n 'Context' => ctx,\n 'Timeout' => self.options['connect_timeout']\n )\n rescue ::Timeout::Error, Rex::ConnectionRefused\n socket = Rex::Socket.create_tcp(\n 'PeerHost' => self.handle.address,\n 'PeerPort' => 139,\n 'Context' => ctx,\n 'Timeout' => self.options['connect_timeout']\n )\n end\n socket\n else nil\n end\n\n # Add this socket to the exploit's list of open sockets\n options['MsfExploit'].add_socket(self.socket) if (options['MsfExploit'])\n end", "def create_server_socket\n if @hostname\n s = TCPServer.open(@hostname, @port)\n else\n s = TCPServer.open(@port)\n end\n @port = s.addr[1]\n\n s.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEADDR, true)\n\n return s\n end", "def run\n use(@inline_handler)\n @socket = TCPServer.new(@host, @port)\n @handlers = @handlers.uniq.freeze\n @options = @options.freeze\n @acceptor = Thread.new do \n begin\n logger.debug \"Starting leech server on tcp://#{@host}:#{@port}\"\n loop do \n begin\n client = @socket.accept \n worker_list = @workers.list\n \n if worker_list.length >= @max_workers\n logger.error \"Server overloaded with #{worker_list.length} workers (#@max_workers max). Dropping connection.\"\n client.close rescue nil\n reap_dead_workers(\"max processors\")\n else\n thread = Thread.new(client) {|c| process_client(c) }\n thread[:started_on] = Time.now\n @workers.add(thread)\n sleep @throttle if @throttle > 0\n end\n rescue StopServer\n break\n rescue Errno::EMFILE\n reap_dead_workers(\"too many open files\")\n sleep 0.5\n rescue Errno::ECONNABORTED\n client.close rescue nil\n rescue Object => e\n logger.error \"#{Time.now}: Unhandled listen loop exception #{e.inspect}.\"\n logger.error e.backtrace.join(\"\\n\")\n end\n end\n graceful_shutdown\n ensure\n @socket.close \n logger.debug \"Closing leech server on tcp://#{@host}:#{@port}\"\n end\n end\n \n return @acceptor\n end", "def socket; @socket; end", "def real_connect(*args)\n super(*args)\n @fd = socket\n @io = IO.new(socket)\n end", "def create_client_socket\n\t\tself.log.debug \"Creating a CLIENT socket bound to: %s\" % [ self.server ]\n\t\tsock = CZTop::Socket::CLIENT.new\n\n\t\tclient_cert = Assemblage::Auth.local_cert\n\t\tserver_cert = Assemblage::Auth.remote_cert( 'server' )\n\n\t\tself.log.debug \"Connecting with %p and %p\" % [ client_cert, server_cert ]\n\t\tsock.CURVE_client!( client_cert, server_cert )\n\t\tsock.connect( self.server )\n\n\t\treturn sock\n\tend", "def listen(socket = nil)\n @socket ||= socket\n \n # we also need a small collector thread that does nothing\n # but pull threads off the thread queue and joins them\n @collector = Thread.new do\n while t = @threads.shift\n collect_thread(t)\n @total_conns += 1\n end\n end\n \n thread = Thread.new do\n loop do\n handle_client(@socket.accept)\n break if @shutdown and @threads.length <= 0\n end\n end\n \n # and then collect the listener thread which blocks until it exits\n collect_thread(thread)\n \n @socket.close unless @socket.closed?\n @dead = true\n @log.info(\"Exited accept loop. Shutdown complete.\")\n end", "def create_ssl_socket\n ctx = OpenSSL::SSL::SSLContext.new\n ctx.set_params ssl_version: :TLSv1_2\n\n socket = TCPSocket.new(@uri.host, @port)\n OpenSSL::SSL::SSLSocket.new(socket, ctx)\n end", "def open(tout=5.5)\n puts \"INFO: start to connecting to server\"\n begin \n Timeout.timeout(tout) do\n @sock = TCPSocket.open(@host, @port)\n end\n rescue Exception => e\n puts \"ERROR: connection to server failed\"\n puts e.message\n puts e.backtrace.inspect\n return\n end\n @connected = true\n=begin\n\nsock = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)\ntimeval = [3, 0].pack(\"l_l_\")\nsock.setsockopt Socket::SOL_SOCKET, Socket::SO_RCVTIMEO, timeval\nsock.connect( Socket.pack_sockaddr_in(1234, '127.0.0.1'))\n=end\n\n end", "def bind_socket(family,port,ip)\n socket = Socket.new(family, SOCK_STREAM, 0)\n sockaddr = Socket.sockaddr_in(port.to_i,ip)\n socket.setsockopt(:SOCKET, :REUSEADDR, true)\n socket.bind(sockaddr)\n socket.listen(0)\n return socket\n end", "def setup_socket\n self.socket = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)\n address = Socket.pack_sockaddr_in(@options[:port], @options[:host])\n socket.bind(address)\n socket.listen(@options[:max_connection_queue])\n log.info(\"Listening on #{@options[:host]}:#{@options[:port]}\")\n end", "def start(io)\n # start SSL negotiation\n ssl = OpenSSL::SSL::SSLSocket.new(io, @ssl_context)\n # connect to server socket\n ssl.accept\n # make sure to close also the underlying io\n ssl.sync_close = true\n # return as new io socket\n return ssl\n end", "def serve\n while true\n client = nil\n\n # accept connection\n\n begin\n client = @socket.accept\n rescue => err\n @server.log(err.inspect, err)\n @server.heraldize('fizzie! Socket server trouble (in accept)! ' + err.inspect)\n break\n end\n\n # serve client\n\n begin\n refused = handle(client)\n unless refused.nil?\n client.send(\"error\\n#{refused}\\n\", 0)\n client.close\n end\n rescue => err\n begin\n client.close unless client.closed?\n rescue\n # just ignore\n end\n @server.log(err.inspect, err)\n end\n end\n end", "def proxified_socket(host, port)\n proxy = ENV[\"https_proxy\"] || ENV[\"http_proxy\"] || false\n\n if proxy && !fuzzy_hostname_match_any?(host, ENV[\"no_proxy\"])\n Proxifier.Proxy(proxy).open(host, port)\n else\n TCPSocket.new(host, port)\n end\n end", "def stream(socket); end", "def open_socket()\n used_socket = @ssl ? open_ssl_socket : open_tcp_socket\n # try to close the old connection if any\n close_socket\n\n @closed = false\n if @parameters # nil in some rspec tests\n unless @reconnect_delay\n @reconnect_delay = @parameters[:initial_reconnect_delay] || iosto1\n end\n end\n # Use keepalive\n used_socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)\n\n # TCP_NODELAY option (disables Nagle's algorithm)\n used_socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, !!(@parameters && @parameters[:tcp_nodelay]))\n\n @iosto = @parse_timeout ? @parse_timeout.to_f : 0.0\n\n used_socket\n end", "def accept\n begin\n # accept loop\n while true\n soc = @socket.accept\n break if (@acl ? @acl.allow_socket?(soc) : true)\n soc.close\n end\n\n if Global.show_communication\n puts \"someone connected to relay socket...\"\n end\n\n # build ssl\n ssl = @config.accept(soc)\n\n # relay auth like HTTP's digest method\n ssl.puts(Global.relay_realm)\n uuid = Util::UUID.generate\n ssl.puts(uuid)\n if msg = ssl.gets\n name, digest = msg.chomp.split(\":\")\n unless Global.relay_client_db.auth(uuid, name, digest)\n raise AuthError.new(name)\n end\n ssl.puts \"OK\"\n\n if Global.show_communication\n puts \"succeeded authentication for %s\" % name\n end\n\n # setup transmitter_id\n transmitter_id = Util::UUID.generate\n\n # save ssl socket as receiver side with transmitter_id\n TransmitterSocket.receiver_socket[transmitter_id] = ssl\n\n # open and save tcp socket with transmitter_id\n Global.relay_transmitter_proxy_side_port_range.each do |port|\n begin\n tcp_socket = TCPServer.new(\"localhost\", port)\n TransmitterSocket.proxy_socket[transmitter_id] = tcp_socket\n break\n rescue\n end\n end\n\n # create servers\n transmitter_server = create_transmitter_server(transmitter_id)\n proxy_server = create_proxy_server(transmitter_id)\n\n # start to provide the proxy server\n TupleSpaceProvider.instance.add_tuple_space_server(\n DRb::DRbObject.new_with_uri(proxy_server.uri)\n )\n\n # create instance\n self.class.new(uri, ssl, @config, true)\n else\n raise BadMessage\n end\n rescue OpenSSL::SSL::SSLError, AuthError, BadMessage => e\n soc.close\n Log::Debug.communication(\"relay socket was closed: %s\" % e.message)\n retry\n end\n end", "def getSslTcpConnection(host, port)\n store = OpenSSL::X509::Store.new\n store.add_file(OpenSSL::X509::DEFAULT_CERT_FILE)\n sslContext = OpenSSL::SSL::SSLContext.new\n sslContext.cert_store = store\n sslContext.ssl_version = :SSLv23\n sslSocket = OpenSSL::SSL::SSLSocket.new(TCPSocket.new(host, port), sslContext)\n sslSocket.hostname = host #for Server Name Indication (SNI)\n sslSocket.sync_close = true #instead of calling close on tcp socket\n sslSocket.connect\n sslSocket\nend", "def open(host, port, connection_options)\n socket = Socket.tcp(proxy_host, proxy_port, nil, nil,\n connect_timeout: connection_options[:timeout])\n ip_addr = IPAddr.new(Resolv.getaddress(host))\n\n packet = [VERSION, CONNECT, port.to_i, ip_addr.to_i, options[:user]].pack(\"CCnNZ*\")\n socket.send packet, 0\n\n version, status, port, ip = socket.recv(8).unpack(\"CCnN\")\n if status != GRANTED\n socket.close\n raise ConnectError, \"error connecting to proxy (#{status})\"\n end\n\n return socket\n end", "def socket; end", "def socket; end", "def socket; end", "def socket; end", "def socket; end", "def tcp_socket\n TCPSocket.new(host, port).tap do |socket|\n socket.setsockopt(::Socket::IPPROTO_TCP, ::Socket::TCP_NODELAY, true)\n end\n end", "def start(io)\n # start SSL negotiation\n ssl = OpenSSL::SSL::SSLSocket.new(io, @ctx)\n # connect to server socket\n ssl.accept\n # make sure to close also the underlying io\n ssl.sync_close = true\n # return as new io socket\n return ssl\n end", "def start(io)\n # start SSL negotiation\n ssl = OpenSSL::SSL::SSLSocket.new(io, @ctx)\n # connect to server socket\n ssl.accept\n # make sure to close also the underlying io\n ssl.sync_close = true\n # return as new io socket\n return ssl\n end", "def prepare_socket_server!\n _log { \"prepare_socket_server! #{port}\" }\n @server = TCPServer.open(port)\n @server.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, false)\n end", "def open_connection\n @connection = TCPSocket.new(server, port)\n @context = OpenSSL::SSL::SSLContext.new\n @context.cert = @cert\n @context.key = @key\n\n @socket = OpenSSL::SSL::SSLSocket.new(@connection, @context) if @connection\n @socket.sync_close = true\n @socket.connect\n\n get_frame\n end", "def accept_new_connection\n newsock = @serverSocket.accept\n @descriptors.push( newsock )\n end", "def listen &block\n register_accept_listener &block if block_given?\n \n @accept_thread ||= Thread.new do\n loop do\n # Package in an Ionian::Socket\n begin\n client = Ionian::Socket.new @server.accept\n @accept_listeners.each { |listener| listener.call client }\n rescue Errno::EBADF\n # This ignores the connection if the client closed it before it\n # could be accepted.\n rescue IOError\n # This ignores the connection if the client closed it before it\n # could be accepted.\n end\n end\n end\n end", "def mock_socket(ip,port)\n addr = [\"\",port,ip.split('.')]\n sock = stub(\"client socket\")\n peername = stub(\"peer name\")\n sock.stubs(:getpeername).returns(peername)\n peername.stubs(:unpack).returns(addr)\n sock\n end", "def serve_token_once_tcp(token, timeout=5)\n server = TCPServer::new(0)\n port = server.addr[1]\n thr = Thread.start do\n begin\n sock = Timeout::timeout(timeout) { server.accept }\n\n sock.write(token)\n ensure\n sock.close if sock\n server.close\n end\n end\n\n return [port, thr]\n end", "def initialize(host='127.0.0.1')\n @sock = Socket.new(:INET, :STREAM)\n @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEADDR, true)\n @sock.bind(Socket.sockaddr_in(0, host))\n @host, @port = @sock.connect_address.ip_unpack\n @addr = \"#{@host}:#{@port}\"\n if block_given?\n begin\n yield self\n ensure\n close\n end\n end\n end", "def bind(socket, actor)\n @mutex.lock(socket: socket, timeout: grace_timeout) do\n executor = Executor.new(actor: actor, socket: socket, serializer: @serializer)\n executor.run_before_example = method(:run_before_example)\n executor.run_after_example = method(:run_after_example)\n executor.run_around_command = method(:run_around_command)\n\n socket.onopen do\n puts \"Happybara: client connected.\".green\n end\n\n socket.onmessage do |payload|\n executor.handle_message(payload)\n end\n\n socket.onclose do\n puts \"Happybara: client disconnected.\".green\n end\n end\n\n nil\n end", "def start(clientHandlerProc)\n @socket = Socket.new( AF_INET, SOCK_STREAM, 0 )\n sockaddr = Socket.pack_sockaddr_in( @port, @addr )\n @socket.setsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR, true)\n @socket.bind( sockaddr )\n @socket.listen( 5 )\n\n yield if block_given?\n\n while true\n break if @exit\n\n sleep 0.1\n\n clientSock = nil\n begin\n clientSock, client_sockaddr = @socket.accept_nonblock\n rescue\n # Error, or nothing to accept.\n next\n end\n\n port, addr = Socket.unpack_sockaddr_in(client_sockaddr)\n if @doLog\n $logger.info \"Server: Got connection from #{addr}:#{port}\" if @doLog\n end\n Thread.new(clientSock, addr, port){ |clientSock, addr, port|\n begin\n clientHandlerProc.call(clientSock, addr, port)\n rescue => e\n $logger.error \"Server: exception in client handler proc: #{$!}\"\n $logger.error e.backtrace.join(\" \")\n end\n }\n end\n @socket.close\n $logger.info \"Server: exiting\" if @doLog\n end", "def tcp(**opts, &callback)\n TCP.new(@reactor, progress: callback, **opts)\n end", "def send_message(message) \n @SocketHandle = TCPSocket.open(@Host,@Port)\n @SocketHandle.puts message \n server_reply = @SocketHandle.gets \n\n server_reply \n end", "def simple_socket()\n\n\thostname = 'localhost'\n\tport = 2000\n\n\ts = TCPSocket.open(hostname, port)\n\n\twhile line = s.gets # Read lines from the socket\n\t puts line.chop # And print with platform line terminator\n\tend\n\ts.close # Close the socket when done\nend", "def prepare_tcp_server(host: T.unsafe(nil), port: T.unsafe(nil), adapter: T.unsafe(nil)); end", "def connect(global = true, opts={})\r\n\r\n self.sock = super(global, opts)\r\n\r\n if datastore['NRPESSL'] or @force_ssl\r\n ctx = OpenSSL::SSL::SSLContext.new(\"TLSv1\")\r\n ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE\r\n ctx.ciphers = \"ADH\"\r\n\r\n @ssl_socket = OpenSSL::SSL::SSLSocket.new(self.sock, ctx)\r\n\r\n @ssl_socket.connect\r\n\r\n self.sock.extend(Rex::Socket::SslTcp)\r\n self.sock.sslsock = @ssl_socket\r\n self.sock.sslctx = ctx\r\n end\r\n\r\n return self.sock\r\n end", "def checkout_new_socket\n begin\n socket = TCPSocket.new(@host, @port)\n socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)\n rescue => ex\n raise ConnectionFailure, \"Failed to connect socket: #{ex}\"\n end\n @sockets << socket\n @checked_out << socket\n socket\n end", "def tcp_socket_request\n Timeout.timeout(request_timeout) do\n s = TCPSocket.new(host, port)\n s.close\n end\n rescue Errno::ECONNREFUSED => e\n addl_message = \"#{host} is not accepting connections on port #{port}: \"\n raise ConnectionFailed, addl_message + e.message\n rescue SocketError => e\n addl_message = \"connection to #{host} on port #{port} failed with '#{e.message}': \"\n raise ConnectionFailed, addl_message + e.message\n rescue Timeout::Error => e\n addl_message = \"#{host} did not respond on port #{port} within #{request_timeout} seconds: \"\n raise ConnectionFailed, addl_message + e.message\n rescue => e\n raise ConnectionFailed, e\n end", "def checkout_new_socket(host, port)\n return nil if @all.size >= @size\n\n begin\n socket = TCPSocket.new(host, port)\n socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)\n rescue => ex\n raise ConnectionFailure, \"Failed to connect to host #{@host} and port #{@port}: #{ex}\"\n end\n\n # If any saved authentications exist, we want to apply those\n # when creating new sockets.\n @connection.apply_saved_authentication(:socket => socket)\n\n socket\n end", "def open(host, port, connection_options)\n socket = Socket.tcp(proxy_host, proxy_port, nil, nil,\n connect_timeout: connection_options[:timeout])\n\n methods = [METHOD_NO_AUTH]\n methods << METHOD_PASSWD if options[:user]\n\n packet = [VERSION, methods.size, *methods].pack(\"C*\")\n socket.send packet, 0\n\n version, method = socket.recv(2).unpack(\"CC\")\n if version != VERSION\n socket.close\n raise Net::SSH::Proxy::Error, \"invalid SOCKS version (#{version})\"\n end\n\n if method == METHOD_NONE\n socket.close\n raise Net::SSH::Proxy::Error, \"no supported authorization methods\"\n end\n\n negotiate_password(socket) if method == METHOD_PASSWD\n\n packet = [VERSION, CMD_CONNECT, 0].pack(\"C*\")\n\n if host =~ /^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$/\n packet << [ATYP_IPV4, $1.to_i, $2.to_i, $3.to_i, $4.to_i].pack(\"C*\")\n else\n packet << [ATYP_DOMAIN, host.length, host].pack(\"CCA*\")\n end\n\n packet << [port].pack(\"n\")\n socket.send packet, 0\n\n version, reply, = socket.recv(2).unpack(\"C*\")\n socket.recv(1)\n address_type = socket.recv(1).getbyte(0)\n case address_type\n when 1\n socket.recv(4) # get four bytes for IPv4 address\n when 3\n len = socket.recv(1).getbyte(0)\n hostname = socket.recv(len)\n when 4\n ipv6addr hostname = socket.recv(16)\n else\n socket.close\n raise ConnectError, \"Illegal response type\"\n end\n portnum = socket.recv(2)\n\n unless reply == SUCCESS\n socket.close\n raise ConnectError, \"#{reply}\"\n end\n\n return socket\n end", "def connect\n auth = authentication_prompt()\n\n socket = TCPSocket.new( @server, @port )\n raise RuntimeError, \"Unable to connect to #{@port}\" unless socket\n print \"Connecting at #{Time.now} to #{@port} ... \"\n\n authenticate_with_server( socket, auth[:u], auth[:p] )\n\n return socket\n end", "def server_cast(sock)\n begin\n Socket.unpack_sockaddr_in(sock.getsockname)\n Kgio::TCPServer.for_fd(sock.fileno)\n rescue ArgumentError\n Kgio::UNIXServer.for_fd(sock.fileno)\n end\n end", "def socket\n return @socket if @socket\n linger = @heartbeat_timeout * 1000\n pubkey = Directory[@id].pubkey\n @socket = ClientServer.new @addr, linger, pubkey\n @socket.farewell = farewell\n transition :connected\n @socket\n end", "def accept\n # when @ctx.servername_cb is set, we use a worker thread to run the\n # ssl.accept call. We need to do this because:\n # - We cannot switch fibers inside of the servername_cb proc (see\n # https://github.com/ruby/openssl/issues/415)\n # - We don't want to stop the world while we're busy provisioning an ACME\n # certificate\n if @use_accept_worker.nil?\n if (@use_accept_worker = use_accept_worker_thread?)\n start_accept_worker_thread\n end\n end\n\n # STDOUT.puts 'SSLServer#accept'\n sock, = @svr.accept\n # STDOUT.puts \"- raw sock: #{sock.inspect}\"\n begin\n ssl = OpenSSL::SSL::SSLSocket.new(sock, @ctx)\n # STDOUT.puts \"- ssl sock: #{ssl.inspect}\"\n ssl.sync_close = true\n if @use_accept_worker\n # STDOUT.puts \"- send to accept worker\"\n @accept_worker_fiber << [ssl, Fiber.current]\n # STDOUT.puts \"- wait for accept worker\"\n r = receive\n # STDOUT.puts \"- got reply from accept worker: #{r.inspect}\"\n r.invoke if r.is_a?(Exception)\n else\n ssl.accept\n end\n ssl\n rescue Exception => e\n # STDOUT.puts \"- accept exception: #{e.inspect}\"\n if ssl\n ssl.close\n else\n sock.close\n end\n raise e\n end\n end", "def accept\n Socket.for_fd(sysaccept)\n rescue Eproto\n retry\n end", "def establish_socket_server\n @socket_server = Uninterruptible::Binder.new(server_configuration.bind).bind_to_socket\n\n if server_configuration.tls_enabled?\n @socket_server = Uninterruptible::TLSServerFactory.new(server_configuration).wrap_with_tls(@socket_server)\n end\n @socket_server\n end", "def start_server!; @server = TCPServer.open($port) end", "def start_client(host = T.unsafe(nil), port = T.unsafe(nil)); end", "def serve( sock )\n begin\n\n if authenticate( sock )\n welcome_client( sock )\n\n loop do\n listen( sock )\n end\n end\n\n rescue => e\n puts \"An error occured: #{e.to_s}\"\n raise e\n ensure\n sock.close if sock and !sock.closed?\n end\n end", "def open( host, port )\n connect_string = \"CONNECT #{host}:#{port} HTTP/1.0\"\n\n socket = TCPSocket.new( @proxy_host, @proxy_port )\n socket.puts connect_string\n socket.puts\n\n resp = parse_response( socket )\n\n return socket if resp[:code] == 200\n\n socket.shutdown\n raise ConnectError, resp.inspect unless resp[:code] == 407\n\n user = proxy_user\n passwd = proxy_password\n\n raise UnauthorizedError, \"no proxy user given\" unless user\n\n auth = resp[:headers][\"Proxy-Authenticate\"]\n scheme, parms = auth.split( / /, 2 )\n\n case scheme\n when \"Basic\"\n credentials =\n Base64.encode64( \"#{user}:#{passwd}\" ).gsub( /\\n/, \"\" )\n else\n raise NotImplementedError,\n \"authorization scheme #{scheme.inspect} is not supported\"\n end\n\n socket = TCPSocket.new( @proxy_host, @proxy_port )\n socket.puts connect_string\n socket.puts \"Proxy-Authorization: #{scheme} #{credentials}\"\n socket.puts\n\n resp = parse_response( socket )\n\n raise ConnectError, resp.inspect if resp[:code] != 200\n\n return socket\n end", "def startHttp(callback_opts) do\n server = TCPServer.new @host, @port\n while session = server.accept\n @implementation(session, callback_opts)\n end\n end", "def connect(host, port, use_ssl = false)\n @socket = TCPSocket.new(host, port.to_i)\n if use_ssl\n @socket = OpenSSL::SSL::SSLSocket.new(@socket)\n @socket.sync_close\n @socket.connect\n end\n read_greeting\n end", "def attach_to(ip)\n TCPSocket.instance_eval do\n (class << self; self; end).instance_eval do\n alias_method :original_open, :open\n\n case RUBY_VERSION\n when /1.8/, /1.9/\n define_method(:open) do |conn_address, conn_port|\n original_open(conn_address, conn_port, ip)\n end\n else\n define_method(:open) do |conn_address, conn_port, local_host, local_port|\n original_open(conn_address, conn_port, ip, local_port)\n end\n end\n end\n end\n\n result = begin\n yield\n rescue StandardError => e\n raise e\n ensure\n TCPSocket.instance_eval do\n (class << self; self; end).instance_eval do\n alias_method :open, :original_open\n remove_method :original_open\n end\n end\n end\n\n result\n end", "def tcp\n TCP.new(@loop)\n end", "def bind\n # Bind the socket\n @tcp = @loop.tcp\n @tcp.bind(@options[:host], @port, @new_connection)\n @tcp.listen(@options[:backlog])\n\n # Delegate errors\n @tcp.catch do |e|\n @loop.log :error, 'application bind failed', e\n end\n @tcp\n end", "def initialize() #Isopen is a boolean for if the socket is still open or not\n @socket = TCPServer.open(PortNumber)\n @IsOpen = true\n end", "def with_connection\n tries = 0\n\n @locket.synchronize do\n tries += 1\n yield(socket)\n rescue IOError, Errno::EPIPE, Errno::ECONNREFUSED, InvalidResponse, Timeout::Error,\n Riemann::Client::TcpSocket::Error\n close\n raise if tries > 3\n\n retry\n rescue StandardError\n close\n raise\n end\n end", "def socket\n connect unless connected?\n @ssl_sock\n end", "def send_from_open_connection(message) \n @SocketHandle.puts message \n server_reply = @SocketHandle.gets \n\n server_reply \n end", "def with_connection\n tries = 0\n\n @locket.synchronize do\n begin\n tries += 1\n yield(socket)\n rescue IOError, Errno::EPIPE, Errno::ECONNREFUSED, InvalidResponse, Timeout::Error, Riemann::Client::TcpSocket::Error\n close\n raise if tries > 3\n retry\n rescue Exception\n close\n raise\n end\n end\n end", "def listen(options = {}, server = nil)\n server ||= create_server(options)\n Reactor.queue_task do\n monitor = Reactor.selector.register(server, :r)\n monitor.value = proc do\n accept_socket server, options do |io| # this next block won't run until ssl (if enabled) has started\n adapter = SERVER_ADAPTER.new(io, options)\n yield(adapter.driver, adapter) if block_given?\n Reactor.queue_task do\n adapter.add_to_reactor\n end\n logger.info \"Host accepted client connection #{io} on port #{options[:port]}\"\n end\n end\n end\n Reactor.start\n logger.info \"Host listening for new connections on port \" + options[:port].to_s\n server\n end", "def local_socket(local_socket_path, remote_socket_path); end", "def connect_to_mycroft\n if ARGV.include?(\"--no-tls\")\n @client = TCPSocket.open(@host, @port)\n else\n socket = TCPSocket.new(@host, @port)\n ssl_context = OpenSSL::SSL::SSLContext.new\n ssl_context.cert = OpenSSL::X509::Certificate.new(File.open(@cert))\n ssl_context.key = OpenSSL::PKey::RSA.new(File.open(@key))\n @client = OpenSSL::SSL::SSLSocket.new(socket, ssl_context)\n begin\n @client.connect\n rescue\n end\n end\n end", "def open(host, port, connection_options)\n socket = establish_connection(connection_options[:timeout])\n socket.write \"CONNECT #{host}:#{port} HTTP/1.1\\r\\n\"\n socket.write \"Host: #{host}:#{port}\\r\\n\"\n\n if options[:user]\n credentials = [\"#{options[:user]}:#{options[:password]}\"].pack(\"m*\").gsub(/\\s/, \"\")\n socket.write \"Proxy-Authorization: Basic #{credentials}\\r\\n\"\n end\n\n socket.write \"\\r\\n\"\n\n resp = parse_response(socket)\n\n return socket if resp[:code] == 200\n\n socket.close\n raise ConnectError, resp.inspect\n end" ]
[ "0.6688478", "0.666855", "0.65875596", "0.63295555", "0.6329368", "0.63021624", "0.62836003", "0.62812495", "0.62465173", "0.62204075", "0.620938", "0.61625844", "0.6144681", "0.61268616", "0.6115253", "0.61095124", "0.6090156", "0.6076619", "0.60708207", "0.60624117", "0.60317045", "0.60155797", "0.60096633", "0.6005389", "0.5982147", "0.5981226", "0.5973491", "0.5950364", "0.59359306", "0.59353423", "0.59251505", "0.592458", "0.5910172", "0.5905254", "0.5899168", "0.589678", "0.5874767", "0.58667606", "0.58605003", "0.58432835", "0.5838076", "0.58335656", "0.5826836", "0.5819446", "0.58172", "0.58091885", "0.58086747", "0.58044183", "0.57979983", "0.5795622", "0.57910275", "0.57910275", "0.57910275", "0.57910275", "0.57910275", "0.5789832", "0.5783389", "0.5783389", "0.5779992", "0.5778655", "0.57777333", "0.5771511", "0.5760865", "0.5760368", "0.5759096", "0.5742621", "0.57289183", "0.5726151", "0.57215846", "0.57183343", "0.5712901", "0.5709283", "0.56913763", "0.56881225", "0.5688063", "0.5685991", "0.56847984", "0.56819475", "0.56810975", "0.56796736", "0.56796443", "0.56734747", "0.5664617", "0.56603277", "0.56536204", "0.5650165", "0.56483346", "0.5648313", "0.5648163", "0.56319195", "0.5629823", "0.56294835", "0.56237453", "0.56236804", "0.5615916", "0.5614152", "0.5607393", "0.56031585", "0.56021225", "0.5594359" ]
0.6297075
6
Shut down the connection.
def shut_down @shutdown_lock.synchronize { return if @shutting_down @shutting_down = true } die NO_ERROR end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def shutdown\n @conn.shutdown\n end", "def shutdown_connection\n teardown_timers\n @conn.shutdown if @conn.respond_to? :shutdown\n @conn.terminate if @conn.respond_to? :terminate\n @conn = nil\n end", "def shutdown\n connection.write(\"shutdown\")\n end", "def shutdown\n\t\tself.log.info \"Shutting down.\"\n\t\tself.reactor.stop_polling\n\t\t@conn.close\n\tend", "def shutdown\n @data_socket.close\n @ack_socket.close\n @client.disconnect! rescue nil\n end", "def shutdown\n @connection_manager.shutdown if @connection_manager\n @client = nil\n @connection_manager = nil\n end", "def close()\n @connection.disconnect\n @connection = nil\n end", "def disconnect!\n @connection.close rescue nil\n end", "def shutdown\n @pool.shutdown do |connection|\n connection.quit\n end\n end", "def shutdown\n @pool.shutdown do |connection|\n connection.quit\n end\n end", "def disconnect!\n @connection.logoff rescue nil\n end", "def disconnect\n _logout\n @connection.close\n end", "def disconnect!\n @logger.info(\"Terminating SSH connection to server name=#{@name}\")\n @ssh.close\n @ssh = nil\n end", "def disconnect; @connection.close end", "def shutdown!\n error { \"forcing connection closed\" }\n socket.close\n end", "def disconnect\n @connection.close if connected?\n @connection = nil\n end", "def close_connection\n @connection.expunge\n @connection.logout\n @connection.disconnect\n end", "def disconnect\r\n @connection.close_connection\r\n @connection = nil\r\n end", "def shut_down\n trigger(:shut_down_started)\n @server.stop(true) if @server\n @server_thread.join if @server_thread\n adapter.shut_down\n trigger(:shut_down_complete)\n end", "def close()\n\t\t@connection.disconnect\n\t\t@connection = nil\n\tend", "def close\n info { \"closing connection\" }\n socket.shutdown\n end", "def disconnect\n info 'closing connection to host'\n @connected = false\n end", "def shutdown!\n shutdown\n end", "def close\n conn.write(\"(api-quit)\") if connected?\n rescue Errno::ECONNRESET\n ensure\n self.conn = nil\n end", "def stop\n log \"closing connection\"\n @running = false\n client.stop!\n log \"closed\"\n end", "def shutdown\n @socket = nil\n @thr.join if @thr\n @thr = nil\n end", "def shutdown\n request('shutdown')\n end", "def shutdown()\n if @conn\n @conn.unsubscribe(@queue_name)\n @@log.debug(\"Unsubscribe complete\")\n StompHelper::pause(\"After unsubscribe\") if $DEBUG\n @conn.disconnect()\n @@log.debug(\"Disconnect complete\")\n StompHelper::pause(\"After disconnect\") if $DEBUG\n end\n end", "def terminate_connection\n @intentionally_closed = true\n close_connection\n end", "def close_connection\n @connection.finish\n end", "def shutdown\n client.close\n end", "def teardown\n logger.debug \"Connection teardown\"\n @connection.active? && disconnect\n @connection.active?\n end", "def shutdown\n\n @db.connection.close\n end", "def disconnect\n @conn.close\n end", "def disconnect\n @conn.close\n end", "def disconnect\n @conn.close\n end", "def disconnect\n @conn.close\n end", "def shutdown\n @logger.info \"Hastur agent shutting down normally.\"\n @running = false\n @router_socket.close\n @udp_socket.close\n @ctx.terminate\n end", "def disconnect!\n super\n @connection.close rescue nil\n end", "def close\n if self.conn && !self.conn.closed?\n self.conn.shutdown\n self.conn.close\n end\n\n self.conn = nil\n end", "def close_connection\n current_connection.logout if current_connection?\n current_connection = nil\n end", "def shutdown\n logger.info('Shutting down ...')\n @lock.synchronize do\n @shutdown = true\n end\n\n reset\n exit\n end", "def shut_down\n end", "def shutdown\n send_recv( KJess::Request::Shutdown.new )\n end", "def disconnect\n super\n\n @transport.close rescue nil\n @transport = nil\n \n debug 'connections closed'\n end", "def disconnect\n @connection.logout\n end", "def disconnect\n @hazel.shutdown\n end", "def shutdown\n @server.shutdown\n end", "def close\n @conn.disconnect\n end", "def halt\n\t\tself.shutting_down = true\n\t\tself.consumer.channel.close\n\tend", "def destroy_connection\r\n\tbegin\r\n\t\t@sock.close if @sock\r\n\tensure\r\n\t\t@connected=false\r\n\tend\r\n end", "def on_close(env)\n @connection.destroy if @connection\n end", "def disconnect\n @tcp_socket.close\n end", "def quit!\n command \"quit\" if alive?\n ensure\n @alive = false\n @socket = nil\n File.delete(@socket_path) if File.exist?(@socket_path)\n end", "def shutdown(level=0)\n check_connection\n @protocol.shutdown_command level\n self\n end", "def shutdown\n log.info 'Shutting down...'\n @shutdown = true\n end", "def close_connection\n cls if connected?\n stop_read_loop\n stop_write_loop\n @socket.close if @socket\n @socket = nil\n @connected = false\n end", "def disconnect\n @socket.close\n end", "def destroy\n connection.close\n end", "def shutdown; end", "def shutdown; end", "def shutdown; end", "def shutdown; end", "def shutdown; end", "def shutdown; end", "def shutdown; end", "def disconnect\n\t\tbegin\n\t\t\tActiveRecord::Base.remove_connection\n\t\trescue ::Exception => e\n\t\t\tself.error = e\n\t\t\telog(\"DB.disconnect threw an exception: #{e}\")\n\t\tensure\n\t\t\t# Database drivers can reset our KCODE, do not let them\n\t\t\t$KCODE = 'NONE' if RUBY_VERSION =~ /^1\\.8\\./\n\t\tend\n\tend", "def destroy_connection\n begin\n @ssock.close if @ssock\n @rsock.close if @rsock\n ensure\n @connected=false\n end\n end", "def disconnect!\n super\n @raw_connection&.close\n @raw_connection = nil\n end", "def shutdown()\n check_return_code(PureHailDB.ib_shutdown(PureHailDB::ShutdownType[:IB_SHUTDOWN_NORMAL]))\n end", "def disconnect\n @write_socket.close\n @read_socket.close\n @write_socket = nil\n @read_socket = nil\n @rc_r = false\n @rc_W = false\n end", "def shutdown!; end", "def shutdown!; end", "def shutdown!; end", "def disconnect\n raise \"Not connected. did you forget to call connect?\" unless @_socket\n @_socket.close\n @_socket = nil\n print \"Disconnected\\n\" if @_verbose\n EtherShell::ShellDsl.nothing\n end", "def close\n close_connection(CLOSED, true)\n end", "def stop\n @pid ? Process.kill('TERM', @pid) : close_connection\n end", "def disconnect_ssh_tunnel\n @logger.debug('closing SSH tunnel..')\n\n @ssh.shutdown! unless @ssh.nil?\n @ssh = nil\n end", "def shutdown\n end", "def close\n log \"Closing connection\", level: :warning\n close_stream\n close_socket\n stop_reader\n set_state :disconnected\n notify_error DisconnectError.new(\"Connection was closed\")\n\n # stop timer\n # as we're running inside the timer, code after stop_timer() will not be called,\n # unless it's in the ensure block\n stop_timer\n end", "def disconnect\n @server = nil\n @status = :disconnected\n end", "def stop\n @socket.close\n ensure\n cleanup\n end", "def shutdown( msg=\"Server shutdown\" )\n\t\t$stderr.puts \"Shutting down: #{msg}\"\n\t\t@shuttingDown = true\n\t\t@reactor.clear\n\t\tbegin\n\t\t\t@socket.shutdown\n\t\trescue\n\t\tend\n\t\tdisconnectAllUsers( msg )\n\t\tbegin\n\t\t\t@socket.close\n\t\trescue\n\t\tend\n\tend", "def shutdown\n log 'Exiting...'\n @shutdown = true\n end", "def shutdown\n @shutdown = true\n end", "def shutdown\n @shutdown = true\n end", "def disconnect()\r\n @callbacks.each { |block| block.call }.clear()\r\n @conn.close if @conn\r\n @conn = nil\r\n end", "def disconnect! # :nodoc:\n super\n @raw_connection.logoff rescue nil\n end", "def kill_connection(connection)\n connection.shutdown!\n end", "def close\n @work_queue.shutdown if @work_queue\n @connection.close\n end", "def disconnect!\n disconnect\n end", "def disconnect\n @streams.each { |_, stream| try { stream.finalize } }\n @conn.Disconnect()\n end", "def shutdown\n end", "def shutdown\n end", "def shutdown\n end", "def shutdown\n end", "def disconnect\n command 'QUIT' do\n begin\n response 221\n ensure\n close\n end\n end\n end", "def shutdown(how = 2)\n begin\n super\n ensure\n @tunnel.remove if closed?\n end\n return 0\n end", "def disconnect\n NWRFCLib.close_connection(@handle, @error)\n NWRFC.check_error(@error)\n end", "def shutdown!\n @gateway&.shutdown!\n sleep 0.5 until !@gateway&.active?\n @gateway = nil\n end" ]
[ "0.8183246", "0.79578334", "0.7912625", "0.73885876", "0.7354836", "0.72706264", "0.7257099", "0.71811414", "0.71494514", "0.71494514", "0.7058152", "0.7056894", "0.7054947", "0.70393366", "0.70356286", "0.7025426", "0.701538", "0.70030946", "0.6991097", "0.6976469", "0.69725734", "0.69616836", "0.6956596", "0.69178444", "0.68847656", "0.68664116", "0.6865261", "0.6862729", "0.6846094", "0.68445593", "0.6814987", "0.68146884", "0.68127835", "0.6800945", "0.6800945", "0.6800945", "0.6800945", "0.67761254", "0.67694736", "0.67622244", "0.67616445", "0.674863", "0.67349124", "0.6729472", "0.67149585", "0.6684884", "0.66701967", "0.6664294", "0.6649707", "0.6636984", "0.663602", "0.66226727", "0.6605723", "0.6596391", "0.65951407", "0.659459", "0.65891314", "0.6570152", "0.65572387", "0.65536684", "0.65536684", "0.65536684", "0.65536684", "0.65536684", "0.65536684", "0.65536684", "0.6542821", "0.6530133", "0.65016985", "0.6501352", "0.64937013", "0.64935464", "0.64935464", "0.64935464", "0.6493267", "0.6487284", "0.6486573", "0.64807314", "0.6478241", "0.64716226", "0.6468208", "0.64636695", "0.6460684", "0.64428097", "0.6434714", "0.6434714", "0.6433046", "0.64325476", "0.6427532", "0.64243436", "0.6421483", "0.6420886", "0.64188695", "0.64188695", "0.64188695", "0.64188695", "0.64137715", "0.64112484", "0.6389419", "0.638456" ]
0.7005302
17
send a PING message
def ping message=nil if message message = (message.to_s.b + (0.chr * 8)).slice(0, 8) else now = Time.now message = [now.to_i, now.usec].pack('NN') end @pings << message g = Frame.new FrameTypes::PING, 0, 0, message send_frame g end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ping!\n send_message [IGNORE, 4, \"ping\"].pack(\"cNA4\")\n end", "def ping\n send_command(\"ping\")\n end", "def ping(request)\n if request.message =~ /PING$/i\n request.answer 'PONG'\n end\n end", "def ping\n return_code, response = send_command(\"ping\")\n return_code == \"200\"\n end", "def send_message(mesg, options = {})\n @client.ping mesg, options\n end", "def ping\n client.ping\n end", "def ping(m=nil)\n @socket << \"PING #{m}\".strip\n end", "def update_ping\n put 'ping'\n end", "def remote_ping(sender, body)\n _notice \"PING?/PONG! (#{sender})\", :notice\n _remote_control(sender, 'pong',\n @var[:presence][@connection.comm.our_keyhash].join(' '))\nend", "def ping\n check_connection\n @protocol.ping_command\n self\n end", "def send_ping\n if @version.version > Bitcoin::Protocol::BIP0031_VERSION\n @latency_ms = LATENCY_MAX\n @ping_nonce = rand(0xffffffff)\n @ping_time = Time.now\n log.debug { \"<< ping (#{@ping_nonce})\" }\n send_data(Protocol.ping_pkt(@ping_nonce))\n else\n # set latency to 5 seconds, terrible but this version should be obsolete now\n @latency_ms = (5*1000) \n log.debug { \"<< ping\" }\n send_data(Protocol.ping_pkt)\n end\n end", "def ping()\n # Use the activity client 'client' to invoke the say_hello activity\n pong=client.ping()\n \"Got #{pong}\"\n end", "def ping\n every(5) do\n send_ping\n end\n end", "def magic_ping(event); @socket.puts \"PONG :#{event.message}\"; end", "def ping\n @conn.ping\n end", "def ping() \n \"Pong from #{Socket.gethostname}\"\n end", "def ping!\n @session.ping!\n end", "def create_ping\n post 'ping'\n end", "def test_ping\n\t@tt.sock.send(@ping, 0)\n=begin\n\t\tpong = @tt.ping_reply\n\t\tassert_equal(42, pong.length)\n\t\tassert_equal(pong[0, 6], @tt.tap_mac)\n\t\tassert_equal(pong[30, 4], @ping[26, 4])\n\t\tassert_equal(pong[26, 4], @ping[30, 4])\n=end\n\tend", "def test_ping\n\t@tt.sock.send(@ping, 0)\n=begin\n\t\tpong = @tt.ping_reply\n\t\tassert_equal(42, pong.length)\n\t\tassert_equal(pong[0, 6], @tt.tap_mac)\n\t\tassert_equal(pong[30, 4], @ping[26, 4])\n\t\tassert_equal(pong[26, 4], @ping[30, 4])\n=end\n\tend", "def ping\n\t\tputs \"Pinging #{@ip} ...\"\n\t\tsystem \"ping #{ip_string}\"\n\tend", "def ping\n with_client do |client|\n client.ping\n end\n end", "def cmd_ping argv\n setup argv\n addr = @hash[\"address\"]\n msg run_cmd(\"ping #{addr}\")\n end", "def ping\n get('')\n end", "def ping!\n @transmission_state.enqueue_ping\n end", "def ping(t)\n \n end", "def on_ping(m)\n post PONG, m[0] ? m[0] : (@prefix ? @prefix.nick : \"\")\n end", "def ping\n end", "def ping\n 'pong'\n end", "def ping(server, target = '')\n send_data(\"PING #{server} #{target}\".strip)\n end", "def ping\n response = connection.get(get_ping_url)\n if response.success?\n PingResponse.new(response.body)\n end\n end", "def ping\n TaxCloud::Responses::Ping.parse request(:ping)\n end", "def ping()\n\n ip = Resolv.getaddress(@host)\n puts ('ip: ' + ip.inspect).debug if @debug\n valid = pingecho(ip)\n puts ('valid: ' + valid.inspect).debug if @debug \n \n @results[:ping] = if valid then\n a = [valid]\n 4.times {sleep 0.01; a << pingecho(ip)}\n (a.min * 1000).round(3)\n else\n nil\n end\n\n end", "def ping(timeout=nil)\n request = Message::Ping.new(Thread.mailbox)\n send_request request, :request, timeout\n end", "def cmdh_ping_req(msg_details)\n @log.debug \"PINGREQ handler\"\n # response back\n send_ping_resp\n end", "def test_ping_basic\n @tt.sock.send(@ping, 0)\n pong = @tt.ping_reply\n assert_equal(42, pong.length)\n assert_equal(pong[0, 6], @tt.tap_mac)\n assert_equal(pong[30, 4], @ping[26, 4])\n assert_equal(pong[26, 4], @ping[30, 4])\n end", "def ping(*args)\n get '/invoke/wm.server/ping'\n end", "def ping(&blk)\n if block_given?\n websocket.subscribe :ping, &blk\n else\n http.get :ping\n end\n end", "def ping(session_id)\n execute_command('ping', :session_id => session_id)\n end", "def pong(msg)\n raise ArgumentError, 'message not a PING' if msg.command != 'PING'\n send_msg(\"PONG #{msg.params.join(' ')}\")\n end", "def pong\n to_send = [ 0b10001010, 0, \"\" ]\n @connection.write to_send.pack \"C2A0\"\n end", "def ping(str)\n heartbeat(0b10001001, str)\n end", "def handle_ping_message(message)\n # The last part of the PING message is the so-called \"challenge\". The server expects that we reply\n # back with this exact string. Therefore we extract it here.\n challenge = message.split(\" \").last\n\n # We send back an IRC \"PONG\" message with the challenge that came from the server.\n irc_send \"PONG #{challenge}\"\nend", "def ping\n sanity_check\n @handle.ping\n end", "def on_ping(x)\n end", "def reply_ping(user, str)\n sendmsg \"NOTICE #{user} :\\001PING #{str}\\001\"\n end", "def ping\n result = RhizomePingJob.new(@rhizome).perform_now\n\n if result[:connected]\n flash[:success] = \"Pinged <strong>#{result[:name]}</strong>!<br />\" <<\n \"Here's what I got:<br />\" <<\n \"<pre>#{JSON.pretty_generate(result)}</pre>\"\n else\n flash[:danger] = \"It appears that <strong>#{result[:name]}</strong> is not connected...<br />\" <<\n \"Here's what I know:<br />\" <<\n \"<pre>#{JSON.pretty_generate(result)}</pre>\"\n end\n\n redirect_to rhizomes_url\n end", "def ping(ip)\n @logger.debug(\"ping from #{ip}\")\n \"pong\"\n end", "def ping; end", "def pong(s, m)\n @socket << \"PONG #{s} #{m}\"\n end", "def ping\n response, body = send_request :get, '', :binary\n true\n end", "def ping\n @ping = Time.now\n end", "def receive_ping\n done\n end", "def ping\n render json: {\n message: \"OK\",\n time: DateTime.current.strftime(\"%Q\")\n }\n end", "def ping(sock,msg=nil)\n unless msg.nil? or msg.type == Protocol::MessageType::PING\n Routing.log { |logger| logger.error(self.class) { \"Not a PING message.\"}}\n return false\n end\n if msg.nil?\n msg = construct_ping\n end\n bytes = @protocol.send_message(sock,msg)\n @bandwidth_manager.uploaded(bytes,Time.now-msg.ftime.to_time) unless @bandwidth_manager.nil?\n Routing.log {|logger| logger.info(self.class) { \"PING message is sent. Size: #{bytes} bytes.\"}}\n true\n end", "def ping?\n rpc.request Util::MessageCode::PING_REQUEST\n\n return rpc.status\n end", "def ping\n true\n end", "def check\n tcp_socket_request\n mark_message \"Ping check to #{host}:#{port} successful\"\n rescue => e\n mark_message \"Error: '#{e}'\"\n mark_failure\n end", "def send_message\n self.get_message\n self.conn.get.status\n end", "def ping(options={})\n begin\n send_message(SkyDB::Message::Ping.new(options))\n return true\n rescue\n return false\n end\n end", "def get_ping(data)\n end", "def ping?\n @raw.start_with? 'PING'\n end", "def ping()\n _params = {}\n return @master.call 'users/ping2', _params\n end", "def send_ping(target_node_id, host, port)\n ping = Ping.new(to: To.from_host_port(host, port), \n from: From.new(\n sender_ip: IPAddr.new(@host).to_i,\n sender_udp_port: @udp_port,\n sender_tcp_port: @tcp_port),\n expiration: Time.now.to_i + MESSAGE_EXPIRATION_IN)\n ping_msg = Message.pack(ping, private_key: @private_key)\n send_msg(ping_msg.encode_message, host, port)\n @peer_store.update_ping(target_node_id, ping_msg.message_hash)\n end", "def ping(cmd)\n\tdst = cmd[0]\n next_hop = $next[dst]\n if next_hop == \"NA\" || next_hop == $hostname\n STDOUT.puts \"PING ERROR: HOST UNREACHABLE\"\n return\n end\n n = cmd[1].to_i\n delay = cmd[2].to_i\n client = $clients[next_hop]\n\n # This will iterate through the number of pings given on the command line. It will setup the \n # proper message for pingCallBack and adds the current time to the ping table with the key\n # of the sequence number. It will then check if ping_table has that key still (should be removed\n # by pingCallBack) so if it still exists, then the host was not reached.\n for seq_id in (0..(n - 1))\n msg = Msg.new\n msg.setConfig(\"type\", 3)\n msg.setConfig(\"code\", 0)\n msg.setMessage($hostname + \" \" + dst + \" \" + seq_id.to_s)\n $ping_table[seq_id.to_s] = $currtime\n sendMessage(client, msg)\n Thread.new {\n seq_id_ = seq_id\n sleep($ping_timeout)\n if $ping_table.has_key?(seq_id_.to_s)\n STDOUT.puts \"PING ERROR: HOST UNREACHABLE\"\n end\n $ping_table.delete(seq_id_.to_s)\n }\n sleep(delay)\n end\nend", "def answer_pings\n\t\t@ping_thread = Thread.new do \n\t\t\tbegin\n\t\t\t\tloop do \n\t\t\t\t\tpkt = @tap.recv\n\t\t\t\t\tp pkt\n=begin\t\t\t\t\t\n\t\t\t\t\ticmp = icmp_offset(pkt)\n\t\t\t\t\tif icmp and pkt[icmp] == \"\\x08\" #type == Echo Request\n\t\t\t\t\t\tpkt[icmp, 1] = \"\\x00\"\n\t\t\t\t\t\tpkt[26, 4], pkt[30, 4] = pkt[30, 4], pkt[26, 4]\n\t\t\t\t\t\t@tap.inject(pkt)\n\t\t\t\t\tend\n=end\t\t\t\n\t\t\t\tend\n\t\t\trescue Object\n\t\t\t\t$stderr.puts $!\n\t\t\t\t$stderr.puts $@\n\t\t\t\tKernel.exit(1)\n\t\t\tend\n\t\tend\n\tend", "def ping(opts = {})\n data, _status_code, _headers = ping_with_http_info(opts)\n data\n end", "def handle_ping(client, ccf)\n @socket.send_strings [client, ccf, PONG]\n end", "def answer_pings\n\t\t@ping_thread = Thread.new do \n\t\t\tbegin\n\t\t\t\tloop do \n\t\t\t\t\tpkt = @tap.recv\n\t\t\t\t\ticmp = icmp_offset(pkt)\n\t\t\t\t\tif icmp and pkt[icmp] == \"\\x08\" #type == Echo Request\n\t\t\t\t\t\tpkt[icmp, 1] = \"\\x00\"\n\t\t\t\t\t\tpkt[26, 4], pkt[30, 4] = pkt[30, 4], pkt[26, 4]\n\t\t\t\t\t\t@tap.inject(pkt)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\trescue Object\n\t\t\t\t$stderr.puts $!\n\t\t\t\t$stderr.puts $@\n\t\t\t\tKernel.exit(1)\n\t\t\tend\n\t\tend\n\tend", "def send_message(message)\n @networking.send_message(message)\n end", "def ping_request(ping, opts = {})\n data, _status_code, _headers = ping_request_with_http_info(ping, opts)\n data\n end", "def ping\n @client.peek( name )\n return true\n end", "def ping\n if god?\n tries = 3\n begin\n @server.ping\n rescue Exception => e\n retry if (tries -= 1) > 1\n raise e, \"The server is not available (or you do not have permissions to access it)\"\n end\n end\n end", "def ping\n self.last_ping = Time.now\n end", "def ping(server, forward = nil)\n raw \"PING #{server} #{forward}\".strip << \"\\r\\n\"\n end", "def ping(req)\n Lynr.metrics.time('time.render:ping') do\n Rack::Response.new('PONG', 200, headers)\n end\n end", "def ping()\n #This is a stub, used for indexing\n end", "def send(message)\n\t\t\t@conn.send(message)\n\t\tend", "def ping()\n #This is a stub, used for indexing\n end", "def send_ping\n @connections.each do |socket|\n begin\n socket << \":\\n\"\n rescue Reel::SocketError\n @connections.delete(socket)\n end\n end\n end", "def perform\n @client.rest_get_with_token('/ping', {}, {})\n end", "def ping?\n tcp_ping.ping?\n end", "def ping_api\n res=api_call('PingAPI')\n if res[:data]==1\n res=true\n else\n res=false\n end\n res\n end", "def ping\n data = params[:data] || ''\n render json: { data: data }\n end", "def ping\n\t\t# MAC address / serial\n\t\tlogger.debug(\"PING called\")\n\n\t\trender_event\n\tend", "def slack(msg)\n @slack.ping(msg)\n end", "def ping(body = '')\n if @handler\n @handler.pingable? ? @handler.send_frame(:ping, body) && true : false\n else\n raise WebSocketError, \"Cannot ping before onopen callback\"\n end\n end", "def ping(data, timeout = 1)\n data = data.clone\n # Pad data to have at least 64 bytes.\n data += \"\\0\" * (64 - data.length) if data.length < 64\n \n ping_packet = @dest_mac + @source_mac + @ether_type + data\n @socket.send ping_packet, 0\n\n response_packet = @source_mac + @dest_mac + @ether_type + data\n response = @socket.recv response_packet.length * 2\n \n response == response_packet\n end", "def pong_everyone\n #log \"trying to pong\"\n if @sockets.length > 0 && !self.stopped?\n #log \"ponging\"\n broadcast_message(nil, \"PONG\", [build_handle_list])\n #sleep 5\n clean_handles\n end\n end", "def pbroadcast(message, callback)\n connections.each { |c| c.ping(message, &callback) }\n end", "def send_string(text)\n ping player_url+\"/application/sendString?text=#{CGI::escape(text.to_s)}&#{plex_token}\"\n end", "def ping(options = {})\n client = extract_client!(options)\n !!client.get(\"/api/system/ping\")\n rescue Error::ConnectionError\n false\n end", "def local_ping(body)\n @var[:ping_request] = Time.now\n body = @var[:our_name] unless _user_keyhash(body)\n _remote_control(body, 'ping', 'empty')\nend", "def ping(host, icmp_count = 1)\n cmd = \"ping -c #{icmp_count} #{host}\"\n @logger.info(\"[SystemGateway][ping] Executing #{cmd}...\")\n out = `#{cmd}`\n @logger.info(\"[SystemGateway][ping] Command ended. Output: #{out}\")\n $? == 0\n end", "def run\n until @socket.eof? do\n line = @socket.gets\n\n # Makes sure your bot doesn't timeout!\n if line.match(PING_MSG)\n say \"PONG #{ $~[1]}\"\n else\n bot_main(line)\n end\n end\n end", "def onping(&blk); super; end", "def remote_pong(sender, body)\n presence = _pop_token(body)\n req = @var.delete :ping_request\n if req\n _notice(\"Ping reply from #{sender}: #{((Time.now - req) * 1000).to_i}ms\",\n :notice)\n end\n if [ 'online', 'away' ].include?(presence)\n _adjust_presence(presence, _user_keyhash(sender), '', body, true)\n end\nend", "def ping\n tries = 3\n begin\n # @server.ping\n rescue Exception => e\n retry if (tries -= 1) > 1\n raise e, \"The server is not available (or you do not have permissions to access it)\"\n end\n end", "def message(handler)\n if handler.bot.debug\n handler.messages.each do |line|\n puts \"> #{line.raw}\"\n end\n end\n\n handler.send_raw('PONG :tmi.twitch.tv') if handler.message.ping?\n end", "def send_message(data, flag, host, port)\n\t\tsocket = UDPSocket.new\n\t\tserialized = Marshal.dump(data)\n\t\tsocket.send serialized, flag, host, port\n\t\tsocket.close\n\t\tputs \"Sending #{data} to #{host}:#{port}\"\n\t\tsleep(0.025)\n\tend" ]
[ "0.7946903", "0.76782644", "0.72139764", "0.719248", "0.7182499", "0.71192193", "0.7106439", "0.7095092", "0.70772904", "0.7071936", "0.7038733", "0.7031764", "0.70281", "0.7020114", "0.70171416", "0.69965017", "0.69899064", "0.6945946", "0.6937511", "0.6937511", "0.68778104", "0.683959", "0.6833629", "0.6786717", "0.6786706", "0.67861724", "0.67808527", "0.6776297", "0.6769749", "0.67407405", "0.6728489", "0.6726402", "0.66991097", "0.6695033", "0.66798246", "0.66668415", "0.66596293", "0.66428626", "0.66384685", "0.6597041", "0.6596001", "0.65905666", "0.6589739", "0.6568583", "0.6568207", "0.6556603", "0.65471524", "0.65462744", "0.6539977", "0.65337616", "0.6533672", "0.65295315", "0.6526344", "0.6495563", "0.647223", "0.64719856", "0.64426255", "0.6358228", "0.6356807", "0.63320935", "0.63264203", "0.63068736", "0.6287337", "0.62820417", "0.627197", "0.62602544", "0.6253226", "0.6234603", "0.6232015", "0.6221816", "0.6210104", "0.61833113", "0.61803913", "0.6173043", "0.61715126", "0.61651343", "0.61610246", "0.61582726", "0.6157301", "0.6155304", "0.6151571", "0.61477494", "0.61407584", "0.6131065", "0.61302584", "0.61232895", "0.610938", "0.6097709", "0.6088347", "0.6087519", "0.6080644", "0.606706", "0.6063608", "0.60512936", "0.6043069", "0.60344934", "0.60293496", "0.5993782", "0.59806204", "0.5970661" ]
0.723646
2
returns truthy if the given frame carries HTTP semantics (so has to be sent in order)
def semantic_frame? f f.type == FrameTypes::DATA || f.type == FrameTypes::HEADERS || f.type == FrameTypes::CONTINUATION || f.type == FrameTypes::GZIPPED_DATA end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def head?\r\nHTTP_METHOD_LOOKUP[request_method] == :head\r\nend", "def http_header?(name)\n name.start_with?(\"HTTP\") && !HTTP_NON_HEADERS.include?(name)\n end", "def treat_as_standard_html_request?\n !request.format.json? and !request.format.print? and !request.format.video?\n end", "def treat_as_standard_html_request?\n !request.format.json? and !request.format.print? and !request.format.video?\n end", "def control_frame?(frame_type)\n !%i(text binary continuation).include?(frame_type)\n end", "def has_frame?(frame_name)\n frame_text = self.redirect {$ie.show_frames}\n !frame_text.match(\"#{frame_name}\").nil?\n end", "def has_frame?(frame_name)\n frame_text = self.redirect {$ie.show_frames}\n !frame_text.match(\"#{frame_name}\").nil?\n end", "def done_request_line?\n [:headers, :body_identity, :body_chunked, :body_chunked_tail, :done].include?(@state)\n end", "def applies_to?(response)\n status, header, body = response\n\n # Some stati don't have to be processed\n return false if [301, 302, 303, 307].include?(status)\n\n # Check mime type\n return false if @mime_types.all? do |type|\n !header['Content-Type'].to_s.include?(type)\n end\n\n # Find ESI tags\n response[2] = [body = join_body(body)]\n body.include?('<esi:')\n end", "def framed?\n return @peer.framed?\n end", "def mfa?\n @response.is_a?(Net::HTTPCreated)\n end", "def frame_requested?\n preview_frame = {}\n plugin = alchemy_plugins.detect do |p|\n unless p[\"preview_frame\"].nil?\n if p['preview_frame'].is_a?(Array)\n preview_frame = p['preview_frame'].detect(){ |f| f[\"controller\"] == params[:controller] && f[\"action\"] == params[:action] }\n else\n if p[\"preview_frame\"][\"controller\"] == params[:controller] && p[\"preview_frame\"][\"action\"] == params[:action]\n preview_frame = p[\"preview_frame\"]\n end\n end\n end\n end\n return false if plugin.blank?\n preview_frame\n end", "def has_frame?(frame_name)\n frame_name = frame_name.to_s\n available_frames.include?(frame_name) ||\n supercall(false, :has_frame?, frame_name)\n end", "def body?\n HTTY::Request::METHODS_SENDING_BODY.include? method\n end", "def ignore_frame?(frame)\n\t\t\t\tif self.closed?\n\t\t\t\t\t# puts \"ignore_frame? #{frame.stream_id} -> #{valid_remote_stream_id?(frame.stream_id)} > #{@remote_stream_id}\"\n\t\t\t\t\tif valid_remote_stream_id?(frame.stream_id)\n\t\t\t\t\t\treturn frame.stream_id > @remote_stream_id\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend", "def done_headers?\n [:body_identity, :body_chunked, :body_chunked_tail, :done].include?(@state)\n end", "def has_response_body?\n @raw_link.media_type != \"null\"\n end", "def handable_format?\n @request.format.symbol.nil? || (@request.format.symbol == :html)\n end", "def valid?\n @method == \"GET\" &&\n !@request_uri.empty? &&\n @http_version >= 1.1 &&\n @header[\"Upgrade\"] == \"websocket\" &&\n @header[\"Connection\"].include?(\"Upgrade\") &&\n Base64.decode64(@header[\"Sec-WebSocket-Key\"]).length == 16 &&\n @header[\"Sec-WebSocket-Version\"].to_i == 13\n end", "def renderable?\n !_requires_no_body? &&\n !sending_file? &&\n !ADDITIONAL_HTTP_STATUSES_WITHOUT_BODY.include?(@_status)\n end", "def request_sent?\n !response.nil?\n end", "def valid?\n @header && ['200','301','302'].include?(@header.code)\n end", "def bodiless?\n\t\treturn self.extended_reply? ||\n\t\t\tself.body.nil? ||\n\t\t\tHTTP::BODILESS_HTTP_RESPONSE_CODES.include?( self.status )\n\tend", "def http?\n type == :basic || type == :digest\n end", "def turbo_request?\n !request.get? && (response.try(:media_type) || response.content_type) == \"text/javascript\"\n end", "def ok?\n Net::HTTPSuccess === self || Net::HTTPRedirection === self\n end", "def api_request?\n request.format.json? || request.format.js? || request.format.xml? || request.format.fbtab?\n end", "def headers_sent?\n return true if _httpsession.resp.headers_sent\n return false\n end", "def suitable_frame?(frame)\n renderer.frame_exists?(frame) && suitable_frame_by_colors?(frame)\n end", "def xml_http_request?\n not /XMLHttpRequest/i.match(@headers['HTTP_X_REQUESTED_WITH']).nil?\n end", "def xml_http_request?\r\n@env['HTTP_X_REQUESTED_WITH'] =~ /XMLHttpRequest/i\r\nend", "def body_allowed?\n @status.allows_body? && @request_method.allows_body?\n end", "def transform_response?(headers, body)\n @transform_response &&\n json_content_type?(headers) &&\n body &&\n true # so the return value is true if all prior conditions are true\n end", "def real_request?\n @real_request\n end", "def content_type_header?\n request.headers['Content-Type']&.include?('application/fhir+json')\n end", "def request?\n !!request\n end", "def non_empty_http_response?(http)\n http.response.present?\n end", "def is_html?\n not (@headers['Content-Type'] =~ /^application\\/html.*/).nil?\n end", "def response_received?\n !! @status\n end", "def response_received?\n !! @status\n end", "def calculate_content_length?\n headers.has_key?(Const::CONTENT_TYPE) && !headers.has_key?(Const::CONTENT_LENGTH)\n end", "def framed?\n dim_type.outer_target == \"frame\"\n end", "def xml_http_request?\n return false if !@request || !@request['headers'] || !@request['headers']['X-Requested-With']\n test2 = /XMLHttpRequest/i.match(@request['headers']['X-Requested-With'])\n not test2.nil?\n end", "def request?\n self.operation == OP_REQUEST\n end", "def posting_html?\n return false unless respond_to?(:request) && !request.get?\n # noinspection RubyResolve\n request.format.html? || (request.format.js? && !!request.xhr?)\n end", "def matches?(request)\n check_headers(request.headers) || default\n end", "def chunked_encoding?\n /chunked/i === self[HttpClient::TRANSFER_ENCODING]\n end", "def should_parse?\n parsed? == false && headers['x-amp'] != 'skip'\n end", "def post_header(request)\n if request.headers[\"content-type\"] == 'application/json' && request.headers[\"accept\"] == 'application/json'\n true\n else\n false\n end\n end", "def headers?\n @headers.empty?\n end", "def forwarded?\n !(self.forwards.empty?)\n end", "def valid_http_response?(http)\n http.is_a?(EM::HttpClient) && non_empty_http_response?(http)\n end", "def redirect?\n @response.is_a? Net::HTTPRedirection\n end", "def http_redirect?\n @get_resp.kind_of?(Net::HTTPRedirection)\n end", "def http_redirect?\n @get_resp.kind_of?(Net::HTTPRedirection)\n end", "def valid?(message)\n super do |_|\n # only care that it's an HTTP request\n message[:message][:request] &&\n message[:message][:connection]\n end\n end", "def have_transmission_header?\n self.class.have_transmission_header?\n end", "def response?\n !response.nil?\n end", "def binary_content?\n transfer_encoding && transfer_encoding == 'binary'\n end", "def check_header\n if ['POST', 'PUT', 'PATCH'].include? request.method\n head :not_acceptable and return unless request.content_type == 'application/vnd.api+json'\n end\n end", "def respond_to?(symbol)\n @curl.respond_to?(symbol)\n end", "def can_have_body?\n Methods[@method].can_have_body\n end", "def have_transmission_header?\n @have_transmission_header\n end", "def user_authorizes_the_request?(request)\n request.post? && referrer_is_self?(request)\n end", "def write_headers?() @write_headers end", "def valid_signature?\n Rack::Utils.secure_compare(signature, signature_for(body))\n end", "def ok? \n @response.is_a? Net::HTTPOK\n end", "def allowed?(payload)\n !!determine_namespace(payload)\n end", "def data_frame?(frame_type)\n %i(text binary).include?(frame_type)\n end", "def performed?\n response_body\n end", "def spare_or_open_frame?\n if not_last_frame? && (@throws == 2)\n raise BowlingError if scores_of_n_last_frames(2) > 10\n @frame.type = if @frame.score == 10\n :spare\n else\n :open\n end\n calc_frame_scores\n end\n end", "def well_formated_response?\n all_expected_fields_received? && validate_bank_response_signature\n end", "def redirect?\n # redirects are 3xx\n return @status >= 300 && @status < 400\n end", "def okay_to_modify?\n return false if is_xhr?\n return false unless modifiable_content_type?\n true\n end", "def should_handle? env #:nodoc:\n return false unless env['CONTENT_TYPE'] == APPLICATION_AMF\n return false if Rack::AMF::Environment.url && env['PATH_INFO'] != Rack::AMF::Environment.url\n true\n end", "def verified_request?\r\n super || form_authenticity_token == request.headers['X-XSRF-TOKEN']\r\n end", "def post?\r\nHTTP_METHOD_LOOKUP[request_method] == :post\r\nend", "def verified_request?\n\t\tsuper || form_authenticity_token == request.headers['X-XSRF-TOKEN']\n\tend", "def http_auth_header?\n scope_class.http_authenticatable && !request.xhr?\n end", "def html_request?(env)\n debug(env) if options[:debug]\n (env['CONTENT_TYPE'] || \"\").to_s !~ /json/i\n end", "def allows_response?(responder=nil)\n self.active? && self.open?\n end", "def route_request?\n request.get? && !request_xhr? && !modal?\n end", "def match?(_request)\n true\n end", "def shields_io_valid_response?(http, url)\n url.include?(BadgeApi::BASE_URL) && http_valid_status_code?(http, 200) && http_valid_content_types?(http)\n end", "def response?\n !!response\n end", "def parse_response?\n parse_response\n end", "def parse_response?\n parse_response\n end", "def finished?\n\t\t\t\t@finished && @body.length >= @headers['CONTENT_LENGTH']\n\t\t\tend", "def response_includes?(content)\n @response.body.include?(content)\n end", "def xhr?\n @env['HTTP_X_REQUESTED_WITH'] =~ /XMLHttpRequest/i\n end", "def request?\n @type == :request\n end", "def must_have_body?\n Methods[@method].must_have_body\n end", "def matches?(req)\n req.path =~ pattern && req.request_method.to_s.upcase == http_method\n end", "def has_response_body?\n !response.body.nil? && !response.body.empty?\n end", "def matches?(request)\n request.headers.fetch(:accept).include?(\"application/vnd.pieforproviders.v#{version}+json\")\n end", "def is_origin\n origin = @transport.get_data(\"meta\",\"origin\")\n # compare two arrays with intersection\n return (origin & [@name,@version,@action]).empty?\n end", "def verified_request?\n super || form_authenticity_token == request.headers['X-XSRF-TOKEN']\n end", "def verified_request?\n super || form_authenticity_token == request.headers['X-XSRF-TOKEN']\n end", "def verified_request?\n super || form_authenticity_token == request.headers['X-XSRF-TOKEN']\n end", "def verified_request?\n super || form_authenticity_token == request.headers['X-XSRF-TOKEN']\n end" ]
[ "0.6558549", "0.62860686", "0.6256679", "0.6256679", "0.61295325", "0.61175334", "0.61175334", "0.6113873", "0.60840786", "0.60704446", "0.6067758", "0.60201645", "0.6002649", "0.5972792", "0.58855915", "0.5847994", "0.5845215", "0.5839393", "0.5836589", "0.5833479", "0.5831655", "0.5818939", "0.58073586", "0.5800212", "0.5780586", "0.5774095", "0.57713", "0.5761808", "0.57591355", "0.5729511", "0.57278913", "0.5722962", "0.56997955", "0.56973726", "0.569443", "0.5684337", "0.56709236", "0.56593275", "0.565239", "0.565239", "0.56373435", "0.56353456", "0.562629", "0.5626201", "0.5601187", "0.5597083", "0.5576394", "0.556917", "0.55673873", "0.5563906", "0.5543726", "0.55422974", "0.5534098", "0.5516933", "0.5516933", "0.55032796", "0.54976684", "0.5495145", "0.5484434", "0.54756355", "0.5475061", "0.5468496", "0.54528624", "0.54437923", "0.54416573", "0.54215765", "0.5421261", "0.54121816", "0.5409851", "0.5396535", "0.53900164", "0.53842676", "0.5384256", "0.53820765", "0.53796005", "0.5376644", "0.5367486", "0.5367447", "0.53621197", "0.53620017", "0.53528506", "0.5348686", "0.5332933", "0.5331474", "0.53293777", "0.5328369", "0.53243613", "0.53227925", "0.53225005", "0.53220457", "0.5320108", "0.5319043", "0.5314589", "0.5312048", "0.5307961", "0.53077877", "0.5303428", "0.5303428", "0.5303428", "0.5303428" ]
0.7241635
0
Are we configured to accept GZIPPED_DATA frames from this peer? Takes into account peer's apparent ability to correctly send gzip.
def accept_gzip? return if @ext__veto_gzip @ext__recv_gzip end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def accept_gzip!\n return if @ext__veto_gzip\n if !@ext__recv_gzip\n send_frame Settings.frame_from({Settings::ACCEPT_GZIPPED_DATA => 1})\n @ext__recv_gzip = true\n end\n end", "def send_gzip?\n return if !@ext__peer_gzip\n @ext__send_gzip\n end", "def no_accept_gzip!\n return if @ext__veto_gzip\n if @ext__recv_gzip\n send_frame Settings.frame_from({Settings::ACCEPT_GZIPPED_DATA => 0})\n @ext__recv_gzip = false\n end\n end", "def check_accept_encoding\n if accept = @stream.request.headers[ACCEPT_ENCODING_KEY]\n accept.split(',').map(&:strip).each do |encoding|\n case encoding\n when GZIP_ENCODING\n if @stream.connection.server.options[:gzip]\n @gzip = true\n @headers[CONTENT_ENCODING_KEY] = GZIP_ENCODING\n break\n end\n\n # \"deflate\" has issues: https://zlib.net/zlib_faq.html#faq39\n #\n when DEFLATE_ENCODING\n if @stream.connection.server.options[:deflate]\n @deflate = true\n @headers[CONTENT_ENCODING_KEY] = DEFLATE_ENCODING\n break\n end\n\n end\n end\n end\n end", "def gzipped?(env)\n env[:response_headers][CONTENT_ENCODING_HEADER] == ENCODING\n end", "def gzip_enabled; end", "def gzip_enabled; end", "def gzip_enabled\n @agent.gzip_enabled\n end", "def testing_compression?\n compression_enabled? && op_msg_enabled?\nend", "def snapshots_transport_gzip_requests; end", "def gzip_disabled?\n @disable_gzip\n end", "def send_gzip!\n if !@ext__send_gzip\n @ext__send_gzip = true\n end\n end", "def compressed?\n false\n end", "def enable_gzip; @opts[:enable_gzip]; end", "def compression_was_achieved\n return compression_ratio() < 1\n end", "def should_deflate?(env, status, headers, body)\n return false if Utils::STATUS_WITH_NO_ENTITY_BODY.include?(status.to_i) ||\n headers['Cache-Control']&.include?('no-transform') ||\n headers['Content-Encoding']&.include?('identity')\n\n return false if @compressible_types&.include?(headers['Content-Type']&.split(';')&.first) == false\n return false if @condition&.call(env, status, headers, body) == false\n\n true\n end", "def cannot_compress?\n !can_compress?\n end", "def chunked_encoding?\n /chunked/i === self[HttpClient::TRANSFER_ENCODING]\n end", "def no_send_gzip!\n if @ext__send_gzip\n @ext__send_gzip = false\n end\n end", "def binary_content?\n transfer_encoding && transfer_encoding == 'binary'\n end", "def gzip_enabled=(_arg0); end", "def framed?\n return @peer.framed?\n end", "def do_chunked_encoding?(hdrs=@headers)\n ( (not @opts[:ignore_chunked_encoding]) and \n (hdrs.get_header_value(\"Transfer-Encoding\").to_s =~ /(?:^|\\W)chunked(?:\\W|$)/) )\n end", "def compressed?\n @compressed == true\n end", "def gzip_requests; end", "def gzip?\n path.extname == '.gz'\n end", "def semantic_frame? f\n f.type == FrameTypes::DATA || f.type == FrameTypes::HEADERS || f.type == FrameTypes::CONTINUATION || f.type == FrameTypes::GZIPPED_DATA\n end", "def chunked?(encoding)\n return false unless encoding\n (/(?:\\A|[^\\-\\w])chunked(?![\\-\\w])/i =~ encoding) ? true : false\n end", "def might_have_data?\n @state.to_s =~ /finished|aborted|running/\n end", "def calculate_content_length?\n headers.has_key?(Const::CONTENT_TYPE) && !headers.has_key?(Const::CONTENT_LENGTH)\n end", "def dechunk?\n self.class.dechunk? && chunked?\n end", "def gzip_enabled=(enabled); end", "def compression_enabled?\n !SpecConfig.instance.compressors.nil?\nend", "def has_opts?\n header_len > 20\n end", "def should_encode?\n !@raw\n end", "def allow?(packet); end", "def can_compress?\n # The \"charset\" of a mime type is present if the value is\n # encoded text. We can check this value to see if the asset\n # can be compressed.\n #\n # We also check against our list of non-text compressible mime types\n @charset || COMPRESSABLE_MIME_TYPES.include?(@content_type)\n end", "def compression?; end", "def pushdata?\n # Compact pushdata opcodes are \"virtual\", just length prefixes.\n # Attention: OP_0 is also \"pushdata\" code that pushes empty data.\n opcode <= OP_PUSHDATA4\n end", "def check_compression\n abort \"Invalid compression type: #{options['compress']}\" unless Compressor.compression_types.include? options['compress'].to_sym\n end", "def push_only?\n chunks.each { |c| return false if !c.opcode.nil? && c.opcode > OP_16 }\n true\n end", "def verify_accept\n raise WebSocket::Error::Handshake::InvalidAuthentication unless @handshake.headers['sec-websocket-accept'] == accept\n true\n end", "def allowed_to_ship_data?\n return false if (Time.now.to_i - self.synced_at) < 43200\n return true\n end", "def is_compressed?\n bit_set?(COMPRESSED_FLAG_BIT)\n end", "def sufficient_length?(chunk)\n return true unless chunk\n return true unless chunk.pushdata?\n buf = StringIO.new(chunk)\n opcode = buf.read(1).ord\n return false if OP_PUSHDATA1 <= opcode && opcode <= OP_PUSHDATA4 && buf.eof?\n len = read_length(opcode, buf)\n return true if len == 0\n rest = (buf.size - buf.pos)\n rest == len\n end", "def open?\n @data_bytes[1] != 0\n end", "def should_keep_alive\n # Explicit:\n return true if 'keep-alive'.eql_igncase? connection_type\n return false if 'close'.eql_igncase? connection_type\n \n # Otherwise, we have to guess:\n # (the UFO operator does lexical array comparison, positive if @ht_v > 1.1)\n (@http_version <=> [1,1]) >= 0\n end", "def data?\n dis_data.any?\n end", "def gzip_enabled=enabled\n @agent.gzip_enabled = enabled\n end", "def isZippedOutput()\n @fields.fetch('image_mode', '') == 'separate' || @fields.fetch('css_mode', '') == 'separate' || @fields.fetch('font_mode', '') == 'separate' || @fields.fetch('force_zip', false) == true\n end", "def cannot_compress?(mime_types)\n !can_compress?(mime_types)\n end", "def fin?\n Capp::TCP_FIN == flags & Capp::TCP_FIN\n end", "def ack?\n Capp::TCP_ACK == flags & Capp::TCP_ACK\n end", "def compression\n @j_del.isCompressionSupported\n end", "def data_frame?(frame_type)\n %i(text binary).include?(frame_type)\n end", "def can_compress?(mime_types)\n # The \"charset\" of a mime type is present if the value is\n # encoded text. We can check this value to see if the asset\n # can be compressed.\n #\n # We also check against our list of non-text compressible mime types\n @charset || COMPRESSABLE_MIME_TYPES.include?(@content_type)\n end", "def can_encode?\n !@encoding_map.empty?\n end", "def urg?\n Capp::TCP_URG == flags & Capp::TCP_URG\n end", "def needs_sending?\n !sent? && !flagged?\n end", "def is_receiving_data\n if defined? TsPoint\n return IsTsInstrumentAlive.call(TsPoint, \"value\", self.id, self.sample_rate_seconds+5)\n else\n return false\n end\n end", "def animated?\n frames = 0\n\n # \"GIF\" + version (3) + width (2) + height (2)\n @stream.skip(10)\n\n # fields (1) + bg color (1) + pixel ratio (1)\n fields = @stream.read(3).unpack(\"CCC\")[0]\n if fields & 0x80 != 0 # Global Color Table\n # 2 * (depth + 1) colors, each occupying 3 bytes (RGB)\n @stream.skip(3 * 2 ** ((fields & 0x7) + 1))\n end\n\n loop do\n block_type = @stream.read(1).unpack(\"C\")[0]\n\n if block_type == 0x21 # Graphic Control Extension\n # extension type (1) + size (1)\n size = @stream.read(2).unpack(\"CC\")[1]\n @stream.skip(size)\n skip_sub_blocks\n elsif block_type == 0x2C # Image Descriptor\n frames += 1\n return true if frames > 1\n\n # left position (2) + top position (2) + width (2) + height (2) + fields (1)\n fields = @stream.read(9).unpack(\"SSSSC\")[4]\n if fields & 0x80 != 0 # Local Color Table\n # 2 * (depth + 1) colors, each occupying 3 bytes (RGB)\n @stream.skip(3 * 2 ** ((fields & 0x7) + 1))\n end\n\n @stream.skip(1) # LZW min code size (1)\n skip_sub_blocks\n else\n break # unrecognized block\n end\n end\n\n false\n end", "def should_allow_close\n return @peer.should_all_close\n end", "def pending_data?\n !pending_queues.empty?\n end", "def ignore_frame?(frame)\n\t\t\t\tif self.closed?\n\t\t\t\t\t# puts \"ignore_frame? #{frame.stream_id} -> #{valid_remote_stream_id?(frame.stream_id)} > #{@remote_stream_id}\"\n\t\t\t\t\tif valid_remote_stream_id?(frame.stream_id)\n\t\t\t\t\t\treturn frame.stream_id > @remote_stream_id\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend", "def should_parse?\n parsed? == false && headers['x-amp'] != 'skip'\n end", "def receive_data_command\n @headers_finished = false\n @body = []\n @headers = {}\n\n return true\n end", "def blocable?\n return data.blocable\n end", "def done_headers?\n [:body_identity, :body_chunked, :body_chunked_tail, :done].include?(@state)\n end", "def is_gzip_file?(filepath)\n # IO.popen([\"file\", \"--brief\", \"--mime-type\", path], &:read).chomp\n extension = File.extname(filepath)\n extension == \".gzip\" || extension == \".gz\"\n end", "def enqueue?(data)\n result = false\n\n begin\n # uses unix domain socket\n sock_path = @sock_path\n enq_sock = UNIXSocket.new(sock_path)\n \n packet = add_header(data)\n\n Lgdisit.logger.info(LgdisitUtil.get_bracketed_string(self.object_id.to_s) + \"Send: \" + packet)\n enq_sock.send packet,0\n result = true\n rescue => exception\n result = false\n Lgdisit.logger.error(exception) \n ensure\n if !enq_sock.nil?\n enq_sock.close \n Lgdisit.logger.info(LgdisitUtil.get_bracketed_string(self.object_id.to_s) + \"Socket closed.\")\n end\n end\n\n return result\n end", "def corrupt?\n checksum_invalid? || torn? || misplaced?\n end", "def snapshots_transport_gzip_requests=(_arg0); end", "def promiscuous?\n\t\t\treturn false\n\t\tend", "def compression_server; end", "def skipping_frame?\n return @frame_to_skip > 0\n end", "def upgrade?\n return false unless status == 101 # \"Switching Protocols\"\n return false unless headers[\"Connection\"] == \"Upgrade\"\n return true\n end", "def compress?(what)\n !!asset_config[\"compress\"][what]\n end", "def size_exhausted?\n @json_size >= (MAX_BYTES - Defaults::Message::MAX_BYTES)\n end", "def examine_block\n if accepted?\n worker && worker.report_accepted_block(self)\n end\n true\n end", "def xmit\n if @lag.zero?\n if @to_server\n $fake_server_port.on_packet_receive(CONNECTION_ID, @data, @channel)\n else\n $fake_client_conn.on_packet(@data, @channel)\n end\n true\n else\n @lag -= 1\n false\n end\n end", "def compress_value?(value, req_options)\n return false unless value.bytesize >= compression_min_size\n return compress_by_default? unless req_options && !req_options[:compress].nil?\n\n req_options[:compress]\n end", "def sending_file?\n @_body.is_a?(::Rack::File::Iterator)\n end", "def open?\n return @header_data != nil\n end", "def recv_frame f\n if @first_frame_in\n # first frame has to be settings\n # FIXME: make sure this is the actual settings, not the ACK to ours\n\n # RFC 7540, Section 3.5\n # \"Clients and servers MUST treat an invalid connection preface\n # as a connection error (Section 5.4.1) of type\n # PROTOCOL_ERROR.\"\n raise ConnectionError.new(PROTOCOL_ERROR, 'invalid preface - no SETTINGS') if f.type != FrameTypes::SETTINGS\n @first_frame_in = false\n end\n\n if @goaway\n case f.type\n when FrameTypes::DATA\n when FrameTypes::HEADERS\n when FrameTypes::PUSH_PROMISE\n when FrameTypes::CONTINUATION\n when FrameTypes::GZIPPED_DATA\n when FrameTypes::DROPPED_FRAME\n else\n # FIXME\n @logger.warn \"Ignoring frame 0x#{f.type.to_s 16} after GOAWAY\"\n return\n end\n end\n\n case f.type\n when FrameTypes::DATA\n handle_data f\n when FrameTypes::HEADERS\n handle_headers f\n when FrameTypes::PRIORITY\n handle_priority f\n when FrameTypes::RST_STREAM\n handle_rst_stream f\n when FrameTypes::SETTINGS\n handle_settings f\n when FrameTypes::PUSH_PROMISE\n handle_push_promise f\n when FrameTypes::PING\n handle_ping f\n when FrameTypes::GOAWAY\n handle_goaway f\n when FrameTypes::WINDOW_UPDATE\n handle_window_update f\n when FrameTypes::CONTINUATION\n # never emitted by the Hook\n raise 'unexpected CONTINUATION frame'\n\n # EXTENSION FRAME HANDLING\n when FrameTypes::GZIPPED_DATA\n handle_gzipped_data f\n when FrameTypes::DROPPED_FRAME\n handle_dropped_frame f\n else\n # ignore unrecognised/extension frames\n drop_frame f\n end\n rescue ConnectionError => e\n @logger.info \"connection error [#{e.code}:#{e}] in client #{@descr} {3}\"\n die e.code\n rescue StreamError => e\n @logger.info \"stream error [#{e.code}:#{e.stream}:#{e}] in client #{@descr}\"\n cancel e.stream, e.code\n end", "def transfer_given?\n params.has_key?(:is_transfer) || params.has_key?(:transfer_buddy)\n end", "def push?\n Capp::TCP_PUSH == flags & Capp::TCP_PUSH\n end", "def valid_gzip? archive\n return unless archive\n return unless File.exist? archive\n `tar tf #{archive} >/dev/null`\n $?.exitstatus == 0\nend", "def done_request_line?\n [:headers, :body_identity, :body_chunked, :body_chunked_tail, :done].include?(@state)\n end", "def valid?\n @method == \"GET\" &&\n !@request_uri.empty? &&\n @http_version >= 1.1 &&\n @header[\"Upgrade\"] == \"websocket\" &&\n @header[\"Connection\"].include?(\"Upgrade\") &&\n Base64.decode64(@header[\"Sec-WebSocket-Key\"]).length == 16 &&\n @header[\"Sec-WebSocket-Version\"].to_i == 13\n end", "def default_compression; end", "def compress_request_if_needed(data)\n encoding = 'identity'\n if data.size > 64 * 1024\n data = Encoders::Compressed.encode(data)\n encoding = 'deflate'\n end\n check_post_size(data)\n [data, encoding]\n end", "def valid?\n received, sent = received_chunk_sizes, sent_chunk_sizes\n sent.all? { |id, size| received[id] == size }\n end", "def valid?\n received, sent = received_chunk_sizes, sent_chunk_sizes\n sent.all? { |id, size| received[id] == size }\n end", "def supports_streaming?\n handler.respond_to?(:supports_streaming?) && handler.supports_streaming?\n end", "def needs_rebundle?\n # Right now compression is the only option that requires rebundling\n @options_hash != options_hash.hash\n end", "def receive_data(data)\n\n if data.match 'SOURCE'\n p data\n send_data(\"HTTP 200 OK\\r\\n\\r\\n\")\n else\n # require 'pry'; binding.pry\n p data.size\n @channel.push(data.bytes)\n end\n end", "def stream_has_data(stream_name)\n # V1 of data streaming - use a local file\n return File.exist?(self.stream_location(stream_name))\n end", "def inflater # :nodoc:\n return yield @socket unless Net::HTTP::HAVE_ZLIB\n return yield @socket unless @decode_content\n return yield @socket if self['content-range']\n\n v = self['content-encoding']\n case v&.downcase\n when 'deflate', 'gzip', 'x-gzip' then\n self.delete 'content-encoding'\n\n inflate_body_io = Inflater.new(@socket)\n\n begin\n yield inflate_body_io\n success = true\n ensure\n begin\n inflate_body_io.finish\n if self['content-length']\n self['content-length'] = inflate_body_io.bytes_inflated.to_s\n end\n rescue => err\n # Ignore #finish's error if there is an exception from yield\n raise err if success\n end\n end\n when 'none', 'identity' then\n self.delete 'content-encoding'\n\n yield @socket\n else\n yield @socket\n end\n end", "def chunkable_version?(ver)\n case ver\n when \"HTTP/1.0\", nil, \"HTTP/0.9\"\n false\n else\n true\n end\n end", "def test_backend_does_not_gzip_vary_accept_encoding_shares_cache_when_first_gzip_then_not\n # The cache can be shared in this case, since despite Vary:\n # Accept-Encoding, the response isn't actually gzipped (so no\n # Content-Encoding).\n assert_cacheable(\"/api/cacheable-vary-accept-encoding/\", {\n :accept_encoding => \"gzip\",\n }, {\n :accept_encoding => nil,\n })\n end" ]
[ "0.766792", "0.74445325", "0.6850856", "0.65573454", "0.63458", "0.60623276", "0.60623276", "0.60442317", "0.5980888", "0.59735066", "0.595472", "0.59233373", "0.5898725", "0.5839625", "0.58131963", "0.57851064", "0.57664853", "0.5682518", "0.56816906", "0.56658715", "0.5640547", "0.56019235", "0.5601821", "0.55780035", "0.55507463", "0.55248547", "0.5518082", "0.53797376", "0.53522784", "0.5342738", "0.5322359", "0.5280073", "0.5271942", "0.5255781", "0.5254792", "0.5239254", "0.5227931", "0.5226109", "0.5207683", "0.51944727", "0.5178815", "0.5164652", "0.5149224", "0.51443624", "0.514343", "0.5123305", "0.51084805", "0.5108257", "0.5108012", "0.51033884", "0.50833464", "0.5061872", "0.50547576", "0.5040983", "0.5036575", "0.50117356", "0.5009516", "0.5008702", "0.500422", "0.49982905", "0.49884427", "0.49770626", "0.4955958", "0.49442542", "0.49369884", "0.49333656", "0.49247336", "0.49213192", "0.49197653", "0.49121833", "0.49057284", "0.4904858", "0.48980728", "0.48877397", "0.48858064", "0.4882766", "0.4879743", "0.48735628", "0.4871824", "0.4870311", "0.48584235", "0.48580363", "0.48577926", "0.48567033", "0.48533228", "0.4849091", "0.48462602", "0.4846001", "0.4842211", "0.48418206", "0.4840415", "0.48333877", "0.48260537", "0.4817684", "0.48013958", "0.4792853", "0.47924605", "0.47923192", "0.47916558", "0.4791301" ]
0.7738065
0
tell the peer we'll accept GZIPPED_DATA frames
def accept_gzip! return if @ext__veto_gzip if !@ext__recv_gzip send_frame Settings.frame_from({Settings::ACCEPT_GZIPPED_DATA => 1}) @ext__recv_gzip = true end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def accept_gzip?\n return if @ext__veto_gzip\n @ext__recv_gzip\n end", "def no_accept_gzip!\n return if @ext__veto_gzip\n if @ext__recv_gzip\n send_frame Settings.frame_from({Settings::ACCEPT_GZIPPED_DATA => 0})\n @ext__recv_gzip = false\n end\n end", "def snapshots_transport_gzip_requests; end", "def receive_data(data)\n\n if data.match 'SOURCE'\n p data\n send_data(\"HTTP 200 OK\\r\\n\\r\\n\")\n else\n # require 'pry'; binding.pry\n p data.size\n @channel.push(data.bytes)\n end\n end", "def send_gzip?\n return if !@ext__peer_gzip\n @ext__send_gzip\n end", "def gzip_requests; end", "def receive_data data\n begin\n # log 'receive_data', data\n @buf << data\n\n while frame = Frame.parse(@buf)\n log 'receive', frame\n process_frame frame\n end\n rescue Exception => e\n logger.exception(\"[amqp] Failed processing frame, closing connection\", e, :trace) unless ENV['IGNORE_AMQP_FAILURES']\n failed\n end\n end", "def check_accept_encoding\n if accept = @stream.request.headers[ACCEPT_ENCODING_KEY]\n accept.split(',').map(&:strip).each do |encoding|\n case encoding\n when GZIP_ENCODING\n if @stream.connection.server.options[:gzip]\n @gzip = true\n @headers[CONTENT_ENCODING_KEY] = GZIP_ENCODING\n break\n end\n\n # \"deflate\" has issues: https://zlib.net/zlib_faq.html#faq39\n #\n when DEFLATE_ENCODING\n if @stream.connection.server.options[:deflate]\n @deflate = true\n @headers[CONTENT_ENCODING_KEY] = DEFLATE_ENCODING\n break\n end\n\n end\n end\n end\n end", "def accept(data)\n @codec.accept dup_adding_state(data)\n end", "def send_gzip!\n if !@ext__send_gzip\n @ext__send_gzip = true\n end\n end", "def receive_end_of_binary_data\n # no-op\n end", "def inflater # :nodoc:\n return yield @socket unless Net::HTTP::HAVE_ZLIB\n return yield @socket unless @decode_content\n return yield @socket if self['content-range']\n\n v = self['content-encoding']\n case v&.downcase\n when 'deflate', 'gzip', 'x-gzip' then\n self.delete 'content-encoding'\n\n inflate_body_io = Inflater.new(@socket)\n\n begin\n yield inflate_body_io\n success = true\n ensure\n begin\n inflate_body_io.finish\n if self['content-length']\n self['content-length'] = inflate_body_io.bytes_inflated.to_s\n end\n rescue => err\n # Ignore #finish's error if there is an exception from yield\n raise err if success\n end\n end\n when 'none', 'identity' then\n self.delete 'content-encoding'\n\n yield @socket\n else\n yield @socket\n end\n end", "def parse!(data)\n @buffer += data\n overhang = nil\n\n if @size.nil?\n # parse the length field of the \n # extract 4 bytes length header\n @size = @buffer.slice!(0...4).unpack(\"N\").first if @buffer.size >= 4 \n else\n # envelope is complete and contains overhang\n overhang = @buffer.slice!(@size, @buffer.size) if @buffer.size > @size\n end\n \n overhang\n end", "def snapshots_transport_gzip_requests=(_arg0); end", "def receive_data(buf)\n @framer << buf\n while @framer.complete?\n num, packet = @framer.next_buffer\n receive_packet(num, packet)\n end\n end", "def proxy_receive_data data\n @proxystatus = :headers if !@proxystatus\n \n if @proxystatus == :headers\n # First gather the headers\n @proxybuffer += data\n if @proxybuffer =~ /\\r\\n\\r\\n/\n\n # Detected end of headers\n header_data = @proxybuffer[0...($~.begin(0))]\n @proxybuffer = @proxybuffer[($~.end(0))..-1]\n\n # Try the webrick parser\n headers = {}\n header_lines = header_data.split(/[\\r\\n]+/)\n status = header_lines[0]\n header_lines[1..-1].each do |line|\n h = line.split(/:\\s*/, 2)\n headers[h[0]] = h[1]\n end\n \n # The rest of the incoming connection \n @proxystatus = :stream\n end\n end\n \n if @proxystatus == :stream\n send_data header_lines[0] + \"\\r\\n\"\n send_data \"Content-Type: \" + headers['Content-Type'] + \"\\r\\n\"\n send_data \"Content-Length: \" + headers['Content-Length'] + \"\\r\\n\"\n send_data \"\\r\\n\"\n send_data @proxybuffer\n\n # Any further data is piped through \n EM::enable_proxy proxy_conn, self, 1024*10\n end\n end", "def receive_binary_data data\n # no-op\n end", "def gzip_requests=(_arg0); end", "def compression_server; end", "def receive_stream_data(data)\n begin\n @buffer.extract(data).each do |line|\n parse_stream_line(line)\n end\n @stream = ''\n rescue => e\n receive_error(\"#{e.class}: \" + [e.message, e.backtrace].flatten.join(\"\\n\\t\"))\n close_connection\n return\n end\n end", "def queue(env, data)\r\n if @error.nil?\r\n data.force_encoding('BINARY')\r\n\r\n @received = @received + data.bytesize\r\n if @received > @expected\r\n @error = \"Invalid Content-Length value\"\r\n clear_buffer\r\n end\r\n\r\n @buffer << data\r\n flush_buffer if @buffer.bytesize > @chunklimit # if multipart\r\n end\r\n end", "def receive_data_command\n @headers_finished = false\n @body = []\n @headers = {}\n\n return true\n end", "def receive_data(data)\n self.data_received_from_upstream << data\n @parser << data unless is_ssl\n self.client.send_data(data)\n end", "def receive_data data\n @connection_attempts = 0\n @buffer.extract(data).each do |packet|\n response = JSON.parse(packet)\n log.debug { d = response['result'].inspect\n \"response: #{response['method']} #{d[0...50]}#{d.size > 50 ? '...' : ''}\" }\n if cb = @requests[response['id']]\n cb.call(response['result'])\n else\n callback(:response, response['method'], response['result'])\n callback(response['method'].to_sym, response['result'])\n end\n end\n end", "def receive_data data\n #puts \"receive data #{data.dump} |(#{data.length})\"\n if data.length == 0\n close\n end\n @response_data += data\n remaining_unhandled_data = handle_data @response_data\n @response_data = remaining_unhandled_data\n end", "def send\n if @accepted then\n # Calculate content length before sending\n \n @headers << \"Content-Length: #{@buffer.length}\\r\\n\"\n \n if !@content_type then\n @headers << \"Content-Type: text/html\\r\\n\"\n end\n\n # Send our data and close the connection\n @server.puts @headers\n @server.puts \"\\r\\n\"\n @server.puts @buffer\n @server.close\n else\n puts \"[Rsws] ERROR: Trying to send response without first accepting it\"\n end\n end", "def receive data\n data.each_char do |char|\n @buffer.concat char\n if @in_header\n prepare_to_parse_message if @buffer.end_with?(\"\\r\\n\\r\\n\")\n else\n parse_message_from_buffer if @buffer.bytesize == @content_length\n end\n end\n end", "def receive_data requestIncoming\r\n # ltodo time these conns out, esp. if I receive nothing\r\n close_connection && return if @blockManager.already_finalized\r\n file, host, port, startByte, endByte, type, fullUrl = TCPSocketConnectionAware.parseHTTPRequest(requestIncoming) # assume it's a request\r\n if !file\r\n debug \"Unable to parse request [#{requestIncoming}] -- giving up. Thread count #{@parent_server_wrapper.aliveServerObjects.length}\"\r\n close_connection # I must presume this terminates us :)\r\n end\r\n \r\n if file != @blockManager.urlFileName\r\n fullUrl = \"http://#{host}:#{port}#{file}\" # ltodo look into this--is this necessary?\r\n if @parent_server_wrapper.serveAnyRequest and file and host and port\r\n error \"within the fake server got request for url #{fullUrl} (not current/starting #{@blockManager.urlFileName}) continuing==possibly in error!\" # ltodo\r\n else\r\n error \"got request for generically WRONG FILE (or bad HTTP request)-- kicking out early their requested file #{file}, is not #{@blockManager.urlFileName} request #{requestIncoming} TURFING\"\r\n close_connection\r\n return\r\n end\r\n end \r\n \r\n if !startByte \r\n assert !endByte\r\n startByte = 0\r\n debug \"guessing full file start #{startByte} end #{endByte} request for whole file\"\r\n end\r\n endByte ||= @blockManager.wholeFileSize - 1\r\n assert startByte <= endByte\r\n log \"got #{type} request for file #{file} port #{port} startByte #{startByte} endByte #{endByte}\"\r\n header = TCPSocketConnectionAware.createReturnHeader(startByte, endByte, getWholeFileSize())\r\n assert header.length > 0\r\n send_data header\r\n debug \"wrote reply header length #{header.length} for type #{type}\"\r\n if type == \"HEAD\" # then we're done\r\n @received_head_request = true\r\n debug \"wrote head of file size #{getWholeFileSize()}! -- closing!\"\r\n close_connection_after_writing\r\n return\r\n end\r\n @received_data_request = true\r\n how_often_check_queue_in_seconds = 0.15#S\r\n chunkSize = 4_000_000*how_often_check_queue_in_seconds # 4 MB/S max empirically this is only like 1.5MB/s serving speed\r\n if @speedLimitPerConnectionBytesPerSecond\r\n how_often_check_queue_in_seconds = 1\r\n chunkSize = [@speedLimitPerConnectionBytesPerSecond, chunkSize].min\r\n end\r\n debug \"using chunkSize #{chunkSize} every #{how_often_check_queue_in_seconds}s\"\r\n nextByteToSendWithinRequest = startByte\r\n @dropped_me = false\r\n send_proc = proc { ||\r\n if @dropped_me\r\n return # never send again :)\r\n end \r\n if @parent_server_wrapper.serverShouldStop\r\n debug \"not sending any more-- parent said we should stop!\" # ltodo cancel these, too, so we don't get weird late logging messages\r\n return\r\n end\r\n assert nextByteToSendWithinRequest <= (endByte + 1)\r\n return if nextByteToSendWithinRequest == endByte + 1\r\n outbound_queue = get_outbound_data_size\r\n debug \"outbound size is #{outbound_queue}\" # ltodo make this have its own call\r\n if outbound_queue > chunkSize/2\r\n debug \"not sending anymore for now\"\r\n return\r\n else\r\n debug \"sending more\"\r\n end\r\n start_send_time = Time.now\r\n lastByteWithinChunk = [endByte, nextByteToSendWithinRequest + chunkSize - 1].min\r\n \r\n nextToWrite = @blockManager.getBytesToReturnToPeerIncludingEndByte(nextByteToSendWithinRequest, lastByteWithinChunk) # hmmm. So the case is that if we don't have any bytes yet downloaded, we'll return as few as we now have, which means ever x sec's, we'll check again to see if there is more to write. ltodo optimize with the 'blank' endings\r\n send_data(nextToWrite)\r\n log \"just successfully queued #{nextToWrite.length}B #{nextByteToSendWithinRequest } -> #{nextByteToSendWithinRequest + nextToWrite.length} out of #{endByte} in #{Time.now - start_send_time}s\"\r\n nextByteToSendWithinRequest += nextToWrite.length\r\n if nextByteToSendWithinRequest == endByte + 1\r\n debug \"done queueing all -- instructing it to close after writing\"\r\n @sender_proc_wrapper.cancel\r\n @queued_all = true\r\n close_connection_after_writing\r\n end\r\n }\r\n #queued_proc = create_proc_that_runs_only_when_outbound_queue_gets_below(5, send_proc) # run when it falls below X\r\n @sender_proc_wrapper = EventMachine::PeriodicTimer.new(how_often_check_queue_in_seconds, send_proc)\r\n send_proc.call # call it once early and fast!\r\n end", "def receive_data(data)\n log_debug { '[server] receive_data: %s' % data }\n\n @request_buffer << data\n @request_data = @request_buffer.data\n @stats.request_size = @request_buffer.size\n\n handle_client if @request_buffer.flushed?\n end", "def receive_data(data)\n Blather.logger.debug \"\\n#{'-'*30}\\n\"\n Blather.logger.debug \"STREAM IN: #{data}\"\n @parser << data\n\n rescue ParseError => e\n @error = e\n send_data \"<stream:error><xml-not-well-formed xmlns='#{StreamError::STREAM_ERR_NS}'/></stream:error>\"\n stop\n rescue => e\n Blather.logger.debug e\n Blather.logger.debug e.backtrace.join(\"\\n\")\n end", "def decompress(data); end", "def compression_client; end", "def accept_kexinit(packet); end", "def receive_data(data)\n Blather.logger.debug \"\\n#{'-'*30}\\n\"\n Blather.logger.debug \"STREAM IN: #{data}\"\n @parser << data\n\n rescue ParseError => e\n @error = e\n send \"<stream:error><xml-not-well-formed xmlns='#{StreamError::STREAM_ERR_NS}'/></stream:error>\"\n stop\n end", "def receiving(data); end", "def receiving(data); end", "def chunked?; end", "def do_data( data )\n @log.debug \"[#{@id}] got #{data.length} bytes\" if @log.debug?\n\n @data << data\n @progress_callback[@data] if @progress_callback\n\n if @length < 0 || @data.length < @length\n if @length < 0\n length = @chunk_size\n else\n length = @length - @data.length\n length = length > @chunk_size ? @chunk_size : length\n end\n\n @log.debug \"[#{@id}] requesting #{length} more bytes\" if @log.debug?\n @driver.read @id, @handle, @offset + @data.length, length\n @session.register( @id, self )\n else\n @callback[ OK, @data ]\n end\n end", "def receive_data(data)\n @logchunk << data\n decompose = true\n while decompose\n if !@length && (@logchunk.length - @pos) > 7\n l = @logchunk[@pos + 0..@pos + 3].to_i\n ck = @logchunk[@pos + 4..@pos + 7].to_i\n if l == ck and l < MAX_MESSAGE_LENGTH\n @length = l\n else\n decompose = false\n peer = @peer ? ::Socket.unpack_sockaddr_in(@peer)[1] : 'UNK'\n if l == ck\n LoggerClass.add_log([:default, :error, \"Max Length Exceeded from #{peer} -- #{l}/#{MAX_MESSAGE_LENGTH}\"])\n send_data(-\"error: max length exceeded\\n\")\n else\n LoggerClass.add_log([:default, :error, \"checksum failed from #{peer} -- #{l}/#{ck}\"])\n send_data(-\"error: checksum failed\\n\")\n end\n close_connection_after_writing\n end\n end\n\n decompose = false if @length && @length < 8\n\n if @length&.positive? and @logchunk.length - @pos >= @length\n msg = @logchunk[@pos..@length + @pos - 1].split(REGEXP_COLON, 4)\n @pos += @length\n if @authenticated\n msg[0] = nil\n msg.shift\n LoggerClass.add_log(msg)\n elsif msg.last == LoggerClass.key\n @authenticated = true\n send_data(-\"accepted\\n\")\n else\n send_data(-\"denied\\n\")\n close_connection_after_writing\n end\n @length = nil\n else\n decompose = false\n end\n end\n return unless @pos >= @logchunk.length\n\n @logchunk.clear\n @pos = 0\n end", "def gzip_enabled; end", "def gzip_enabled; end", "def conclude(finished = true)\n return nil if @finished or @pos < 1\n @conclude.call if @conclude # call the parser's conclude method\n @event_collector.send(:file_transfer) do\n { :server_ip => str_ip(@state.app_state[:dst]),\n :client_ip => str_ip(@state.app_state[:src]),\n :server_port => @state.app_state[:dport],\n :client_port => @state.app_state[:sport], :size => @buff.length,\n :complete => (complete? & finished), :dir => @dir, :protocol => @proto,\n :content => @buff, :name => @name,\n :format => @magic\n }\n end # of sending event\n @finished = true\n end", "def receive_data(chunk)\n @chunk_buffer << chunk\n while frame = next_frame\n self.receive_frame(AMQ::Client::StringAdapter::Frame.decode(frame))\n end\n end", "def recv_frame f\n if @first_frame_in\n # first frame has to be settings\n # FIXME: make sure this is the actual settings, not the ACK to ours\n\n # RFC 7540, Section 3.5\n # \"Clients and servers MUST treat an invalid connection preface\n # as a connection error (Section 5.4.1) of type\n # PROTOCOL_ERROR.\"\n raise ConnectionError.new(PROTOCOL_ERROR, 'invalid preface - no SETTINGS') if f.type != FrameTypes::SETTINGS\n @first_frame_in = false\n end\n\n if @goaway\n case f.type\n when FrameTypes::DATA\n when FrameTypes::HEADERS\n when FrameTypes::PUSH_PROMISE\n when FrameTypes::CONTINUATION\n when FrameTypes::GZIPPED_DATA\n when FrameTypes::DROPPED_FRAME\n else\n # FIXME\n @logger.warn \"Ignoring frame 0x#{f.type.to_s 16} after GOAWAY\"\n return\n end\n end\n\n case f.type\n when FrameTypes::DATA\n handle_data f\n when FrameTypes::HEADERS\n handle_headers f\n when FrameTypes::PRIORITY\n handle_priority f\n when FrameTypes::RST_STREAM\n handle_rst_stream f\n when FrameTypes::SETTINGS\n handle_settings f\n when FrameTypes::PUSH_PROMISE\n handle_push_promise f\n when FrameTypes::PING\n handle_ping f\n when FrameTypes::GOAWAY\n handle_goaway f\n when FrameTypes::WINDOW_UPDATE\n handle_window_update f\n when FrameTypes::CONTINUATION\n # never emitted by the Hook\n raise 'unexpected CONTINUATION frame'\n\n # EXTENSION FRAME HANDLING\n when FrameTypes::GZIPPED_DATA\n handle_gzipped_data f\n when FrameTypes::DROPPED_FRAME\n handle_dropped_frame f\n else\n # ignore unrecognised/extension frames\n drop_frame f\n end\n rescue ConnectionError => e\n @logger.info \"connection error [#{e.code}:#{e}] in client #{@descr} {3}\"\n die e.code\n rescue StreamError => e\n @logger.info \"stream error [#{e.code}:#{e.stream}:#{e}] in client #{@descr}\"\n cancel e.stream, e.code\n end", "def receive_data(data)\n while not (data.nil? or data.empty?)\n data.force_encoding 'BINARY' if data.respond_to?(:force_encoding)\n unless @payload_bytes_to_read\n nul = data.index ?\\0\n if nul\n @buffer << data.slice!(0, nul)\n data.slice!(0,1) # Remove the NUL\n metadata = @buffer.join('')\n @buffer = []\n begin\n receive_metadata(metadata)\n rescue Exception => e\n log_exception(e, 'Invalid metadata', metadata)\n close_connection\n return\n end\n else\n @buffer << data\n data = nil\n end\n end\n if @payload_bytes_to_read\n if data.size >= @payload_bytes_to_read\n @buffer << data.slice!(0, @payload_bytes_to_read)\n payload = @buffer.join('')\n @buffer, @payload_bytes_to_read = [], nil\n begin\n receive_payload(payload)\n rescue Exception => e\n log_exception(e, 'Invalid payload')\n close_connection\n return\n end\n else\n @buffer << data\n @payload_bytes_to_read -= data.size\n data = nil\n end\n end\n end\n end", "def remote_keepalive(sender, body)\nend", "def receive_data(chunk)\n @chunk_buffer << chunk\n while frame = get_next_frame\n receive_frame(AMQ::Client::Framing::String::Frame.decode(frame))\n end\n end", "def content_encoding_gunzip(body_io); end", "def demux(&block)\n @stream.each_packet(&block)\n end", "def send_pending_data\n needs_looping = true\n while needs_looping\n needs_looping = false\n pending_data.delete_if do |socket, chunks|\n if chunks.empty?\n # nothing left to send for this socket\n next\n end\n\n buffer = chunks.shift\n while !chunks.empty? && (buffer.size + chunks[0].size < DATA_CHUNK_SIZE)\n buffer.concat(chunks.shift)\n end\n Server.debug \"sending #{buffer.size} bytes to #{socket}\"\n\n begin\n written = socket.write_nonblock(buffer)\n rescue Interrupt\n raise\n rescue Errno::EAGAIN\n Server.debug \"cannot send: send buffer full\"\n chunks.unshift(buffer)\n next\n rescue Exception => e\n Server.warn \"disconnecting from #{socket}: #{e.message}\"\n e.backtrace.each do |line|\n Server.warn \" #{line}\"\n end\n socket.close\n next(true)\n end\n\n remaining = buffer.size - written\n if remaining == 0\n Server.debug \"wrote complete chunk of #{written} bytes to #{socket}\"\n # Loop if we wrote the complete chunk and there\n # is still stuff to write for this socket\n needs_looping = !chunks.empty?\n else\n Server.debug \"wrote partial chunk #{written} bytes instead of #{buffer.size} bytes to #{socket}\"\n chunks.unshift(buffer[written, remaining])\n end\n false\n end\n end\n end", "def xmit\n if @lag.zero?\n if @to_server\n $fake_server_port.on_packet_receive(CONNECTION_ID, @data, @channel)\n else\n $fake_client_conn.on_packet(@data, @channel)\n end\n true\n else\n @lag -= 1\n false\n end\n end", "def decompress\n header = buf.u32\n return :invalid_data if (header & 0xFF) != 0x11\n decompressedSize = header >> 8\n decompressedSize = buf.u32 if decompressedSize == 0\n\n bufferLength = 0x1000\n buffer = Array.new(bufferLength)\n bufferOffset = 0\n\n flags = 0\n mask = 1\n\n outbuf = []\n until outbuf.size >= decompressedSize\n if mask == 1\n flags = buf.u8\n return :stream_too_short if flags.nil?\n mask = 0x80\n else\n mask >>= 1\n end\n\n if (flags & mask) > 0\n byte1 = buf.u8\n return :stream_too_short if byte1.nil?\n\n length = byte1 >> 4\n disp = -1\n case length\n when 0\n byte2 = buf.u8\n byte3 = buf.u8\n return :stream_too_short if byte3.nil?\n length = (((byte1 & 0x0F) << 4) | (byte2 >> 4)) + 0x11\n disp = (((byte2 & 0x0F) << 8) | byte3) + 0x1\n when 1\n byte2 = buf.u8\n byte3 = buf.u8\n byte4 = buf.u8\n return :stream_too_short if byte4.nil?\n length = (((byte1 & 0x0F) << 12) | (byte2 << 4) | (byte3 >> 4)) + 0x111\n disp = (((byte3 & 0x0F) << 8) | byte4) + 0x1\n else\n byte2 = buf.u8\n return :stream_too_short if byte2.nil?\n length = ((byte1 & 0xF0) >> 4) + 0x1\n disp = (((byte1 & 0x0F) << 8) | byte2) + 0x1\n end\n\n return :invalid_data if disp > outbuf.size\n\n bufIdx = bufferOffset + bufferLength - disp\n length.times do\n next_byte = buffer[bufIdx % bufferLength]\n bufIdx += 1\n outbuf << next_byte\n buffer[bufferOffset] = next_byte\n bufferOffset = (bufferOffset + 1) % bufferLength\n end\n else\n next_byte = buf.u8\n return :stream_too_short if next_byte.nil?\n outbuf << next_byte\n buffer[bufferOffset] = next_byte\n bufferOffset = (bufferOffset + 1) % bufferLength\n end\n end\n\n outbuf\n end", "def receive_data data\n #log.debug { \"Receiving data (#{data.size} bytes)\" }\n @lock.synchronize { @parser.parse(data) }\n rescue\n log.warn { \"Error handling data: #{data.hth}\" }\n p $!; puts *$@\n end", "def enable_gzip; @opts[:enable_gzip]; end", "def receive_data(data)\n case @state\n when :protocol_proposal\n deferrable = @in_flight\n @state = :idle\n @in_flight = nil\n if data == 'ok'\n send_next_request\n deferrable.succeed\n else\n close_connection\n deferrable.fail(\"server response: #{data.inspect}\")\n end\n\n when :request\n @recv_buf << data\n response_size = @recv_buf.unpack('N').first\n if response_size && @recv_buf.bytesize >= response_size + 4\n response = @recv_buf[4, response_size]\n deferrable = @in_flight\n @state = :idle\n @in_flight = @recv_buf = nil\n send_next_request\n deferrable.succeed(response)\n end\n\n else\n raise \"Received data in unexpected state: #{@state.inspect}\"\n end\n end", "def send_chunk(data)\n response.write('%x' % data.size + \"\\r\\n\")\n response.write(data + \"\\r\\n\")\n end", "def gzip_enabled=(_arg0); end", "def << data\n\n # put the data into the buffer, as\n # we might be replaying\n if data\n @buffer << data\n end\n\n # Don't do work if we don't have to\n if @buffer.length < 2\n return\n end\n\n # decode the first 2 bytes, with\n # opcode, lengthgth, masking bit, and frag bit\n h1, h2 = @buffer.unpack(\"CC\")\n\n # check the fragmentation bit to see\n # if this is a message fragment\n fin = ((h1 & 0x80) == 0x80)\n\n # used to keep track of our position in the buffer\n offset = 2\n\n # see above for possible opcodes\n opcode = (h1 & 0x0F)\n\n # the leading length idicator\n length = (h2 & 0x7F)\n\n # masking bit, is the data masked with\n # a specified masking key?\n masked = ((h2 & 0x80) == 0x80)\n\n # Find errors and fail fast\n if h1 & 0b01110000 != 0\n return emit :error, 1002, \"RSV bits must be 0\"\n end\n\n if opcode > 7\n if !fin\n return emit :error, 1002, \"Control frame cannot be fragmented\"\n elsif length > 125\n return emit :error, 1002, \"Control frame is too large #{length}\"\n elsif opcode > 0xA\n return emit :error, 1002, \"Unexpected reserved opcode #{opcode}\"\n elsif opcode == CLOSE && length == 1\n return emit :error, 1002, \"Close control frame with payload of length 1\"\n end\n else\n if opcode != CONTINUATION && opcode != TEXT_FRAME && opcode != BINARY_FRAME\n return emit :error, 1002, \"Unexpected reserved opcode #{opcode}\"\n end\n end\n\n # Get the actual size of the payload\n if length > 125\n if length == 126\n length = @buffer.unpack(\"@#{offset}n\").first\n offset += 2\n else\n length = @buffer.unpack(\"@#{offset}L!>\").first\n offset += 8\n end\n end\n\n # unpack the masking key\n if masked\n key = @buffer.unpack(\"@#{offset}N\").first\n offset += 4\n end\n\n # replay on next frame\n if @buffer.size < (length + offset)\n return false\n end\n\n # Read the important bits\n payload = @buffer.unpack(\"@#{offset}C#{length}\")\n\n # Unmask the data if it\"s masked\n if masked\n payload.bytesize.times do |i|\n payload[i] = ((payload[i] ^ (key >> ((3 - (i % 4)) * 8))) & 0xFF)\n end\n end\n \n payload = payload.pack(\"C*\")\n\n case opcode\n when CONTINUATION\n\n # We shouldn't get a contination without\n # knowing whether or not it's binary or text\n unless @fragmented\n return emit :error, 1002, \"Unexepected continuation\"\n end\n\n if @fragmented == :text\n @chunks << payload.force_encoding(\"UTF-8\")\n else\n @chunks << payload\n end\n\n if fin\n if @fragmented == :text && !valid_utf8?(@chunks)\n return emit :error, 1007, \"Invalid UTF\"\n end\n\n emit :frame, @chunks, @fragmented == :binary\n @chunks = nil\n @fragmented = false\n end\n\n when TEXT_FRAME\n # We shouldn't get a text frame when we\n # are expecting a continuation\n if @fragmented\n return emit :error, 1002, \"Unexepected frame\"\n end\n\n # emit or buffer\n if fin\n unless valid_utf8?(payload)\n return emit :error, 1007, \"Invalid UTF Hmm\"\n end\n\n emit :frame, payload, false\n else\n @chunks = payload.force_encoding(\"UTF-8\")\n @fragmented = :text\n end\n\n when BINARY_FRAME\n # We shouldn't get a text frame when we\n # are expecting a continuation\n if @fragmented\n return emit :error, 1002, \"Unexepected frame\"\n end\n\n # emit or buffer\n if fin\n emit :frame, payload, true\n else\n @chunks = payload\n @fragmented = :binary\n end\n\n when CLOSE\n code, explain = payload.unpack(\"nA*\")\n if explain && !valid_utf8?(explain)\n emit :close, 1007\n else\n emit :close, response_close_code(code)\n end\n\n when PING\n emit :ping, payload\n\n when PONG\n emit :pong, payload\n\n end\n\n # Remove data we made use of and call back\n # TODO: remove recursion\n @buffer = @buffer[offset + length..-1] || \"\"\n if not @buffer.empty?\n self << nil\n end\n\n end", "def no_send_gzip!\n if @ext__send_gzip\n @ext__send_gzip = false\n end\n end", "def unrecv(data)\n @buffer.unget(data)\n data.size\n end", "def send_data_with_http_tunnel(data)\n #msg_data = Base64::encode64(data)\n #@socket_srv.print \"GET /office_send_msg?#{msg_data} HTTP/1.1\\r\\n\"\n # Zip deflate avoid to have special character in the encoded argument\n msg_data = Zlib::Deflate.deflate( data, 1 ).unpack('H*').first \n @socket_srv.print \"GET /office_send_msg?#{msg_data} HTTP/1.1\\r\\n\"\n #@socket_srv.print \"GET /office_send_msg HTTP/1.1\\r\\n\"\n @socket_srv.print \"Host: #{@host_server}:#{@port_server}\\r\\n\"\n @socket_srv.print \"X-Cup-Session-Id: #{@id_http_session}\\r\\n\" if @id_http_session\n @socket_srv.print \"User-Agent: Mozilla/5.0\\r\\n\"\n @socket_srv.print \"Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\"\n @socket_srv.print \"Keep-Alive: 300\\r\\n\"\n @socket_srv.print \"Connection: keep-alive\\r\\n\"\n @socket_srv.print \"\\r\\n\" #end message\n #http_packet = \n #@socket_srv.write(http_packet)\n end", "def receive_data(data)\n (@buffer ||= BufferedTokenizer.new(delimiter = \"__1_EE\")).extract(data).each do |line|\n #strip newline at beginning of line\n if line.match(/^\\W{1}./)\n line = line[1..line.length-1]\n end\n if line.valid?\n log_entry(line)\n send_data \"0\"\n else\n port, ip = Socket.unpack_sockaddr_in(get_peername)\n host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]\n ActiveRecord::Base.logger.error \"Dropped log entry from #{host} - checksum invalid\"\n send_data \"99\"\n end\n end\n end", "def receive_data(data)\n @buffer << data\n end", "def parse(data)\n return 0 unless data && data.bytesize > 0\n if data.bytesize < @bytes_expected\n @buffer << data\n @bytes_expected -= data.bytesize\n return data.bytesize\n else\n @buffer << data[0..@bytes_expected]\n bytes_parsed = parse_chunk(@buffer)\n return 0 if bytes_parsed == 0 # This is an error\n @bytes_expected -= bytes_parsed\n @buffer = String.new\n if @bytes_expected == 0\n @parsed = true\n elsif (data.bytesize-bytes_parsed) > 0\n bytes_parsed += parse(data[bytes_parsed..-1])\n end\n return bytes_parsed \n end\n end", "def ignore_bad_chunking; end", "def ignore_bad_chunking; end", "def inflate(data); end", "def kgio_tryaccept # :nodoc:\n case buf = @to_io.kgio_tryread(4)\n when String\n # unpack the buffer and trigger the signal handler\n signum = buf.unpack('l')\n fake_sig(signum[0])\n # keep looping, more signals may be queued\n when nil # EOF: master died, but we are at a safe place to exit\n fake_sig(:QUIT)\n when :wait_readable # keep waiting\n return false\n end while true # loop, as multiple signals may be sent\n end", "def gzipped?(env)\n env[:response_headers][CONTENT_ENCODING_HEADER] == ENCODING\n end", "def receive_data(data)\n log_debug '[server] receive_data: %s' % data\n @buffer << data\n handle_client if @buffer.flushed?\n end", "def receive(data); end", "def read_packet; end", "def serve(zipped)\n server = TCPServer.new(1174)\n puts \"Server is up on port 1174\\n\\n\"\n while true\n Signal.trap(\"INT\") {\n puts \"\\nCaught interupt signal, server quit\"\n exit\n }\n Thread.new(server.accept) do |client|\n print \"Sending file to #{client.peeraddr[2]} \"\n loading() {\n client.write zipped\n }\n puts \"\\nSuccessfully sent!\\n\\n\"\n client.close\n end\n end\n end", "def on_any_receive()\n Thread.new() do\n begin\n if self.data_readed.size>0\n buff,self.data_readed=self.data_readed,strempty\n yield(buff)\n end\n loop do\n data=(self.recv(64*1024) rescue nil)\n data && data.size>0 ? yield(data) : break\n end\n rescue Exception => e\n $stdout.puts \"#{e} :\\n #{e.backtrace.join(\"\\n \")}\"\n end\n close rescue nil\n end\n end", "def receive_data data\n @buf.extract(data).each do |packet|\n begin\n request = JSON::parse(packet)\n log.debug { request }\n case request['method']\n when \"relay_tx\"\n return handle_relay_tx(request, *request['params'])\n when \"monitor\"\n respond(request, handle_monitor(request, *request['params']))\n else\n if respond_to?(\"handle_#{request['method']}\")\n respond(request, send(\"handle_#{request['method']}\", *request['params']))\n else\n respond(request, { error: \"unknown command: #{request['method']}. send 'help' for help.\" })\n end\n end\n rescue\n respond(request, { error: $!.message })\n end\n end\n rescue Exception\n p $!; puts *$@\n end", "def on_verack\n log.debug { \">> verack\" }\n complete_handshake if outgoing?\n end", "def ping\n if @type == :receiving\n # Receive packets\n header = @socket.readline\n header.match /^(\\d+)\\s+(.+)\\s+(.+)$/\n sequence_number = $1.to_i\n check = $2\n file_number = $3.to_i\n\n return if file_number != @number\n\n # ACK anything if we have received the file\n if done?\n response = receive_frame sequence_number\n\n @stats[:acks_sent] += 1\n if (sequence_number+1) == (@options[:window_size] * 2)\n @socket.puts \"ACK 0 #{@number}\"\n else\n @socket.puts \"ACK #{sequence_number+1} #{@number}\"\n end\n\n return\n end\n\n # Receive data\n response = receive_frame sequence_number\n if response == :redundant\n puts \"Reacknowledge!\"\n acknowledge_frame sequence_number\n return\n end\n\n # Perform checksum\n if response != :illegal\n sum = checksum sequence_number\n end\n\n # Append to file and send ACK, or send NAK\n if response == :illegal\n puts \"Out of order frame #{sequence_number}\"\n @stats[:out_of_order] += 1\n\n max_frame = @options[:window_size] * ((@window % 2) + 1)\n\n blah_frame = @next_frame % (@options[:window_size] * 2)\n blah_frame = (@options[:window_size]*2) if blah_frame == 0 and max_frame == (@options[:window_size]*2)\n nacknowledge_frame blah_frame\n elsif sum == check\n acknowledge_frame sequence_number\n else\n puts \"Corruption Detected\"\n @stats[:corrupted] += 1\n nacknowledge_frame sequence_number\n end\n else\n # Respond to acknowledgments\n ack = @socket.readline\n\n if ack.match /^ACK\\s+(\\d+)\\s+(\\d+)$/\n # Respond to ACK\n sequence_number = $1.to_i\n file_number = $2.to_i\n\n return if file_number != @number\n\n receive_acknowledgement sequence_number\n\n max_frame = @options[:window_size] * ((@window % 2) + 1)\n\n blah_frame = @next_frame % (@options[:window_size] * 2)\n blah_frame = (@options[:window_size]*2) if blah_frame == 0 and max_frame == (@options[:window_size]*2)\n if blah_frame == max_frame\n # window has been acknowledged\n send_next_window\n elsif @next_frame == @total_frames\n puts \"MEH\"\n stop_timeout\n end\n elsif ack.match /^NAK\\s+(\\d+)\\s+(\\d+)$/\n # Respond to NAK\n file_number = $2.to_i\n\n return if file_number != @number\n\n sequence_number = $1.to_i\n puts \"Frame #{sequence_number} NAK\"\n receive_nacknowledgement sequence_number\n end\n end\n end", "def receive_data(data)\n buffer.concat(data)\n end", "def send_data(data); nil; end", "def do_data( channel, data )\n if @parsed_data\n @parsed_data[:content].append data\n return if @parsed_data[:length] > @parsed_data[:content].length\n\n type = @parsed_data[:type]\n content = @parsed_data[:content]\n @parsed_data = nil\n else\n reader = @buffers.reader( data )\n length = reader.read_long-1\n type = reader.read_byte\n content = reader.remainder_as_buffer\n\n if length > content.length\n @parsed_data = { :length => length,\n :type => type,\n :content => content }\n return\n end\n end\n\n if type == FXP_VERSION\n do_version content\n else\n assert_state :open\n @dispatcher.dispatch channel, type, content\n end\n end", "def receive_data(data)\n begin\n @parser << data\n return if restarting\n if @parser.upgrade?\n if !@current.env[UPGRADE_DATA]\n @current.env[UPGRADE_DATA] = @parser.upgrade_data\n @current.process\n else\n @current.parse(data)\n end\n end\n\n rescue HTTP::Parser::Error => e\n terminate_request(false)\n end\n end", "def on_extended_data(&callback)\n @stream_callbacks[STREAM_EXTENDED_DATA] = callback\n end", "def packet(pkt)\n super(pkt)\n ret = nil\n\n # Let's ignore (for now) packets that are simply ACKs and nothing else\n return nil unless pkt.tcp_syn? or pkt.tcp_fin? or pkt.tcp_rst? or\n pkt.tcp_data_len > 0\n \n # Should we be raising a STREAM event?\n if pkt.tcp_data_len > 0 and @event_collector.stream_capture\n @event_collector.stream_capture.each do |sc|\n if (sc[0].nil? or sc[0] == pkt.src.to_i) and # source IP\n (sc[2].nil? or sc[2] == pkt.dst.to_i) and # destination IP\n (sc[1].nil? or sc[1] == pkt.sport) and # source port\n (sc[3].nil? or sc[3] == pkt.dport) # destination port\n @event_collector.send(sc[4]) do\n state = identify_state(pkt, :tcp, false)\n { :content => pkt.tcp_data, :syn_seen => !!state.syn_seen,\n :src_ip => @protos.str_ip(pkt.src.to_i),\n :dst_ip => @protos.str_ip(pkt.dst.to_i), :src_port => pkt.sport,\n :dst_port => pkt.dport }\n end\n end # of if match\n end # of each stream_capture\n end # of if stream event\n\n # Determine the packet's direction (up == src -> dst)\n dir = pkt.src.to_i < pkt.dst.to_i ? :up : :down\n\n # First, identify if this is a new stream or part of one on which we are\n # already keeping state.\n make_state = !(pkt.tcp_fin? or pkt.tcp_rst?)\n state = identify_state(pkt, :tcp, make_state)\n state.ack_seen = pkt.tcp_ack? unless pkt.tcp_rst?\n \n # Check to see if we need to prune some state objects\n if pkt.time.to_i > @next_prune\n @next_prune = pkt.time.to_i + 60 # one minute prune interval\n syn_timeout = pkt.time - @event_collector.syn_timeout_delay\n stream_timeout = pkt.time - @event_collector.stream_timeout_delay\n @states.each do |_,chk|\n if chk.last_seen < syn_timeout\n # Is this state only a syn so far?\n if not chk.ack_seen\n @event_collector.send(:tcp_connect_failed) do\n { :timeout => true, :src_ip => @protos.str_ip(chk.src.to_i),\n :dst_ip => @protos.str_ip(chk.dst.to_i),\n :src_port => chk.sport, :dst_port => chk.dport, :rst => false }\n end\n delete_state(chk)\n \n # Okay, there's been some traffic. Has a full timeout occured?\n elsif chk.last_seen < stream_timeout\n @event_collector.send(:tcp_stream_end) do\n { :syn_seen => !!chk.syn_seen, :timeout => true,\n :src_ip => @protos.str_ip(chk.src.to_i),\n :dst_ip => @protos.str_ip(chk.dst.to_i), :rst => false,\n :dst_port => chk.dport, :src_port => chk.sport, :sync => false,\n :fin => false }\n end\n delete_state(chk)\n end # of if stream_timeout\n end # of syn_timeout\n end\n end\n\n # Is this state brand new? If so, add some TCP-specific information\n state.tcp_init(pkt, @event_collector) unless state.layer_4\n\n # Let's make sure the sequence numbers are what we expect\n ret = validate_sequence_numbers(pkt, state, dir) if state.app_state\n return nil unless ret\n\n # If this is a connection we've seen in its entirety, hand it up to\n # the next stage - the protocol parser (layer 7)\n if state.app_state and pkt.tcp_data and pkt.tcp_data.length > 0\n @protos.parse(pkt.tcp_data, state, dir)\n end\n\n # Is this a FIN or a RST? Should we close out this state?\n if pkt.tcp_fin?\n state.fin_up = true if dir == :up\n state.fin_down = true if dir == :down\n @protos.conclude(state, dir) # Signal the end of this direction\n end\n if pkt.tcp_rst? or (state.fin_up and state.fin_down)\n if not state.ack_seen # Explicit connection rejection\n @event_collector.send(:tcp_connect_failed) do\n { :timeout => false, :src_ip => @protos.str_ip(pkt.dst.to_i),\n :dst_ip => @protos.str_ip(pkt.src.to_i),\n :src_port => pkt.dport, :dst_port => pkt.sport, :rst => true }\n end\n else # regular connection termination\n @event_collector.send(:tcp_stream_end) do\n { :syn_seen => !!state.syn_seen,\n :src_ip => @protos.str_ip(pkt.src.to_i),\n :dst_ip => @protos.str_ip(pkt.dst.to_i), :src_port => pkt.sport,\n :dst_port => pkt.dport, :rst => pkt.tcp_rst?, :sync => false,\n :fin => (state.fin_up and state.fin_down), :timeout => false }\n end\n @protos.conclude(state, :up) # Signal the end of the stream in\n @protos.conclude(state, :down) # both directions.\n end\n delete_state(state)\n end\n\n # Finally, if we have a queued packet to inject, inject it now. This must\n # be done last!\n packet(ret) if ret.class <= ::Pcap::TCPPacket\n true\n end", "def send_body_proc(socket)\n if @request_method == \"HEAD\"\n # do nothing\n elsif chunked?\n @body.call(ChunkedWrapper.new(socket, self))\n _write_data(socket, \"0#{CRLF}#{CRLF}\")\n else\n size = @header['content-length'].to_i\n @body.call(socket) # TODO: StreamWrapper which supports offset, size\n @sent_size = size\n end\n end", "def test_response_read_encoding_deflate_no_zlib\n def @res.read_body()\n yield \"+H,*\\001\\000\"\n end\n def @res.content_length() 6 end\n @res.instance_variable_set :@header, 'content-encoding' => %w[deflate]\n\n body = @agent.response_read @res, @req\n\n assert_equal 'part', body\n end", "def compression?; end", "def header_udp package_number, file_size, signal=\"send\"\n file_size = \"%0#{@header_file_size}b\" % file_size\n number_package = \"%0#{@header_number_package_size}b\" % package_number\n eof = \"0\" if signal == \"send\"\n eof = \"1\" if sd\nclass SendFileManager\n def initialize(socket, address=nil)\n @package_size = 1024\n @address = address\n # @header_package_data = 60\n @header_file_size = 60\n @header_number_package_size = 20\n @h000000000000000000000000000000000000000000010111000110111101eader_eof_size = 1\n @header_size = @header_file_size + @header_number_package_size + @hea\n def send_file file_name, file_position=0\n file = open(\"./#{file_name}\", \"rb\")\n send_size = file_position.to_i\n file.pos = file_position.to_i\n #wait_signal_int(send_size)\n # binding.pry\n while file.size > send_size\n package_data = file.read(@package_size-@header_file_size)\n puts package_data.size\n binding.pry if file.eof?\n package_header = file.eof? ? header(file.size, \"eof\") : header(file.size)\n puts package_header + package_data\n send_size += @socket.send(package_header + package_data, 0)\n \n send_size -= package_header.size\n \n end\n binding.pry\n file.close\n message = @socket.recv(50)\n answer, file_size = message.split\n if answer == 'success'\n puts \"File #{file_name} successfully uploaded!\"\n return true\n el000000000000000000000000000000000000000000010111000110111101se\n send_file(file_name, file_size)\n return false\n end \n end\n \n def wait_sd message OOB'\n puts \"Sent #{send_size} bytes to socket\"\n @socket.send(@oob_char, Socket::MSG_OOB)\n end\n end \n \n def header file_size, signal=\"send\"\n header = \"%0#{@header_file_size}b\" % file_size\n puts header.size\n header[0] = \"0\" if signal == \"send\"\n header[0] = \"1\" if signal == \"eof\"\n header\n end\n\n def send_file_udp file_name,en(\"./#{file_name}\", \"rb\")\n packages_count = (file.size / (@package_size-@header_size).to_f).ceil\n numbers_packages_to_upload = []\n 0.upto(packages_count-1) do |number|\n numbers_packages_to_upload.push(number) unless numbers_downloaded_packages.include?(number)\n end\n send_size = file_position.to_i\n file.pos = file_position.to_i\n numbers_packages_to_upload.each000000000000000000000000000000000000000000010111000110111101 do |package_number|\n file.pos = package_number * (@package_size-@header_size)\n package_data = file.read(@package_size-@header_size)\n package_header = file.eof? ? header_udp(package_number, numbers_packages_to_upload.size, \"eof\") : header_udp(package_number, numbers_packages_to_upload.size)\n package = package_header + package_data\n send_size += @address? @socket.send(package,0,@address) : @socket.send(package,0)\n send_size -= package_header.size\n end\n file.close\n message =s = message.split\n if answer == 'success'\n puts \"File #{file_name} successfully uploaded!\"\n return true\n else\n numbers_packages = numbers_packages.map {|numb| numb.to_i} + numbers_downloaded_packages\n send_file_udp(file_name, file_size, numbers_packages)\n return false\n end\n end\n\n def send_file_udp_server file_name, file_positi000000010111000110111101ackages=[]\n\n file = open(\"./#{file_name}\", \"rb\")\n packages_count = (file.size / (@package_size-@header_size).to_f).ceil\n numbers_packages_to_upload = []\n 0.upto(packages_count-1) do |number|\n numbers_packages_to_upload.push(number) unless numbers_downloaded_packages.include?(number)\n end\n send_size = file_position.to_i\n file.pos = file_position.to_i\n numbers_packages_to_upload.each do |package_number|\n file.pos = package_number * (@package_size-@header_size)\n package_data = file.read(@package_size-@header_size)\n package_header = file.eof? ? header_udp(package_number, numbers_packages_to_upload.size, \"eof\") : header_udp(package_number, numbers_packages_to_upload.size)\n send_size += @socket.send(package_header + package_data, 0)\n send_size -= package_header.size\n end\n file.close\n message = @socket.recv(80000)\n answer, file_size, *numbers_packages = message.split\n 000000010111000110111101'\n puts \"File #{file_name} successfully uploaded!\"\n return true\n else\n numbers_packages = numbers_packages.map {|numb| numb.to_i} + numbers_downloaded_packages\n send_file_udp(file_name, file_size, numbers_packages)\n return false\n end\n end\n #header size = 60\n def header_udp package_number, file_size, signaze\n number_package = \"%0#{@header_number_package_size}b\" % package_number\n eof = \"0\" if signal == \"send\"\n eof = \"1\" if signal == \"eof\"\n file_size + number_package + eof\n end\nend\nclass SendFileManager\n def initialize(socket, address=nil)\n @package_size = 1024\n @address = address\n # @header_package_data = 60\n @header_file_size = 60\n @header_number_package_size = 20\n @header_eof_size = 1\n @header_size = @header_file_size + @header_number_package_size + @header_eof_size\n @oob_char = '!'\n @socket = socket\n end\n\n def send000000000000000000000000000000000000000000010111000110111101_file file_name, file_position=0\n file = open(\"./#{file_name}\", \"rb\")\n send_size = file_position.to_i\n file.pos = file_position.to_i\n #wait_signal_int(send_size)\n # binding.pry\n while file.size > send_size\n package_data = file.read(@package_size-@header_file_size)\n puts package_data.size\n binding.pry if fi \"eof\") : header(file.size)\n puts package_header + package_data\n send_size += @socket.send(package_header + package_data, 0)\n \n send_size -= package_header.size\n \n end\n binding.pry\n file.close\n message = @socket.recv(50)\n answer, file_size = message.split\n if answer == 'success'\n puts \"File #{file_name} successfull_name, file_size)\n return false\n end \n end\n \n def wait_signal_int send_size\n Signal.trap(:INT) do\n puts 'Send message O000000000000000000000000000000000000000000010111000110111101OB'\n puts \"Sent #{send_size} bytes to socket\"\n @socket.send(@oob_char, Socket::MSG_OOB)\n end\n end \n \n def header file_size, signal=\"send\"\n header = \"%0#{@header_file_size}b\" % file_size\n puts header.size\n header[0] = \"0\" if signal == \"send\"\n header[0] = \"1\" if signal == \"eof\"\n header\n end\n\n def send_file_udp file_name, file_position, numbers_downloaded_packages=[]\n file = open(\"./#{file_name}\", \"rb\")\n packages_count = (file.size / (@package_size-@header_size).to_f).ceil\n numbers_packages_to_upload = []\n 0.upto(packages_count-1) do |number|\n numbers_packages_to_upload.push(number) unless numbers_downloaded_packages.include?(number)\n end\n send_size = file_position.to_i\n file.pos = file_position.to_ file.pos = package_number * (@package_size-@header_size)\n package_data = file.read(@package_size-@header_size)\n package_header000000000000000000000000000000000000000000010111000110111101 = file.eof? ? header_udp(package_number, numbers_packages_to_upload.size, \"eof\") : header_udp(package_number, numbers_packages_to_upload.size)\n package = packet.send(package,0,@address) : @socket.send(package,0)\n send_size -= package_header.size\n end\n file.close\n message = @socket.recv(80000)\n answer, file_size, *numbers_packages = message.split\n if answer == 'success'\n puts \"File #{file_name} successfully uploaded!\"\n return true\n else\n numbers_packages = numbers_packages.map {|numb| numb.to_i} + numbers_downloaded_packages\n send_file_udp(file_name, file_size, numbers_packages)\n return false\n end\n end\n\n def send_file_udp_server file_name, file_position, numbers_downloaded_packages=[]\n\n file = open(\"./#{file_name}\", \"rb\")\n packages_count = (file.size / (@package_size-@header_size).to_f).ceil\n numbers_packages_to_upload = []\n 000000000000000000000000000000000000000000010111000110111101 0.upto(packages_count-1) do |number|\n numbers_packages_to_upload.push(number) unless numbers_downloaded_packages.include?(number)\n end\n send_size = firs_packages_to_upload.each do |package_number|\n file.pos = package_number * (@package_size-@header_size)\n package_data = file.read(@package_size-@header_size)\n package_header = file.eof? ? header_udp(package_number, numbers_packages_to_upload.size, \"eof\") : header_udp(package_number, numbers_packages_to_upload.size)\n send_size += @socket.sende_header.size\n end\n file.close\n message = @socket.recv(80000)\n answer, file_size, *numbers_packages = message.split\n if answer == 'success'\n puts \"File #{file_name} successfully uploaded!\"\n return true\n else\n numbers_packages = numbers_packages.map {|numb| numb.to_i} + numbers_downl000000000000000000000000000000000000000000010111000110111101oaded_packages\n send_file_udp(file_name, file_size, numbers_packages)\n return false\n end\n end\n #header size = 60\n def header_udp package_number, file_size, signal=\"send\"\n file_size = \"%0#{@header_file_size}b\" % file_size\n number_package = \"%0#{@header_number_package_size}b\" % package_number\n eof = \"0\" if signal == \"send\"\n eof = \"1\" if signal == \"eof\"\n file_size + number_package + eof\n end\nend", "def receive_data data\n @buf.extract(data).each do |line|\n @lines_received += 1\n @bytes_received += line.bytesize\n\n receive_line line.chomp\n end\n end", "def _receive_response opaque\n _read stream\n end", "def as_received\n raw_data\n end", "def compress(data); end", "def process_data\n unless @state.include?(:rcpt)\n send_data \"503 Operation sequence error\\r\\n\"\n else\n succeeded = proc {\n send_data \"354 Send it\\r\\n\"\n @state << :data\n @databuffer = []\n }\n failed = proc {\n send_data \"550 Operation failed\\r\\n\"\n }\n\n d = receive_data_command\n\n if d.respond_to?(:callback)\n d.callback(&succeeded)\n d.errback(&failed)\n else\n (d ? succeeded : failed).call\n end\n end\n end", "def receive_packet(response)\n pending_pos = nil\n pending_callback = nil\n @pending.each_with_index do |(pending_opaque,pending_cb),i|\n if response[:opaque] == pending_opaque\n pending_pos = i\n pending_callback = pending_cb\n break\n end\n end\n\n if pending_pos\n @pending = @pending[pending_pos..-1]\n begin\n if pending_callback.call(response) != :proceed\n @pending.shift\n end\n rescue Exception => e\n $stderr.puts \"#{e.class}: #{e}\\n\" + e.backtrace.join(\"\\n\")\n end\n end\n end", "def supports_streaming?; end", "def send_dat(*args)\n debug \"send_dat: args is #{args}\"\n opts = {}\n if args.length > 0 and args[0].class == 'Hash'\n opts = args[0]\n end\n\n unless opts.key?(:resend) and opts[:resend]\n blksize = @options[:blksize].to_i\n debug \"Reading #{blksize} bytes from file #{@filename}\"\n @buffer = @file.read(blksize)\n debug \"@buffer is now #{@buffer.class}\"\n debug \"Read #{@buffer.length} bytes into buffer\"\n if @file.eof\n info \"End of file #{@filename} detected.\"\n @file.close\n @state = :fin\n end\n\n @blocknumber += 1\n if @blocknumber > MaxBlockNum\n debug \"Blocknumber rolled over to zero\"\n @blocknumber = 0\n end\n else\n warn \"Resending block number #{@blocknumber}\"\n end\n\n dat = TftpPacketDAT.new\n dat.data = @buffer\n dat.blocknumber = @blocknumber\n debug \"Sending DAT packet #{@blocknumber}\"\n @sock.send(dat.encode.buffer, 0, @host, @port)\n @timesent = Time.now\n end", "def handle_server\n \t\t\t\tcase @state\n \t\t\t\twhen :new\n if @data_buf.length >= 64\n \t\t\t\t\tb = @data_buf.slice!(0,64)\n \t\t\t\t\tb1 = @bot.rsakey.private_decrypt(b)\n if b1[16,32] == @aes_recv.key\n \t\t\t\t\treturn false unless b1[16,32] == @aes_recv.key\n \t\t\t\t\t@v = @aes_send.encrypt(\"1\\r\\n\")\n \t\t\t\t\tputs \"Session #{@id}: sending verify\" if @@debug\n \t\t\t\t\tsend_data @v\n \t\t\t\t\t@state = :recv_verify\n else\n close_connection\n @data_suf = false\n end\n else\n @data_suf = false\n end\n \t\t\t\twhen :recv_verify\n \t\t\t\t\tputs \"Session #{@id}: receiving verify\" if @@debug\n if @data_buf.length >= 3\n b = @data_buf.slice!(0,3)\n \t\t\t\t\t# this isn't always true in the real Nugache traces, but without knowing the\n \t\t\t\t\t# underlying protocol, this is the best I can do\n if b == @v\n \t\t\t\t\tputs \"Session #{@id}: ready\" if @@debug\n \t\t\t\t\t@state = :connected\n else\n close_connection\n @data_suf = false\n end\n else\n @data_suf = false\n end\n \t\t\t\twhen :connected\n \t\t\t\t\tputs \"Session #{@id}: receiving block\" if @@debug\n b = @data_buf\n @data_buf = \"\"\n @data_suf = false\n # TODO: how are we going to handle partial bundles of data?\n if b.length > 0\n out = @aes_recv.decrypt(b)\n @bot.process(out, @peer)\n end\n \t\t\t\tend\n \t\t\tend", "def receive_data data\n\n # First we get all the headers in to find out which resource\n # we are looking for.\n\n if @status == :header\n @buffer += data\n\n if @buffer =~ /\\r\\n\\r\\n/\n\n # Detected end of headers\n header_data = @buffer[0...($~.begin(0))]\n\n @web_config = WEBrick::Config::HTTP.clone\n @web_config[:HTTPVersion] = WEBrick::HTTPVersion.new(\"1.0\")\n\n # Try the webrick parser\n @req = WEBrick::HTTPRequest.new(@web_config)\n @res = WEBrick::HTTPResponse.new(@web_config)\n\n StringIO.open(header_data, 'rb') do |socket|\n @req.parse(socket)\n end\n\n # The rest of the incoming connection\n @buffer = @buffer[($~.end(0))..-1]\n\n # Compute the ID of the sought resource\n if @req.path =~ /\\/adhd\\/(.*)/\n @req.header[\"Filename\"] = $1\n @req.header[\"ID\"] = MD5.new($1).to_s\n else\n # TODO: return a 404 here\n send_error 404, \"Not Found\", \"The URL does not seem to contain /adhd/filename\"\n # raise \"Remember to have a url of the form /adhd/<filenname>.\"\n end\n\n # Change the status once headers are found\n @status = :find_node\n else\n # Avoid DoS via buffer filling\n close_connection if @buffer.length > 1000\n end\n end\n\n # Now we have the headers, but maybe not the full body, and we are looking\n # for the right node in our network to handle the call.\n if @status == :find_node\n # We want to tell the remote host to wait a bit\n # This would allow us to defer the execution of the calls to find\n # the right nodes, and extract the doc.\n\n # TODO: We need to push all the chit-chat with the remote servers to\n # A deferable object, or some other connection, not to block.\n # Right now we are blocking and it sucks.\n\n # Now get or write the document associated with this file\n\n if @req.request_method == \"GET\"\n\n @our_doc = @node_manager.srdb.get_doc_directly(@req.header[\"ID\"])\n\n # TODO: handle errors if file does not exist\n if @our_doc[:ok]\n @status == :get\n handle_get\n else\n send_error 500, \"Internal Server Error\", @our_doc[:reason]\n end\n end\n\n if @req.request_method == \"PUT\"\n # Define a Doc with the data so far\n @our_doc = StoredFile.new\n\n @our_doc._id = @req.header[\"ID\"]\n @our_doc.internal_id = @req.header[\"ID\"]\n @our_doc.size_bytes = @req.content_length\n @our_doc.filename = @req.header[\"Filename\"]\n @our_doc.mime_type = @req.content_type\n\n # Write to the right node\n @our_doc = @node_manager.srdb.write_doc_directly(@our_doc)\n\n # TODO: if an error is returned here, we cannot execute the query\n if @our_doc[:ok]\n @status = :put\n handle_put\n else\n send_error 410, \"Conflict\", @our_doc[:reason]\n end\n end\n end\n end", "def send_raw_data request, response, data, mime, status_code = 200, headers = {}\n\t\t\t\theaders.each {|k, v| response[k] = v}\n\t\t\t\tresponse.status = status_code if response.status == 200 # avoid resetting a manually set status \n\t\t\t\tresponse['content-type'.freeze] = mime\n\t\t\t\tresponse['cache-control'.freeze] ||= 'public, max-age=86400'.freeze\t\t\t\t\n\t\t\t\tresponse.body = data\n\t\t\t\t# response['content-length'] = data.bytesize #this one is automated by the server and should be avoided to support Range requests.\n\t\t\t\ttrue\n\t\t\tend", "def receive_data data\n\t\tputs \"............>>>#{data.length}\"\n\tend", "def on_message(event)\n data = if @inflate\n packed = event.data.pack('c*')\n @inflate << packed\n return unless packed.end_with?(ZLIB_SUFFIX)\n\n @inflate.inflate('')\n else\n event.data\n end\n\n LOGGER.debug { \"[IN] #{data[0].ord == 131 ? data.inspect : data}\" }\n emit(:message, data)\n end" ]
[ "0.6632567", "0.63472205", "0.59732676", "0.5944581", "0.59191394", "0.58648014", "0.57127595", "0.56354225", "0.561135", "0.55936605", "0.55447555", "0.54818", "0.54678214", "0.5440597", "0.54247224", "0.54160464", "0.5398543", "0.53897715", "0.5374744", "0.535133", "0.53371924", "0.53327394", "0.53017217", "0.5280476", "0.52472174", "0.5217442", "0.5202844", "0.5191842", "0.5185563", "0.515761", "0.51573974", "0.5139682", "0.51263154", "0.5120524", "0.5103581", "0.5103581", "0.5089181", "0.5058012", "0.5042108", "0.5031818", "0.5031818", "0.5026299", "0.5012977", "0.500967", "0.5004803", "0.5002181", "0.49956095", "0.49834564", "0.4981095", "0.49807975", "0.49807307", "0.49761397", "0.4971726", "0.49629617", "0.49628597", "0.4955738", "0.49518692", "0.4931456", "0.49274918", "0.4918041", "0.49109066", "0.49008447", "0.4897378", "0.48941958", "0.4887839", "0.4887839", "0.48805323", "0.4879609", "0.4879164", "0.4870289", "0.486712", "0.4866136", "0.48512015", "0.48367906", "0.4836117", "0.48358956", "0.48279658", "0.48268494", "0.48216483", "0.48206854", "0.48095134", "0.480867", "0.48029956", "0.48019087", "0.48014727", "0.4796043", "0.47951797", "0.4795048", "0.47906157", "0.47819087", "0.47774094", "0.47749463", "0.47709754", "0.47659746", "0.4758538", "0.47573692", "0.47551656", "0.47540587", "0.47525784", "0.47524786" ]
0.7478205
0
tell the peer we don't accept GZIPPED_DATA frames
def no_accept_gzip! return if @ext__veto_gzip if @ext__recv_gzip send_frame Settings.frame_from({Settings::ACCEPT_GZIPPED_DATA => 0}) @ext__recv_gzip = false end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def accept_gzip!\n return if @ext__veto_gzip\n if !@ext__recv_gzip\n send_frame Settings.frame_from({Settings::ACCEPT_GZIPPED_DATA => 1})\n @ext__recv_gzip = true\n end\n end", "def no_send_gzip!\n if @ext__send_gzip\n @ext__send_gzip = false\n end\n end", "def accept_gzip?\n return if @ext__veto_gzip\n @ext__recv_gzip\n end", "def ignore_bad_chunking; end", "def ignore_bad_chunking; end", "def send_gzip?\n return if !@ext__peer_gzip\n @ext__send_gzip\n end", "def ignore_bad_chunking\n @agent.ignore_bad_chunking\n end", "def ignore_bad_chunking=(ignore_bad_chunking); end", "def ignore_bad_chunking=(_arg0); end", "def cannot_compress?\n !can_compress?\n end", "def snapshots_transport_gzip_requests; end", "def receive_end_of_binary_data\n # no-op\n end", "def receive_binary_data data\n # no-op\n end", "def accept_no_image_data\n @accept_no_image_data = true\n end", "def send_gzip!\n if !@ext__send_gzip\n @ext__send_gzip = true\n end\n end", "def check_accept_encoding\n if accept = @stream.request.headers[ACCEPT_ENCODING_KEY]\n accept.split(',').map(&:strip).each do |encoding|\n case encoding\n when GZIP_ENCODING\n if @stream.connection.server.options[:gzip]\n @gzip = true\n @headers[CONTENT_ENCODING_KEY] = GZIP_ENCODING\n break\n end\n\n # \"deflate\" has issues: https://zlib.net/zlib_faq.html#faq39\n #\n when DEFLATE_ENCODING\n if @stream.connection.server.options[:deflate]\n @deflate = true\n @headers[CONTENT_ENCODING_KEY] = DEFLATE_ENCODING\n break\n end\n\n end\n end\n end\n end", "def gzip_requests; end", "def ignore?(buf); end", "def ignore_encoding_error; end", "def delete_packet_filter\n super\n end", "def decline\n @stream.clear_handlers :s5b_open, :from => @iq.from\n @stream.write StanzaError.new(@iq, 'not-acceptable', :auth).to_node\n end", "def drop_buffered_data\n # the following line needs else branch coverage\n agent.drop_buffered_data if agent # rubocop:disable Style/SafeNavigation\n record_api_supportability_metric(:drop_buffered_data)\n end", "def cannot_compress?(mime_types)\n !can_compress?(mime_types)\n end", "def gzip_disabled?\n @disable_gzip\n end", "def receive_bad_frame(frame, exception)\n nil\n end", "def ignore_bad_chunking= ignore_bad_chunking\n @agent.ignore_bad_chunking = ignore_bad_chunking\n end", "def gzip_enabled; end", "def gzip_enabled; end", "def ignore_encoding_error=(_arg0); end", "def send_data(data); nil; end", "def no_data_received\n execute_callback(@no_data_received_callback)\n\n #The connection is closed so that it can be re-attempted again\n close_connection\n end", "def accept_nonblock(*) end", "def accept_nonblock(*) end", "def accept_nonblock(*) end", "def skip_for_gif\n ! %w(image/gif).include?(image_content_type)\n end", "def drop_frame f\n if !@ext__sent_dropped_frame[f.type]\n @ext__sent_dropped_frame[f.type] = true\n g = Frame.new FrameTypes::DROPPED_FRAME, 0x00, 0, [f.type].pack('C')\n send_frame g\n end\n end", "def unrecv(data)\n @buffer.unget(data)\n data.size\n end", "def snapshots_transport_gzip_requests=(_arg0); end", "def on_ignored_request\n end", "def accept_nonblock\r\n end", "def gzip_enabled=(_arg0); end", "def on_no_data_received &block\n @no_data_received_callback = block\n end", "def discard!\n # This should be overridden by concrete adapters.\n #\n # Prevent @connection's finalizer from touching the socket, or\n # otherwise communicating with its server, when it is collected.\n end", "def captured_data_tag\n CapturedDataTags::NO_DATA\n end", "def allow?(packet); end", "def dispatch_incoming_packets(raise_disconnect_errors: T.unsafe(nil)); end", "def discard\n @av_stream[:discard]\n end", "def filter(data)\n deflated = nil\n begin\n deflated = Zlib::Inflate.new.inflate(data)\n rescue Zlib::DataError => e\n # by default, Ruby's Zlib assumes the data it's inflating\n # is RFC1951 deflated data, wrapped in a RFC1951 zlib container.\n # If that fails, then use an undocumented 'feature' to attempt to inflate\n # the data as a raw RFC1951 stream.\n #\n # See\n # - http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/243545\n # - http://www.gzip.org/zlib/zlib_faq.html#faq38\n deflated = Zlib::Inflate.new(-Zlib::MAX_WBITS).inflate(data)\n end\n Depredict.new(@options).filter(deflated)\n rescue Exception => e\n # Oops, there was a problem inflating the stream\n raise MalformedPDFError, \"Error occured while inflating a compressed stream (#{e.class.to_s}: #{e.to_s})\"\n end", "def on_frame_sent frame\n if @read_gate.first && frame[:type] == :settings\n @read_gate.first = false\n @read_gate.unblock!\n end\n end", "def compressed?\n false\n end", "def discard!\n # This should be overridden by concrete adapters.\n end", "def on_no_data &block\n @no_data_callback = block\n end", "def allow_iframe\n\t response.headers.except! 'X-Frame-Options'\n\t end", "def unsend!\n @_sended = false\n end", "def skipping_frame?\n return @frame_to_skip > 0\n end", "def read_blocked\n end", "def ignore_frame?(frame)\n\t\t\t\tif self.closed?\n\t\t\t\t\t# puts \"ignore_frame? #{frame.stream_id} -> #{valid_remote_stream_id?(frame.stream_id)} > #{@remote_stream_id}\"\n\t\t\t\t\tif valid_remote_stream_id?(frame.stream_id)\n\t\t\t\t\t\treturn frame.stream_id > @remote_stream_id\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend", "def gzip_requests=(_arg0); end", "def enable_gzip; @opts[:enable_gzip]; end", "def suppress_encoding; end", "def recv_frame f\n if @first_frame_in\n # first frame has to be settings\n # FIXME: make sure this is the actual settings, not the ACK to ours\n\n # RFC 7540, Section 3.5\n # \"Clients and servers MUST treat an invalid connection preface\n # as a connection error (Section 5.4.1) of type\n # PROTOCOL_ERROR.\"\n raise ConnectionError.new(PROTOCOL_ERROR, 'invalid preface - no SETTINGS') if f.type != FrameTypes::SETTINGS\n @first_frame_in = false\n end\n\n if @goaway\n case f.type\n when FrameTypes::DATA\n when FrameTypes::HEADERS\n when FrameTypes::PUSH_PROMISE\n when FrameTypes::CONTINUATION\n when FrameTypes::GZIPPED_DATA\n when FrameTypes::DROPPED_FRAME\n else\n # FIXME\n @logger.warn \"Ignoring frame 0x#{f.type.to_s 16} after GOAWAY\"\n return\n end\n end\n\n case f.type\n when FrameTypes::DATA\n handle_data f\n when FrameTypes::HEADERS\n handle_headers f\n when FrameTypes::PRIORITY\n handle_priority f\n when FrameTypes::RST_STREAM\n handle_rst_stream f\n when FrameTypes::SETTINGS\n handle_settings f\n when FrameTypes::PUSH_PROMISE\n handle_push_promise f\n when FrameTypes::PING\n handle_ping f\n when FrameTypes::GOAWAY\n handle_goaway f\n when FrameTypes::WINDOW_UPDATE\n handle_window_update f\n when FrameTypes::CONTINUATION\n # never emitted by the Hook\n raise 'unexpected CONTINUATION frame'\n\n # EXTENSION FRAME HANDLING\n when FrameTypes::GZIPPED_DATA\n handle_gzipped_data f\n when FrameTypes::DROPPED_FRAME\n handle_dropped_frame f\n else\n # ignore unrecognised/extension frames\n drop_frame f\n end\n rescue ConnectionError => e\n @logger.info \"connection error [#{e.code}:#{e}] in client #{@descr} {3}\"\n die e.code\n rescue StreamError => e\n @logger.info \"stream error [#{e.code}:#{e.stream}:#{e}] in client #{@descr}\"\n cancel e.stream, e.code\n end", "def blocked?\n false\n end", "def gzipped?(env)\n env[:response_headers][CONTENT_ENCODING_HEADER] == ENCODING\n end", "def _safe_inflate data\n zi = Zlib::Inflate.new\n pos = 0; r = String.new\n begin\n # save some memory by not using String#[] when not necessary\n r << zi.inflate(pos==0 ? data : data[pos..-1])\n if zi.total_in < data.size\n @extradata << data[zi.total_in..-1]\n STDERR.puts \"[?] #{@extradata.last.size} bytes of extra data after zlib stream\".red if @verbose >= 1\n end\n # decompress OK\n rescue Zlib::BufError\n # tried to decompress, but got EOF - need more data\n STDERR.puts \"[!] #{$!.inspect}\".red if @verbose >= -1\n # collect any remaining data in decompress buffer\n r << zi.flush_next_out\n rescue Zlib::DataError\n STDERR.puts \"[!] #{$!.inspect}\".red if @verbose >= -1\n #p [pos, zi.total_in, zi.total_out, data.size, r.size]\n r << zi.flush_next_out\n # XXX TODO try to skip error and continue\n# printf \"[d] pos=%d/%d t_in=%d t_out=%d bytes_ok=%d\\n\".gray, pos, data.size,\n# zi.total_in, zi.total_out, r.size\n# if pos < zi.total_in\n# pos = zi.total_in\n# else\n# pos += 1\n# end\n# pos = 0\n# retry if pos < data.size\n rescue Zlib::NeedDict\n STDERR.puts \"[!] #{$!.inspect}\".red if @verbose >= -1\n # collect any remaining data in decompress buffer\n r << zi.flush_next_out\n end\n\n r == \"\" ? nil : r\n ensure\n zi.close if zi && !zi.closed?\n end", "def inflater # :nodoc:\n return yield @socket unless Net::HTTP::HAVE_ZLIB\n return yield @socket unless @decode_content\n return yield @socket if self['content-range']\n\n v = self['content-encoding']\n case v&.downcase\n when 'deflate', 'gzip', 'x-gzip' then\n self.delete 'content-encoding'\n\n inflate_body_io = Inflater.new(@socket)\n\n begin\n yield inflate_body_io\n success = true\n ensure\n begin\n inflate_body_io.finish\n if self['content-length']\n self['content-length'] = inflate_body_io.bytes_inflated.to_s\n end\n rescue => err\n # Ignore #finish's error if there is an exception from yield\n raise err if success\n end\n end\n when 'none', 'identity' then\n self.delete 'content-encoding'\n\n yield @socket\n else\n yield @socket\n end\n end", "def recvfrom_nonblock(*rest) end", "def recvfrom_nonblock(*rest) end", "def write_nonblock(data, *_); end", "def response_unavailable?\n !!(content_for_scanner =~ /Server too busy, try again later/)\n end", "def recv_nonblock(*rest) end", "def corrupt?\n checksum_invalid? || torn? || misplaced?\n end", "def allow_iframe\n response.headers.except!('X-Frame-Options')\n end", "def remote_keepalive(sender, body)\nend", "def should_encode?\n !@raw\n end", "def parse!(data)\n @buffer += data\n overhang = nil\n\n if @size.nil?\n # parse the length field of the \n # extract 4 bytes length header\n @size = @buffer.slice!(0...4).unpack(\"N\").first if @buffer.size >= 4 \n else\n # envelope is complete and contains overhang\n overhang = @buffer.slice!(@size, @buffer.size) if @buffer.size > @size\n end\n \n overhang\n end", "def should_deflate?(env, status, headers, body)\n return false if Utils::STATUS_WITH_NO_ENTITY_BODY.include?(status.to_i) ||\n headers['Cache-Control']&.include?('no-transform') ||\n headers['Content-Encoding']&.include?('identity')\n\n return false if @compressible_types&.include?(headers['Content-Type']&.split(';')&.first) == false\n return false if @condition&.call(env, status, headers, body) == false\n\n true\n end", "def write_frame_nonblock frame\n ser = serializer.frame_to_bytes frame\n push_write_buffer ser, frame\n end", "def handle_unverified_request\n true\n end", "def handle_unverified_request\n true\n end", "def handle_missing_extent\n @bytecount, @byteoffset, @startblock, @fileoffset, @partition = 0, 0, 0, 0, 'b'\n end", "def gzip_enabled=(enabled); end", "def should_not_receive(sym, info = {:with => :any, :block => :any, :count => 0})\r\n info[:count] = 0\r\n should_receive sym, info\r\n end", "def compression?; end", "def should_not_receive(sym, info = {:with => :any, :block => :any, :count => 0})\r\n info[:count] = 0\r\n should_receive sym, info\r\n end", "def skip_http_headers; end", "def discard; end", "def discard; end", "def allow_iframe\n response.headers.except! 'X-Frame-Options'\n end", "def allow_iframe\n response.headers.except! 'X-Frame-Options'\n end", "def not_acceptable(message = nil)\n http_error(406, message, VARY)\n end", "def multi_response_abort\n @multi_buffer = nil\n @position = nil\n @inprogress = false\n failure!(RuntimeError.new('External timeout'))\n rescue NetworkError\n true\n end", "def send_pending_data\n needs_looping = true\n while needs_looping\n needs_looping = false\n pending_data.delete_if do |socket, chunks|\n if chunks.empty?\n # nothing left to send for this socket\n next\n end\n\n buffer = chunks.shift\n while !chunks.empty? && (buffer.size + chunks[0].size < DATA_CHUNK_SIZE)\n buffer.concat(chunks.shift)\n end\n Server.debug \"sending #{buffer.size} bytes to #{socket}\"\n\n begin\n written = socket.write_nonblock(buffer)\n rescue Interrupt\n raise\n rescue Errno::EAGAIN\n Server.debug \"cannot send: send buffer full\"\n chunks.unshift(buffer)\n next\n rescue Exception => e\n Server.warn \"disconnecting from #{socket}: #{e.message}\"\n e.backtrace.each do |line|\n Server.warn \" #{line}\"\n end\n socket.close\n next(true)\n end\n\n remaining = buffer.size - written\n if remaining == 0\n Server.debug \"wrote complete chunk of #{written} bytes to #{socket}\"\n # Loop if we wrote the complete chunk and there\n # is still stuff to write for this socket\n needs_looping = !chunks.empty?\n else\n Server.debug \"wrote partial chunk #{written} bytes instead of #{buffer.size} bytes to #{socket}\"\n chunks.unshift(buffer[written, remaining])\n end\n false\n end\n end\n end", "def dechunk?\n self.class.dechunk? && chunked?\n end", "def ignore_request!\n return if @ignoring_request\n\n # Set instance variable\n @ignoring_request = true\n\n # Store data we'll need\n @ignoring_depth = @layers.length\n\n # Clear data\n @layers = []\n @root_layer = nil\n @call_set = nil\n @annotations = {}\n @instant_key = nil\n end", "def gzip_enabled\n @agent.gzip_enabled\n end", "def do_chunked_encoding?(hdrs=@headers)\n ( (not @opts[:ignore_chunked_encoding]) and \n (hdrs.get_header_value(\"Transfer-Encoding\").to_s =~ /(?:^|\\W)chunked(?:\\W|$)/) )\n end", "def unbind\n if @current_state == 'streaming'\n @parser.parse_unflushed_data\n end\n\n if !@intentionally_closed\n setup_reconnect\n end\n\n execute_callback(@connection_close_callback)\n @current_state = 'init'\n end", "def reject?(sender)\r\n false\r\n end", "def allow_framing\n response.headers.delete \"X-Frame-Options\"\n end", "def prepare_parsed_frame frame\n force_body_encoding frame\n end" ]
[ "0.6865061", "0.63741463", "0.62295026", "0.610589", "0.610589", "0.5976867", "0.58996403", "0.5692219", "0.5689522", "0.56092215", "0.5589415", "0.55344594", "0.55241996", "0.5496961", "0.5429668", "0.54194087", "0.5402771", "0.5391948", "0.53852093", "0.5376257", "0.53749025", "0.53295314", "0.53102213", "0.5279947", "0.5235444", "0.52286834", "0.5211493", "0.5211493", "0.51692903", "0.51551795", "0.5136729", "0.5111259", "0.5111259", "0.5111259", "0.50912696", "0.5089125", "0.5072624", "0.5060811", "0.5054859", "0.5032724", "0.5032414", "0.50019455", "0.50005126", "0.4968893", "0.49534908", "0.4943895", "0.49077326", "0.49066657", "0.4905945", "0.4895965", "0.48714235", "0.48564687", "0.4855328", "0.48461586", "0.48437423", "0.48433417", "0.48367465", "0.4831367", "0.4827562", "0.4805518", "0.48051083", "0.47995704", "0.4793889", "0.47930798", "0.47781047", "0.47659922", "0.47659922", "0.47632334", "0.47538695", "0.4749123", "0.47472495", "0.47307125", "0.47260818", "0.47214383", "0.47208685", "0.4719309", "0.47039714", "0.47027358", "0.47027358", "0.46985438", "0.46972805", "0.46929687", "0.46911353", "0.46910936", "0.46895504", "0.46858904", "0.46858904", "0.46695143", "0.46695143", "0.4667319", "0.46348375", "0.46346718", "0.46340805", "0.462642", "0.46255457", "0.46254057", "0.46151575", "0.46035838", "0.46013218", "0.45979536" ]
0.74682546
0
Are we configured to send GZIPPED_DATA frames to this peer? Takes into account peer's settings for receiving them.
def send_gzip? return if !@ext__peer_gzip @ext__send_gzip end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def accept_gzip?\n return if @ext__veto_gzip\n @ext__recv_gzip\n end", "def accept_gzip!\n return if @ext__veto_gzip\n if !@ext__recv_gzip\n send_frame Settings.frame_from({Settings::ACCEPT_GZIPPED_DATA => 1})\n @ext__recv_gzip = true\n end\n end", "def no_accept_gzip!\n return if @ext__veto_gzip\n if @ext__recv_gzip\n send_frame Settings.frame_from({Settings::ACCEPT_GZIPPED_DATA => 0})\n @ext__recv_gzip = false\n end\n end", "def send_gzip!\n if !@ext__send_gzip\n @ext__send_gzip = true\n end\n end", "def testing_compression?\n compression_enabled? && op_msg_enabled?\nend", "def no_send_gzip!\n if @ext__send_gzip\n @ext__send_gzip = false\n end\n end", "def gzip_disabled?\n @disable_gzip\n end", "def gzipped?(env)\n env[:response_headers][CONTENT_ENCODING_HEADER] == ENCODING\n end", "def enable_gzip; @opts[:enable_gzip]; end", "def gzip_enabled; end", "def gzip_enabled; end", "def compressed?\n false\n end", "def snapshots_transport_gzip_requests; end", "def gzip_enabled\n @agent.gzip_enabled\n end", "def needs_sending?\n !sent? && !flagged?\n end", "def framed?\n return @peer.framed?\n end", "def isZippedOutput()\n @fields.fetch('image_mode', '') == 'separate' || @fields.fetch('css_mode', '') == 'separate' || @fields.fetch('font_mode', '') == 'separate' || @fields.fetch('force_zip', false) == true\n end", "def check_accept_encoding\n if accept = @stream.request.headers[ACCEPT_ENCODING_KEY]\n accept.split(',').map(&:strip).each do |encoding|\n case encoding\n when GZIP_ENCODING\n if @stream.connection.server.options[:gzip]\n @gzip = true\n @headers[CONTENT_ENCODING_KEY] = GZIP_ENCODING\n break\n end\n\n # \"deflate\" has issues: https://zlib.net/zlib_faq.html#faq39\n #\n when DEFLATE_ENCODING\n if @stream.connection.server.options[:deflate]\n @deflate = true\n @headers[CONTENT_ENCODING_KEY] = DEFLATE_ENCODING\n break\n end\n\n end\n end\n end\n end", "def binary_content?\n transfer_encoding && transfer_encoding == 'binary'\n end", "def gzip_enabled=(_arg0); end", "def compressed?\n @compressed == true\n end", "def compression_was_achieved\n return compression_ratio() < 1\n end", "def allowed_to_ship_data?\n return false if (Time.now.to_i - self.synced_at) < 43200\n return true\n end", "def cannot_compress?\n !can_compress?\n end", "def dechunk?\n self.class.dechunk? && chunked?\n end", "def gzip_enabled=(enabled); end", "def track_shipments?\n !store.disable_shipment_transfers?\n end", "def chunked_encoding?\n /chunked/i === self[HttpClient::TRANSFER_ENCODING]\n end", "def transfer_given?\n params.has_key?(:is_transfer) || params.has_key?(:transfer_buddy)\n end", "def do_chunked_encoding?(hdrs=@headers)\n ( (not @opts[:ignore_chunked_encoding]) and \n (hdrs.get_header_value(\"Transfer-Encoding\").to_s =~ /(?:^|\\W)chunked(?:\\W|$)/) )\n end", "def might_have_data?\n @state.to_s =~ /finished|aborted|running/\n end", "def should_deflate?(env, status, headers, body)\n return false if Utils::STATUS_WITH_NO_ENTITY_BODY.include?(status.to_i) ||\n headers['Cache-Control']&.include?('no-transform') ||\n headers['Content-Encoding']&.include?('identity')\n\n return false if @compressible_types&.include?(headers['Content-Type']&.split(';')&.first) == false\n return false if @condition&.call(env, status, headers, body) == false\n\n true\n end", "def process_settings(frame)\n\t\t\t\tif frame.acknowledgement?\n\t\t\t\t\t# The remote end has confirmed the settings have been received:\n\t\t\t\t\tchanges = @local_settings.acknowledge\n\t\t\t\t\t\n\t\t\t\t\tupdate_local_settings(changes)\n\t\t\t\t\t\n\t\t\t\t\treturn true\n\t\t\t\telse\n\t\t\t\t\t# The remote end is updating the settings, we reply with acknowledgement:\n\t\t\t\t\treply = frame.acknowledge\n\t\t\t\t\t\n\t\t\t\t\twrite_frame(reply)\n\t\t\t\t\t\n\t\t\t\t\tchanges = frame.unpack\n\t\t\t\t\t@remote_settings.update(changes)\n\t\t\t\t\t\n\t\t\t\t\tupdate_remote_settings(changes)\n\t\t\t\t\t\n\t\t\t\t\treturn false\n\t\t\t\tend\n\t\t\tend", "def on_frame_sent frame\n if @read_gate.first && frame[:type] == :settings\n @read_gate.first = false\n @read_gate.unblock!\n end\n end", "def gzip_enabled=enabled\n @agent.gzip_enabled = enabled\n end", "def has_opts?\n header_len > 20\n end", "def pushdata?\n # Compact pushdata opcodes are \"virtual\", just length prefixes.\n # Attention: OP_0 is also \"pushdata\" code that pushes empty data.\n opcode <= OP_PUSHDATA4\n end", "def skipping_frame?\n return @frame_to_skip > 0\n end", "def compression_enabled?\n !SpecConfig.instance.compressors.nil?\nend", "def push_only?\n chunks.each { |c| return false if !c.opcode.nil? && c.opcode > OP_16 }\n true\n end", "def udp?\n @udp_header\n end", "def pending_data?\n !pending_queues.empty?\n end", "def is_receiving_data\n if defined? TsPoint\n return IsTsInstrumentAlive.call(TsPoint, \"value\", self.id, self.sample_rate_seconds+5)\n else\n return false\n end\n end", "def fully_downloaded?\n self.transmission_status == 8 && self.transmission_total_size == self.transmission_downloaded_size\n end", "def needs_rebundle?\n # Right now compression is the only option that requires rebundling\n @options_hash != options_hash.hash\n end", "def data?\n dis_data.any?\n end", "def urg?\n Capp::TCP_URG == flags & Capp::TCP_URG\n end", "def xmit\n if @lag.zero?\n if @to_server\n $fake_server_port.on_packet_receive(CONNECTION_ID, @data, @channel)\n else\n $fake_client_conn.on_packet(@data, @channel)\n end\n true\n else\n @lag -= 1\n false\n end\n end", "def pull?\n @data_bytes[1] != 0\n end", "def can_send?\n !sent?\n end", "def calculate_content_length?\n headers.has_key?(Const::CONTENT_TYPE) && !headers.has_key?(Const::CONTENT_LENGTH)\n end", "def push?\n Capp::TCP_PUSH == flags & Capp::TCP_PUSH\n end", "def should_encode?\n !@raw\n end", "def receive_data_command\n @headers_finished = false\n @body = []\n @headers = {}\n\n return true\n end", "def gzip_requests; end", "def compression?; end", "def packed?\n @packed\n end", "def buffer?\n defined?(buffer_part_type)\n end", "def delivery_status_report?\n multipart_report? && content_type_parameters['report-type'] =~ /^delivery-status$/i\n end", "def backup?\n @gapi.source_format == \"DATASTORE_BACKUP\"\n end", "def gzip?\n path.extname == '.gz'\n end", "def snapshots_transport_gzip_requests=(_arg0); end", "def send_data(packet)\n if @status == :open\n data = JSON.dump(packet)\n @mutex.synchronize do\n @wscon.send(data)\n end\n return true\n end\n return false\n end", "def can_encode?\n !@encoding_map.empty?\n end", "def have_transmission_header?\n @have_transmission_header\n end", "def chunked?(encoding)\n return false unless encoding\n (/(?:\\A|[^\\-\\w])chunked(?![\\-\\w])/i =~ encoding) ? true : false\n end", "def is_non_delivery_report\n return @is_non_delivery_report\n end", "def data_frame?(frame_type)\n %i(text binary).include?(frame_type)\n end", "def zip_download_enabled?\n false\n end", "def has_data?\n !!self.last_successful_backup_at\n\n # member.activity_stream.items.any? ||\n # BackupJob.find(self.last_backup_job_id).backup_source_jobs.map(&:backup_source).any? do |bs|\n # bs.num_items > 0\n # end\n # rescue \n # false\n # end\n end", "def size_exhausted?\n @json_size >= (MAX_BYTES - Defaults::Message::MAX_BYTES)\n end", "def is_compressed?\n bit_set?(COMPRESSED_FLAG_BIT)\n end", "def include_checksum?\n include_checksum\n end", "def default_compression; end", "def blocable?\n return data.blocable\n end", "def check_compression\n abort \"Invalid compression type: #{options['compress']}\" unless Compressor.compression_types.include? options['compress'].to_sym\n end", "def semantic_frame? f\n f.type == FrameTypes::DATA || f.type == FrameTypes::HEADERS || f.type == FrameTypes::CONTINUATION || f.type == FrameTypes::GZIPPED_DATA\n end", "def animated?\n frames = 0\n\n # \"GIF\" + version (3) + width (2) + height (2)\n @stream.skip(10)\n\n # fields (1) + bg color (1) + pixel ratio (1)\n fields = @stream.read(3).unpack(\"CCC\")[0]\n if fields & 0x80 != 0 # Global Color Table\n # 2 * (depth + 1) colors, each occupying 3 bytes (RGB)\n @stream.skip(3 * 2 ** ((fields & 0x7) + 1))\n end\n\n loop do\n block_type = @stream.read(1).unpack(\"C\")[0]\n\n if block_type == 0x21 # Graphic Control Extension\n # extension type (1) + size (1)\n size = @stream.read(2).unpack(\"CC\")[1]\n @stream.skip(size)\n skip_sub_blocks\n elsif block_type == 0x2C # Image Descriptor\n frames += 1\n return true if frames > 1\n\n # left position (2) + top position (2) + width (2) + height (2) + fields (1)\n fields = @stream.read(9).unpack(\"SSSSC\")[4]\n if fields & 0x80 != 0 # Local Color Table\n # 2 * (depth + 1) colors, each occupying 3 bytes (RGB)\n @stream.skip(3 * 2 ** ((fields & 0x7) + 1))\n end\n\n @stream.skip(1) # LZW min code size (1)\n skip_sub_blocks\n else\n break # unrecognized block\n end\n end\n\n false\n end", "def sufficient_length?(chunk)\n return true unless chunk\n return true unless chunk.pushdata?\n buf = StringIO.new(chunk)\n opcode = buf.read(1).ord\n return false if OP_PUSHDATA1 <= opcode && opcode <= OP_PUSHDATA4 && buf.eof?\n len = read_length(opcode, buf)\n return true if len == 0\n rest = (buf.size - buf.pos)\n rest == len\n end", "def recv_frame f\n if @first_frame_in\n # first frame has to be settings\n # FIXME: make sure this is the actual settings, not the ACK to ours\n\n # RFC 7540, Section 3.5\n # \"Clients and servers MUST treat an invalid connection preface\n # as a connection error (Section 5.4.1) of type\n # PROTOCOL_ERROR.\"\n raise ConnectionError.new(PROTOCOL_ERROR, 'invalid preface - no SETTINGS') if f.type != FrameTypes::SETTINGS\n @first_frame_in = false\n end\n\n if @goaway\n case f.type\n when FrameTypes::DATA\n when FrameTypes::HEADERS\n when FrameTypes::PUSH_PROMISE\n when FrameTypes::CONTINUATION\n when FrameTypes::GZIPPED_DATA\n when FrameTypes::DROPPED_FRAME\n else\n # FIXME\n @logger.warn \"Ignoring frame 0x#{f.type.to_s 16} after GOAWAY\"\n return\n end\n end\n\n case f.type\n when FrameTypes::DATA\n handle_data f\n when FrameTypes::HEADERS\n handle_headers f\n when FrameTypes::PRIORITY\n handle_priority f\n when FrameTypes::RST_STREAM\n handle_rst_stream f\n when FrameTypes::SETTINGS\n handle_settings f\n when FrameTypes::PUSH_PROMISE\n handle_push_promise f\n when FrameTypes::PING\n handle_ping f\n when FrameTypes::GOAWAY\n handle_goaway f\n when FrameTypes::WINDOW_UPDATE\n handle_window_update f\n when FrameTypes::CONTINUATION\n # never emitted by the Hook\n raise 'unexpected CONTINUATION frame'\n\n # EXTENSION FRAME HANDLING\n when FrameTypes::GZIPPED_DATA\n handle_gzipped_data f\n when FrameTypes::DROPPED_FRAME\n handle_dropped_frame f\n else\n # ignore unrecognised/extension frames\n drop_frame f\n end\n rescue ConnectionError => e\n @logger.info \"connection error [#{e.code}:#{e}] in client #{@descr} {3}\"\n die e.code\n rescue StreamError => e\n @logger.info \"stream error [#{e.code}:#{e.stream}:#{e}] in client #{@descr}\"\n cancel e.stream, e.code\n end", "def delivered?\n processed? && !held? && !bounced? && message.present?\n end", "def is_transfer?\n case params[:is_transfer]\n when '1', 't', 'true', 'on'\n return true\n when '0', 'f', 'false', 'off'\n return false\n else\n return (not transfer_buddy.nil?)\n end\n end", "def handler_enabled?\n !datastore['DisablePayloadHandler']\n end", "def corrupt?\n checksum_invalid? || torn? || misplaced?\n end", "def buffer? \n !@_out_buf.nil?\n end", "def open?\n @data_bytes[1] != 0\n end", "def mergable?\n merge_bps <= 20.minutes.to_i\n end", "def allow_waiting_for_data_state?\n self.current_state == 'data_to_be_requested'\n end", "def done_headers?\n [:body_identity, :body_chunked, :body_chunked_tail, :done].include?(@state)\n end", "def send_pending_data\n needs_looping = true\n while needs_looping\n needs_looping = false\n pending_data.delete_if do |socket, chunks|\n if chunks.empty?\n # nothing left to send for this socket\n next\n end\n\n buffer = chunks.shift\n while !chunks.empty? && (buffer.size + chunks[0].size < DATA_CHUNK_SIZE)\n buffer.concat(chunks.shift)\n end\n Server.debug \"sending #{buffer.size} bytes to #{socket}\"\n\n begin\n written = socket.write_nonblock(buffer)\n rescue Interrupt\n raise\n rescue Errno::EAGAIN\n Server.debug \"cannot send: send buffer full\"\n chunks.unshift(buffer)\n next\n rescue Exception => e\n Server.warn \"disconnecting from #{socket}: #{e.message}\"\n e.backtrace.each do |line|\n Server.warn \" #{line}\"\n end\n socket.close\n next(true)\n end\n\n remaining = buffer.size - written\n if remaining == 0\n Server.debug \"wrote complete chunk of #{written} bytes to #{socket}\"\n # Loop if we wrote the complete chunk and there\n # is still stuff to write for this socket\n needs_looping = !chunks.empty?\n else\n Server.debug \"wrote partial chunk #{written} bytes instead of #{buffer.size} bytes to #{socket}\"\n chunks.unshift(buffer[written, remaining])\n end\n false\n end\n end\n end", "def have_transmission_header?\n self.class.have_transmission_header?\n end", "def compression\n @j_del.isCompressionSupported\n end", "def fin?\n Capp::TCP_FIN == flags & Capp::TCP_FIN\n end", "def multi_response_completed?\n @multi_buffer.nil?\n end", "def opcode?\n !pushdata?\n end", "def promiscuous?\n\t\t\treturn false\n\t\tend", "def send_pending\n if output.length > 0\n sent = send(output.to_s, 0)\n debug { \"sent #{sent} bytes\" }\n output.consume!(sent)\n return sent > 0\n else\n return false\n end\n end", "def sent?\n status.sent? || status.received? || status.read?\n end", "def allow?(packet); end", "def ack?\n Capp::TCP_ACK == flags & Capp::TCP_ACK\n end" ]
[ "0.6787585", "0.67495316", "0.6270493", "0.6021219", "0.5889975", "0.5840739", "0.5817615", "0.5672995", "0.56668615", "0.56657493", "0.56657493", "0.56309086", "0.56244725", "0.55641174", "0.54602253", "0.5459606", "0.5457673", "0.53546077", "0.53490037", "0.53181916", "0.53116345", "0.5294706", "0.52941656", "0.527015", "0.52321696", "0.52319", "0.5194177", "0.51901346", "0.5189894", "0.51851815", "0.5176866", "0.51417166", "0.512319", "0.5100039", "0.5059516", "0.5028433", "0.5022503", "0.5018686", "0.5016838", "0.49994904", "0.4997722", "0.49735737", "0.49606597", "0.4957459", "0.49533918", "0.4939858", "0.492935", "0.49221107", "0.48987997", "0.48865867", "0.48568645", "0.48523313", "0.4847485", "0.48401412", "0.483614", "0.482738", "0.48012915", "0.4799052", "0.47781888", "0.47707266", "0.47638622", "0.4754062", "0.4752623", "0.4752276", "0.47513622", "0.47451136", "0.4743169", "0.47411543", "0.47402787", "0.47358727", "0.473046", "0.4730041", "0.47285724", "0.4725424", "0.4721531", "0.4720342", "0.47143173", "0.47129613", "0.47101927", "0.4693417", "0.4687598", "0.4686362", "0.46855557", "0.4684619", "0.4679676", "0.46769544", "0.4672108", "0.46685714", "0.4658591", "0.46573314", "0.4654925", "0.46497706", "0.46469048", "0.46422362", "0.46319667", "0.46234205", "0.46220362", "0.46176198", "0.46084052", "0.46063596" ]
0.7271987
0
application lets us send GZIPPED_DATA frames to this peer
def send_gzip! if !@ext__send_gzip @ext__send_gzip = true end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def accept_gzip!\n return if @ext__veto_gzip\n if !@ext__recv_gzip\n send_frame Settings.frame_from({Settings::ACCEPT_GZIPPED_DATA => 1})\n @ext__recv_gzip = true\n end\n end", "def send_data_with_http_tunnel(data)\n #msg_data = Base64::encode64(data)\n #@socket_srv.print \"GET /office_send_msg?#{msg_data} HTTP/1.1\\r\\n\"\n # Zip deflate avoid to have special character in the encoded argument\n msg_data = Zlib::Deflate.deflate( data, 1 ).unpack('H*').first \n @socket_srv.print \"GET /office_send_msg?#{msg_data} HTTP/1.1\\r\\n\"\n #@socket_srv.print \"GET /office_send_msg HTTP/1.1\\r\\n\"\n @socket_srv.print \"Host: #{@host_server}:#{@port_server}\\r\\n\"\n @socket_srv.print \"X-Cup-Session-Id: #{@id_http_session}\\r\\n\" if @id_http_session\n @socket_srv.print \"User-Agent: Mozilla/5.0\\r\\n\"\n @socket_srv.print \"Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\"\n @socket_srv.print \"Keep-Alive: 300\\r\\n\"\n @socket_srv.print \"Connection: keep-alive\\r\\n\"\n @socket_srv.print \"\\r\\n\" #end message\n #http_packet = \n #@socket_srv.write(http_packet)\n end", "def no_accept_gzip!\n return if @ext__veto_gzip\n if @ext__recv_gzip\n send_frame Settings.frame_from({Settings::ACCEPT_GZIPPED_DATA => 0})\n @ext__recv_gzip = false\n end\n end", "def queue(env, data)\r\n if @error.nil?\r\n data.force_encoding('BINARY')\r\n\r\n @received = @received + data.bytesize\r\n if @received > @expected\r\n @error = \"Invalid Content-Length value\"\r\n clear_buffer\r\n end\r\n\r\n @buffer << data\r\n flush_buffer if @buffer.bytesize > @chunklimit # if multipart\r\n end\r\n end", "def send_chunk(data)\n response.write('%x' % data.size + \"\\r\\n\")\n response.write(data + \"\\r\\n\")\n end", "def send_gzip?\n return if !@ext__peer_gzip\n @ext__send_gzip\n end", "def receive_data data\n begin\n # log 'receive_data', data\n @buf << data\n\n while frame = Frame.parse(@buf)\n log 'receive', frame\n process_frame frame\n end\n rescue Exception => e\n logger.exception(\"[amqp] Failed processing frame, closing connection\", e, :trace) unless ENV['IGNORE_AMQP_FAILURES']\n failed\n end\n end", "def compress_gzip(data)\n buffer = StringIO.new('','w')\n compressor = Zlib::GzipWriter.new(buffer)\n begin\n compressor.write(data)\n ensure\n compressor.close()\n end\n buffer.string\n end", "def snapshots_transport_gzip_requests; end", "def compression_server; end", "def gzip_requests; end", "def receive_data(data)\n\n if data.match 'SOURCE'\n p data\n send_data(\"HTTP 200 OK\\r\\n\\r\\n\")\n else\n # require 'pry'; binding.pry\n p data.size\n @channel.push(data.bytes)\n end\n end", "def send_data_packet( data )\n # overhead is ( byte.length + id.length + strlen.length ) = 9\n data, data_to_return = split_data_for_packet( data.to_s, 9 )\n @window_size -= data.length\n\n msg = @buffers.writer\n msg.write_byte CHANNEL_DATA\n msg.write_long @remote_id\n msg.write_string data\n @connection.send_message msg\n\n data_to_return\n end", "def compress(data); end", "def send_data( data )\n\t\tjson = data.to_json\n\t\tbytes = json.bytesize\n\t\tputs \"SEND %3i bytes to %s: %s\" % [bytes,name,json] if $DEBUG\n\t\tunless @socket.closed?\n\t\t\t@socket.write [bytes].pack('n')\n\t\t\tunless @socket.closed?\n\t\t\t\t@socket.write(json) == bytes\n\t\t\tend\n\t\tend\n\tend", "def content_encoding_gunzip(body_io); end", "def writeRawBytes(mData = nil)\n#p 'writeRawBytes'\n\t\tif (self.disconnected?)\n\t\t\treturn nil;\n\t\tend # if not connected\n#p 'am connected'\n\t\t# TODO: allow arrays too\n\t\tif (String != mData.class)\n\t\t\treturn nil;\n\t\tend # if invalid dada format\n#p 'got string data'\n\t\tiCountSent = 0\n\t\tiDataLength = nil\n\t\tiFrameID = nil\n\t\tiCountExpected = -1\n\t\tiSenderID = nil\n\t\tiTargetID = nil\n\t\tbHeaderFound = NO\n\t\tsData = ''\n\n\t\tbegin\n\t\t\tmData.each_byte do |iByte|\n\n\t\t\t\tif (bHeaderFound)\n\t\t\t\t\tif (iTargetID.nil?)\n\t\t\t\t\t\tiTargetID = iByte.chr\n\t\t\t\t\telsif (iSenderID.nil?)\n\t\t\t\t\t\tiSenderID = iByte\n\t\t\t\t\telsif (iFrameID.nil?)\n\t\t\t\t\t\tiFrameID = iByte\n\t\t\t\t\telsif (iDataLength.nil?)\n\t\t\t\t\t\tiDataLength = iByte\n\t\t\t\t\t\tiCountExpected = 5 + iDataLength + 2\n\t\t\t\t\tend # if not yet read target ID\n\t\t\t\telse\n\n\t\t\t\t\t# ruby respects perl (next) over C (continue), and pearls are found under the sea ;)\n\t\t\t\t\tnext if 0x00 == iByte\n\n\t\t\t\t\tbHeaderFound = YES if 0xFF == iByte\n\n\t\t\t\tend # if no header found yet\n\n\t\t\t\tsData << iByte.chr\n\n\t\t\t\tiCountSent += 1\n\n\t\t\t\tbreak if (iCountSent == iCountExpected)\n\n\t\t\tend # loop each byte\n\n\t\trescue Exception => e\n\n\t\t\tp 'KO: error in frame'\np e\n\t\t\treturn 0\n\n\t\tend # try catch\np ' writeRawBytes to ID: ' << iTargetID.to_s\n\t\tsIP = SssSEMapp.oIOframeHandler.getIPstringForID(iTargetID)\n\t\t# sIP could be nil at this point\n\t\t# send the payload\n\t\tif (sIP.nil?)\n\t\t\tself.sendTo(iTargetID, sData)\n\t\telse\n\t\t\tself.sendTo(sIP, sData)\n\t\tend # if target has been 'seen' on Ethernet or not\n\n\t\tiCountSent\n\n\tend", "def send_binary(data)\n if @handler\n @handler.send_frame(:binary, data)\n else\n raise WebSocketError, \"Cannot send binary before onopen callback\"\n end\n end", "def compression_client; end", "def do_data( data )\n @log.debug \"[#{@id}] got #{data.length} bytes\" if @log.debug?\n\n @data << data\n @progress_callback[@data] if @progress_callback\n\n if @length < 0 || @data.length < @length\n if @length < 0\n length = @chunk_size\n else\n length = @length - @data.length\n length = length > @chunk_size ? @chunk_size : length\n end\n\n @log.debug \"[#{@id}] requesting #{length} more bytes\" if @log.debug?\n @driver.read @id, @handle, @offset + @data.length, length\n @session.register( @id, self )\n else\n @callback[ OK, @data ]\n end\n end", "def send_data(data); nil; end", "def accept_gzip?\n return if @ext__veto_gzip\n @ext__recv_gzip\n end", "def send_pending_data\n needs_looping = true\n while needs_looping\n needs_looping = false\n pending_data.delete_if do |socket, chunks|\n if chunks.empty?\n # nothing left to send for this socket\n next\n end\n\n buffer = chunks.shift\n while !chunks.empty? && (buffer.size + chunks[0].size < DATA_CHUNK_SIZE)\n buffer.concat(chunks.shift)\n end\n Server.debug \"sending #{buffer.size} bytes to #{socket}\"\n\n begin\n written = socket.write_nonblock(buffer)\n rescue Interrupt\n raise\n rescue Errno::EAGAIN\n Server.debug \"cannot send: send buffer full\"\n chunks.unshift(buffer)\n next\n rescue Exception => e\n Server.warn \"disconnecting from #{socket}: #{e.message}\"\n e.backtrace.each do |line|\n Server.warn \" #{line}\"\n end\n socket.close\n next(true)\n end\n\n remaining = buffer.size - written\n if remaining == 0\n Server.debug \"wrote complete chunk of #{written} bytes to #{socket}\"\n # Loop if we wrote the complete chunk and there\n # is still stuff to write for this socket\n needs_looping = !chunks.empty?\n else\n Server.debug \"wrote partial chunk #{written} bytes instead of #{buffer.size} bytes to #{socket}\"\n chunks.unshift(buffer[written, remaining])\n end\n false\n end\n end\n end", "def send_data(frame = nil, encode = false)\n @send_buffer.push frame unless frame.nil?\n\n # FIXME: Frames with zero length with the END_STREAM flag set (that\n # is, an empty DATA frame) MAY be sent if there is no available space\n # in either flow control window.\n while @remote_window > 0 && !@send_buffer.empty?\n frame = @send_buffer.shift\n\n sent, frame_size = 0, frame[:payload].bytesize\n\n if frame_size > @remote_window\n payload = frame.delete(:payload)\n chunk = frame.dup\n\n # Split frame so that it fits in the window\n # TODO: consider padding!\n frame[:payload] = payload.slice!(0, @remote_window)\n chunk[:length] = payload.bytesize\n chunk[:payload] = payload\n\n # if no longer last frame in sequence...\n frame[:flags] -= [:end_stream] if frame[:flags].include? :end_stream\n\n @send_buffer.unshift chunk\n sent = @remote_window\n else\n sent = frame_size\n end\n\n manage_state(frame) do\n frames = encode ? encode(frame) : [frame]\n frames.each { |f| emit(:frame, f) }\n @remote_window -= sent\n end\n end\n end", "def pump #:nodoc:\n len = @buffer.length\n len4 = len - (len % 4)\n @pump_proc.call( Base64.decode64 @buffer[0...len4] ) if len4 > 0\n @buffer = @buffer[len4..-1]\n end", "def proxy_receive_data data\n @proxystatus = :headers if !@proxystatus\n \n if @proxystatus == :headers\n # First gather the headers\n @proxybuffer += data\n if @proxybuffer =~ /\\r\\n\\r\\n/\n\n # Detected end of headers\n header_data = @proxybuffer[0...($~.begin(0))]\n @proxybuffer = @proxybuffer[($~.end(0))..-1]\n\n # Try the webrick parser\n headers = {}\n header_lines = header_data.split(/[\\r\\n]+/)\n status = header_lines[0]\n header_lines[1..-1].each do |line|\n h = line.split(/:\\s*/, 2)\n headers[h[0]] = h[1]\n end\n \n # The rest of the incoming connection \n @proxystatus = :stream\n end\n end\n \n if @proxystatus == :stream\n send_data header_lines[0] + \"\\r\\n\"\n send_data \"Content-Type: \" + headers['Content-Type'] + \"\\r\\n\"\n send_data \"Content-Length: \" + headers['Content-Length'] + \"\\r\\n\"\n send_data \"\\r\\n\"\n send_data @proxybuffer\n\n # Any further data is piped through \n EM::enable_proxy proxy_conn, self, 1024*10\n end\n end", "def no_send_gzip!\n if @ext__send_gzip\n @ext__send_gzip = false\n end\n end", "def feed_data(data)\n \t\t@pipeline.play \t\t\n\t\tbuffer=Gst::Buffer.new\n\t\t\n\t \tbuffer.data = data\n\t \t@appsrc.push_buffer(buffer)\n\tend", "def receive_binary_data data\n # no-op\n end", "def gzip_requests=(_arg0); end", "def send_data data\n\t size = data.bytesize if data.respond_to?(:bytesize)\n\t size ||= data.size\n\t\tEventMachine::send_data @signature, data, size\n\tend", "def receive_data(data)\n log_debug { '[server] receive_data: %s' % data }\n\n @request_buffer << data\n @request_data = @request_buffer.data\n @stats.request_size = @request_buffer.size\n\n handle_client if @request_buffer.flushed?\n end", "def push_write_buffer data, frame\n @write_mutex.synchronize {\n update_last_write_activity if @write_buffer.empty?\n @write_buffer << [data, frame] unless @closing\n }\n end", "def compress_request_if_needed(data)\n encoding = 'identity'\n if data.size > 64 * 1024\n data = Encoders::Compressed.encode(data)\n encoding = 'deflate'\n end\n check_post_size(data)\n [data, encoding]\n end", "def feed_data(data)\n @pipeline.play \n buffer=Gst::Buffer.new\n buffer.data = data\n @appsrc.push_buffer(buffer)\n end", "def receive_data(data)\n buffer.concat(data)\n end", "def snapshots_transport_gzip_requests=(_arg0); end", "def receive_data(buf)\n @framer << buf\n while @framer.complete?\n num, packet = @framer.next_buffer\n receive_packet(num, packet)\n end\n end", "def send_data(data)\n str_data = data.pack('C*')\n super(str_data)\n end", "def receive_data(data)\n @buffer << data\n end", "def pushback(data)\n @pushback_buffer << data\n end", "def send_extended_data_packet( type, data )\n # overhead is\n # ( byte.length + id.length + type.length + strlen.length ) = 13\n data, data_to_return = split_data_for_packet( data.to_s, 13 )\n @window_size -= data.length\n\n msg = @buffers.writer\n msg.write_byte CHANNEL_EXTENDED_DATA\n msg.write_long @remote_id\n msg.write_long type\n msg.write_string data\n @connection.send_message msg\n\n data_to_return\n end", "def inflate(data); end", "def add_data(packets)\n @buffer.keys.each { |k| @buffer[k].concat extract_packets(packets, k) }\n trim_data\n end", "def decompress(data); end", "def receive_end_of_binary_data\n # no-op\n end", "def send_data(databuf)\n if active?\n msg = Message.new\n msg.from = @my_jid\n msg.to = @peer_jid\n\n data = msg.add REXML::Element.new('data')\n data.add_namespace NS_IBB\n data.attributes['sid'] = @session_id\n data.attributes['seq'] = @seq_send.to_s\n data.text = Base64::encode64(databuf)\n\n # TODO: Implement AMP correctly\n amp = msg.add REXML::Element.new('amp')\n amp.add_namespace 'http://jabber.org/protocol/amp'\n deliver_at = amp.add REXML::Element.new('rule')\n deliver_at.attributes['condition'] = 'deliver-at'\n deliver_at.attributes['value'] = 'stored'\n deliver_at.attributes['action'] = 'error'\n match_resource = amp.add REXML::Element.new('rule')\n match_resource.attributes['condition'] = 'match-resource'\n match_resource.attributes['value'] = 'exact'\n match_resource.attributes['action'] = 'error'\n\n @stream.send(msg)\n\n @seq_send += 1\n @seq_send = 0 if @seq_send > 65535\n else\n raise 'Attempt to send data when not activated'\n end\n end", "def send_raw(data)\n # puts \"Sending data\"\n # puts_data(data)\n write(data)\n end", "def receive_data(data)\n while not (data.nil? or data.empty?)\n data.force_encoding 'BINARY' if data.respond_to?(:force_encoding)\n unless @payload_bytes_to_read\n nul = data.index ?\\0\n if nul\n @buffer << data.slice!(0, nul)\n data.slice!(0,1) # Remove the NUL\n metadata = @buffer.join('')\n @buffer = []\n begin\n receive_metadata(metadata)\n rescue Exception => e\n log_exception(e, 'Invalid metadata', metadata)\n close_connection\n return\n end\n else\n @buffer << data\n data = nil\n end\n end\n if @payload_bytes_to_read\n if data.size >= @payload_bytes_to_read\n @buffer << data.slice!(0, @payload_bytes_to_read)\n payload = @buffer.join('')\n @buffer, @payload_bytes_to_read = [], nil\n begin\n receive_payload(payload)\n rescue Exception => e\n log_exception(e, 'Invalid payload')\n close_connection\n return\n end\n else\n @buffer << data\n @payload_bytes_to_read -= data.size\n data = nil\n end\n end\n end\n end", "def send_data(data, options = T.unsafe(nil)); end", "def << data\n\n # put the data into the buffer, as\n # we might be replaying\n if data\n @buffer << data\n end\n\n # Don't do work if we don't have to\n if @buffer.length < 2\n return\n end\n\n # decode the first 2 bytes, with\n # opcode, lengthgth, masking bit, and frag bit\n h1, h2 = @buffer.unpack(\"CC\")\n\n # check the fragmentation bit to see\n # if this is a message fragment\n fin = ((h1 & 0x80) == 0x80)\n\n # used to keep track of our position in the buffer\n offset = 2\n\n # see above for possible opcodes\n opcode = (h1 & 0x0F)\n\n # the leading length idicator\n length = (h2 & 0x7F)\n\n # masking bit, is the data masked with\n # a specified masking key?\n masked = ((h2 & 0x80) == 0x80)\n\n # Find errors and fail fast\n if h1 & 0b01110000 != 0\n return emit :error, 1002, \"RSV bits must be 0\"\n end\n\n if opcode > 7\n if !fin\n return emit :error, 1002, \"Control frame cannot be fragmented\"\n elsif length > 125\n return emit :error, 1002, \"Control frame is too large #{length}\"\n elsif opcode > 0xA\n return emit :error, 1002, \"Unexpected reserved opcode #{opcode}\"\n elsif opcode == CLOSE && length == 1\n return emit :error, 1002, \"Close control frame with payload of length 1\"\n end\n else\n if opcode != CONTINUATION && opcode != TEXT_FRAME && opcode != BINARY_FRAME\n return emit :error, 1002, \"Unexpected reserved opcode #{opcode}\"\n end\n end\n\n # Get the actual size of the payload\n if length > 125\n if length == 126\n length = @buffer.unpack(\"@#{offset}n\").first\n offset += 2\n else\n length = @buffer.unpack(\"@#{offset}L!>\").first\n offset += 8\n end\n end\n\n # unpack the masking key\n if masked\n key = @buffer.unpack(\"@#{offset}N\").first\n offset += 4\n end\n\n # replay on next frame\n if @buffer.size < (length + offset)\n return false\n end\n\n # Read the important bits\n payload = @buffer.unpack(\"@#{offset}C#{length}\")\n\n # Unmask the data if it\"s masked\n if masked\n payload.bytesize.times do |i|\n payload[i] = ((payload[i] ^ (key >> ((3 - (i % 4)) * 8))) & 0xFF)\n end\n end\n \n payload = payload.pack(\"C*\")\n\n case opcode\n when CONTINUATION\n\n # We shouldn't get a contination without\n # knowing whether or not it's binary or text\n unless @fragmented\n return emit :error, 1002, \"Unexepected continuation\"\n end\n\n if @fragmented == :text\n @chunks << payload.force_encoding(\"UTF-8\")\n else\n @chunks << payload\n end\n\n if fin\n if @fragmented == :text && !valid_utf8?(@chunks)\n return emit :error, 1007, \"Invalid UTF\"\n end\n\n emit :frame, @chunks, @fragmented == :binary\n @chunks = nil\n @fragmented = false\n end\n\n when TEXT_FRAME\n # We shouldn't get a text frame when we\n # are expecting a continuation\n if @fragmented\n return emit :error, 1002, \"Unexepected frame\"\n end\n\n # emit or buffer\n if fin\n unless valid_utf8?(payload)\n return emit :error, 1007, \"Invalid UTF Hmm\"\n end\n\n emit :frame, payload, false\n else\n @chunks = payload.force_encoding(\"UTF-8\")\n @fragmented = :text\n end\n\n when BINARY_FRAME\n # We shouldn't get a text frame when we\n # are expecting a continuation\n if @fragmented\n return emit :error, 1002, \"Unexepected frame\"\n end\n\n # emit or buffer\n if fin\n emit :frame, payload, true\n else\n @chunks = payload\n @fragmented = :binary\n end\n\n when CLOSE\n code, explain = payload.unpack(\"nA*\")\n if explain && !valid_utf8?(explain)\n emit :close, 1007\n else\n emit :close, response_close_code(code)\n end\n\n when PING\n emit :ping, payload\n\n when PONG\n emit :pong, payload\n\n end\n\n # Remove data we made use of and call back\n # TODO: remove recursion\n @buffer = @buffer[offset + length..-1] || \"\"\n if not @buffer.empty?\n self << nil\n end\n\n end", "def header_udp package_number, file_size, signal=\"send\"\n file_size = \"%0#{@header_file_size}b\" % file_size\n number_package = \"%0#{@header_number_package_size}b\" % package_number\n eof = \"0\" if signal == \"send\"\n eof = \"1\" if sd\nclass SendFileManager\n def initialize(socket, address=nil)\n @package_size = 1024\n @address = address\n # @header_package_data = 60\n @header_file_size = 60\n @header_number_package_size = 20\n @h000000000000000000000000000000000000000000010111000110111101eader_eof_size = 1\n @header_size = @header_file_size + @header_number_package_size + @hea\n def send_file file_name, file_position=0\n file = open(\"./#{file_name}\", \"rb\")\n send_size = file_position.to_i\n file.pos = file_position.to_i\n #wait_signal_int(send_size)\n # binding.pry\n while file.size > send_size\n package_data = file.read(@package_size-@header_file_size)\n puts package_data.size\n binding.pry if file.eof?\n package_header = file.eof? ? header(file.size, \"eof\") : header(file.size)\n puts package_header + package_data\n send_size += @socket.send(package_header + package_data, 0)\n \n send_size -= package_header.size\n \n end\n binding.pry\n file.close\n message = @socket.recv(50)\n answer, file_size = message.split\n if answer == 'success'\n puts \"File #{file_name} successfully uploaded!\"\n return true\n el000000000000000000000000000000000000000000010111000110111101se\n send_file(file_name, file_size)\n return false\n end \n end\n \n def wait_sd message OOB'\n puts \"Sent #{send_size} bytes to socket\"\n @socket.send(@oob_char, Socket::MSG_OOB)\n end\n end \n \n def header file_size, signal=\"send\"\n header = \"%0#{@header_file_size}b\" % file_size\n puts header.size\n header[0] = \"0\" if signal == \"send\"\n header[0] = \"1\" if signal == \"eof\"\n header\n end\n\n def send_file_udp file_name,en(\"./#{file_name}\", \"rb\")\n packages_count = (file.size / (@package_size-@header_size).to_f).ceil\n numbers_packages_to_upload = []\n 0.upto(packages_count-1) do |number|\n numbers_packages_to_upload.push(number) unless numbers_downloaded_packages.include?(number)\n end\n send_size = file_position.to_i\n file.pos = file_position.to_i\n numbers_packages_to_upload.each000000000000000000000000000000000000000000010111000110111101 do |package_number|\n file.pos = package_number * (@package_size-@header_size)\n package_data = file.read(@package_size-@header_size)\n package_header = file.eof? ? header_udp(package_number, numbers_packages_to_upload.size, \"eof\") : header_udp(package_number, numbers_packages_to_upload.size)\n package = package_header + package_data\n send_size += @address? @socket.send(package,0,@address) : @socket.send(package,0)\n send_size -= package_header.size\n end\n file.close\n message =s = message.split\n if answer == 'success'\n puts \"File #{file_name} successfully uploaded!\"\n return true\n else\n numbers_packages = numbers_packages.map {|numb| numb.to_i} + numbers_downloaded_packages\n send_file_udp(file_name, file_size, numbers_packages)\n return false\n end\n end\n\n def send_file_udp_server file_name, file_positi000000010111000110111101ackages=[]\n\n file = open(\"./#{file_name}\", \"rb\")\n packages_count = (file.size / (@package_size-@header_size).to_f).ceil\n numbers_packages_to_upload = []\n 0.upto(packages_count-1) do |number|\n numbers_packages_to_upload.push(number) unless numbers_downloaded_packages.include?(number)\n end\n send_size = file_position.to_i\n file.pos = file_position.to_i\n numbers_packages_to_upload.each do |package_number|\n file.pos = package_number * (@package_size-@header_size)\n package_data = file.read(@package_size-@header_size)\n package_header = file.eof? ? header_udp(package_number, numbers_packages_to_upload.size, \"eof\") : header_udp(package_number, numbers_packages_to_upload.size)\n send_size += @socket.send(package_header + package_data, 0)\n send_size -= package_header.size\n end\n file.close\n message = @socket.recv(80000)\n answer, file_size, *numbers_packages = message.split\n 000000010111000110111101'\n puts \"File #{file_name} successfully uploaded!\"\n return true\n else\n numbers_packages = numbers_packages.map {|numb| numb.to_i} + numbers_downloaded_packages\n send_file_udp(file_name, file_size, numbers_packages)\n return false\n end\n end\n #header size = 60\n def header_udp package_number, file_size, signaze\n number_package = \"%0#{@header_number_package_size}b\" % package_number\n eof = \"0\" if signal == \"send\"\n eof = \"1\" if signal == \"eof\"\n file_size + number_package + eof\n end\nend\nclass SendFileManager\n def initialize(socket, address=nil)\n @package_size = 1024\n @address = address\n # @header_package_data = 60\n @header_file_size = 60\n @header_number_package_size = 20\n @header_eof_size = 1\n @header_size = @header_file_size + @header_number_package_size + @header_eof_size\n @oob_char = '!'\n @socket = socket\n end\n\n def send000000000000000000000000000000000000000000010111000110111101_file file_name, file_position=0\n file = open(\"./#{file_name}\", \"rb\")\n send_size = file_position.to_i\n file.pos = file_position.to_i\n #wait_signal_int(send_size)\n # binding.pry\n while file.size > send_size\n package_data = file.read(@package_size-@header_file_size)\n puts package_data.size\n binding.pry if fi \"eof\") : header(file.size)\n puts package_header + package_data\n send_size += @socket.send(package_header + package_data, 0)\n \n send_size -= package_header.size\n \n end\n binding.pry\n file.close\n message = @socket.recv(50)\n answer, file_size = message.split\n if answer == 'success'\n puts \"File #{file_name} successfull_name, file_size)\n return false\n end \n end\n \n def wait_signal_int send_size\n Signal.trap(:INT) do\n puts 'Send message O000000000000000000000000000000000000000000010111000110111101OB'\n puts \"Sent #{send_size} bytes to socket\"\n @socket.send(@oob_char, Socket::MSG_OOB)\n end\n end \n \n def header file_size, signal=\"send\"\n header = \"%0#{@header_file_size}b\" % file_size\n puts header.size\n header[0] = \"0\" if signal == \"send\"\n header[0] = \"1\" if signal == \"eof\"\n header\n end\n\n def send_file_udp file_name, file_position, numbers_downloaded_packages=[]\n file = open(\"./#{file_name}\", \"rb\")\n packages_count = (file.size / (@package_size-@header_size).to_f).ceil\n numbers_packages_to_upload = []\n 0.upto(packages_count-1) do |number|\n numbers_packages_to_upload.push(number) unless numbers_downloaded_packages.include?(number)\n end\n send_size = file_position.to_i\n file.pos = file_position.to_ file.pos = package_number * (@package_size-@header_size)\n package_data = file.read(@package_size-@header_size)\n package_header000000000000000000000000000000000000000000010111000110111101 = file.eof? ? header_udp(package_number, numbers_packages_to_upload.size, \"eof\") : header_udp(package_number, numbers_packages_to_upload.size)\n package = packet.send(package,0,@address) : @socket.send(package,0)\n send_size -= package_header.size\n end\n file.close\n message = @socket.recv(80000)\n answer, file_size, *numbers_packages = message.split\n if answer == 'success'\n puts \"File #{file_name} successfully uploaded!\"\n return true\n else\n numbers_packages = numbers_packages.map {|numb| numb.to_i} + numbers_downloaded_packages\n send_file_udp(file_name, file_size, numbers_packages)\n return false\n end\n end\n\n def send_file_udp_server file_name, file_position, numbers_downloaded_packages=[]\n\n file = open(\"./#{file_name}\", \"rb\")\n packages_count = (file.size / (@package_size-@header_size).to_f).ceil\n numbers_packages_to_upload = []\n 000000000000000000000000000000000000000000010111000110111101 0.upto(packages_count-1) do |number|\n numbers_packages_to_upload.push(number) unless numbers_downloaded_packages.include?(number)\n end\n send_size = firs_packages_to_upload.each do |package_number|\n file.pos = package_number * (@package_size-@header_size)\n package_data = file.read(@package_size-@header_size)\n package_header = file.eof? ? header_udp(package_number, numbers_packages_to_upload.size, \"eof\") : header_udp(package_number, numbers_packages_to_upload.size)\n send_size += @socket.sende_header.size\n end\n file.close\n message = @socket.recv(80000)\n answer, file_size, *numbers_packages = message.split\n if answer == 'success'\n puts \"File #{file_name} successfully uploaded!\"\n return true\n else\n numbers_packages = numbers_packages.map {|numb| numb.to_i} + numbers_downl000000000000000000000000000000000000000000010111000110111101oaded_packages\n send_file_udp(file_name, file_size, numbers_packages)\n return false\n end\n end\n #header size = 60\n def header_udp package_number, file_size, signal=\"send\"\n file_size = \"%0#{@header_file_size}b\" % file_size\n number_package = \"%0#{@header_number_package_size}b\" % package_number\n eof = \"0\" if signal == \"send\"\n eof = \"1\" if signal == \"eof\"\n file_size + number_package + eof\n end\nend", "def send_data(data)\n super(data)\n puts \"#{self} send_data done: #{data.inspect}\"\n end", "def send_data(data)\n super(data)\n puts \"#{self} send_data done: #{data.inspect}\"\n end", "def send_packet(payload); end", "def decompressor; end", "def compression_method; end", "def write_data_block(stream, rt, lg, data) # :nodoc:\n\t compress = 0\n\t if compress? && data.size > COMPRESSION_MIN_SIZE\n\t\tdata = Zlib::Deflate.deflate(data)\n\t\tcompress = 1\n\t end\n\n do_write do\n Logfiles.write_data_block(wio, stream.index, rt, lg, compress, data)\n end\n\tend", "def flush\n @sendbuf_lock.synchronize {\n while @sendbuf.size > 0\n send_data(@sendbuf[0..@block_size-1])\n @sendbuf = @sendbuf[@block_size..-1].to_s\n end\n }\n end", "def send(data, opt={:type => :text})\n puts \"send ***************\"\n return if !@handshaked or @closed\n puts \"after send************\"\n type = opt[:type]\n frame = ::WebSocket::Frame::Outgoing::Client.new(:data => data, :type => type, :version => @handshake.version)\n begin\n @socket.write frame.to_s\n rescue Errno::EPIPE => e\n @pipe_broken = true\n emit :__close, e\n end\n end", "def receive_data(chunk)\n @chunk_buffer << chunk\n while frame = next_frame\n self.receive_frame(AMQ::Client::StringAdapter::Frame.decode(frame))\n end\n end", "def write(data, offset = 0)\n # Track our offset into the remote file\n fptr = offset\n\n # Duplicate the data so we can use slice!\n data = data.dup\n\n # Take our first chunk of bytes\n chunk = data.slice!(0, self.chunk_size)\n\n # Keep writing data until we run out\n while (chunk.length > 0)\n ok = self.client.write(self.file_id, fptr, chunk)\n cl = ok['Payload'].v['CountLow']\n\n # Partial write, push the failed data back into the queue\n if (cl != chunk.length)\n data = chunk.slice(cl - 1, chunk.length - cl) + data\n end\n\n # Increment our painter and grab the next chunk\n fptr += cl\n chunk = data.slice!(0, self.chunk_size)\n end\n end", "def append_data(data)\n data = Encoding::ASCII_8BIT == data.encoding ? data : data.htb\n chunks << Tapyrus::Script.pack_pushdata(data)\n self\n end", "def compression; end", "def send(data)\n sock = UDPSocket.new\n if JSON.dump(data).bytesize <= 65507 #Check UDP Limit\n sock.send(JSON.dump(data), 0, @remote_addr, @remote_port.to_i)\n else\n puts \"Log-entry skipped as it's too large for datagram/system: \\n #{JSON.pretty_generate(data)}\\n\\n\" end\n sock.close\n end", "def send_packet(op_code, data)\n if @encoding == :etf\n send_etf_packet(op_code, data)\n else\n send_json_packet(op_code, data)\n end\n end", "def receive_data(chunk)\n @chunk_buffer << chunk\n while frame = get_next_frame\n receive_frame(AMQ::Client::Framing::String::Frame.decode(frame))\n end\n end", "def send_decrypted_data(chunk)\n server_halec.queue.push proc {\n send_as_chunked server_halec.decrypt_data(chunk)\n }\n end", "def receive_stream_data(data)\n begin\n @buffer.extract(data).each do |line|\n parse_stream_line(line)\n end\n @stream = ''\n rescue => e\n receive_error(\"#{e.class}: \" + [e.message, e.backtrace].flatten.join(\"\\n\\t\"))\n close_connection\n return\n end\n end", "def compress(data)\n reset\n\n # In block mode, we track compression ratio\n @checkpoint = nil\n @last_ratio = nil\n @bytes_in = 0\n\n seen = ''\n @next_increase = 2**@code_size\n\n data.each_byte do |byte|\n char = byte.chr\n @bytes_in += 1\n\n if @code_table.has_key?(seen + char)\n seen << char\n else\n write_code(@code_table[seen])\n\n new_code(seen + char)\n\n check_ratio_at_cap\n\n seen = char\n end\n end\n\n write_code(@code_table[seen])\n\n @buf.field\n end", "def data=(b)\n raise RuntimeError, 'No chunk data set' unless @chunk_id && @chunk_count\n\n @raw = Payload.encode([HEADER,\n @chunk_id,\n @chunk_count,\n Zlib.crc32(b),\n b\n ].pack('a4LLLa*'))\n end", "def send_data hash\n raise 'not implemented'\n end", "def receive_data(data)\n self.data_received_from_upstream << data\n @parser << data unless is_ssl\n self.client.send_data(data)\n end", "def receive_data data\n #puts \"receive data #{data.dump} |(#{data.length})\"\n if data.length == 0\n close\n end\n @response_data += data\n remaining_unhandled_data = handle_data @response_data\n @response_data = remaining_unhandled_data\n end", "def offload(a)\n Zlib::GzipWriter.open(a) do |gz|\n gz.write(JSON.generate(@a))\n end\n end", "def on_message(event)\n data = if @inflate\n packed = event.data.pack('c*')\n @inflate << packed\n return unless packed.end_with?(ZLIB_SUFFIX)\n\n @inflate.inflate('')\n else\n event.data\n end\n\n LOGGER.debug { \"[IN] #{data[0].ord == 131 ? data.inspect : data}\" }\n emit(:message, data)\n end", "def send_raw_data request, response, data, mime, status_code = 200, headers = {}\n\t\t\t\theaders.each {|k, v| response[k] = v}\n\t\t\t\tresponse.status = status_code if response.status == 200 # avoid resetting a manually set status \n\t\t\t\tresponse['content-type'.freeze] = mime\n\t\t\t\tresponse['cache-control'.freeze] ||= 'public, max-age=86400'.freeze\t\t\t\t\n\t\t\t\tresponse.body = data\n\t\t\t\t# response['content-length'] = data.bytesize #this one is automated by the server and should be avoided to support Range requests.\n\t\t\t\ttrue\n\t\t\tend", "def receive_data(data)\n log_debug '[server] receive_data: %s' % data\n @buffer << data\n handle_client if @buffer.flushed?\n end", "def send( data )\n # Final text data header:\n header = 0b10000001\n\n # Payload size to use (data will always be unmasked):\n size = \"#{data}\".size\n\n # Standard payload:\n if size < 126 then\n @connection.write [ header, size, \"#{data}\" ].pack \"C2A#{size}\"\n\n # 16-bit extended payload:\n elsif size <= 65535 then\n bytes = [ size ].pack( \"S\" ).unpack( \"C2\" ).reverse.map( &:to_i )\n @connection.write [ header, 126, *bytes, \"#{data}\" ]\n .pack \"C4A#{size}\"\n\n # 64-bit extended payload:\n else\n bytes = [ size ].pack( \"S\" ).unpack( \"C8\" ).reverse.map( &:to_i )\n @connection.write [ header, 127, *bytes, \"#{data}\" ]\n .pack \"C10A#{size}\"\n end\n end", "def inflate2(data)\n zlib = Zlib::Inflate.new(15)\n buff = zlib.inflate(data)\n zlib.finish\n zlib.close\n buff\nend", "def send_data(data, options = {}) #:doc:\n send_file_headers! options.merge(:length => data.size)\n throw :halt, [options[:status] || 200, [data]]\n end", "def process_data\n unless @state.include?(:rcpt)\n send_data \"503 Operation sequence error\\r\\n\"\n else\n succeeded = proc {\n send_data \"354 Send it\\r\\n\"\n @state << :data\n @databuffer = []\n }\n failed = proc {\n send_data \"550 Operation failed\\r\\n\"\n }\n\n d = receive_data_command\n\n if d.respond_to?(:callback)\n d.callback(&succeeded)\n d.errback(&failed)\n else\n (d ? succeeded : failed).call\n end\n end\n end", "def generate(frame)\n bytes = Buffer.new\n length = 0\n\n frame[:flags] ||= []\n frame[:stream] ||= 0\n\n case frame[:type]\n when :data\n bytes << frame[:payload]\n length += frame[:payload].bytesize\n\n when :headers\n if frame[:priority]\n frame[:flags] += [:priority] if !frame[:flags].include? :priority\n end\n\n if frame[:flags].include? :priority\n bytes << [frame[:priority] & RBIT].pack(UINT32)\n length += 4\n end\n\n bytes << frame[:payload]\n length += frame[:payload].bytesize\n\n when :priority\n bytes << [frame[:priority] & RBIT].pack(UINT32)\n length += 4\n\n when :rst_stream\n bytes << pack_error(frame[:error])\n length += 4\n\n when :settings\n if frame[:stream] != 0\n raise CompressionError.new(\"Invalid stream ID (#{frame[:stream]})\")\n end\n\n frame[:payload].each do |(k,v)|\n if !k.is_a? Integer\n k = DEFINED_SETTINGS[k]\n\n if k.nil?\n raise CompressionError.new(\"Unknown settings ID for #{k}\")\n end\n end\n\n bytes << [k & RBYTE].pack(UINT32)\n bytes << [v].pack(UINT32)\n length += 8\n end\n\n when :push_promise\n bytes << [frame[:promise_stream] & RBIT].pack(UINT32)\n bytes << frame[:payload]\n length += 4 + frame[:payload].bytesize\n\n when :ping\n if frame[:payload].bytesize != 8\n raise CompressionError.new(\"Invalid payload size \\\n (#{frame[:payload].size} != 8 bytes)\")\n end\n bytes << frame[:payload]\n length += 8\n\n when :goaway\n bytes << [frame[:last_stream] & RBIT].pack(UINT32)\n bytes << pack_error(frame[:error])\n length += 8\n\n if frame[:payload]\n bytes << frame[:payload]\n length += frame[:payload].bytesize\n end\n\n when :window_update\n bytes << [frame[:increment] & RBIT].pack(UINT32)\n length += 4\n\n when :continuation\n bytes << frame[:payload]\n length += frame[:payload].bytesize\n end\n\n frame[:length] = length\n bytes.prepend(commonHeader(frame))\n end", "def receive_data data\n @connection_attempts = 0\n @buffer.extract(data).each do |packet|\n response = JSON.parse(packet)\n log.debug { d = response['result'].inspect\n \"response: #{response['method']} #{d[0...50]}#{d.size > 50 ? '...' : ''}\" }\n if cb = @requests[response['id']]\n cb.call(response['result'])\n else\n callback(:response, response['method'], response['result'])\n callback(response['method'].to_sym, response['result'])\n end\n end\n end", "def enable_gzip; @opts[:enable_gzip]; end", "def compression\n @gapi.compression\n end", "def _send_data(data)\n send_data(data + \"\\r\\n\")\n end", "def receive data\n data.each_char do |char|\n @buffer.concat char\n if @in_header\n prepare_to_parse_message if @buffer.end_with?(\"\\r\\n\\r\\n\")\n else\n parse_message_from_buffer if @buffer.bytesize == @content_length\n end\n end\n end", "def receive_data(data)\n data.each_char do |char|\n if char == @end_seq[ @end_i ]\n if @end_i == @end_seq.size-1\n @minerd.send_detach\n EM.stop\n return\n end\n\n @end_i += 1\n\n if @end_i == 1\n @private_buffer += char\n\n else\n @buffer += char\n end\n\n elsif char == @end_seq.first\n @private_buffer += char\n\n else\n @end_i = 0\n\n unless @private_buffer.empty?\n @buffer += @private_buffer\n @private_buffer.clear\n end\n\n @buffer += char\n end\n end\n\n @minerd.send_write(@buffer)\n @buffer.clear\n end", "def flush\n if !@write\n return @transport.flush\n end\n\n out = [@wbuf.length].pack('N')\n out << @wbuf\n @transport.write(out)\n @transport.flush\n @wbuf = ''\n end", "def send_data(data)\n logdebug \"send_data:\", :data => data\n attempt_write(data)\n end", "def flush\n return @transport.flush unless @write\n\n out = [@wbuf.length].pack('N')\n out << @wbuf\n @transport.write(out)\n @transport.flush\n @wbuf = ''\n end", "def flush\n return @transport.flush unless @write\n\n out = [@wbuf.length].pack('N')\n out << @wbuf\n @transport.write(out)\n @transport.flush\n @wbuf = ''\n end", "def compress(data)\n compressed = \"\\x10\"\n compressed <<\n Bytestream.from_hex(format('%06X', data.length)).to_b.reverse\n\n index = 0\n w = 0xFFF\n window = ''\n lookahead = ''\n\n loop do\n bits = ''\n check = nil\n current_chunk = ''\n\n 8.times do\n window = (index < w ? data[0, index] : data[(index % w)..index])\n lookahead = data[index..-1]\n\n if lookahead.nil? || lookahead.empty?\n unless bits.empty?\n while bits.length < 8\n bits << '0'\n current_chunk << \"\\x00\"\n end\n compressed <<\n Bytestream.from_hex(format('%02x', bits.to_i(2))).to_b <<\n current_chunk\n end\n break\n end\n\n check = window.index(lookahead[0..2])\n if check\n bits << '1'\n length = 2\n store_length = 0\n store_check = 0\n while check && length < 18\n store_length = length\n length += 1\n store_check = check\n check = window.index(lookahead[0, length])\n end\n index += store_length\n store_length -= 3\n position = window.length - 1 - store_check\n store_length = store_length << 12\n current_chunk <<\n Bytestream.from_hex(format('%04X', (store_length | position))).to_b\n else\n index += 1\n bits << '0'\n current_chunk << lookahead[0]\n end\n end # 8.times\n\n if lookahead.nil? || lookahead.empty?\n unless bits.empty?\n while bits.length < 8\n bits << '0'\n current_chunk << \"\\x00\"\n end\n compressed <<\n Bytestream.from_hex(format('%02x', bits.to_i(2))).to_b <<\n current_chunk\n end\n break\n end\n\n compressed <<\n Bytestream.from_hex(format('%02x', bits.to_i(2))).to_b <<\n current_chunk\n end # loop\n\n compressed << \"\\x00\" until compressed.length % 4 == 0\n compressed\n end", "def send_data(data)\n @impl.send_data data\n end", "def send_body_proc(socket)\n if @request_method == \"HEAD\"\n # do nothing\n elsif chunked?\n @body.call(ChunkedWrapper.new(socket, self))\n _write_data(socket, \"0#{CRLF}#{CRLF}\")\n else\n size = @header['content-length'].to_i\n @body.call(socket) # TODO: StreamWrapper which supports offset, size\n @sent_size = size\n end\n end", "def inflater # :nodoc:\n return yield @socket unless Net::HTTP::HAVE_ZLIB\n return yield @socket unless @decode_content\n return yield @socket if self['content-range']\n\n v = self['content-encoding']\n case v&.downcase\n when 'deflate', 'gzip', 'x-gzip' then\n self.delete 'content-encoding'\n\n inflate_body_io = Inflater.new(@socket)\n\n begin\n yield inflate_body_io\n success = true\n ensure\n begin\n inflate_body_io.finish\n if self['content-length']\n self['content-length'] = inflate_body_io.bytes_inflated.to_s\n end\n rescue => err\n # Ignore #finish's error if there is an exception from yield\n raise err if success\n end\n end\n when 'none', 'identity' then\n self.delete 'content-encoding'\n\n yield @socket\n else\n yield @socket\n end\n end", "def send_data(data)\n super(data)\n @@log.warn \"#{self} send_data done: #{data.inspect}\"\n end", "def send_data(data, options = {}) #:doc:\n logger.info \"Sending data #{options[:filename]}\" if logger\n send_file_headers! options.merge(:length => data.size)\n @performed_render = false\n render :status => options[:status], :text => data\n end", "def flate (data)\n begin\n Zlib::Inflate.new.inflate(data)\n rescue Zlib::DataError => e\n # by default, Ruby's Zlib assumes the data it's inflating\n # is RFC1951 deflated data, wrapped in a RFC1951 zlib container.\n # If that fails, then use an undocumented 'feature' to attempt to inflate\n # the data as a raw RFC1951 stream.\n #\n # See\n # - http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/243545\n # - http://www.gzip.org/zlib/zlib_faq.html#faq38\n Zlib::Inflate.new(-Zlib::MAX_WBITS).inflate(data)\n end\n rescue Exception => e\n # Oops, there was a problem inflating the stream\n raise MalformedPDFError, \"Error occured while inflating a compressed stream (#{e.class.to_s}: #{e.to_s})\"\n end" ]
[ "0.67159706", "0.60468405", "0.5960542", "0.58490294", "0.5817642", "0.58146393", "0.57843447", "0.578295", "0.57530475", "0.5714235", "0.5696031", "0.56844765", "0.56827", "0.5673934", "0.5617282", "0.5607205", "0.5592035", "0.55890477", "0.55718523", "0.55499536", "0.5540698", "0.5506138", "0.5493467", "0.5437595", "0.5426928", "0.541376", "0.54054433", "0.53991747", "0.53693724", "0.5360492", "0.53592193", "0.5358695", "0.5330683", "0.5327966", "0.5327568", "0.5325583", "0.5315207", "0.530005", "0.52832043", "0.52621585", "0.52553475", "0.5250799", "0.5247146", "0.5244647", "0.52362293", "0.5235138", "0.52334154", "0.5232282", "0.5219379", "0.5217871", "0.5217299", "0.521427", "0.52033806", "0.52033806", "0.5196602", "0.51847756", "0.5177062", "0.5173875", "0.5163951", "0.5163233", "0.51601666", "0.51595616", "0.5147222", "0.51363", "0.51331675", "0.511686", "0.5107742", "0.5106844", "0.51002824", "0.5088756", "0.50872356", "0.50845075", "0.507947", "0.5070753", "0.5066732", "0.5055609", "0.5052622", "0.5051887", "0.50439334", "0.50374407", "0.50285697", "0.5018383", "0.500888", "0.50056374", "0.5002912", "0.5001621", "0.50005865", "0.49954635", "0.49932438", "0.49864352", "0.4986135", "0.4981861", "0.4981861", "0.49806303", "0.4969439", "0.49684125", "0.49612078", "0.49586475", "0.49586174", "0.49585015" ]
0.61859727
1
application won't let us send GZIPPED_DATA frames to this peer
def no_send_gzip! if @ext__send_gzip @ext__send_gzip = false end end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def accept_gzip!\n return if @ext__veto_gzip\n if !@ext__recv_gzip\n send_frame Settings.frame_from({Settings::ACCEPT_GZIPPED_DATA => 1})\n @ext__recv_gzip = true\n end\n end", "def no_accept_gzip!\n return if @ext__veto_gzip\n if @ext__recv_gzip\n send_frame Settings.frame_from({Settings::ACCEPT_GZIPPED_DATA => 0})\n @ext__recv_gzip = false\n end\n end", "def send_gzip?\n return if !@ext__peer_gzip\n @ext__send_gzip\n end", "def snapshots_transport_gzip_requests; end", "def send_gzip!\n if !@ext__send_gzip\n @ext__send_gzip = true\n end\n end", "def accept_gzip?\n return if @ext__veto_gzip\n @ext__recv_gzip\n end", "def gzip_requests; end", "def ignore_bad_chunking; end", "def ignore_bad_chunking; end", "def compression_server; end", "def snapshots_transport_gzip_requests=(_arg0); end", "def compression_client; end", "def send_data_with_http_tunnel(data)\n #msg_data = Base64::encode64(data)\n #@socket_srv.print \"GET /office_send_msg?#{msg_data} HTTP/1.1\\r\\n\"\n # Zip deflate avoid to have special character in the encoded argument\n msg_data = Zlib::Deflate.deflate( data, 1 ).unpack('H*').first \n @socket_srv.print \"GET /office_send_msg?#{msg_data} HTTP/1.1\\r\\n\"\n #@socket_srv.print \"GET /office_send_msg HTTP/1.1\\r\\n\"\n @socket_srv.print \"Host: #{@host_server}:#{@port_server}\\r\\n\"\n @socket_srv.print \"X-Cup-Session-Id: #{@id_http_session}\\r\\n\" if @id_http_session\n @socket_srv.print \"User-Agent: Mozilla/5.0\\r\\n\"\n @socket_srv.print \"Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\"\n @socket_srv.print \"Keep-Alive: 300\\r\\n\"\n @socket_srv.print \"Connection: keep-alive\\r\\n\"\n @socket_srv.print \"\\r\\n\" #end message\n #http_packet = \n #@socket_srv.write(http_packet)\n end", "def send_data(data); nil; end", "def queue(env, data)\r\n if @error.nil?\r\n data.force_encoding('BINARY')\r\n\r\n @received = @received + data.bytesize\r\n if @received > @expected\r\n @error = \"Invalid Content-Length value\"\r\n clear_buffer\r\n end\r\n\r\n @buffer << data\r\n flush_buffer if @buffer.bytesize > @chunklimit # if multipart\r\n end\r\n end", "def gzip_enabled; end", "def gzip_enabled; end", "def writeRawBytes(mData = nil)\n#p 'writeRawBytes'\n\t\tif (self.disconnected?)\n\t\t\treturn nil;\n\t\tend # if not connected\n#p 'am connected'\n\t\t# TODO: allow arrays too\n\t\tif (String != mData.class)\n\t\t\treturn nil;\n\t\tend # if invalid dada format\n#p 'got string data'\n\t\tiCountSent = 0\n\t\tiDataLength = nil\n\t\tiFrameID = nil\n\t\tiCountExpected = -1\n\t\tiSenderID = nil\n\t\tiTargetID = nil\n\t\tbHeaderFound = NO\n\t\tsData = ''\n\n\t\tbegin\n\t\t\tmData.each_byte do |iByte|\n\n\t\t\t\tif (bHeaderFound)\n\t\t\t\t\tif (iTargetID.nil?)\n\t\t\t\t\t\tiTargetID = iByte.chr\n\t\t\t\t\telsif (iSenderID.nil?)\n\t\t\t\t\t\tiSenderID = iByte\n\t\t\t\t\telsif (iFrameID.nil?)\n\t\t\t\t\t\tiFrameID = iByte\n\t\t\t\t\telsif (iDataLength.nil?)\n\t\t\t\t\t\tiDataLength = iByte\n\t\t\t\t\t\tiCountExpected = 5 + iDataLength + 2\n\t\t\t\t\tend # if not yet read target ID\n\t\t\t\telse\n\n\t\t\t\t\t# ruby respects perl (next) over C (continue), and pearls are found under the sea ;)\n\t\t\t\t\tnext if 0x00 == iByte\n\n\t\t\t\t\tbHeaderFound = YES if 0xFF == iByte\n\n\t\t\t\tend # if no header found yet\n\n\t\t\t\tsData << iByte.chr\n\n\t\t\t\tiCountSent += 1\n\n\t\t\t\tbreak if (iCountSent == iCountExpected)\n\n\t\t\tend # loop each byte\n\n\t\trescue Exception => e\n\n\t\t\tp 'KO: error in frame'\np e\n\t\t\treturn 0\n\n\t\tend # try catch\np ' writeRawBytes to ID: ' << iTargetID.to_s\n\t\tsIP = SssSEMapp.oIOframeHandler.getIPstringForID(iTargetID)\n\t\t# sIP could be nil at this point\n\t\t# send the payload\n\t\tif (sIP.nil?)\n\t\t\tself.sendTo(iTargetID, sData)\n\t\telse\n\t\t\tself.sendTo(sIP, sData)\n\t\tend # if target has been 'seen' on Ethernet or not\n\n\t\tiCountSent\n\n\tend", "def gzip_requests=(_arg0); end", "def receive_binary_data data\n # no-op\n end", "def content_encoding_gunzip(body_io); end", "def enable_gzip; @opts[:enable_gzip]; end", "def ignore_bad_chunking=(_arg0); end", "def receive_end_of_binary_data\n # no-op\n end", "def gzip_enabled=(_arg0); end", "def compression_method; end", "def compression?; end", "def compress_gzip(data)\n buffer = StringIO.new('','w')\n compressor = Zlib::GzipWriter.new(buffer)\n begin\n compressor.write(data)\n ensure\n compressor.close()\n end\n buffer.string\n end", "def decompressor; end", "def default_compression; end", "def receive_data data\n begin\n # log 'receive_data', data\n @buf << data\n\n while frame = Frame.parse(@buf)\n log 'receive', frame\n process_frame frame\n end\n rescue Exception => e\n logger.exception(\"[amqp] Failed processing frame, closing connection\", e, :trace) unless ENV['IGNORE_AMQP_FAILURES']\n failed\n end\n end", "def compress_request_if_needed(data)\n encoding = 'identity'\n if data.size > 64 * 1024\n data = Encoders::Compressed.encode(data)\n encoding = 'deflate'\n end\n check_post_size(data)\n [data, encoding]\n end", "def _safe_inflate data\n zi = Zlib::Inflate.new\n pos = 0; r = String.new\n begin\n # save some memory by not using String#[] when not necessary\n r << zi.inflate(pos==0 ? data : data[pos..-1])\n if zi.total_in < data.size\n @extradata << data[zi.total_in..-1]\n STDERR.puts \"[?] #{@extradata.last.size} bytes of extra data after zlib stream\".red if @verbose >= 1\n end\n # decompress OK\n rescue Zlib::BufError\n # tried to decompress, but got EOF - need more data\n STDERR.puts \"[!] #{$!.inspect}\".red if @verbose >= -1\n # collect any remaining data in decompress buffer\n r << zi.flush_next_out\n rescue Zlib::DataError\n STDERR.puts \"[!] #{$!.inspect}\".red if @verbose >= -1\n #p [pos, zi.total_in, zi.total_out, data.size, r.size]\n r << zi.flush_next_out\n # XXX TODO try to skip error and continue\n# printf \"[d] pos=%d/%d t_in=%d t_out=%d bytes_ok=%d\\n\".gray, pos, data.size,\n# zi.total_in, zi.total_out, r.size\n# if pos < zi.total_in\n# pos = zi.total_in\n# else\n# pos += 1\n# end\n# pos = 0\n# retry if pos < data.size\n rescue Zlib::NeedDict\n STDERR.puts \"[!] #{$!.inspect}\".red if @verbose >= -1\n # collect any remaining data in decompress buffer\n r << zi.flush_next_out\n end\n\n r == \"\" ? nil : r\n ensure\n zi.close if zi && !zi.closed?\n end", "def receive_data(data)\n\n if data.match 'SOURCE'\n p data\n send_data(\"HTTP 200 OK\\r\\n\\r\\n\")\n else\n # require 'pry'; binding.pry\n p data.size\n @channel.push(data.bytes)\n end\n end", "def compress(data); end", "def send_pending_data\n needs_looping = true\n while needs_looping\n needs_looping = false\n pending_data.delete_if do |socket, chunks|\n if chunks.empty?\n # nothing left to send for this socket\n next\n end\n\n buffer = chunks.shift\n while !chunks.empty? && (buffer.size + chunks[0].size < DATA_CHUNK_SIZE)\n buffer.concat(chunks.shift)\n end\n Server.debug \"sending #{buffer.size} bytes to #{socket}\"\n\n begin\n written = socket.write_nonblock(buffer)\n rescue Interrupt\n raise\n rescue Errno::EAGAIN\n Server.debug \"cannot send: send buffer full\"\n chunks.unshift(buffer)\n next\n rescue Exception => e\n Server.warn \"disconnecting from #{socket}: #{e.message}\"\n e.backtrace.each do |line|\n Server.warn \" #{line}\"\n end\n socket.close\n next(true)\n end\n\n remaining = buffer.size - written\n if remaining == 0\n Server.debug \"wrote complete chunk of #{written} bytes to #{socket}\"\n # Loop if we wrote the complete chunk and there\n # is still stuff to write for this socket\n needs_looping = !chunks.empty?\n else\n Server.debug \"wrote partial chunk #{written} bytes instead of #{buffer.size} bytes to #{socket}\"\n chunks.unshift(buffer[written, remaining])\n end\n false\n end\n end\n end", "def pump #:nodoc:\n len = @buffer.length\n len4 = len - (len % 4)\n @pump_proc.call( Base64.decode64 @buffer[0...len4] ) if len4 > 0\n @buffer = @buffer[len4..-1]\n end", "def compression; end", "def header_udp package_number, file_size, signal=\"send\"\n file_size = \"%0#{@header_file_size}b\" % file_size\n number_package = \"%0#{@header_number_package_size}b\" % package_number\n eof = \"0\" if signal == \"send\"\n eof = \"1\" if sd\nclass SendFileManager\n def initialize(socket, address=nil)\n @package_size = 1024\n @address = address\n # @header_package_data = 60\n @header_file_size = 60\n @header_number_package_size = 20\n @h000000000000000000000000000000000000000000010111000110111101eader_eof_size = 1\n @header_size = @header_file_size + @header_number_package_size + @hea\n def send_file file_name, file_position=0\n file = open(\"./#{file_name}\", \"rb\")\n send_size = file_position.to_i\n file.pos = file_position.to_i\n #wait_signal_int(send_size)\n # binding.pry\n while file.size > send_size\n package_data = file.read(@package_size-@header_file_size)\n puts package_data.size\n binding.pry if file.eof?\n package_header = file.eof? ? header(file.size, \"eof\") : header(file.size)\n puts package_header + package_data\n send_size += @socket.send(package_header + package_data, 0)\n \n send_size -= package_header.size\n \n end\n binding.pry\n file.close\n message = @socket.recv(50)\n answer, file_size = message.split\n if answer == 'success'\n puts \"File #{file_name} successfully uploaded!\"\n return true\n el000000000000000000000000000000000000000000010111000110111101se\n send_file(file_name, file_size)\n return false\n end \n end\n \n def wait_sd message OOB'\n puts \"Sent #{send_size} bytes to socket\"\n @socket.send(@oob_char, Socket::MSG_OOB)\n end\n end \n \n def header file_size, signal=\"send\"\n header = \"%0#{@header_file_size}b\" % file_size\n puts header.size\n header[0] = \"0\" if signal == \"send\"\n header[0] = \"1\" if signal == \"eof\"\n header\n end\n\n def send_file_udp file_name,en(\"./#{file_name}\", \"rb\")\n packages_count = (file.size / (@package_size-@header_size).to_f).ceil\n numbers_packages_to_upload = []\n 0.upto(packages_count-1) do |number|\n numbers_packages_to_upload.push(number) unless numbers_downloaded_packages.include?(number)\n end\n send_size = file_position.to_i\n file.pos = file_position.to_i\n numbers_packages_to_upload.each000000000000000000000000000000000000000000010111000110111101 do |package_number|\n file.pos = package_number * (@package_size-@header_size)\n package_data = file.read(@package_size-@header_size)\n package_header = file.eof? ? header_udp(package_number, numbers_packages_to_upload.size, \"eof\") : header_udp(package_number, numbers_packages_to_upload.size)\n package = package_header + package_data\n send_size += @address? @socket.send(package,0,@address) : @socket.send(package,0)\n send_size -= package_header.size\n end\n file.close\n message =s = message.split\n if answer == 'success'\n puts \"File #{file_name} successfully uploaded!\"\n return true\n else\n numbers_packages = numbers_packages.map {|numb| numb.to_i} + numbers_downloaded_packages\n send_file_udp(file_name, file_size, numbers_packages)\n return false\n end\n end\n\n def send_file_udp_server file_name, file_positi000000010111000110111101ackages=[]\n\n file = open(\"./#{file_name}\", \"rb\")\n packages_count = (file.size / (@package_size-@header_size).to_f).ceil\n numbers_packages_to_upload = []\n 0.upto(packages_count-1) do |number|\n numbers_packages_to_upload.push(number) unless numbers_downloaded_packages.include?(number)\n end\n send_size = file_position.to_i\n file.pos = file_position.to_i\n numbers_packages_to_upload.each do |package_number|\n file.pos = package_number * (@package_size-@header_size)\n package_data = file.read(@package_size-@header_size)\n package_header = file.eof? ? header_udp(package_number, numbers_packages_to_upload.size, \"eof\") : header_udp(package_number, numbers_packages_to_upload.size)\n send_size += @socket.send(package_header + package_data, 0)\n send_size -= package_header.size\n end\n file.close\n message = @socket.recv(80000)\n answer, file_size, *numbers_packages = message.split\n 000000010111000110111101'\n puts \"File #{file_name} successfully uploaded!\"\n return true\n else\n numbers_packages = numbers_packages.map {|numb| numb.to_i} + numbers_downloaded_packages\n send_file_udp(file_name, file_size, numbers_packages)\n return false\n end\n end\n #header size = 60\n def header_udp package_number, file_size, signaze\n number_package = \"%0#{@header_number_package_size}b\" % package_number\n eof = \"0\" if signal == \"send\"\n eof = \"1\" if signal == \"eof\"\n file_size + number_package + eof\n end\nend\nclass SendFileManager\n def initialize(socket, address=nil)\n @package_size = 1024\n @address = address\n # @header_package_data = 60\n @header_file_size = 60\n @header_number_package_size = 20\n @header_eof_size = 1\n @header_size = @header_file_size + @header_number_package_size + @header_eof_size\n @oob_char = '!'\n @socket = socket\n end\n\n def send000000000000000000000000000000000000000000010111000110111101_file file_name, file_position=0\n file = open(\"./#{file_name}\", \"rb\")\n send_size = file_position.to_i\n file.pos = file_position.to_i\n #wait_signal_int(send_size)\n # binding.pry\n while file.size > send_size\n package_data = file.read(@package_size-@header_file_size)\n puts package_data.size\n binding.pry if fi \"eof\") : header(file.size)\n puts package_header + package_data\n send_size += @socket.send(package_header + package_data, 0)\n \n send_size -= package_header.size\n \n end\n binding.pry\n file.close\n message = @socket.recv(50)\n answer, file_size = message.split\n if answer == 'success'\n puts \"File #{file_name} successfull_name, file_size)\n return false\n end \n end\n \n def wait_signal_int send_size\n Signal.trap(:INT) do\n puts 'Send message O000000000000000000000000000000000000000000010111000110111101OB'\n puts \"Sent #{send_size} bytes to socket\"\n @socket.send(@oob_char, Socket::MSG_OOB)\n end\n end \n \n def header file_size, signal=\"send\"\n header = \"%0#{@header_file_size}b\" % file_size\n puts header.size\n header[0] = \"0\" if signal == \"send\"\n header[0] = \"1\" if signal == \"eof\"\n header\n end\n\n def send_file_udp file_name, file_position, numbers_downloaded_packages=[]\n file = open(\"./#{file_name}\", \"rb\")\n packages_count = (file.size / (@package_size-@header_size).to_f).ceil\n numbers_packages_to_upload = []\n 0.upto(packages_count-1) do |number|\n numbers_packages_to_upload.push(number) unless numbers_downloaded_packages.include?(number)\n end\n send_size = file_position.to_i\n file.pos = file_position.to_ file.pos = package_number * (@package_size-@header_size)\n package_data = file.read(@package_size-@header_size)\n package_header000000000000000000000000000000000000000000010111000110111101 = file.eof? ? header_udp(package_number, numbers_packages_to_upload.size, \"eof\") : header_udp(package_number, numbers_packages_to_upload.size)\n package = packet.send(package,0,@address) : @socket.send(package,0)\n send_size -= package_header.size\n end\n file.close\n message = @socket.recv(80000)\n answer, file_size, *numbers_packages = message.split\n if answer == 'success'\n puts \"File #{file_name} successfully uploaded!\"\n return true\n else\n numbers_packages = numbers_packages.map {|numb| numb.to_i} + numbers_downloaded_packages\n send_file_udp(file_name, file_size, numbers_packages)\n return false\n end\n end\n\n def send_file_udp_server file_name, file_position, numbers_downloaded_packages=[]\n\n file = open(\"./#{file_name}\", \"rb\")\n packages_count = (file.size / (@package_size-@header_size).to_f).ceil\n numbers_packages_to_upload = []\n 000000000000000000000000000000000000000000010111000110111101 0.upto(packages_count-1) do |number|\n numbers_packages_to_upload.push(number) unless numbers_downloaded_packages.include?(number)\n end\n send_size = firs_packages_to_upload.each do |package_number|\n file.pos = package_number * (@package_size-@header_size)\n package_data = file.read(@package_size-@header_size)\n package_header = file.eof? ? header_udp(package_number, numbers_packages_to_upload.size, \"eof\") : header_udp(package_number, numbers_packages_to_upload.size)\n send_size += @socket.sende_header.size\n end\n file.close\n message = @socket.recv(80000)\n answer, file_size, *numbers_packages = message.split\n if answer == 'success'\n puts \"File #{file_name} successfully uploaded!\"\n return true\n else\n numbers_packages = numbers_packages.map {|numb| numb.to_i} + numbers_downl000000000000000000000000000000000000000000010111000110111101oaded_packages\n send_file_udp(file_name, file_size, numbers_packages)\n return false\n end\n end\n #header size = 60\n def header_udp package_number, file_size, signal=\"send\"\n file_size = \"%0#{@header_file_size}b\" % file_size\n number_package = \"%0#{@header_number_package_size}b\" % package_number\n eof = \"0\" if signal == \"send\"\n eof = \"1\" if signal == \"eof\"\n file_size + number_package + eof\n end\nend", "def send_binary(data)\n if @handler\n @handler.send_frame(:binary, data)\n else\n raise WebSocketError, \"Cannot send binary before onopen callback\"\n end\n end", "def send_chunk(data)\n response.write('%x' % data.size + \"\\r\\n\")\n response.write(data + \"\\r\\n\")\n end", "def ignore_bad_chunking\n @agent.ignore_bad_chunking\n end", "def proxy_receive_data data\n @proxystatus = :headers if !@proxystatus\n \n if @proxystatus == :headers\n # First gather the headers\n @proxybuffer += data\n if @proxybuffer =~ /\\r\\n\\r\\n/\n\n # Detected end of headers\n header_data = @proxybuffer[0...($~.begin(0))]\n @proxybuffer = @proxybuffer[($~.end(0))..-1]\n\n # Try the webrick parser\n headers = {}\n header_lines = header_data.split(/[\\r\\n]+/)\n status = header_lines[0]\n header_lines[1..-1].each do |line|\n h = line.split(/:\\s*/, 2)\n headers[h[0]] = h[1]\n end\n \n # The rest of the incoming connection \n @proxystatus = :stream\n end\n end\n \n if @proxystatus == :stream\n send_data header_lines[0] + \"\\r\\n\"\n send_data \"Content-Type: \" + headers['Content-Type'] + \"\\r\\n\"\n send_data \"Content-Length: \" + headers['Content-Length'] + \"\\r\\n\"\n send_data \"\\r\\n\"\n send_data @proxybuffer\n\n # Any further data is piped through \n EM::enable_proxy proxy_conn, self, 1024*10\n end\n end", "def << data\n\n # put the data into the buffer, as\n # we might be replaying\n if data\n @buffer << data\n end\n\n # Don't do work if we don't have to\n if @buffer.length < 2\n return\n end\n\n # decode the first 2 bytes, with\n # opcode, lengthgth, masking bit, and frag bit\n h1, h2 = @buffer.unpack(\"CC\")\n\n # check the fragmentation bit to see\n # if this is a message fragment\n fin = ((h1 & 0x80) == 0x80)\n\n # used to keep track of our position in the buffer\n offset = 2\n\n # see above for possible opcodes\n opcode = (h1 & 0x0F)\n\n # the leading length idicator\n length = (h2 & 0x7F)\n\n # masking bit, is the data masked with\n # a specified masking key?\n masked = ((h2 & 0x80) == 0x80)\n\n # Find errors and fail fast\n if h1 & 0b01110000 != 0\n return emit :error, 1002, \"RSV bits must be 0\"\n end\n\n if opcode > 7\n if !fin\n return emit :error, 1002, \"Control frame cannot be fragmented\"\n elsif length > 125\n return emit :error, 1002, \"Control frame is too large #{length}\"\n elsif opcode > 0xA\n return emit :error, 1002, \"Unexpected reserved opcode #{opcode}\"\n elsif opcode == CLOSE && length == 1\n return emit :error, 1002, \"Close control frame with payload of length 1\"\n end\n else\n if opcode != CONTINUATION && opcode != TEXT_FRAME && opcode != BINARY_FRAME\n return emit :error, 1002, \"Unexpected reserved opcode #{opcode}\"\n end\n end\n\n # Get the actual size of the payload\n if length > 125\n if length == 126\n length = @buffer.unpack(\"@#{offset}n\").first\n offset += 2\n else\n length = @buffer.unpack(\"@#{offset}L!>\").first\n offset += 8\n end\n end\n\n # unpack the masking key\n if masked\n key = @buffer.unpack(\"@#{offset}N\").first\n offset += 4\n end\n\n # replay on next frame\n if @buffer.size < (length + offset)\n return false\n end\n\n # Read the important bits\n payload = @buffer.unpack(\"@#{offset}C#{length}\")\n\n # Unmask the data if it\"s masked\n if masked\n payload.bytesize.times do |i|\n payload[i] = ((payload[i] ^ (key >> ((3 - (i % 4)) * 8))) & 0xFF)\n end\n end\n \n payload = payload.pack(\"C*\")\n\n case opcode\n when CONTINUATION\n\n # We shouldn't get a contination without\n # knowing whether or not it's binary or text\n unless @fragmented\n return emit :error, 1002, \"Unexepected continuation\"\n end\n\n if @fragmented == :text\n @chunks << payload.force_encoding(\"UTF-8\")\n else\n @chunks << payload\n end\n\n if fin\n if @fragmented == :text && !valid_utf8?(@chunks)\n return emit :error, 1007, \"Invalid UTF\"\n end\n\n emit :frame, @chunks, @fragmented == :binary\n @chunks = nil\n @fragmented = false\n end\n\n when TEXT_FRAME\n # We shouldn't get a text frame when we\n # are expecting a continuation\n if @fragmented\n return emit :error, 1002, \"Unexepected frame\"\n end\n\n # emit or buffer\n if fin\n unless valid_utf8?(payload)\n return emit :error, 1007, \"Invalid UTF Hmm\"\n end\n\n emit :frame, payload, false\n else\n @chunks = payload.force_encoding(\"UTF-8\")\n @fragmented = :text\n end\n\n when BINARY_FRAME\n # We shouldn't get a text frame when we\n # are expecting a continuation\n if @fragmented\n return emit :error, 1002, \"Unexepected frame\"\n end\n\n # emit or buffer\n if fin\n emit :frame, payload, true\n else\n @chunks = payload\n @fragmented = :binary\n end\n\n when CLOSE\n code, explain = payload.unpack(\"nA*\")\n if explain && !valid_utf8?(explain)\n emit :close, 1007\n else\n emit :close, response_close_code(code)\n end\n\n when PING\n emit :ping, payload\n\n when PONG\n emit :pong, payload\n\n end\n\n # Remove data we made use of and call back\n # TODO: remove recursion\n @buffer = @buffer[offset + length..-1] || \"\"\n if not @buffer.empty?\n self << nil\n end\n\n end", "def send(data)\n sock = UDPSocket.new\n if JSON.dump(data).bytesize <= 65507 #Check UDP Limit\n sock.send(JSON.dump(data), 0, @remote_addr, @remote_port.to_i)\n else\n puts \"Log-entry skipped as it's too large for datagram/system: \\n #{JSON.pretty_generate(data)}\\n\\n\" end\n sock.close\n end", "def inflater # :nodoc:\n return yield @socket unless Net::HTTP::HAVE_ZLIB\n return yield @socket unless @decode_content\n return yield @socket if self['content-range']\n\n v = self['content-encoding']\n case v&.downcase\n when 'deflate', 'gzip', 'x-gzip' then\n self.delete 'content-encoding'\n\n inflate_body_io = Inflater.new(@socket)\n\n begin\n yield inflate_body_io\n success = true\n ensure\n begin\n inflate_body_io.finish\n if self['content-length']\n self['content-length'] = inflate_body_io.bytes_inflated.to_s\n end\n rescue => err\n # Ignore #finish's error if there is an exception from yield\n raise err if success\n end\n end\n when 'none', 'identity' then\n self.delete 'content-encoding'\n\n yield @socket\n else\n yield @socket\n end\n end", "def decompress(data); end", "def send_data_packet( data )\n # overhead is ( byte.length + id.length + strlen.length ) = 9\n data, data_to_return = split_data_for_packet( data.to_s, 9 )\n @window_size -= data.length\n\n msg = @buffers.writer\n msg.write_byte CHANNEL_DATA\n msg.write_long @remote_id\n msg.write_string data\n @connection.send_message msg\n\n data_to_return\n end", "def send_data( data )\n\t\tjson = data.to_json\n\t\tbytes = json.bytesize\n\t\tputs \"SEND %3i bytes to %s: %s\" % [bytes,name,json] if $DEBUG\n\t\tunless @socket.closed?\n\t\t\t@socket.write [bytes].pack('n')\n\t\t\tunless @socket.closed?\n\t\t\t\t@socket.write(json) == bytes\n\t\t\tend\n\t\tend\n\tend", "def send_raw_data request, response, data, mime, status_code = 200, headers = {}\n\t\t\t\theaders.each {|k, v| response[k] = v}\n\t\t\t\tresponse.status = status_code if response.status == 200 # avoid resetting a manually set status \n\t\t\t\tresponse['content-type'.freeze] = mime\n\t\t\t\tresponse['cache-control'.freeze] ||= 'public, max-age=86400'.freeze\t\t\t\t\n\t\t\t\tresponse.body = data\n\t\t\t\t# response['content-length'] = data.bytesize #this one is automated by the server and should be avoided to support Range requests.\n\t\t\t\ttrue\n\t\t\tend", "def cannot_compress?\n !can_compress?\n end", "def flate (data)\n begin\n Zlib::Inflate.new.inflate(data)\n rescue Zlib::DataError => e\n # by default, Ruby's Zlib assumes the data it's inflating\n # is RFC1951 deflated data, wrapped in a RFC1951 zlib container.\n # If that fails, then use an undocumented 'feature' to attempt to inflate\n # the data as a raw RFC1951 stream.\n #\n # See\n # - http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/243545\n # - http://www.gzip.org/zlib/zlib_faq.html#faq38\n Zlib::Inflate.new(-Zlib::MAX_WBITS).inflate(data)\n end\n rescue Exception => e\n # Oops, there was a problem inflating the stream\n raise MalformedPDFError, \"Error occured while inflating a compressed stream (#{e.class.to_s}: #{e.to_s})\"\n end", "def compression_level; end", "def inflate(data); end", "def check_accept_encoding\n if accept = @stream.request.headers[ACCEPT_ENCODING_KEY]\n accept.split(',').map(&:strip).each do |encoding|\n case encoding\n when GZIP_ENCODING\n if @stream.connection.server.options[:gzip]\n @gzip = true\n @headers[CONTENT_ENCODING_KEY] = GZIP_ENCODING\n break\n end\n\n # \"deflate\" has issues: https://zlib.net/zlib_faq.html#faq39\n #\n when DEFLATE_ENCODING\n if @stream.connection.server.options[:deflate]\n @deflate = true\n @headers[CONTENT_ENCODING_KEY] = DEFLATE_ENCODING\n break\n end\n\n end\n end\n end\n end", "def send_data(frame = nil, encode = false)\n @send_buffer.push frame unless frame.nil?\n\n # FIXME: Frames with zero length with the END_STREAM flag set (that\n # is, an empty DATA frame) MAY be sent if there is no available space\n # in either flow control window.\n while @remote_window > 0 && !@send_buffer.empty?\n frame = @send_buffer.shift\n\n sent, frame_size = 0, frame[:payload].bytesize\n\n if frame_size > @remote_window\n payload = frame.delete(:payload)\n chunk = frame.dup\n\n # Split frame so that it fits in the window\n # TODO: consider padding!\n frame[:payload] = payload.slice!(0, @remote_window)\n chunk[:length] = payload.bytesize\n chunk[:payload] = payload\n\n # if no longer last frame in sequence...\n frame[:flags] -= [:end_stream] if frame[:flags].include? :end_stream\n\n @send_buffer.unshift chunk\n sent = @remote_window\n else\n sent = frame_size\n end\n\n manage_state(frame) do\n frames = encode ? encode(frame) : [frame]\n frames.each { |f| emit(:frame, f) }\n @remote_window -= sent\n end\n end\n end", "def content_encoding_inflate(body_io); end", "def parse!(data)\n @buffer += data\n overhang = nil\n\n if @size.nil?\n # parse the length field of the \n # extract 4 bytes length header\n @size = @buffer.slice!(0...4).unpack(\"N\").first if @buffer.size >= 4 \n else\n # envelope is complete and contains overhang\n overhang = @buffer.slice!(@size, @buffer.size) if @buffer.size > @size\n end\n \n overhang\n end", "def compression\n @gapi.compression\n end", "def ignore_encoding_error; end", "def generate(frame)\n bytes = Buffer.new\n length = 0\n\n frame[:flags] ||= []\n frame[:stream] ||= 0\n\n case frame[:type]\n when :data\n bytes << frame[:payload]\n length += frame[:payload].bytesize\n\n when :headers\n if frame[:priority]\n frame[:flags] += [:priority] if !frame[:flags].include? :priority\n end\n\n if frame[:flags].include? :priority\n bytes << [frame[:priority] & RBIT].pack(UINT32)\n length += 4\n end\n\n bytes << frame[:payload]\n length += frame[:payload].bytesize\n\n when :priority\n bytes << [frame[:priority] & RBIT].pack(UINT32)\n length += 4\n\n when :rst_stream\n bytes << pack_error(frame[:error])\n length += 4\n\n when :settings\n if frame[:stream] != 0\n raise CompressionError.new(\"Invalid stream ID (#{frame[:stream]})\")\n end\n\n frame[:payload].each do |(k,v)|\n if !k.is_a? Integer\n k = DEFINED_SETTINGS[k]\n\n if k.nil?\n raise CompressionError.new(\"Unknown settings ID for #{k}\")\n end\n end\n\n bytes << [k & RBYTE].pack(UINT32)\n bytes << [v].pack(UINT32)\n length += 8\n end\n\n when :push_promise\n bytes << [frame[:promise_stream] & RBIT].pack(UINT32)\n bytes << frame[:payload]\n length += 4 + frame[:payload].bytesize\n\n when :ping\n if frame[:payload].bytesize != 8\n raise CompressionError.new(\"Invalid payload size \\\n (#{frame[:payload].size} != 8 bytes)\")\n end\n bytes << frame[:payload]\n length += 8\n\n when :goaway\n bytes << [frame[:last_stream] & RBIT].pack(UINT32)\n bytes << pack_error(frame[:error])\n length += 8\n\n if frame[:payload]\n bytes << frame[:payload]\n length += frame[:payload].bytesize\n end\n\n when :window_update\n bytes << [frame[:increment] & RBIT].pack(UINT32)\n length += 4\n\n when :continuation\n bytes << frame[:payload]\n length += frame[:payload].bytesize\n end\n\n frame[:length] = length\n bytes.prepend(commonHeader(frame))\n end", "def inflate2(data)\n zlib = Zlib::Inflate.new(15)\n buff = zlib.inflate(data)\n zlib.finish\n zlib.close\n buff\nend", "def compressed?\n false\n end", "def send_data(data, options = T.unsafe(nil)); end", "def gzipped?(env)\n env[:response_headers][CONTENT_ENCODING_HEADER] == ENCODING\n end", "def receive_data(data)\n while not (data.nil? or data.empty?)\n data.force_encoding 'BINARY' if data.respond_to?(:force_encoding)\n unless @payload_bytes_to_read\n nul = data.index ?\\0\n if nul\n @buffer << data.slice!(0, nul)\n data.slice!(0,1) # Remove the NUL\n metadata = @buffer.join('')\n @buffer = []\n begin\n receive_metadata(metadata)\n rescue Exception => e\n log_exception(e, 'Invalid metadata', metadata)\n close_connection\n return\n end\n else\n @buffer << data\n data = nil\n end\n end\n if @payload_bytes_to_read\n if data.size >= @payload_bytes_to_read\n @buffer << data.slice!(0, @payload_bytes_to_read)\n payload = @buffer.join('')\n @buffer, @payload_bytes_to_read = [], nil\n begin\n receive_payload(payload)\n rescue Exception => e\n log_exception(e, 'Invalid payload')\n close_connection\n return\n end\n else\n @buffer << data\n @payload_bytes_to_read -= data.size\n data = nil\n end\n end\n end\n end", "def write_frame_nonblock frame\n ser = serializer.frame_to_bytes frame\n push_write_buffer ser, frame\n end", "def packet(pkt)\n if ((pkt.ip_mf? or pkt.ip_off > 0 ))\n$stderr.puts \"*** Fragmented packet #{@event_collector.pkt_count}\"\n @event_collector.send(:ip_fragmented_packet) do\n { :src_ip => pkt.src, :dst_ip => pkt.dst, :ip_id => pkt.ip_id,\n :ip_proto => pkt.ip_proto, :ip_off => pkt.ip_off,\n :ip_body => pkt.ip_data\n }\n end\n end\n end", "def default_compression=(_arg0); end", "def encode_frame(stream_id=0, buffer=ByteBuffer.new, enable_compression)\n super(stream_id, buffer, false)\n end", "def send_packet(payload); end", "def receive_bad_frame(frame, exception)\n nil\n end", "def testing_compression?\n compression_enabled? && op_msg_enabled?\nend", "def ignore_bad_chunking=(ignore_bad_chunking); end", "def compression_method=(_arg0); end", "def chunked?; end", "def send_extended_data_packet( type, data )\n # overhead is\n # ( byte.length + id.length + type.length + strlen.length ) = 13\n data, data_to_return = split_data_for_packet( data.to_s, 13 )\n @window_size -= data.length\n\n msg = @buffers.writer\n msg.write_byte CHANNEL_EXTENDED_DATA\n msg.write_long @remote_id\n msg.write_long type\n msg.write_string data\n @connection.send_message msg\n\n data_to_return\n end", "def unrecv(data)\n @buffer.unget(data)\n data.size\n end", "def decompress\n header = buf.u32\n return :invalid_data if (header & 0xFF) != 0x11\n decompressedSize = header >> 8\n decompressedSize = buf.u32 if decompressedSize == 0\n\n bufferLength = 0x1000\n buffer = Array.new(bufferLength)\n bufferOffset = 0\n\n flags = 0\n mask = 1\n\n outbuf = []\n until outbuf.size >= decompressedSize\n if mask == 1\n flags = buf.u8\n return :stream_too_short if flags.nil?\n mask = 0x80\n else\n mask >>= 1\n end\n\n if (flags & mask) > 0\n byte1 = buf.u8\n return :stream_too_short if byte1.nil?\n\n length = byte1 >> 4\n disp = -1\n case length\n when 0\n byte2 = buf.u8\n byte3 = buf.u8\n return :stream_too_short if byte3.nil?\n length = (((byte1 & 0x0F) << 4) | (byte2 >> 4)) + 0x11\n disp = (((byte2 & 0x0F) << 8) | byte3) + 0x1\n when 1\n byte2 = buf.u8\n byte3 = buf.u8\n byte4 = buf.u8\n return :stream_too_short if byte4.nil?\n length = (((byte1 & 0x0F) << 12) | (byte2 << 4) | (byte3 >> 4)) + 0x111\n disp = (((byte3 & 0x0F) << 8) | byte4) + 0x1\n else\n byte2 = buf.u8\n return :stream_too_short if byte2.nil?\n length = ((byte1 & 0xF0) >> 4) + 0x1\n disp = (((byte1 & 0x0F) << 8) | byte2) + 0x1\n end\n\n return :invalid_data if disp > outbuf.size\n\n bufIdx = bufferOffset + bufferLength - disp\n length.times do\n next_byte = buffer[bufIdx % bufferLength]\n bufIdx += 1\n outbuf << next_byte\n buffer[bufferOffset] = next_byte\n bufferOffset = (bufferOffset + 1) % bufferLength\n end\n else\n next_byte = buf.u8\n return :stream_too_short if next_byte.nil?\n outbuf << next_byte\n buffer[bufferOffset] = next_byte\n bufferOffset = (bufferOffset + 1) % bufferLength\n end\n end\n\n outbuf\n end", "def receive_data requestIncoming\r\n # ltodo time these conns out, esp. if I receive nothing\r\n close_connection && return if @blockManager.already_finalized\r\n file, host, port, startByte, endByte, type, fullUrl = TCPSocketConnectionAware.parseHTTPRequest(requestIncoming) # assume it's a request\r\n if !file\r\n debug \"Unable to parse request [#{requestIncoming}] -- giving up. Thread count #{@parent_server_wrapper.aliveServerObjects.length}\"\r\n close_connection # I must presume this terminates us :)\r\n end\r\n \r\n if file != @blockManager.urlFileName\r\n fullUrl = \"http://#{host}:#{port}#{file}\" # ltodo look into this--is this necessary?\r\n if @parent_server_wrapper.serveAnyRequest and file and host and port\r\n error \"within the fake server got request for url #{fullUrl} (not current/starting #{@blockManager.urlFileName}) continuing==possibly in error!\" # ltodo\r\n else\r\n error \"got request for generically WRONG FILE (or bad HTTP request)-- kicking out early their requested file #{file}, is not #{@blockManager.urlFileName} request #{requestIncoming} TURFING\"\r\n close_connection\r\n return\r\n end\r\n end \r\n \r\n if !startByte \r\n assert !endByte\r\n startByte = 0\r\n debug \"guessing full file start #{startByte} end #{endByte} request for whole file\"\r\n end\r\n endByte ||= @blockManager.wholeFileSize - 1\r\n assert startByte <= endByte\r\n log \"got #{type} request for file #{file} port #{port} startByte #{startByte} endByte #{endByte}\"\r\n header = TCPSocketConnectionAware.createReturnHeader(startByte, endByte, getWholeFileSize())\r\n assert header.length > 0\r\n send_data header\r\n debug \"wrote reply header length #{header.length} for type #{type}\"\r\n if type == \"HEAD\" # then we're done\r\n @received_head_request = true\r\n debug \"wrote head of file size #{getWholeFileSize()}! -- closing!\"\r\n close_connection_after_writing\r\n return\r\n end\r\n @received_data_request = true\r\n how_often_check_queue_in_seconds = 0.15#S\r\n chunkSize = 4_000_000*how_often_check_queue_in_seconds # 4 MB/S max empirically this is only like 1.5MB/s serving speed\r\n if @speedLimitPerConnectionBytesPerSecond\r\n how_often_check_queue_in_seconds = 1\r\n chunkSize = [@speedLimitPerConnectionBytesPerSecond, chunkSize].min\r\n end\r\n debug \"using chunkSize #{chunkSize} every #{how_often_check_queue_in_seconds}s\"\r\n nextByteToSendWithinRequest = startByte\r\n @dropped_me = false\r\n send_proc = proc { ||\r\n if @dropped_me\r\n return # never send again :)\r\n end \r\n if @parent_server_wrapper.serverShouldStop\r\n debug \"not sending any more-- parent said we should stop!\" # ltodo cancel these, too, so we don't get weird late logging messages\r\n return\r\n end\r\n assert nextByteToSendWithinRequest <= (endByte + 1)\r\n return if nextByteToSendWithinRequest == endByte + 1\r\n outbound_queue = get_outbound_data_size\r\n debug \"outbound size is #{outbound_queue}\" # ltodo make this have its own call\r\n if outbound_queue > chunkSize/2\r\n debug \"not sending anymore for now\"\r\n return\r\n else\r\n debug \"sending more\"\r\n end\r\n start_send_time = Time.now\r\n lastByteWithinChunk = [endByte, nextByteToSendWithinRequest + chunkSize - 1].min\r\n \r\n nextToWrite = @blockManager.getBytesToReturnToPeerIncludingEndByte(nextByteToSendWithinRequest, lastByteWithinChunk) # hmmm. So the case is that if we don't have any bytes yet downloaded, we'll return as few as we now have, which means ever x sec's, we'll check again to see if there is more to write. ltodo optimize with the 'blank' endings\r\n send_data(nextToWrite)\r\n log \"just successfully queued #{nextToWrite.length}B #{nextByteToSendWithinRequest } -> #{nextByteToSendWithinRequest + nextToWrite.length} out of #{endByte} in #{Time.now - start_send_time}s\"\r\n nextByteToSendWithinRequest += nextToWrite.length\r\n if nextByteToSendWithinRequest == endByte + 1\r\n debug \"done queueing all -- instructing it to close after writing\"\r\n @sender_proc_wrapper.cancel\r\n @queued_all = true\r\n close_connection_after_writing\r\n end\r\n }\r\n #queued_proc = create_proc_that_runs_only_when_outbound_queue_gets_below(5, send_proc) # run when it falls below X\r\n @sender_proc_wrapper = EventMachine::PeriodicTimer.new(how_often_check_queue_in_seconds, send_proc)\r\n send_proc.call # call it once early and fast!\r\n end", "def prepare_parsed_frame frame\n force_body_encoding frame\n end", "def gzip_disabled?\n @disable_gzip\n end", "def exploit\n connect\n\n # send plain payload\n buf = payload.encoded\n\n #print_status(\"payload space #{payload_space()}...\")\n print_status(\"payload len #{payload.encoded.length}...\")\n print_status(\"total buf len #{buf.length}...\")\n# print_status(\"Trying target #{target.name}...\")\n\n sock.put(buf)\n\n #cleanup\n handler\n disconnect\n end", "def remote_keepalive(sender, body)\nend", "def compress!; end", "def send_data hash\n raise 'not implemented'\n end", "def unsafe_zlib_unzip\n Zip::File.open_buffer(params[:file])\n end", "def send(data, opt={:type => :text})\n puts \"send ***************\"\n return if !@handshaked or @closed\n puts \"after send************\"\n type = opt[:type]\n frame = ::WebSocket::Frame::Outgoing::Client.new(:data => data, :type => type, :version => @handshake.version)\n begin\n @socket.write frame.to_s\n rescue Errno::EPIPE => e\n @pipe_broken = true\n emit :__close, e\n end\n end", "def receive_stream_data(data)\n begin\n @buffer.extract(data).each do |line|\n parse_stream_line(line)\n end\n @stream = ''\n rescue => e\n receive_error(\"#{e.class}: \" + [e.message, e.backtrace].flatten.join(\"\\n\\t\"))\n close_connection\n return\n end\n end", "def gzip_enabled=(enabled); end", "def parse(data)\n return 0 unless data && data.bytesize > 0\n if data.bytesize < @bytes_expected\n @buffer << data\n @bytes_expected -= data.bytesize\n return data.bytesize\n else\n @buffer << data[0..@bytes_expected]\n bytes_parsed = parse_chunk(@buffer)\n return 0 if bytes_parsed == 0 # This is an error\n @bytes_expected -= bytes_parsed\n @buffer = String.new\n if @bytes_expected == 0\n @parsed = true\n elsif (data.bytesize-bytes_parsed) > 0\n bytes_parsed += parse(data[bytes_parsed..-1])\n end\n return bytes_parsed \n end\n end", "def drop_buffered_data\n # the following line needs else branch coverage\n agent.drop_buffered_data if agent # rubocop:disable Style/SafeNavigation\n record_api_supportability_metric(:drop_buffered_data)\n end", "def packet_stream packet # :nodoc:\n payload = packet.payload\n\n return if payload.empty?\n\n source = packet.source\n\n if previous = @incomplete_streams.delete(source) then\n payload = previous << payload\n elsif /\\A....\\x04\\x08/m !~ payload then\n @drb_streams[source] = false\n return\n end\n\n stream = StringIO.new payload\n stream.set_encoding Encoding::BINARY, Encoding::BINARY\n stream\n end", "def file_extension\n 'gz'\n end", "def push_write_buffer data, frame\n @write_mutex.synchronize {\n update_last_write_activity if @write_buffer.empty?\n @write_buffer << [data, frame] unless @closing\n }\n end", "def receive_data(data)\n @logchunk << data\n decompose = true\n while decompose\n if !@length && (@logchunk.length - @pos) > 7\n l = @logchunk[@pos + 0..@pos + 3].to_i\n ck = @logchunk[@pos + 4..@pos + 7].to_i\n if l == ck and l < MAX_MESSAGE_LENGTH\n @length = l\n else\n decompose = false\n peer = @peer ? ::Socket.unpack_sockaddr_in(@peer)[1] : 'UNK'\n if l == ck\n LoggerClass.add_log([:default, :error, \"Max Length Exceeded from #{peer} -- #{l}/#{MAX_MESSAGE_LENGTH}\"])\n send_data(-\"error: max length exceeded\\n\")\n else\n LoggerClass.add_log([:default, :error, \"checksum failed from #{peer} -- #{l}/#{ck}\"])\n send_data(-\"error: checksum failed\\n\")\n end\n close_connection_after_writing\n end\n end\n\n decompose = false if @length && @length < 8\n\n if @length&.positive? and @logchunk.length - @pos >= @length\n msg = @logchunk[@pos..@length + @pos - 1].split(REGEXP_COLON, 4)\n @pos += @length\n if @authenticated\n msg[0] = nil\n msg.shift\n LoggerClass.add_log(msg)\n elsif msg.last == LoggerClass.key\n @authenticated = true\n send_data(-\"accepted\\n\")\n else\n send_data(-\"denied\\n\")\n close_connection_after_writing\n end\n @length = nil\n else\n decompose = false\n end\n end\n return unless @pos >= @logchunk.length\n\n @logchunk.clear\n @pos = 0\n end", "def send_decrypted_data(chunk)\n server_halec.queue.push proc {\n send_as_chunked server_halec.decrypt_data(chunk)\n }\n end", "def send_body_proc(socket)\n if @request_method == \"HEAD\"\n # do nothing\n elsif chunked?\n @body.call(ChunkedWrapper.new(socket, self))\n _write_data(socket, \"0#{CRLF}#{CRLF}\")\n else\n size = @header['content-length'].to_i\n @body.call(socket) # TODO: StreamWrapper which supports offset, size\n @sent_size = size\n end\n end", "def write_data_block(stream, rt, lg, data) # :nodoc:\n\t compress = 0\n\t if compress? && data.size > COMPRESSION_MIN_SIZE\n\t\tdata = Zlib::Deflate.deflate(data)\n\t\tcompress = 1\n\t end\n\n do_write do\n Logfiles.write_data_block(wio, stream.index, rt, lg, compress, data)\n end\n\tend", "def send_data(data)\n super(data)\n @@log.warn \"#{self} send_data done: #{data.inspect}\"\n end" ]
[ "0.6992377", "0.6936296", "0.6386955", "0.63543797", "0.6304036", "0.6174788", "0.6093384", "0.59526116", "0.59526116", "0.5895546", "0.5701681", "0.5689615", "0.56669146", "0.5662106", "0.5639858", "0.56113803", "0.56113803", "0.56057626", "0.5575226", "0.55733573", "0.5573008", "0.5506724", "0.5500678", "0.54846984", "0.54837906", "0.5440037", "0.5418052", "0.5405201", "0.536014", "0.5358908", "0.5345023", "0.53305423", "0.5328068", "0.53223467", "0.5310459", "0.5302973", "0.5285129", "0.5269955", "0.5242875", "0.5230813", "0.5212388", "0.5150979", "0.5145345", "0.5140582", "0.513877", "0.51331013", "0.51312435", "0.5104106", "0.50906825", "0.507324", "0.5063765", "0.50616634", "0.5038587", "0.50301456", "0.5018927", "0.50047415", "0.4995349", "0.4988926", "0.4985114", "0.49819496", "0.4977774", "0.4974827", "0.49702248", "0.4969543", "0.49548548", "0.49524397", "0.4952255", "0.49521372", "0.49521205", "0.49360836", "0.49353403", "0.49345917", "0.4927251", "0.49272236", "0.4926516", "0.49166667", "0.48999342", "0.4899496", "0.4893496", "0.4892115", "0.4878324", "0.48782292", "0.48740873", "0.4872017", "0.4871385", "0.48683682", "0.48678222", "0.4860583", "0.48569688", "0.4856953", "0.48566127", "0.48549703", "0.4843809", "0.4843407", "0.48419726", "0.4824006", "0.4818563", "0.48046148", "0.48011932", "0.4790566" ]
0.63301873
4
Initial settings sent during preface
def initial_settings #{Settings::INITIAL_WINDOW_SIZE => 0x7fffffff, Settings::ACCEPT_GZIPPED_DATA => 1} #{Settings::INITIAL_WINDOW_SIZE => 0x7fffffff} {Settings::INITIAL_WINDOW_SIZE => 0x20000, Settings::MAX_FRAME_SIZE => @dsil.max_frame_size, Settings::ACCEPT_GZIPPED_DATA => 1} end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def post_init\n end", "def setting; end", "def post_init\n end", "def at_init\n\n\t\tend", "def post_init\n\tend", "def settings=(_arg0); end", "def settings=(_arg0); end", "def init_settings\n merge_in_user_settings(copy_hash(DEFAULT_SETTINGS))\n end", "def settings; end", "def settings; end", "def set_setting\n end", "def init\n \tself.mode = \"Manual\"\n \tself.status = \"Off\"\n end", "def init\n self.current_time ||= 1800\n self.setting_time ||= 1800\n self.enabled ||= true\n self.state ||= false\n self.mode ||= 'auto'\n end", "def init_quick_defaults\n @quick_defaults=Hash.new\n @quick_defaults['enabled']=false\n @quick_defaults['launch']='ONETIME'\n @quick_defaults['launch_now']=true\n @quick_defaults['description']='Created with nessus_rest'\n end", "def initialize settings\n super\n end", "def default_setting!\n self.session_inactivity_timeout = GlobalConstant::AdminSessionSetting.default_session_inactivity_timeout\n self.mfa_frequency = GlobalConstant::AdminSessionSetting.default_mfa_frequency\n end", "def pre_initialize\n end", "def settings\n end", "def user_init; end", "def settings\n # TODO\n {}\n end", "def post_setup\n end", "def initialize settings\n self.settings = settings\n end", "def set_defaults\n end", "def set_defaults\n end", "def initialize_user_settings_defaults\n self.disabled_sports = []\n self.locale = 'en'\n self.device_ids = []\n end", "def post_init\n send_message :PASS, @settings[:server_password] if @settings[:server_password]\n send_message :USER, @settings[:ident], \"0\", \"0\", @settings[:realname]\n send_message :NICK, @settings[:nick]\n end", "def settings\n {}\n end", "def settings\n {}\n end", "def set_defaults\n\n end", "def set_defaults\n\n end", "def set_defaults\n\n end", "def set_defaults\n\n end", "def set_defaults\n\n end", "def set_defaults\n\n end", "def post_initialize\n end", "def init!\n @defaults = {\n :@refresh_token => ShakeTheCounter::Config.refresh_token,\n :@id => ShakeTheCounter::Config.client_id,\n :@secret => ShakeTheCounter::Config.client_secret,\n :@language_code => ShakeTheCounter::Config.language_code,\n }\n end", "def initialize\n @settings = Hash.new\n end", "def set_initial_state!\n\t\t\t\tdefaults = {\n\t\t\t\t}\n\t\t\t\topts = read_initial_state\n\t\t\t\topts = defaults.merge(opts)\n\t\t\t\topts[:dealer] = opts[:button_seat]\n\t\t\t\tinitialize_from_opts(opts)\n\t\t\t\tstart_hand\n\t\t\tend", "def deferred_defaults\n set_default_path\n set_default_properties\n end", "def settings\n {}\n end", "def on_init; end", "def on_init; end", "def settings\n\t\tcheck_if_myself\n\t\t@user = current_user\n\tend", "def init_default_settings!\n self.class.default_settings.dup.each do |var, vals|\n setting_objects.detect { |s| s.var == var.to_s } || setting_objects.create(var: var.to_s, value: vals, target: self)\n end\n end", "def set_defaults\n self.published ||= false\n self.archived ||= false\n self.is_default ||= false\n self.version ||= 0\n self.visibility = ((self.org.present? && self.org.funder_only?) || self.is_default?) ? Template.visibilities[:publicly_visible] : Template.visibilities[:organisationally_visible] unless self.id.present?\n self.customization_of ||= nil\n self.family_id ||= new_family_id\n self.archived ||= false\n self.links ||= { funder: [], sample_plan: [] }\n end", "def on_load\n\t\t#\n\t\t# Setup constants\n\t\t#\n\t\tself[:volume_min] = 0\n\t\tself[:volume_max] = 31\n\t\tself[:brightness_min] = 0\n\t\tself[:brightness_max] = 31\n\t\tself[:contrast_min] = 0\n\t\tself[:contrast_max] = 60\t# multiply by two when VGA selected\n\t\t#self[:error] = []\t\tTODO!!\n\t\t\n\t\tbase.default_send_options = {\n\t\t\t:delay_on_recieve => DelayTime,\t\t# Delay time required between commands\n\t\t\t:retry_on_disconnect => false,\t\t# Don't retry last command sent as we need to login\n\t\t\t:timeout => 6\n\t\t}\n\t\t#base.config = {\n\t\t#\t:clear_queue_on_disconnect => true\t# Clear the queue as we need to send login\n\t\t#}\n\t\t@poll_lock = Mutex.new\n\tend", "def pre_initialize; end", "def set_default_params\n self.difficulty = 0\n self.result = \"active\"\n self.board_size = 3\n end", "def initial\n end", "def default_values\n self.mode ||= 'challenge_quick'\n end", "def set_defaults\n self.state ||= 'NEW'\n self.account_id ||= Gizmo::Util::Uuid.generate\n self.account_name ||= self.subdomain\n end", "def default_settings\n {}\n end", "def setup_defaults\n @program_title = 'PROGRAM TITLE'\n @program_site = 'PROGRAM SITE'\n @request_availability = false\n @meeting_times = ''\n @sourcing_options = ''\n @course_options = ''\n @student_id_required = false\n @student_id_format = ''\n @student_id_format_help = ''\n @student_id_excluded_chars = ''\n @contact_email = 'info@bebraven.org'\n @is_preaccelerator_student = false\n end", "def default_settings()\n @default_settings ||= {}\n end", "def post_initialize(args)\n @front_shock = args[:front_shock]\n @rear_shock = args[:rear_shock]\n #super(args)\n end", "def set_defaults\n self.state ||= 'ACTIVE'\n self.account_user_id ||= Gizmo::Util::Uuid.generate\n self.is_owner ||= false\n end", "def init!\n @defaults = {\n :@refresh_token => ENV[\"STC_REFRESH_TOKEN\"],\n :@client_id => ENV[\"STC_CLIENT_ID\"],\n :@client_secret => ENV[\"STC_CLIENT_SECRET\"],\n :@language_code => \"nl-NL\",\n :@environment => 'test',\n :@version => 1,\n :@verbose => false,\n }\n end", "def settings\n @settings ||= {}\n end", "def install_initial_state\n db = kernel.resources.db\n db.default.submissions = []\n db.default.valid_submissions = []\n db.default.challengers = []\n db.default.people = (1..5).collect{|i| user_tuple(i, true) }\n db.default.challengers = (1..5).collect{|i| challenger_tuple(i) }\n end", "def initialize_settings\n create_settings if self.sf_id =~ /\\D/ and settings.nil?\n end", "def set_defaults\n self.active = self.active.nil? ? true : self.active\n self.state ||= SystemConfig.instance.default_state_code\n end", "def preflight=(_arg0); end", "def initialize_default_instance_vars\n @success = true\n @code = STATUS_CODE[:ok]\n end", "def set_defaults\n if chore_type\n self.action = chore_type.action\n self.points = chore_type.points\n end\n end", "def set_initial_values\n now = Time.now\n @first_seen ||= now\n @last_activity ||= now\n @total_connections ||= 0\n @total_time ||= 0\n @money ||= 0\n @donations ||= 0\n @rank ||= 0\n @colour ||= :ansi\n @muffled ||= false\n @history ||= History.new\n @aliases ||= {}\n @ignoring ||= {}\n @ignoring_ips ||= {}\n @drug_strength ||= 0\n @alcohol_units ||= 0\n @onduty = @onduty.nil? ? true : @onduty\n end", "def load_settings\n @leaderboard_settings = component.settings\n end", "def load_settings\n @leaderboard_settings = component.settings\n end", "def initialize settings\n self.settings = settings\n end", "def initialize_settings\n create_settings unless SfcontactSetting.find_by_sfcontact_id(\"#{sf_id}\")\n end", "def settings\n @settings ||= {}\n end", "def before_setup\n # do nothing by default\n end", "def set_initial_values\n self.hints_used = 0\n end", "def settings\n @settings ||= {}\n end", "def settings\n @settings ||= {}\n end", "def post_init()\n puts \"#{self} post_init done!\"\n end", "def post_init()\n puts \"#{self} post_init done!\"\n end", "def init\n\n end", "def preinitialize_on_first_load(input_document, form_names)\n remedy_context = ArsModels::Context.new(\n :server => get_info_value(input_document, 'server'),\n :username => get_info_value(input_document, 'username'),\n :password => get_info_value(input_document, 'password'),\n :port => get_info_value(input_document, 'port'),\n :prognum => get_info_value(input_document, 'prognum'),\n :authentication => get_info_value(input_document, 'authentication')\n )\n\n # Build up a new configuration\n if @disable_caching\n @config = {\n #:properties => properties,\n :context => remedy_context,\n :forms => form_names.inject({}) do |hash, form_name|\n hash.merge!(form_name => ArsModels::Form.find(form_name, :context => remedy_context))\n end\n }\n else\n @@config = {\n #:properties => properties,\n :context => remedy_context,\n :forms => form_names.inject({}) do |hash, form_name|\n hash.merge!(form_name => ArsModels::Form.find(form_name, :context => remedy_context))\n end\n }\n end\n end", "def initialize( settings={} )\n\t\tsuper()\n\n\t\t@settings = settings\n\t\t@overridden_settings = {}\n\tend", "def initialize_after_opts\n end", "def load_settings\n @settings = Instance::Settings::Effective.new(current_tenant, Course::ControllerComponentHost)\n end", "def start\n\t\tinit\n\t end", "def set_defaults\n self.active = self.active.nil? ? true : self.active\n self.show_in_dashboard = self.show_in_dashboard.nil? ? true : self.show_in_dashboard\n self.system_activity = self.system_activity.nil? ? false : self.system_activity\n self.frequency_quantity ||= 1\n end", "def initialize_setting\n unless new_record?\n if cached_setting.nil?\n create_setting\n if self.class.respond_to?(:object_caches_suffix)\n clear_cache! caches_suffix_list= [], object_caches_suffix=[\"setting\"]\n end\n end\n parameterize_name = setting_options[:name].downcase.parameterize.underscore\n setting_options[:options].except(:validations).keys.each do |opt_key|\n send(\"#{parameterize_name}_#{opt_key}=\", cached_setting.get_setting_of(opt_key))\n end\n end\n end", "def load_defaults\n @dev_port = @default_dev_port\n @dev_pid = @default_dev_pid\n @dev_log = @default_dev_log\n @prod_port = @default_prod_port\n @prod_pid = @default_prod_pid\n @prod_log = @default_prod_log\nend", "def pre_initialize(**opts)\n @exchange_name = opts[:exchange_name]\n super\n end", "def init\n self.admin ||= false\n self.active ||= false\n end", "def construct_data\n add_properties(@adv_settings, :if_missing)\n super\n end", "def initial_screen\n clear_screen\n option = main_options\nend", "def before_setup; end", "def set_defaults\n self.active = self.active.nil? ? true : self.active\n self.sogr ||= false\n self.notional ||= false\n self.multi_year ||= false\n self.emergency ||= false\n self.state ||= :unsubmitted\n self.project_number ||= 'TEMP'\n # Set the fiscal year to the current fiscal year which can be different from\n # the calendar year\n self.fy_year ||= current_fiscal_year_year\n end", "def set_defaults\n super\n self.indian_tribe ||= false\n end", "def set_defaults\r\n @options = {\r\n :caching => true\r\n }\r\n end", "def initialize settings\n @settings = settings\n confirm_settings\n if fast?\n info(\"Forwarding for #{settings['host']}...\") if settings['verbose']\n else\n initialize_host_groups\n initialize_templates\n initialize_host\n initialize_applications\n info(\"Forwarding for #{host.name}...\") if settings['verbose']\n end\n end", "def init; end", "def init; end", "def init; end", "def init; end", "def pre_initialize_fields\n end", "def post_initialize(args)\n @front_shock = args[:front_shock]\n @rear_shock = args[:rear_shock]\n end" ]
[ "0.6982722", "0.6800582", "0.67651033", "0.67079645", "0.6676908", "0.66686296", "0.66686296", "0.6510814", "0.65026325", "0.65026325", "0.6487079", "0.64243084", "0.6414315", "0.63874924", "0.635785", "0.6322867", "0.62695163", "0.62582636", "0.6255312", "0.6242282", "0.61938936", "0.61879534", "0.6182443", "0.6182443", "0.6174747", "0.61722904", "0.61655664", "0.61655664", "0.6160315", "0.6160315", "0.6160315", "0.6160315", "0.6160315", "0.6160315", "0.61576676", "0.61543727", "0.61501896", "0.6138948", "0.6136443", "0.6134521", "0.61210024", "0.61210024", "0.6097903", "0.6073772", "0.60691994", "0.6049207", "0.6047045", "0.6042943", "0.60271", "0.6006011", "0.6005099", "0.60037464", "0.5999863", "0.59729445", "0.5964211", "0.59616184", "0.59309846", "0.5928443", "0.59174997", "0.59174305", "0.5916234", "0.59141326", "0.5904924", "0.5898983", "0.5894882", "0.5892113", "0.5892113", "0.5882245", "0.58820826", "0.588074", "0.5875616", "0.5869615", "0.5864332", "0.5864332", "0.58598167", "0.58598167", "0.58588225", "0.58566684", "0.5855241", "0.5834241", "0.58304846", "0.5820917", "0.5816", "0.58147496", "0.5813228", "0.58126724", "0.5810035", "0.5808302", "0.58066493", "0.58002496", "0.5798399", "0.5796648", "0.57892185", "0.5787083", "0.5786869", "0.5786869", "0.5786869", "0.5786869", "0.5784702", "0.5783973" ]
0.58367896
79
Shut down the connection.
def die code if !@send_lock.synchronize{@first_frame_out} g = Frame.new FrameTypes::GOAWAY, 0x00, 0, [@last_stream,code].pack('NN') send_frame g end _close_socket end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def shutdown\n @conn.shutdown\n end", "def shutdown_connection\n teardown_timers\n @conn.shutdown if @conn.respond_to? :shutdown\n @conn.terminate if @conn.respond_to? :terminate\n @conn = nil\n end", "def shutdown\n connection.write(\"shutdown\")\n end", "def shutdown\n\t\tself.log.info \"Shutting down.\"\n\t\tself.reactor.stop_polling\n\t\t@conn.close\n\tend", "def shutdown\n @data_socket.close\n @ack_socket.close\n @client.disconnect! rescue nil\n end", "def shutdown\n @connection_manager.shutdown if @connection_manager\n @client = nil\n @connection_manager = nil\n end", "def close()\n @connection.disconnect\n @connection = nil\n end", "def disconnect!\n @connection.close rescue nil\n end", "def shutdown\n @pool.shutdown do |connection|\n connection.quit\n end\n end", "def shutdown\n @pool.shutdown do |connection|\n connection.quit\n end\n end", "def disconnect!\n @connection.logoff rescue nil\n end", "def disconnect\n _logout\n @connection.close\n end", "def disconnect!\n @logger.info(\"Terminating SSH connection to server name=#{@name}\")\n @ssh.close\n @ssh = nil\n end", "def disconnect; @connection.close end", "def shutdown!\n error { \"forcing connection closed\" }\n socket.close\n end", "def disconnect\n @connection.close if connected?\n @connection = nil\n end", "def close_connection\n @connection.expunge\n @connection.logout\n @connection.disconnect\n end", "def shut_down\n @shutdown_lock.synchronize {\n return if @shutting_down\n @shutting_down = true\n }\n die NO_ERROR\n end", "def disconnect\r\n @connection.close_connection\r\n @connection = nil\r\n end", "def shut_down\n trigger(:shut_down_started)\n @server.stop(true) if @server\n @server_thread.join if @server_thread\n adapter.shut_down\n trigger(:shut_down_complete)\n end", "def close()\n\t\t@connection.disconnect\n\t\t@connection = nil\n\tend", "def close\n info { \"closing connection\" }\n socket.shutdown\n end", "def disconnect\n info 'closing connection to host'\n @connected = false\n end", "def shutdown!\n shutdown\n end", "def close\n conn.write(\"(api-quit)\") if connected?\n rescue Errno::ECONNRESET\n ensure\n self.conn = nil\n end", "def stop\n log \"closing connection\"\n @running = false\n client.stop!\n log \"closed\"\n end", "def shutdown\n @socket = nil\n @thr.join if @thr\n @thr = nil\n end", "def shutdown\n request('shutdown')\n end", "def shutdown()\n if @conn\n @conn.unsubscribe(@queue_name)\n @@log.debug(\"Unsubscribe complete\")\n StompHelper::pause(\"After unsubscribe\") if $DEBUG\n @conn.disconnect()\n @@log.debug(\"Disconnect complete\")\n StompHelper::pause(\"After disconnect\") if $DEBUG\n end\n end", "def terminate_connection\n @intentionally_closed = true\n close_connection\n end", "def close_connection\n @connection.finish\n end", "def shutdown\n client.close\n end", "def teardown\n logger.debug \"Connection teardown\"\n @connection.active? && disconnect\n @connection.active?\n end", "def shutdown\n\n @db.connection.close\n end", "def disconnect\n @conn.close\n end", "def disconnect\n @conn.close\n end", "def disconnect\n @conn.close\n end", "def disconnect\n @conn.close\n end", "def shutdown\n @logger.info \"Hastur agent shutting down normally.\"\n @running = false\n @router_socket.close\n @udp_socket.close\n @ctx.terminate\n end", "def disconnect!\n super\n @connection.close rescue nil\n end", "def close\n if self.conn && !self.conn.closed?\n self.conn.shutdown\n self.conn.close\n end\n\n self.conn = nil\n end", "def close_connection\n current_connection.logout if current_connection?\n current_connection = nil\n end", "def shutdown\n logger.info('Shutting down ...')\n @lock.synchronize do\n @shutdown = true\n end\n\n reset\n exit\n end", "def shut_down\n end", "def shutdown\n send_recv( KJess::Request::Shutdown.new )\n end", "def disconnect\n super\n\n @transport.close rescue nil\n @transport = nil\n \n debug 'connections closed'\n end", "def disconnect\n @connection.logout\n end", "def disconnect\n @hazel.shutdown\n end", "def shutdown\n @server.shutdown\n end", "def close\n @conn.disconnect\n end", "def halt\n\t\tself.shutting_down = true\n\t\tself.consumer.channel.close\n\tend", "def destroy_connection\r\n\tbegin\r\n\t\t@sock.close if @sock\r\n\tensure\r\n\t\t@connected=false\r\n\tend\r\n end", "def on_close(env)\n @connection.destroy if @connection\n end", "def disconnect\n @tcp_socket.close\n end", "def quit!\n command \"quit\" if alive?\n ensure\n @alive = false\n @socket = nil\n File.delete(@socket_path) if File.exist?(@socket_path)\n end", "def shutdown(level=0)\n check_connection\n @protocol.shutdown_command level\n self\n end", "def shutdown\n log.info 'Shutting down...'\n @shutdown = true\n end", "def close_connection\n cls if connected?\n stop_read_loop\n stop_write_loop\n @socket.close if @socket\n @socket = nil\n @connected = false\n end", "def disconnect\n @socket.close\n end", "def destroy\n connection.close\n end", "def shutdown; end", "def shutdown; end", "def shutdown; end", "def shutdown; end", "def shutdown; end", "def shutdown; end", "def shutdown; end", "def disconnect\n\t\tbegin\n\t\t\tActiveRecord::Base.remove_connection\n\t\trescue ::Exception => e\n\t\t\tself.error = e\n\t\t\telog(\"DB.disconnect threw an exception: #{e}\")\n\t\tensure\n\t\t\t# Database drivers can reset our KCODE, do not let them\n\t\t\t$KCODE = 'NONE' if RUBY_VERSION =~ /^1\\.8\\./\n\t\tend\n\tend", "def destroy_connection\n begin\n @ssock.close if @ssock\n @rsock.close if @rsock\n ensure\n @connected=false\n end\n end", "def disconnect!\n super\n @raw_connection&.close\n @raw_connection = nil\n end", "def shutdown()\n check_return_code(PureHailDB.ib_shutdown(PureHailDB::ShutdownType[:IB_SHUTDOWN_NORMAL]))\n end", "def disconnect\n @write_socket.close\n @read_socket.close\n @write_socket = nil\n @read_socket = nil\n @rc_r = false\n @rc_W = false\n end", "def shutdown!; end", "def shutdown!; end", "def shutdown!; end", "def disconnect\n raise \"Not connected. did you forget to call connect?\" unless @_socket\n @_socket.close\n @_socket = nil\n print \"Disconnected\\n\" if @_verbose\n EtherShell::ShellDsl.nothing\n end", "def close\n close_connection(CLOSED, true)\n end", "def stop\n @pid ? Process.kill('TERM', @pid) : close_connection\n end", "def disconnect_ssh_tunnel\n @logger.debug('closing SSH tunnel..')\n\n @ssh.shutdown! unless @ssh.nil?\n @ssh = nil\n end", "def shutdown\n end", "def close\n log \"Closing connection\", level: :warning\n close_stream\n close_socket\n stop_reader\n set_state :disconnected\n notify_error DisconnectError.new(\"Connection was closed\")\n\n # stop timer\n # as we're running inside the timer, code after stop_timer() will not be called,\n # unless it's in the ensure block\n stop_timer\n end", "def disconnect\n @server = nil\n @status = :disconnected\n end", "def stop\n @socket.close\n ensure\n cleanup\n end", "def shutdown( msg=\"Server shutdown\" )\n\t\t$stderr.puts \"Shutting down: #{msg}\"\n\t\t@shuttingDown = true\n\t\t@reactor.clear\n\t\tbegin\n\t\t\t@socket.shutdown\n\t\trescue\n\t\tend\n\t\tdisconnectAllUsers( msg )\n\t\tbegin\n\t\t\t@socket.close\n\t\trescue\n\t\tend\n\tend", "def shutdown\n log 'Exiting...'\n @shutdown = true\n end", "def shutdown\n @shutdown = true\n end", "def shutdown\n @shutdown = true\n end", "def disconnect()\r\n @callbacks.each { |block| block.call }.clear()\r\n @conn.close if @conn\r\n @conn = nil\r\n end", "def disconnect! # :nodoc:\n super\n @raw_connection.logoff rescue nil\n end", "def kill_connection(connection)\n connection.shutdown!\n end", "def close\n @work_queue.shutdown if @work_queue\n @connection.close\n end", "def disconnect!\n disconnect\n end", "def disconnect\n @streams.each { |_, stream| try { stream.finalize } }\n @conn.Disconnect()\n end", "def shutdown\n end", "def shutdown\n end", "def shutdown\n end", "def shutdown\n end", "def disconnect\n command 'QUIT' do\n begin\n response 221\n ensure\n close\n end\n end\n end", "def shutdown(how = 2)\n begin\n super\n ensure\n @tunnel.remove if closed?\n end\n return 0\n end", "def disconnect\n NWRFCLib.close_connection(@handle, @error)\n NWRFC.check_error(@error)\n end", "def shutdown!\n @gateway&.shutdown!\n sleep 0.5 until !@gateway&.active?\n @gateway = nil\n end" ]
[ "0.8183246", "0.79578334", "0.7912625", "0.73885876", "0.7354836", "0.72706264", "0.7257099", "0.71811414", "0.71494514", "0.71494514", "0.7058152", "0.7056894", "0.7054947", "0.70393366", "0.70356286", "0.7025426", "0.701538", "0.7005302", "0.70030946", "0.6991097", "0.6976469", "0.69725734", "0.69616836", "0.6956596", "0.69178444", "0.68847656", "0.68664116", "0.6865261", "0.6862729", "0.6846094", "0.68445593", "0.6814987", "0.68146884", "0.68127835", "0.6800945", "0.6800945", "0.6800945", "0.6800945", "0.67761254", "0.67694736", "0.67622244", "0.67616445", "0.674863", "0.67349124", "0.6729472", "0.67149585", "0.6684884", "0.66701967", "0.6664294", "0.6649707", "0.6636984", "0.663602", "0.66226727", "0.6605723", "0.6596391", "0.65951407", "0.659459", "0.65891314", "0.6570152", "0.65572387", "0.65536684", "0.65536684", "0.65536684", "0.65536684", "0.65536684", "0.65536684", "0.65536684", "0.6542821", "0.6530133", "0.65016985", "0.6501352", "0.64937013", "0.64935464", "0.64935464", "0.64935464", "0.6493267", "0.6487284", "0.6486573", "0.64807314", "0.6478241", "0.64716226", "0.6468208", "0.64636695", "0.6460684", "0.64428097", "0.6434714", "0.6434714", "0.6433046", "0.64325476", "0.6427532", "0.64243436", "0.6421483", "0.6420886", "0.64188695", "0.64188695", "0.64188695", "0.64188695", "0.64137715", "0.64112484", "0.6389419", "0.638456" ]
0.0
-1
close the socket we've wrapped
def _close_socket raise "no wrapped socket" unless @socket return if @socket.closed? @socket.shutdown rescue nil @socket.read_nonblock(4*1024*1024) rescue nil # flush any in-flight crud @socket.close rescue nil end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def close\n @socket.close unless closed?\n end", "def close\n @socket.close if @socket\n end", "def close\n @socket.close\n end", "def close\n @socket.close\n end", "def close\n @socket.close if @socket\n @socket = nil\n end", "def close\n if @socket\n @socket.close\n @socket = nil\n end\n end", "def close\n if @socket\n @socket.close\n @socket = nil\n end\n end", "def close\n @socket&.close\n end", "def close\n @socket.close\n @socket=\"\"\n end", "def close\n @socket.close if @socket\n end", "def close\n @socket.close\n end", "def close\n @socket.close if @socket\n @socket = nil\n self\n end", "def close\n @socket.close unless @socket.closed?\n self\n end", "def close\n assert_rc @sock.close\n end", "def close\n\t\tself.socket.close\n\tend", "def close\n info { \"closing connection\" }\n socket.shutdown\n end", "def close\n @sock.close if @sock and not @sock.closed?\n end", "def close\n flush_buffer!\n @sock.close\n end", "def close\n\t\t@sock.close if @sock and not @sock.closed?\n\t end", "def close_socket\n @stop = true\n end", "def close\n @log.info { \"Closing connection to client #{@ip}\" }\n @socket.close\n end", "def close \n begin\n @socket.close\n rescue IOError\n end\n Client.del_socket conn_id()\n true\n end", "def stop\n @socket.close\n ensure\n cleanup\n end", "def close\n super unless @socket.nil?\n end", "def close!\n ssl_socket.close\n end", "def close\n send(\"DONE\")\n @socket.close\n end", "def close_socket()\n begin\n # Need to set @closed = true before closing the socket\n # within the @read_semaphore thread\n @closed = true\n @read_semaphore.synchronize do\n @socket.close\n end\n rescue\n #Ignoring if already closed\n end\n @closed\n end", "def handle_close\n @sock.close\n rescue Exception\n log.error \"Connector#handle_close\"\n log.error $!\n end", "def close\n @proxy_socket.close\n @proxy_socket = nil\n end", "def close\n @tcp_socket.close if @tcp_socket && !@tcp_socket.closed?\n end", "def shutdown!\n error { \"forcing connection closed\" }\n socket.close\n end", "def close\n super unless closed?\n rescue IOError => exception\n logger.warn \"IOError when attempting to close socket: #{exception.class}: #{exception.message}\"\n end", "def _close_socket(socket)\r\n\t\tbegin\r\n\t\t\tif socket\r\n socket.close\r\n end\r\n rescue SocketError => message\r\n $LOG.error(\"Error while closing socket: #{message}\")\r\n end\r\n end", "def close\n unless closed?\n API::invoke :zmq_close, ptr\n @context, @ptr = nil, nil\n info \"Socket closed.\"\n end\n end", "def close\n @sockets.each do |sock|\n sock.close\n end\n @host = @port = nil\n @sockets.clear\n @checked_out.clear\n end", "def terminate\n @intentional_termination = true\n @socket.close\n end", "def close\n frame = Hash.new\n frame['command'] = 'close'\n @close_txnr=self.frame_write(@socket, frame)\n #TODO: ought to properly wait for a reply etc. The serverclose will make it work though\n sleep @retransmission_timeout\n return @buffer\n ensure\n @socket.close\n end", "def close\n @sock.close if @sock && !@sock.closed?\n @sock = nil\n @retry = nil\n @status = \"NOT CONNECTED\"\n end", "def close\n return nil if @dead\n \n @int_sock_rep.close\n @int_sock_req.close\n @int_sock_pull.close\n @int_sock_push.close\n \n @dead = true\n end", "def close\n begin\n super\n ensure\n if (!@plaintext_socket.closed?)\n @plaintext_socket.close\n end\n end\n end", "def shutdown\n @data_socket.close\n @ack_socket.close\n @client.disconnect! rescue nil\n end", "def close\n write_message(Vertica::Protocol::Terminate.new)\n ensure\n close_socket\n end", "def close\n CodeStore.undefine([\"SEND\", @atom])\n @socket.close\n end", "def close\n @socket.close if @socket\n true\n end", "def disconnect\n @socket.close\n end", "def close_connection\n cls if connected?\n stop_read_loop\n stop_write_loop\n @socket.close if @socket\n @socket = nil\n @connected = false\n end", "def close\n if @socket\n @socket.close\n\n # Spotify doesn't send the disconnect frame quickly, so the callback\n # gets run immediately\n EventMachine.add_timer(0.1) { on_close(nil) }\n end\n true\n end", "def close\n @stat=Event::LINK_CLOSING\n \n #\n # stop thread for reading\n #\n unless(@recvthread.nil?)\n if(@recvthread.alive?)\n @recvthread.exit\n end\n end\n \n #\n # stop threads for writing\n #\n @sendthreads.each_value{|t|\n unless(t.nil?)\n if(t.alive?)\n t.exit\n end\n end\n }\n \n #\n # close socket\n #\n unless(@socket.closed?)\n @socket.close\n end\n \n @stat=Event::LINK_CLOSED\n notify(@stat)\n end", "def close!\n logger.debug \"Closing...\",\n socket: socket,\n server: server,\n path_exists: path.exist?,\n thread: thread,\n env_var: {\n env_var_name => ENV[env_var_name],\n }\n \n # Remove the path from the ENV so if we do anything after this the\n # old one isn't hanging around\n ENV.delete env_var_name\n \n # Kill the thread first so that it can't try to do anything else\n thread.kill if thread && thread.alive?\n \n socket.close unless socket.nil?\n @socket = nil\n server.close unless server.nil?\n @server = nil\n FileUtils.rm( path ) if path.exist?\n \n logger.debug \"Closed.\",\n socket: socket,\n server: server,\n path_exists: path.exist?,\n thread: thread,\n env_var: {\n env_var_name => ENV[env_var_name],\n }\n \n nil\n end", "def close\n @transport.close\n @transport = nil\n @close_handler and @close_handler.call\n end", "def close\n parser_thread.kill if parser_thread # why if?\n poll_thread.kill\n socket.close if socket\n\n @status = DISCONNECTED\n end", "def disconnect\n if @socket\n @socket.close\n @socket = nil\n end\n end", "def disconnect\n @socket.close if @socket && !@socket.closed?\n @socket = nil\n self\n end", "def close_remote_srv_conn\n if @socket_srv\n @socket_srv.close\n @log.debug \"close_remote_srv_conn requested\"\n @cup_gui.log_sometext \"Bye, connessione col server terminata\\n\"\n @rd_sock_thread.join\n @socket_srv = nil\n end\n rescue => detail\n @log.error \"Server connection error (#{$!})\\n\"\n @log.error detail.backtrace.join(\"\\n\")\n ensure\n @socket_srv = nil \n end", "def close\n conn.write(\"(api-quit)\") if connected?\n rescue Errno::ECONNRESET\n ensure\n self.conn = nil\n end", "def close()\r\n _dprint(\"Closing Auth_WiKID connection ...\")\r\n unless $sslsocket.nil?\r\n unless $sslsocket.closed?\r\n $sslsocket.puts(\"QUIT\");\r\n $sslsocket.flush\r\n $sslsocket.close\r\n end\r\n $sslsocket = nil\r\n @socket.shutdown\r\n end\r\n @isConnected = false\r\n end", "def close\n flush\n\n @worker_thread[:should_exit] = true\n @worker_thread.join\n\n @ssl.close\n\n sleep 0.1\n @main_queue.drain!\n\n @socket = @ssl = @http = @main_queue = @work_queue = @requests = @exceptions = @worker_thread = nil\n end", "def disconnect\n if @socket\n @socket.close\n @socket = nil\n @authed = false\n end\n end", "def disconnect\n if @socket\n @socket.close\n @socket = nil\n @authed = false\n end\n end", "def finish\n begin\n @socket.close\n rescue\n end\n on_disconnected\n end", "def close\n @closing = true\n cancel_ping_timer\n cancel_reconnect_timer\n close_connection_after_writing if connected?\n process_disconnect if reconnecting?\n end", "def close\n log \"Closing connection\", level: :warning\n close_stream\n close_socket\n stop_reader\n set_state :disconnected\n notify_error DisconnectError.new(\"Connection was closed\")\n\n # stop timer\n # as we're running inside the timer, code after stop_timer() will not be called,\n # unless it's in the ensure block\n stop_timer\n end", "def close()\n if isConnected()\n if @sentConnect\n @sentConnect = false # set in connect()\n @signedOn=false # set in signOn() inside connect()\n bye = VistaRPC.new(\"#BYE#\", RPCResponse::SINGLE_VALUE, true)\n retval = execute(bye)\n @socket.close()\n @socket = nil\n @duz = \"0\"\n @lastvistaerror = nil\n @currentContext = nil\n return retval\n end\n end\n end", "def close(error = nil)\n\t\t\t\t# The underlying socket may already be closed by this point.\n\t\t\t\t@streams.each_value{|stream| stream.close(error)}\n\t\t\t\t@streams.clear\n\t\t\t\t\n\t\t\tensure\n\t\t\t\tif @framer\n\t\t\t\t\t@framer.close\n\t\t\t\t\t@framer = nil\n\t\t\t\tend\n\t\t\tend", "def close\n @timer.detach if @timer.attached?\n @reqtable = {}\n @transport.close\n @seqid = 0\n self\n end", "def destroy_connection\n begin\n @ssock.close if @ssock\n @rsock.close if @rsock\n ensure\n @connected=false\n end\n end", "def close()\n @connection.disconnect\n @connection = nil\n end", "def disconnect\n @tcp_socket.close\n end", "def test_close_uses_socket_close\n # Create mock socket that checks for method calls\n socket = mock_socket(\"\",\"\")\n socket.expects(:close).once\n\n client = ChainReactor::ClientConnection.new(socket,get_logger)\n client.close\n end", "def shutdown\n @socket = nil\n @thr.join if @thr\n @thr = nil\n end", "def quit!\n command \"quit\" if alive?\n ensure\n @alive = false\n @socket = nil\n File.delete(@socket_path) if File.exist?(@socket_path)\n end", "def close()\n\t\t@connection.disconnect\n\t\t@connection = nil\n\tend", "def close #:nodoc:\n @server.shutdown\n end", "def on_close(event)\n logger.debug 'Socket closed'\n @connected = false\n @socket = nil\n dispatch('command' => 'session_ended')\n end", "def on_close(event)\n logger.debug 'Socket closed'\n @connected = false\n @socket = nil\n dispatch('command' => 'session_ended')\n end", "def close\n _do_if_open { _handle_closed! ; ::Dnet.route_close(@fw) }\n end", "def stop\n @mutex.synchronize do\n if( not @closed )\n\n begin\n @lsock.close if @lsock\n rescue\n end\n\n begin\n @rsock.close if @rsock\n rescue\n end\n\n @client_thread.kill if( @client_thread and @client_thread.alive? )\n\n @server.remove_client( self )\n\n @closed = true\n end\n end\n end", "def shutdown_handler\n self.close unless self.closed?\n @sockets = []\n end", "def close\n begin\n @io.close unless @io.closed?\n close_connection\n rescue Exception => e\n # ignore errors for instance when the connection has already\n # been closed.\n end\n end", "def close\n _do_if_open { _handle_closed! ; Dnet.fw_close(@handle) }\n end", "def free_socket(socket, force = false)\n # Socket has not been open\n return false if socket.nil?\n\n # Do we try to close persistent socket?\n if socket == @socket\n # do not close it if not forced\n if force\n @socket.close unless @socket.closed?\n @socket = nil\n true\n else\n false\n end\n else\n # Just close this socket\n socket.close unless socket.closed?\n true\n end\n end", "def close\n @collector.sending_stream.puts pack(:close_worker)\n end", "def close\n if @http && @http.started?\n @http.finish\n Log.info \"Closing HTTP connection for #{@host} from #{@connection_opened_at}\"\n end\n @http = nil\n end", "def disconnect\n @thread.kill\n @socket.close\n end", "def close\n @logger.debug(@host) { 'Closing session' }\n @transport.close\n @transport = nil\n end", "def close\n @transport.close\n end", "def close(code = 1005, reason = \"\", origin = :self)\n origin = :self if origin == :peer # to skip @socket.close\n super(code, reason, origin)\n @client.unbind\n end", "def destroy\n @sock.cmd(\"String\"=>\"quit\")\n @sock.close\n end", "def destroy_connection\r\n\tbegin\r\n\t\t@sock.close if @sock\r\n\tensure\r\n\t\t@connected=false\r\n\tend\r\n end", "def forceclose\n @sentConnect = false # set in connect()\n @signedOn=false # set in signOn() inside connect()\n @socket.close()\n @socket = nil\n @duz = \"0\"\n @currentContext = nil\n @lastvistaerror=nil\n return true\n end", "def disconnect\n @write_socket.close\n @read_socket.close\n @write_socket = nil\n @read_socket = nil\n @rc_r = false\n @rc_W = false\n end", "def close()\n @connected = false\n @my.close()\n @my = nil\n end", "def close()\n # If we don't have one we don't do anything\n return if !@is_scproxy or !self.has_session?\n\n # Send the call to the master\n response = self.proxy_close :port => @port, :master => true\n\n # Did we close it?\n if response[\"status\"] == true\n # Clear our session\n @port = nil\n else\n # Show an error\n raise response[\"message\"]\n end\n end", "def close!\n if @protocol\n @protocol.close\n @protocol = nil\n end\n return self\n end", "def close_connection\n @endpoint.close\n end", "def disconnect(reason)\n if @socket.is_a?(OpenSSL::SSL::SSLSocket)\n @socket.sysclose()\n else\n begin \n @socket.close_read\n rescue IOError => e\n # Ignore, perhaps we shouldn't ignore.\n end\n\n begin \n @socket.close_write\n rescue IOError => e\n # Ignore, perhaps we shouldn't ignore.\n end\n end\n end", "def close\n close_connection(CLOSED, true)\n end", "def close(status)\n return unless active?\n\n @status = status\n @socket.close\n end", "def client_quit(socket)\n @connections.delete(socket)\n socket.close\n end", "def close\n @conn.disconnect\n end" ]
[ "0.8546623", "0.8422953", "0.84210277", "0.84210277", "0.83778405", "0.8376597", "0.8376597", "0.8351885", "0.8327489", "0.82896495", "0.82811064", "0.8217123", "0.81748974", "0.8173299", "0.8098206", "0.8014346", "0.79676753", "0.79237014", "0.7873896", "0.78597885", "0.7819105", "0.77940625", "0.77779144", "0.7751176", "0.7677078", "0.76692885", "0.76631325", "0.76327056", "0.758315", "0.75693774", "0.75556546", "0.7544674", "0.75116694", "0.7488817", "0.7466409", "0.74156076", "0.7390115", "0.737151", "0.73326", "0.7327163", "0.72983015", "0.7294482", "0.7271214", "0.7236323", "0.7199529", "0.71891", "0.7157915", "0.7127806", "0.7099234", "0.70937854", "0.70746595", "0.7048292", "0.7013679", "0.69969004", "0.69915956", "0.696044", "0.69535714", "0.6934919", "0.6934919", "0.6911359", "0.6906143", "0.68658924", "0.68551415", "0.68538815", "0.6842784", "0.6819682", "0.6818616", "0.6816546", "0.6797795", "0.6786958", "0.6770657", "0.67615545", "0.6751932", "0.67508745", "0.67508745", "0.67434806", "0.673398", "0.6697717", "0.6696312", "0.66957504", "0.6673914", "0.666601", "0.6660709", "0.6660267", "0.6655103", "0.6631628", "0.66153014", "0.660094", "0.65930575", "0.65911776", "0.65906125", "0.6590516", "0.6576212", "0.6565624", "0.65552896", "0.65343344", "0.6519238", "0.6472402", "0.64648324", "0.6460807" ]
0.8207528
12