query
stringlengths
7
9.5k
document
stringlengths
10
1.07M
negatives
listlengths
19
19
metadata
dict
Checks if a network exists or not
def network_exists?(name) net_obj = Com::Vmware::Vcenter::Network.new(vapi_config) filter = Com::Vmware::Vcenter::Network::FilterSpec.new(names: Set.new([name])) net = net_obj.list(filter) raise format("Unable to find target network: %s", name) if net.empty? end
[ "def network_exists?(network_name)\n networks_list.include?(network_name)\n end", "def network_exists?(network_name,network_addr=nil)\n network_names = list_objtype(\"ent\")\n if network_names.include?(network_name)\n return true\n end\n network_names.each do |net_name|\n address = execute_cmd(\"lsnim -l #{net_name} | awk '{if ($1 ~ /net_addr/) print $3}'\").chomp\n if address == network_addr\n return true\n end\n end\n\n return false\n end", "def exists?\n if self.class.onevnet_list().include?(\"#{resource[:name]}\")\n self.debug \"Found network #{resource[:name]}\"\n true\n end\n end", "def existing_named_network?(network_name)\n result = list_network_names\n result.any?{|net_name| net_name == network_name}\n end", "def missing_network_def_found?\n @project.get_element('networks').each do |network_name, network_data|\n nw = network_data[:network]\n mark(\"Network #{network_name} has no network ip range.\",\n 'network', network_name) unless nw\n end\n end", "def network?(name)\n networks.items.map(&:name).include?(name)\n end", "def network_ok\n\t\t\tiface = ConcertoConfig.configured_interface\n\t\t\tif iface\n\t\t\t\tif iface.ip != \"0.0.0.0\"\n\t\t\t\t\ttrue\n\t\t\t\telse\n\t\t\t\t\tfalse\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tfalse\n\t\t\tend\n\t\tend", "def exists?\n# ip('link', 'list', @resource[:name])\n ip('addr', 'show', 'label', @resource[:device]).include?(\"inet\") || ip('addr', 'show', 'label', @resource[:device]).include?(\"SLAVE\")\n rescue Puppet::ExecutionFailure\n return false\n# raise Puppet::Error, \"Network interface %s does not exist\" % @resource[:name] \n end", "def add_network?\n networks_to_add.any?\n end", "def check_network_device_exists(options)\n exists = false\n net_dev = options['network'].to_s\n message = \"Information:\\tChecking network device #{net_dev} exists\"\n command = \"ifconfig #{net_dev} |grep ether\"\n output = execute_command(options,message,command)\n if output.match(/ether/)\n exists = true\n end\n return exists\nend", "def validate_network_name!(network_name, env)\n if !env[:machine].provider.driver.existing_named_network?(network_name)\n raise Errors::NetworkNameUndefined,\n network_name: network_name\n end\n true\n end", "def network_route_exists?(network, nat_server_ip)\n routes = routes_show()\n matchdata = routes.match(route_regex(network, nat_server_ip))\n matchdata != nil\n end", "def check_network_bridge_exists(options)\n exists = false\n net_dev = options['bridge'].to_s\n message = \"Information:\\tChecking network device #{net_dev} exists\"\n command = \"ifconfig #{net_dev} |grep ether\"\n output = execute_command(options,message,command)\n if output.match(/ether/)\n exists = true\n end\n return exists\nend", "def network?\n has_node? :NET\n end", "def update_network?(network_device)\n networks_to_update.any? && network_device\n end", "def check_netdbs\n continue = true\n if (address = @resolver.getaddress(name) rescue false)\n errors.add_to_base \"#{name} is already in DNS with an address of #{address}\"\n continue = false\n end\n if (hostname = @resolver.getname(ip) rescue false)\n errors.add_to_base \"#{ip} is already in the DNS with a name of #{hostname}\"\n continue = false\n end\n if (entry = @dhcp.get subnet.number, mac) and @dhcp.error.empty?\n errors.add_to_base \"#{subnet}/#{mac} is already managed by DHCP and configures #{entry[\"title\"]}\"\n continue = false\n end\n continue\n end", "def find_network(networkName)\n baseEntity = Vsimple::Config[:dc].network\n baseEntity.find { |f| f.name == networkName } or raise Vsimple::Error.new \"no such network #{networkName}\"\n end", "def reachable?\n name_service.has_node?(name)\n true\n rescue ComError\n false\n end", "def has_nics?\n properties.networkProfile.networkInterfaces.count != 0\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get location of lookup service
def lookup_service_host # Allow manual overrides return config[:lookup_service_host] unless config[:lookup_service_host].nil? # Retrieve SSO service via RbVmomi, which is always co-located with the Lookup Service. vim = RbVmomi::VIM.connect @connection_options vim_settings = vim.serviceContent.setting.setting sso_url = vim_settings.select { |o| o.key == "config.vpxd.sso.sts.uri" }&.first&.value # Configuration fallback, if no SSO URL found for some reason ls_host = sso_url.nil? ? config[:vcenter_host] : URI.parse(sso_url).host debug("Using Lookup Service at: " + ls_host) ls_host end
[ "def service_location\n return @service_location\n end", "def lookup\n if !options[:street_address] and (options[:ip_address] or ip_address?)\n name = options[:ip_lookup] || Configuration.ip_lookup || Geocoder::Lookup.ip_services.first\n else\n name = options[:lookup] || Configuration.lookup || Geocoder::Lookup.street_services.first\n end\n Lookup.get(name)\n end", "def location\n fetch('doraemon.locations')\n end", "def location\n fetch('hey_arnold.locations')\n end", "def lookup_service(service_name)\n service_name = service_name + \".apps.gureu.me\"\n resolver = Resolv::DNS.open\n record = resolver.getresource(service_name, Resolv::DNS::Resource::IN::A)\n #return resolver.getaddress(record.target), record.port\n return service_name, 80\nend", "def find_location; end", "def lookup_location (location, units = 'f')\n\t url = @api_url + '?p=' + escape(location) + '&u=' + escape(units)\n\t _lookup(location, url)\n\t end", "def location\n fetch('tolkien.locations')\n end", "def location\n fetch('futurama.locations')\n end", "def location\n fetch('harry_potter.locations')\n end", "def lookup_service(service_name)\n resolver = Resolv::DNS.open\n record = resolver.getresource(service_name, Resolv::DNS::Resource::IN::SRV)\n return resolver.getaddress(record.target), record.port\nend", "def location\n fetch('the_expanse.locations')\n end", "def location\n fetch('simpsons.locations')\n end", "def get_location\n JSON.parse(get_results('/locations.json'), {symbolize_names: true})\n end", "def location\n fetch('archer.locations')\n end", "def location\n fetch('family_guy.location')\n end", "def location\n fetch('games.warhammer_fantasy.locations')\n end", "def location\n fetch('rick_and_morty.locations')\n end", "def get_location(server = nil)\n @has_dns_name = server.respond_to?(:dns_name)\n return nil unless (@has_dns_name or server.respond_to?(:public_ip_address))\n @has_dns_name ? server.dns_name : server.public_ip_address\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
== GET /about/list/:topic An informational listing on a given subject. == GET /about/list/library == GET /about/list/libraries == GET /about/list/location == GET /about/list/locations
def list @topic = get_topic(params) @topic_list = get_topic_list(@topic) respond_to do |format| format.html format.xml { render xml: @topic_list.to_xml } format.json { render json: @topic_list.to_json } end end
[ "def list\n\t\t@notes = Note.where(topic: params[:topic])\n\tend", "def index\n joins = {:user_id => doorkeeper_token.resource_owner_id, :slug => params[:topic_id]}\n joins.merge!(:application_id => doorkeeper_token.application_id) unless has_scope?(\"read_any_publications\")\n @publications = Topic::Publication.joins(:topic).where(:sensit_topics => joins).page(params[:page] || 1).per(params[:per] || 10)\n respond_with(@publications)\n end", "def index\n @topics = Topic.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @topics }\n end\n end", "def index\n @api_v1_topics = Api::V1::Topic.all\n end", "def get_topic(org_unit_id, topic_id) # GET\n query_string = \"/d2l/api/le/#{$le_ver}/#{org_unit_id}/content/topics/#{topic_id}\"\n _get(query_string)\nend", "def index\n @topics = Topic.order(:name).all\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @topics }\n end\n end", "def topics\n puts '[INFO] Getting topics...'\n url = \"#{Playit.config.attributes[\"governance\"]}/getTopics\"\n open(url) { |f|\n f.each_line {\n |line| puts line\n }\n }\n end", "def topics_for_course\n redirect_guest\n @course = Course.find(params[:id])\n @topics = @course.topics\n end", "def view\n get_topic(@current_id, :resolve => false)\n get_complete_topic(@current_id, :resolve => false)\n get_related_for_current\n end", "def index\n @topics = @category.topics.preload(:category)\n render 'api/v1/topics/index'\n end", "def index\n @topic = Topic.find(params[:topic_id])\n @replies = @topic.replies\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @replies }\n end\n end", "def get_topics\n @chapter = Chapter.find(params[:id]) unless params[:id].blank?\n if current_user.is?(\"EA\") or current_user.is?(\"IA\")\n list = @chapter.topics.map {|u| Hash[value: u.id, name: u.name]}\n else\n topic_ids = ContentUserLayout.get_unlocked_topics(@chapter,current_user)\n if !topic_ids.nil?\n list = @chapter.topics.where(:id=>topic_ids).map {|u| Hash[value: u.id, name: u.name]}\n else\n list = @chapter.topics.map {|u| Hash[value: u.id, name: u.name]}\n end\n end\n render json: list\n end", "def get_bookmarked_topics(org_unit_id) # GET\n query_string = \"/d2l/api/le/#{$le_ver}/#{org_unit_id}/content/bookmarks\"\n _get(query_string)\n # Returns: a JSON array of Topic ToC entries.\nend", "def index\n @article_topics = ArticleTopic.all\n end", "def index\n\n\t\t@topics = Topic.all\n\n\t\treturn @topics\n\n\tend", "def index\n @topic_articles = TopicArticle.all\n end", "def index\n @topics = @ip.topics\n end", "def index\n @chapter = Chapter.find(params[:chapter_id])\n @topics = @chapter.topics\n end", "def topics\n topics = [\"News\", \"A.I.\", \"V.R.\", \"RMIT\", \"Game\", \"Rails\", \"Go\", \"Web\", \"M.L\", \"Joke\", \"React\", \"Vue\", \"Node\", \"iOS\", \"AWS\"]\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
== GET /about/solr == GET /about/solr?lens=:lens Administratoronly Solr information.
def solr @solr_fields = get_solr_fields @solr_info = get_solr_information end
[ "def solr_stats\n @solr_stats = get_solr_statistics\n render 'about/solr'\n end", "def url\n \"http://127.0.0.1:#{port}/solr/\"\n end", "def solr\n @solr ||= RSolr.connect(url: solr_url)\n end", "def url\n \"http://#{host}:#{port}/solr/\"\n end", "def search_solr( solr_args )\n raise \"solr_args should at least contain a ':q' key\" unless solr_args.has_key? :q\n\n unless defined? @solr\n @solr = RSolr.connect :url => 'http://www.sanger.ac.uk/mouseportal/solr'\n end\n\n @solr.get 'select', :params => solr_args\n end", "def show\n @solr_server = SolrServer.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @solr_server }\n end\n end", "def solr_get(query, args = {})\n response = ActiveFedora::SolrService.get(query, args)\n logger.debug(\"Solr params: #{response['responseHeader']['params']}\")\n response\n end", "def getSolrDescription\n uri = URI.parse(\"http://#{@host}:#{@port}/solr/admin/cores\")\n out = Net::HTTP.get_response(uri)\n if out.code.to_i == 200 \n return out.body\n else \n STDERR.puts \"Error reaching Solr: \" + \n \"#{out.header.code} -- #{out.header.message}\"\n return nil\n end \n end", "def show\n query = query_for_identifier(Spot::Identifier.new('hdl', params[:id]))\n result, _documents = repository.search(query)\n\n raise Blacklight::Exceptions::RecordNotFound if result.response['numFound'].zero?\n document = result.response['docs'].first\n\n redirect_to redirect_params_for(solr_document: document)\n end", "def get_solr_response_for_doc_id(id=nil, extra_controller_params={})\n unless @current_search_session.nil?\n extra_controller_params[\"hl.q\".to_sym] ||= []\n extra_controller_params[\"hl.q\".to_sym] << @current_search_session.query_params[:q]\n end \n super\n end", "def solr_powered?\n self.solr_powered\n end", "def solr_url\n @solr_url ||= endpoint_url.gsub(/\\/select$/, '')\n end", "def add_facetting_to_solr(solr_params)\n if %w[collection_context online_contents].include? blacklight_params[:view]\n return solr_params\n end\n\n super(solr_params)\n end", "def render_solr_core\n unless request.host == 'search.library.cornell.edu' or request.host == 'catalog.library.cornell.edu'\n core = Blacklight.connection_config[:url]\n # Remove http protocol string\n start = core.rindex(/:\\/\\//) + 3\n display = '<p class=\"solr-core\">Solr core: ' + core[start..-1] + '</p>'\n display.html_safe\n end\n end", "def solr_resp_single_doc(doc_id, solr_params = {})\n solr_response(solr_params.merge({'qt'=>'document','id'=>doc_id}))\nend", "def setup_solr\n RSolr.connect url: ActiveFedora::FileConfigurator.new.solr_config[:url]\n end", "def index\n page = params[:page].to_i.lbound(0)\n per_page = (current_user.try(:per_page) ||\n params[:per_page].try(:to_i) || 10).bound(10, 100)\n\n # Default sort to relevance if there's a search, otherwise year\n if params[:precise] || params[:q]\n sort = 'score desc'\n else\n sort = 'year_sort desc'\n end\n sort = params[:sort] if params[:sort]\n\n solr_query = search_params_to_solr_query(params)\n solr_query.merge!(sort: sort,\n start: page * per_page,\n rows: per_page)\n\n # Get the documents\n @result = RLetters::Solr::Connection.search(solr_query)\n end", "def index\n @solr_mappings = SolrMapping.all\n end", "def first_level_ead_components id, opts={}, docs = Array.new\n solr_response = Blacklight.solr.get \"select\", :params => first_level_solr_query(id,opts)\n return number_found_from_solr_response(solr_response), docs_from_solr_response(solr_response)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
== GET /about/solr_stats Administratoronly Solr information.
def solr_stats @solr_stats = get_solr_statistics render 'about/solr' end
[ "def solr\n @solr_fields = get_solr_fields\n @solr_info = get_solr_information\n end", "def stats\n perform_get('/stats', Neows::Models::Stat)\n end", "def stats\n request :get, \"_stats\"\n end", "def solr_status\n show_environment_info\n log_block('get server status') do\n service = $rays_config.environment.solr.service\n if service.alive?\n $log.info(\"running on #{service.host}:#{service.port}\")\n else\n $log.info(\"stopped\")\n end\n end\n end", "def getSolrDescription\n uri = URI.parse(\"http://#{@host}:#{@port}/solr/admin/cores\")\n out = Net::HTTP.get_response(uri)\n if out.code.to_i == 200 \n return out.body\n else \n STDERR.puts \"Error reaching Solr: \" + \n \"#{out.header.code} -- #{out.header.message}\"\n return nil\n end \n end", "def totals\n is_test = Rails.env == 'test' ? :test : :live\n @totals = Solr.get_totals(is_test)\n# results = [ { :name => 'NINES', :total_docs => 400, :total_archives => 12}, { :name => '18thConnect', :total_docs => 800, :total_archives => 24 } ]\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml # index.xml.builder\n end\n end", "def search_server_status\n solr = RSolr.connect(url: Kumquat::Application.kumquat_config[:solr_url])\n begin\n solr.get('select', params: { q: '*:*', start: 0, rows: 1 })\n rescue RSolr::Error::Http\n render text: 'offline', status: 503\n else\n render text: 'online'\n end\n end", "def admin_gists_stats\n get_admin_stats \"gists\"\n end", "def stats\n get 'stats', format: 'json'\n end", "def admin_gists_stats; end", "def index\n @system_stats = SystemStat.all\n end", "def totals\n\t\tis_test = Rails.env == 'test' ? :test : :live\n\t\t@totals = Solr.get_totals(is_test)\n#\t\tresults = [ { :name => 'NINES', :total_docs => 400, :total_archives => 12}, { :name => '18thConnect', :total_docs => 800, :total_archives => 24 } ]\n\n\t\trespond_to do |format|\n\t\t\tformat.html # index.html.erb\n\t\t\tformat.json { render json: @totals }\n\t\t\tformat.xml # index.xml.builder\n\t\tend\n\tend", "def show\n @solr_server = SolrServer.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @solr_server }\n end\n end", "def stats(params = {})\n response = client.get \"/_cluster/stats\", params.merge(action: \"cluster.stats\", rest_api: \"cluster.stats\")\n response.body\n end", "def names\n\t\tquery_params = QueryFormat.names_format()\n\t\tbegin\n\t\t\tQueryFormat.transform_raw_parameters(params)\n\t\t\tquery = QueryFormat.create_solr_query(query_params, params, request.remote_ip)\n\t\t\tis_test = Rails.env == 'test' ? :test : :live\n\t\t\tis_test = :shards if params[:test_index]\n\t\t\tsolr = Solr.factory_create(is_test)\n\t\t\t@results = solr.names(query)\n\n\t\t\trespond_to do |format|\n\t\t\t\tformat.html # index.html.erb\n\t\t\t\tformat.json { render json: { results: @results }}\n\t\t\t\tformat.xml\n\t\t\tend\n\t\trescue ArgumentError => e\n\t\t\trender_error(e.to_s)\n\t\trescue SolrException => e\n\t\t\trender_error(e.to_s, e.status())\n\t\trescue Exception => e\n\t\t\tExceptionNotifier.notify_exception(e, :env => request.env)\n\t\t\trender_error(\"Something unexpected went wrong.\", :internal_server_error)\n\t\tend\n end", "def manager_analysisd_stats\n get '/manager/stats/analysisd'\n end", "def overview\n authorize! :show, @pool\n (@response, @document_list) = get_search_results(rows:0)\n respond_to do |format|\n format.json { render :json=>{id:@pool.id, models:@pool.models.as_json, perspectives:@pool.exhibits.as_json, facets:@response[\"facet_counts\"][\"facet_fields\"], numFound:@response[\"response\"][\"numFound\"] } } \n end\n end", "def admin_repository_stats; end", "def facets\n @solr_data[:facets]\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
== DELETE /about/log Administratoronly command to wipe the application log.
def log_wipe lines = wipe_log respond_with(lines, template: 'about/log') end
[ "def clear_log\n request('clearLog')\n end", "def rm_log\n FileUtils.rm_rf( logfile_path ) \n end", "def delete_log\n unless UserSession.find == nil\n Log.create(user_id: self.user.id, message: \"#{UserSession.find.user.name} har slettet kortet til #{self.user.name}.\", logtype_id: 3)\n end\n end", "def clear_log!(name)\n put :clear_log!, {:name => name}\n end", "def delete_passing\n @log.delete_if { |entry| entry[:status] == PASS }\n end", "def delete_passing\n @log.delete_if { |entry| entry[:status] == PASS }\n end", "def destroy\n if current_user.has_role? :admin\n @shift_log.destroy\n respond_to do |format|\n format.html {redirect_to shift_logs_url, notice: 'Shift log was successfully destroyed.'}\n format.json {head :no_content}\n end\n else\n flash[:alert] = \"Access To Logs Denied\"\n redirect_to root_path\n end\n end", "def delete_sleep_log(log_id)\n successful_delete?(delete(path_user_version(\"/sleep/#{log_id}\")))\n end", "def delete_sleep_log(user_id: '-', log_id:)\n delete(\"#{API_URI}/#{SLEEP_API_VERSION}/user/#{user_id}/sleep/#{log_id}.json\")\n end", "def clear_log\n\t ContactLog.find_each do |log|\n\t\t log.destroy\n\t end\n\t\tredirect_to(contacts_url)\n\tend", "def delete(app_id_or_app_name, log_drain_id_or_log_drain_url_or_log_drain_token)\n @client.log_drain.delete(app_id_or_app_name, log_drain_id_or_log_drain_url_or_log_drain_token)\n end", "def remove_log!\n File.delete log_file if File.exist?(log_file) && (output_mode == :std_with_log)\n rescue Exception => e\n warn e.message\n end", "def command_delete(name, date)\n \t@log.remove_logItem(name,date)\n end", "def command_delete(name, date)\n a=@log.remove_logItem(name,date)\n @logChanged = true\n end", "def delete_log(container, log)\n delete(log_path(container, log))\n end", "def delete(app_id_or_app_name, log_drain_id_or_log_drain_url)\n @client.log_drain.delete(app_id_or_app_name, log_drain_id_or_log_drain_url)\n end", "def destroy\n @admin_log.destroy\n respond_to do |format|\n format.html { redirect_to admin_logs_url }\n format.json { head :no_content }\n end\n end", "def delete_activity_log(user_id: '-', log_id:)\n delete(\"#{API_URI}/#{ACTIVITY_API_VERSION}/user/#{user_id}/activities/#{log_id}.json\")\n end", "def del_weblog_explain; \"Remove weblog from your list.\"; end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Override __prefix__ class method to have better prefixes for some of these longer vocabulary names.
def __prefix__ __name__.demodulize.underscore.dasherize.to_sym end
[ "def __prefix__=(prefix)\n params = RDF::Vocabulary.vocab_map[__prefix__]\n @__prefix__ = prefix.to_sym\n RDF::Vocabulary.register(@__prefix__, self, **params)\n @__prefix__\n end", "def name_prefix; end", "def words_with_prefix(prefix, words)\n raise NotImplementedError # TODO\nend", "def name_prefix=(_arg0); end", "def prefix\n name.gsub(/\\s+/, \"\").downcase\n # name.gsub(/\\W/, \"\").downcase\n end", "def build_key_prefix(name)\n \"mize/#{name}\"\n end", "def apphelp_prefixed( prefix, suffix, ctrl = controller, substitutions = {} )\n ctrl ||= controller\n\n I18n::t(\n \"uk.org.pond.trackrecord.controllers.#{ ctrl.controller_name }.#{ prefix }_#{ suffix }\",\n substitutions\n ).html_safe()\n end", "def i18n_prefix\n self.class.i18n_prefix\n end", "def ns_prefixes\n {\n 'jerm' => JERMVocab.to_uri.to_s,\n 'dcterms' => RDF::Vocab::DC.to_uri.to_s,\n 'owl' => RDF::Vocab::OWL.to_uri.to_s,\n 'foaf' => RDF::Vocab::FOAF.to_uri.to_s,\n 'sioc' => RDF::Vocab::SIOC.to_uri.to_s\n }\n end", "def nesting_name_prefix\n np = name_prefix.nil? ? nil : name_prefix.sub(/_$/, '')\n [np, singular].reject{|i|i.nil?}.join('_')\n end", "def prefix(word)\n word[0..2]\n end", "def new_item_prefix; end", "def short_prefixes(arg)\n regular(arg).short_prefixes\n end", "def prefix_mappings_for(*args)\n res = []\n\n args.each do |arg|\n vocabs = vocabularies_for(arg)\n\n if vocabs.blank?\n raise ArgumentError, \"Unable to find a vocabulary for the argument `#{arg.inspect}`\"\n end\n\n res << vocabs\n end\n\n res.flatten.map { |vocab| \"#{vocab.fetch(:prefix)}: #{vocab.fetch(:namespace_uri)}\" }.join(' ')\n end", "def unique_prefix; end", "def current_prefix; end", "def inherited_prefix\n\t\t\tprefix\n\t\tend", "def prefix\n self.class.prefix\n end", "def two_word_name; end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make department requirement junction when new requirement is made. Also serves as a Model.within(dept), minus foreign key injection
def core(d) dept = Department.search!(d) raise "[Requirement.core] Error: core already declared for department #{dept.name}" unless dept.core_requirements.empty? requirement = make "#{dept.abbreviation}" # make junctions mk = self.method(:make) self.define_singleton_method(:make) do |*args| req = mk.call(*args) Departments_Requirement.create(department_id: dept.id, requirement_id: req.id) req end @within_model = dept yield @within_model = nil self.define_singleton_method :make, mk end
[ "def add_department(valid_department)\n departments << valid_department\n end", "def department=(new_department) \n\n @department.users.delete(self) \n\n @department = new_department \n\n @department.users << self \n\n end", "def belongs_to_sublease(tenant, options = {})\n belongs_to tenant.to_sym, options.delete(:dependent)\n\n before_validation -> {valid_sublease_change(tenant)}, on: :update\n\n validates \"#{tenant}_id\".to_sym, presence: true\n validate -> {valid_sublease_tenant(tenant)}\n\n end", "def set_deptid(dept); @deptid = dept; end", "def add_dependent(dependent)\n unless dependent.blank? || dependent[:product_id].blank?\n @product.dependents << Product.find(dependent[:product_id])\n end \n end", "def add_department\n @employee_department_new = EmployeeDepartment.new\n @employee_department = EmployeeDepartment.new(department_params)\n flash[:notice] = t('add_emp_dept') if @employee_department.save\n emp_department\n end", "def set_dept(dept)\n @dept = dept ? dept : (BOACDepartments::DEPARTMENTS.find { |d| d.code == CONFIG['test_dept'] })\n end", "def department_gatekeeper_permissions(user)\n # TODO multi-level\n gatekept_departments = Department.where(id: user.department_gatekeepers.pluck(:department_id))\n gatekept_department_ids = gatekept_departments.map(&:child_ids).flatten\n gatekept_department_ids += gatekept_departments.map(&:id)\n gatekept_department_ids.uniq!\n\n # can [:read, :create, :update], Guest, company_id: user.company_id\n\n\n\n can [:read, :create, :update], Guest, department_partitioning_id: user.department_partitioning_point_id, company_id: user.company_id\n\n can :create, Employee, company_id: user.company_id\n\n can [:read, :update], Department, id: gatekept_department_ids\n can :create, Department, parent_id: gatekept_department_ids\n\n can [:read, :update], [InventoryRelease, Employee], department_id: gatekept_department_ids\n\n # Lock down with a join on inventoryrelease\n # releasedinventoryrequest#removing\n # can :manage, ReleasedInventoryRequest, inventory_release: {department_id: gatekept_department_ids}\n\n #\n # releasedinventoryrequest#removing\n # can :manage, RequestAttendance, released_inventory_request: {inventory_release: {department_id: gatekept_department_ids}}\n can :manage, RequestAttendance, inventory_release: {department_id: gatekept_department_ids}\n # can :manage, RequestAttendance do |request_attendance|\n # user.department_gatekeepers.pluck(:department_id).include? request_attendance.requester.department_id\n # end\n\n end", "def assign_department_tag\n # self.tag_list = self.tag_list - Department.all.map {|dept| dept.tag_name}\n self.tag_list.add(self.department.tag_name) if self.department\n end", "def foreign_key_adds; end", "def create\n @degree_requirement = DegreeRequirement.new(params[:degree_requirement])\n \n respond_to do |format|\n if @degree_requirement.save\n flash[:notice] = 'Degree Requirement was successfully created.'\n flash[:new_req_div] = true\n format.html { redirect_to degree_requirements_path(@degree_requirement.degree_program.department_id, @degree_requirement.degree_program.id) }\n format.xml { render :xml => @degree_requirement, :status => :created, :location => @degree_requirement }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @degree_requirement.errors, :status => :unprocessable_entity }\n end\n end\n end", "def add_constraint(constraint); end", "def add_dependency_condition(dc_obj)\n dc_obj.dependency_id = self.id\n self.dependency_conditions << dc_obj\n end", "def create\n \n \n @dept = current_user.depts.new(params[:dept])\n \n respond_to do |format|\n if @dept.save\n format.html { redirect_to @dept, :notice => 'Dept was successfully created.' }\n format.json { render :json => @dept, :status => :created, :location => @dept }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @dept.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @sub_department.update(sub_department_params)\n @sub_departments = SubDepartment.all\n @sub_department = SubDepartment.new\n end", "def can_not_dep_on_self\n unless id != dependent\n errors.add(:dependent, \"Jobs can’t depend on themselves\")\n end\n end", "def create\n @medical_procedure = MedicalProcedure.new(params[:medical_procedure])\n @department = Department.find(params[:department_id])\n\n if @medical_procedure.save\n @department_medical_procedure = DepartmentsMedicalProcedure.new\n @department_medical_procedure.medical_procedure_id = @medical_procedure.id\n @department_medical_procedure.department_id = @department.id\n @department.medical_procedures << @medical_procedure\n redirect_to :action => \"index\", :hospital_id => @department.hospital.id\n flash[:notice] = 'MedicalProcedure was successfully created.'\n\n else\n render :action => \"new\", :hospital_id => @department.hospital.id\n end\n end", "def new_department\n @employee_department_new = EmployeeDepartment.new\n emp_department\n authorize! :create, @employee_department_new\n end", "def dependant(assoc_targets, target_model_name, assoc_net, assoc_name = nil, options = {})\n @_assoc_dependant = @_assoc_dependant.to_a <<\n new_assoc(assoc_targets, target_model_name, assoc_net, :dependant, assoc_name) \n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Configure the isaac backend for basic functions
def configure # Give the bot a handle to config and handler conf = @config # Configure the bot @bot = Isaac::Bot.new @bot.configure{|c| c.server = conf[:server] c.port = conf[:port] c.ssl = conf[:ssl] c.nick = conf[:nick] c.password = conf[:password] c.realname = conf[:name] c.environment = :production c.verbose = conf[:verbose] || false c.log = $log } end
[ "def main_audio ; end", "def backends=(_arg0); end", "def enable_backend\n add option: \"-backend=true\"\n end", "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 set_mixer_control!(pre_amp: nil, amp: nil, hpf: nil, lpf: nil, hpf_bypass: nil, lpf_bypass: nil, limiter_bypass: nil, leak_dc_bypass: nil)\n #This is a stub, used for indexing\nend", "def backend_configure(adapter, config)\n @backend = Connector.new(adapter,config)\n end", "def setup_aka2\n if File.exist?(\"#{Dir.home}/.zshrc\") #if zshec exist\n setZSHRC2\n append_with_newline(\"export HISTSIZE=10000\",\"#{Dir.home}/.zshrc\")\n elsif\n File.exist?(\"#{Dir.home}/.bashrc\") #if bashrc exist\n setBASHRC2\n append_with_newline(\"export HISTSIZE=10000\",\"#{Dir.home}/.bashrc\")\n elsif File.exist?(\"#{Dir.home}/.bash_profile\") #if bash_profile exist\n setBASH2\n append_with_newline(\"export HISTSIZE=10000\",\"#{Dir.home}/.bash_profile\")\n else\n puts \"Currently aka2 just support zshrc, bashrc and bash_profile\"\n puts \"Pleaes contact aka2 creator for more info.\"\n end\n\n trap = \"sigusr2() { unalias $1;}\n sigusr1() { source #{readYML(\"#{Dir.home}/.aka/.config\")[\"dotfile\"]}; history -a; echo 'reloaded dot file'; }\n trap sigusr1 SIGUSR1\n trap 'sigusr2 $(cat ~/sigusr1-args)' SIGUSR2\\n\".pretty\n append(trap, readYML(\"#{Dir.home}/.aka/.config\")['profile'])\n puts \"Done. Please restart this shell.\".red\n end", "def enable_advanced_intra_coding\n FFMpegCommand << \"-aic\"\n end", "def backend=(backend)\n @backend = backend&.to_sym\n set_encoder\n end", "def setupBackend\n lBackendInitHere = false\n if (!@BackendInit)\n @BackendInstance.init_session(@Conf[:Backends][@Backend])\n @BackendInit = true\n lBackendInitHere = true\n end\n yield\n if (lBackendInitHere)\n @BackendInstance.close_session\n @BackendInit = false\n end\n end", "def live_audio(_name = nil, input: nil, stereo: nil)\n #This is a stub, used for indexing\nend", "def backends; end", "def initialize\n extend backend_instance_methods\n end", "def apply_audio\n # TODO\n # @output.set_audio\n end", "def setup_aca(aca)\n on aca, 'curl -L -O https://github.com/nsacyber/HIRS/releases/download/v1.0.2/HIRS_AttestationCA-1.0.2-1541093721.d1bdf9.el7.noarch.rpm'\n on aca, 'yum install -y mariadb-server openssl tomcat java-1.8.0 rpmdevtools coreutils initscripts chkconfig sed grep firewalld policycoreutils'\n on aca, 'yum localinstall -y HIRS_AttestationCA-1.0.2-1541093721.d1bdf9.el7.noarch.rpm'\n sleep(10)\n end", "def configure t\n t.library_path << 'lib'\n t.source_path << 'src'\n t.include_sources << 'src'\n t.optimize = true\n # t.load_config << 'birdbase-config-sample.xml'\n t.load_config << 'birdbase-config.xml'\n t.target_player = '10.2'\nend", "def setup\n @config[\"syntax_highlighter\"] ||= highlighter\n @config[\"syntax_highlighter_opts\"] ||= {}\n @config[\"syntax_highlighter_opts\"][\"default_lang\"] ||= \"plaintext\"\n @config[\"syntax_highlighter_opts\"][\"guess_lang\"] = @config[\"guess_lang\"]\n @config[\"coderay\"] ||= {} # XXX: Legacy.\n modernize_coderay_config\n make_accessible\n end", "def set_algorithms( cipher, mac )\n @cipher, @hmac = cipher, mac\n end", "def enable\n {\n method: \"WebAudio.enable\"\n }\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run the bot This can be done in a blocking or nonblocking way if verify is true and threaded is true, the bot will sit and check that it has successfully connected before continuing (and raise an exception on connection failure).
def run(threaded=true, verify=true) $log.info "Starting IRC Bot..." if threaded then # Run the bot. @thread = Thread.new do $log.info "Bot thread started." @bot.start end # Wait for it to connect if verify then delay = 0 while(not @bot.connected? and delay < @config[:connect_timeout]) do sleep(0.5) delay += 0.5 end raise "Bot timed out during first connect." if(delay >= @config[:connect_timeout]) end else @bot.start end end
[ "def run\n # Jabber::debug = true\n @client = Jabber::Client.new(@jid)\n @client.allow_tls = false\n @client.connect\n @client.auth(@password)\n @client.send(Presence.new.set_type(:available))\n\n @room = Jabber::MUC::SimpleMUCClient.new(@client)\n\n # SimpleMUCClient callback-blocks\n\n @room.on_message do |time, nick, text|\n log.debug(\"#{Date.today}, #{nick}, #{text}\")\n handle_message(time, nick, text)\n end\n\n @room.join(@channel)\n\n @scheduler = BotScheduler.new(log)\n setup_scheduler(@scheduler)\n @scheduler.join\n\n @client.close\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 run\n connect = false\n until connect do\n begin\n call { |server| @server = server ; start }\n rescue\n Waves::Logger.error e.to_s\n sleep 1\n end\n connect = true\n end\n end", "def verify\n raise \"channel not connected\" unless active?\n\n response = peer.connect({\n :channel => channel\n })\n if response.failed?\n raise \"verification attempt failed\"\n end\n\n self[:remote_state] = response[:state]\n self.save\n end", "def do_login\n\t\tif not @@connected\n\t\t\tbegin\n\t\t\t\tif @nexpose_api.login\n\t\t\t\t\t@@connected = true\n\t\t\t\tend\n\t\t\trescue Exception => e\n\t\t\t\tputs e.message\n\t\t\tend\n\t\tend\n\tend", "def run\n begin\n @notification =\n Libnotify.new :body => nil, :timeout => Catfriend.notification_timeout\n @message_count = connect\n notify_message @message_count\n # :body => nil means summary only\n rescue OpenSSL::SSL::SSLError\n error \"try providing ssl certificate\"\n rescue Net::IMAP::NoResponseError\n error \"no response to connect, try ssl\"\n else\n loop {\n sleep_until_change\n break if stopping?\n }\n end\n end", "def do_login\n if not @@connected\n begin\n if @nexpose_api.login\n @@connected = true\n end\n rescue Exception => e\n puts e.message\n end\n end\n end", "def run\n Thread.start do\n begin\n while true\n main_loop\n end\n ensure\n @protocol.close if @protocol\n end\n end\n end", "def perform\n puts \"Running...\"\n looping = true\n \n while(looping) do\n @bots.each { |bot|\n has_error = bot.error\n assessment = bot.assess\n if has_error == false && assessment == false\n @an_error_ocurred = true\n puts bot.message\n elsif has_error && assessment\n puts \"\\e[32m\" + bot.referer + \" is back online.\" + \"\\e[0m\"\n end\n }\n if @first_attempt\n if @an_error_ocurred\n puts \"Some services are down. I'll continue monitoring the targets anyway.\"\n else\n puts \"Everything's working fine. I'll continue monitoring the targets.\"\n end\n \n @first_attempt = false\n end\n @total_attempts += 1\n sleep(5)\n end\n \n end", "def start\n EM.run do\n @running = true\n @bots.each do |key, bot|\n begin\n bot.start\n rescue => e\n log_error(e, \"attempting to start bot #{bot.key}\")\n end\n end\n listen_for_instructions if queue\n end\n end", "def run!\n self.debug(\"is running\")\n while self.base.should_run \n self.debug(\"Checking for message\")\n\n if http.message && http.message[:plugin] == self.name\n parse(http)\n end\n sleep 3\n end\n exit\n end", "def run\n connect\n end", "def main\n @t.each do \n |line|\n info = grab_info(line) # grabs the info from an PRIVMSG\n STDOUT.puts line, \"\\n\" # puts to the console\n ##\n # An IRC client (a bot is a client) must respond to PINGs from the IRC server.\n # If not, the bot will be kicked.\n pong(line) if line[0..3] == \"PING\"\n if info and info[4] # only called if grabbing the info was successful\n ##\n # Are there any commands? This bot won't even check for a command unless it starts with a dot (.)\n # and the caller is authorized\n check_for_cmd(info[4], info[0]) if info and info[4] =~ /^\\.(.+)/ and auth(info)\n self.check_for_greet(info[4], info[0]) if info[4].include?(@config[:nick]) # should i respond with a greeting?\n end\n end\n end", "def connect!\n if wechat_api_connect_solver.success?\n signin! user\n true\n else\n failed! wechat_api_connect_solver.error\n false\n end\n end", "def run\n # if test: fetch specified test set\n if @config[\"test\"] === true\n run_test\n end\n # initial command: query all ids\n if @config[\"crawl_all_ids\"] === true\n @queues[\"crawler\"].push(command: :all_ids, retries: @config[\"command_retries\"])\n end\n # loop: get and execute commands\n loop do\n command, queue_name = next_command\n unless command.nil?\n puts \"### Executing command: #{command}...\"\n execute(command, queue_name)\n else\n # no command available\n if @config[\"insomnia\"] === true\n # push the initial command again, thus starting another \n # cycle of crawling and fetching\n puts \"### Empty queue. Pushing initial command again...\"\n @queues[\"crawler\"].push(command: :all_ids, retries: @config[\"command_retries\"])\n else\n # sleep\n puts \"Sleeping...\"\n sleep @config[\"sleep_seconds\"]\n end\n end\n end\n end", "def start_bot( id, magickey )\n\n\tfound = false\n\tdb = Mysql::new(\"localhost\", ENV['DBUSER'], ENV['DBPASS'], \"neurobots\")\n db.query(\"select userid from synergy_running_bots where userid='#{id}'\").each do |row|\n found = true\n end\n if(!found)\n newbot = Thread.new do\n\t\t\tme = newbot\n bot = Neurobot.new(id,magickey,me)\n\t\t\tTurntabler.interactive\n Turntabler.run do\n bot.client = Turntabler::Client.new('', '', :room => bot.roomid, :user_id => bot.userid, :auth => bot.authid, :reconnect => true, :reconnect_wait => 15)\n # Pull in all the information and spit out the startup\n bot.rehash(nil)\n # Sync the user database with the current room settings\n bot.syncUserList\n# Start Auto dj watcher, alone dj watcher, and blacklist watcher\n bot.backgroundLoopInit\n bot.trapEvents\n end\n end\n $botlist[id] = newbot\n \tdb.query(\"insert into synergy_running_bots values ('#{CONTROLLER}', '#{THREAD}', '#{id}') \")\n return \"1\"\n end\n return \"0\"\nend", "def run\n begin\n server = start_server\n rescue ::StandardError => e\n error e.message\n end\n server.wait_until_stopped\n self\n end", "def run(*args, &block)\n if EM.reactor_running?\n EM.next_tick do\n EM.synchrony do\n begin\n if args.any?\n # Run the block within a client\n Client.new(*args, &block)\n else\n # Just run the block within a fiber\n block.call\n end\n rescue StandardError => ex\n logger.error(([ex.message] + ex.backtrace) * \"\\n\")\n end\n end\n end\n else\n EM.synchrony { run(*args, &block) }\n end\n end", "def connect\n unless connected?\n hostname = 'api.syncano.com'\n port = 8200\n\n sleep(3)\n\n Thread.new do\n begin\n EM.run do\n EM.connect(hostname, port, Syncano::SyncConnection)\n end\n rescue Exception => e\n p e.message\n p e.backtrace\n end\n end\n\n timeout = 30\n\n while connection.blank? && timeout > 0\n timeout -= 1\n sleep 1\n end\n\n raise ::Syncano::ConnectionError.new('Connection timeout') unless timeout > 0\n\n timeout = 300\n\n while (response = connection.get_response('auth')).blank? && timeout > 0\n timeout -= 1\n sleep 1.0/10.0\n end\n\n raise ::Syncano::ConnectionError.new(response.error) if response.status == 'NOK'\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is the bot currently connected? Falls through to Isaac.
def connected? @bot.connected? end
[ "def is_connected?\n if @client.is_connected?\n @log.info \"Asked if bot is connected: YES it is\"\n return true\n else\n @log.info \"Asked if bot is connected: NO it isn't\"\n return false\n end\n end", "def is_connected?\n return @status == CONNECTED\n end", "def is_connected?\n return @status == CONNECTED\n end", "def connected?\n app.speakers.ID(@id).connected.get\n end", "def connected?\n @skype.connected?\n end", "def connected?\n with_timeout { listening? }\n end", "def connected?\n state == :CONNECTED\n end", "def talking_to_bot?\n @talking_to_bot\n end", "def connected?\n !!@session_id && !!@cluster\n end", "def connected?\n bunny_connection.connected?\n end", "def connected?\n return @ide_connection_thread.alive?\n end", "def connected?\n connection.status == :started\n end", "def running?\n\t\tif self.messaging_client and self.messaging_client.state == :CONNECTED\n\t\t\ttrue\n\t\telse\n\t\t\tfalse\n\t\tend\n\tend", "def connected?\n !connections.empty?\n end", "def connectable?\n begin; ping; rescue; false; end\n end", "def activeConnections?\n if @connectedClients then do return true else return false end\n end", "def connected_to?(user)\n current_user?(user) or Connection.connected?(user, current_user)\n end", "def connected?\n Drone::Client.connected?\n end", "def connecting?\n @state == ZOO_CONNECTING_STATE\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Which server is the bot connected to?
def server @bot.server end
[ "def current_remote_server; end", "def current_server\n @_current_server\n end", "def server\n object.player_server_id\n end", "def bot_mode\n self['BOT']\n end", "def nick\n @bot.nick\n end", "def server\n Whois::Server.list[@server_tld_key] rescue nil\n end", "def bot\n \"bot:#{device_detector.bot_name&.gsub(' ', '_')}\" if device_detector.bot?\n end", "def peer\n \"server\"\n end", "def bot\n return @bot\n end", "def bot\r\n return @botstate\r\n end", "def client_name\n sockname[0]\n end", "def bot\n self.class.bot\n end", "def server\n @server ||= Scout::Server.first(client_id)\n end", "def bot?\n @bot.bot_user.id == @id\n end", "def server?\n return (server == true)\n end", "def server\n @@server ||= Server::Cli.new\n #@@server ||= Server::SkypeBot.new\n end", "def context_nick nick\n case nick.downcase\n when \"you\"; server.current_nick\n when \"me\" ; sender.nick\n else ; nick\n end\n end", "def get_current_client\n get_current_hub&.current_client\n end", "def current_guild\n if current_user\n @current_guild || find_current_guild\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Which nick does the bot currently have?
def nick @bot.nick end
[ "def nick\r\n return for_context(nil, false) { |c| c.nick }\r\n end", "def nickname\n @nick\n end", "def context_nick nick\n case nick.downcase\n when \"you\"; server.current_nick\n when \"me\" ; sender.nick\n else ; nick\n end\n end", "def nick_name\n return @nick_name\n end", "def get_nick(irc, sn = nil)\n if sn: sn = sn.server.name if sn.kind_of?(IrcWrapper)\n else sn = irc.server.name end\n if irc.kind_of?(String)\n nn = irc\n irc = nil\n else nn = irc.from.nick end\n if !(s = @active_users[sn]) or !(u = s[IRC::Address.normalize(nn)])\n irc.reply \"Do I know you? At least not right now.\" if irc\n nil\n else (u == true) ? nn : u end\n end", "def get_nick(irc, sn = nil)\n if sn: sn = sn.server.name if sn.kind_of?(IrcWrapper)\n else sn = irc.server.name end\n if irc.kind_of?(String)\n nn = irc\n irc = nil\n else nn = irc.from.nick end\n if !(s = @serv[sn]) or !(u = s[IRC::Address.normalize(nn)])\n irc.reply \"Do I know you? At least not right now.\" if irc\n nil\n else (u == true) ? nn : u end\n end", "def nick_find(login)\n shortnick = db_connect do |db|\n doc = db[$login_collection].find_one({login: login})\n doc['_id'] if doc\n end\n\n nick = Channel(ENV['TRELLO_BOT_CHANNEL']).users.collect do |user, mode|\n user.nick if shortnick == nick_parse(user.nick)\n end\n nick.delete_if { |n| n.nil? }\n\n nick[0]\nend", "def ownNick\n\t\townVCard=getVCard(@jid.to_s)\n\t\tif ownVCard.nil? or ownVCard['NICKNAME'].nil?\n \t\t\treturn @jid.node\n\t\telse\n\t\t\townVCard['NICKNAME']\n\t\tend\n\tend", "def nick(nickname)\n raw \"NICK #{nickname}\\r\\n\"\n end", "def connection_for nick\n @connection_cache[nick]\n end", "def nick\n @prefix =~ PREFIX_PAT and $1\n end", "def nickname\n v = value(\"NICKNAME\")\n v = v.first if v\n v\n end", "def change_nick(new_nick)\n nick new_nick\n end", "def check_nick_matches_authenticated_user\n campfire.user(\"me\") do |user|\n name = irc_name user.name\n if name != nick\n user_reply :nick, name\n @nick = name\n end\n end\n end", "def nickname\n user_info['nickname']\n end", "def lookup_bot(nick) \n return @bots[Bot.new(:network => self, :nick => nick).key]\n end", "def nickname\n info['nickname']\n end", "def getuser(nick)\n if @users[nick] and @users[nick][:user]\n @users[nick][:user]\n else\n Thread.new do\n sleep(1)\n whois(nick)\n end\n wait_for(type: :code, code: ProtonBot::Numeric::WHOISUSER)\n @users[nick][:user]\n end\n end", "def single_nick?\n @nick != '*'\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tell the bot to join a channel
def join(channel) @bot.join(channel) end
[ "def join(channel)\n send \"JOIN #{channel}\"\n end", "def irc_send_join(channel)\n # We send an IRC message that joins a channel\n irc_send(\"JOIN #{channel}\")\nend", "def join(channel)\n self.class.post('/channels.join', body: {name: channel, token: @token}).tap do |response|\n raise \"error posting message: #{response.fetch('error', 'unknown error')}\" unless response['ok']\n end\n end", "def join(channel, password=nil)\n write_optional(\"JOIN #{channel}\", password)\n end", "def join(channel, password = '')\n @irc.join(channel, password)\n end", "def join_channel( bot, chan )\n # Join the channel\n bot.join( chan )\n\n return if @config[:connect_only]\n me = self\n\n # Hook for when we have successfully joined\n register_hook(\"chan_join_#{chan}\".to_sym, lambda{|m| m.channel == chan}, /join/){\n me.join( chan ) if nick == bot_nick # Ensure we only fire if the bot has joined, not other people\n }\n end", "def joinChannel(idUser,idChannel)\n \n end", "def join *channels\n send \"JOIN #{channels.join(',')}\"\n end", "def join\n if request_valid?\n request_user.online!\n \n msg = message(\"joined\")\n msg = javascript_chat_message(msg)\n \n # Inform all joined channels that the user has joined\n Juggernaut.send_to_channels(msg, params[:channels])\n \n render :nothing => true\n else\n # Prevent the user from joining the channel if the request is not\n # from a valid session/user combination\n render :text => \"403\", :status => 403\n end\n end", "def on_join(connection, channel, user)\n end", "def on_join(context, channel, user)\n return unless context.nick.strip.downcase == user.nick.strip.downcase\n context.join_succeeded(channel) \n @log.debug(\"#{network_name(context)} Successfully joined channel #{channel}.\")\n end", "def join(chan)\n # First, stop listening for this event\n unregister_hooks(\"chan_join_#{chan}\".to_sym)\n\n # Then notice the channel\n @channels << chan\n\n # And hook for when we leave it\n me = self\n register_hook(\"chan_part_#{chan}\".to_sym, lambda{|m| m.channel == chan}, /part/){\n me.part( bot, channel ) if nick == bot_nick # Ensure we only fire if the bot has parted, not other people\n }\n register_hook(\"chan_quit_#{chan}\".to_sym, lambda{|m| m.channel == chan}, /kick/){\n me.part( bot, channel ) \n }\n end", "def add_channel channel\n join(channel)\n self\n end", "def join_channel(channel, password=nil)\n channel = normalized_channel_name(channel)\n return if channels.include? channel\n join channel, password\n @channel_passwords[channel] = password if password\n end", "def conversations_join(options = {})\n raise ArgumentError, 'Required arguments :channel missing' if options[:channel].nil?\n options = options.merge(channel: conversations_id(options)['channel']['id']) if options[:channel]\n post('conversations.join', options)\n end", "def join\n if room.locked?\n client.numeric_reply :err_inviteonlychan, \"Cannot join #{channel} (locked)\"\n return false\n\n elsif room.full?\n client.numeric_reply :err_channelisfull, \"Cannot join #{channel} (full)\"\n return false\n\n else\n update_users do\n # join channel\n client.user_reply :join, \":#{channel}\"\n\n # current topic\n client.numeric_reply :rpl_topic, channel, ':' + (room.topic || \"\")\n\n # List the current users, which must always include myself\n # (race condition, server may not realize the user has joined yet)\n nicks = users.values.map { |u| u.nick }\n nicks.unshift client.nick unless nicks.include? client.nick\n\n nicks.each_slice(10) do |list|\n client.numeric_reply :rpl_namereply, \"=\", channel, \":#{list.join ' '}\"\n end\n client.numeric_reply :rpl_endofnames, channel, \"End of /NAMES list.\"\n\n # begin streaming the channel events (joins room implicitly)\n stream_campfire_to_channel\n end\n end\n\n true\n end", "def in_a_channel \n unless joined_channel?\n flash[:danger] = \"Please join a channel\"\n redirect_to join_channel_url\n end\n end", "def do_invite(irc_channel)\n\tS.puts(\"JOIN #{irc_channel}\")\n\tS.puts(\"PRIVMSG #{irc_channel} : I AM HERE, CLICK ME\")\nend", "def someone_did_join_channel(stem, person, channel)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register a command, only invoked when COMMAND_RX is triggered. mod A link to the module object, used in tracking threads name A name for this command, for unregistering later trigger A regex which, if the command matches (see COMMAND_RX), will cause the callback to fire types The types of message to respond to. p A procedure to run when all the checks work out
def register_command(mod, name, trigger, types = /channel/, &p) raise "Please define a block" if not block_given? raise "That command is already hooked." if @cmds[name] raise "The module given is not a module" if not mod.is_a?(HookService) # Ensure types is an array and is full of regex types = [types] if not types.is_a?(Array) types.map!{|x| (x.is_a? Regexp) ? x : Regexp.new(x.to_s)} # convert to rx if not already @hooks_mutex.synchronize{ # Ensure default and register @cmds[name] ||= {} @cmds[name] = {:types => types, :trigger => trigger, :proc => p, :module => mod} # register hook or command for a given module @modules[mod] ||= {:hooks => [], :cmds => [], :threads => [], :threaded => mod.threaded?} @modules[mod][:cmds] << name } $log.debug "Registered command '#{name}'" end
[ "def register_hook(mod, name, trigger = nil, types = /channel/, &p)\n raise \"Please define a block\" if not block_given?\n raise \"That command is already hooked.\" if @hooks[name]\n raise \"The module given is not a module\" if not mod.is_a?(HookService)\n trigger ||= lambda{|*| return true} # set trigger if someone has allowed it to be default\n raise \"Cannot call the trigger expression (type: #{trigger.class})! Ensure it responds to call()\" if not trigger.respond_to?(:call)\n \n # Ensure types is an array and is full of regex\n types = [types] if not types.is_a?(Array)\n types.map!{|x| (x.is_a? Regexp) ? x : Regexp.new(x.to_s)} # convert to rx if not already\n \n @hooks_mutex.synchronize{\n # Ensure defaults and register \n @hooks[name] ||= {}\n @hooks[name] = {:types => types, :trigger => trigger, :proc => p, :module => mod}\n \n # Register a given hook or command for a give module\n @modules[mod] ||= {:hooks => [], :cmds => [], :threads => [], :threaded => mod.threaded?}\n @modules[mod][:hooks] << name\n }\n\n $log.debug \"Registered hook '#{name}'\"\n end", "def register_command(notification_name, command_class)\n @view.register_observer( notification_name, Observer.new(:execute_command, self) );\n @command_map[notification_name] = command_class\n end", "def register_commands\n #first revalidate Class for good token, to ensure it was set\n self.class.validate_token self.class.get_token\n \n # Register defined commands\n self.class.commands.each do |command|\n meth, context = command\n warn \"Registering #{meth} for #{self.class.name} for event #{context}\"\n \n # This allows 'auto' for commands to work in channel and private\n if context == :auto\n contexts = [:channel, :private] \n else\n contexts = [context]\n end\n contexts.each do |c| \n # Wrap m in an error handler:\n bloc = self.class.meth_wrap_proc(self.method(meth.to_sym))\n #Register with global $bot as an event\n @bot.on(c.to_sym, /^\\s*!#{self.class.get_token.to_s}\\s+#{meth.to_s}\\s?(.*)$/i, &bloc)\n end\n end\n # Register default command\n if (self.class.get_default_command_context == :auto) then\n contexts = [:channel, :private] \n else\n contexts = [self.class.get_default_command_context]\n end\n contexts.each do |c|\n bloc = self.class.meth_wrap_proc(self.method(self.class.get_default_command))\n @bot.on(c.to_sym, /^\\s*!#{self.class.get_token.to_s}(.*)$/i, &bloc)\n end\n end", "def register_command(cmd)\n registered_commands << cmd\n\n self\n end", "def register_command! cmd\n # $stderr.puts \"#{self.inspect} register_command! #{cmd.name.inspect}\"\n\n return nil if @commands.include? cmd\n\n # Check for name and aliase collisions.\n collisions = cmd.names.select{ |name| @command_by_name[name] }\n unless collisions.empty?\n raise Error::InvalidCommand, \"A command named #{collisions.inspect} is already registered\"\n end\n\n # Associate.\n @commands << cmd\n cmd.names.each do | name |\n @command_by_name[name] = cmd\n # $stderr.puts \" register_command! #{cmd.inspect} as #{name.inspect}\"\n end\n cmd.manager = self\n\n cmd\n end", "def register_command(command)\n @commands << command\n @command_names << command.name\n end", "def register_handler(command, options = {})\n cmd = Command.new(command, options)\n yield(cmd) if block_given?\n Base.commands[cmd.command] = cmd\n Messenger.register_message_handler(instance.class, \"receive_#{cmd.method.to_s}\", cmd.options)\n end", "def register_command(name, command_class_ref)\n @controller.register_command(name, command_class_ref)\n end", "def register_observer(observer, cmd_name=nil)\n codes= []\n if cmd_name\n codes << Protocol.find_cmd_by_name(cmd_name).code\n else\n codes+= CMDS_BY_CODE.keys\n end\n codes.each {|code|\n list= @observers[code]\n if list.nil?\n @observers[code]= list= []\n end\n list.push(observer)\n }\n end", "def on_command(command_name, &block)\n handlers[{ regexp: command_name, type: :command_name }] = block\n end", "def register_simple(param, match_re, fetch_cmd, cmd)\n register_param param do\n match match_re\n cmd fetch_cmd\n add do |transport, value|\n transport.command(\"#{cmd} #{value}\")\n end\n remove do |transport, old_value|\n transport.command(\"no #{cmd} #{old_value}\")\n end\n end\n end", "def on command, forever = true, &block\n @subscriptions ||= {}\n @subscriptions[command.upcase] ||= []\n @subscriptions[command.upcase] << Proc.new do |frame|\n instance_exec frame, &block\n # Return the param \"forever\", which was passed to \"on\", so that\n # the received_frame method will know whether to remove the sub\n # or not.\n forever\n end\n\n end", "def add_command_spec(command, callback) #:nodoc:\n @commands[:spec] << {\n :regex => command[:regex],\n :callback => callback\n }\n end", "def register_command(name, parser, func)\n @commands[name] = {\n :parser => parser,\n :func => func,\n }\n end", "def on_command(message, arguments); end", "def register_command(klass)\n boot.register_command(klass) if boot\n end", "def add_command(command_class)\n @handlers[command_class.message_type] = build_command_proc(command_class)\n end", "def register(msg, callback)\n key = msg.kind_of?(Numeric) \\\n ? (\"%03d\" % msg) \\\n : msg.to_s.upcase\n @callbacks.add(key, callback)\n end", "def add_command_spec(command, callback) #:nodoc:\n @commands[:spec] << {\n :regex => command[:regex],\n :callback => callback,\n :is_public => command[:is_public] || false }\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register a hook to be run on any message. mod A link to the module object, used in tracking threads name A name for this hook, for unregistering later trigger A procedure to run. If this returns true, it will cause the callback to fire. types The types of message to respond to. p A procedure to run when all the checks work out
def register_hook(mod, name, trigger = nil, types = /channel/, &p) raise "Please define a block" if not block_given? raise "That command is already hooked." if @hooks[name] raise "The module given is not a module" if not mod.is_a?(HookService) trigger ||= lambda{|*| return true} # set trigger if someone has allowed it to be default raise "Cannot call the trigger expression (type: #{trigger.class})! Ensure it responds to call()" if not trigger.respond_to?(:call) # Ensure types is an array and is full of regex types = [types] if not types.is_a?(Array) types.map!{|x| (x.is_a? Regexp) ? x : Regexp.new(x.to_s)} # convert to rx if not already @hooks_mutex.synchronize{ # Ensure defaults and register @hooks[name] ||= {} @hooks[name] = {:types => types, :trigger => trigger, :proc => p, :module => mod} # Register a given hook or command for a give module @modules[mod] ||= {:hooks => [], :cmds => [], :threads => [], :threaded => mod.threaded?} @modules[mod][:hooks] << name } $log.debug "Registered hook '#{name}'" end
[ "def dispatch_hooks(msg, type, bot)\n return if @hooks.length == 0\n\n @hooks_mutex.synchronize{\n @hooks.each{|name, hook|\n types, trigger, p, mod, mod_info = hook[:types], hook[:trigger], hook[:proc], hook[:module], @modules[hook[:module]]\n\n # Go through and kill any old threads,\n purge_module_threads(mod)\n\n # If the module is not threaded, we must find the current\n # thread in order to let it finish before starting a new one\n thread_to_await = mod_info[:threads][0] if not mod_info[:threaded]\n\n # Check types match the rx\n types.each{|type_trigger|\n if type_trigger.match(type) then\n\n $log.debug \"Inspecting hook '#{name}' for module #{mod.class} (threaded? #{mod_info[:threaded]}) [#{trigger.call(msg)}]\"\n begin\n # Check the hook trigger works if it's of the right type\n if(trigger.call(msg)) then\n # Then invoke\n raise \"Too many active threads for module: #{mod_info[:name]}.\" if mod_info[:threads].length > MAX_MODULE_THREADS\n $log.debug \"Dispatching hook '#{name}'...\"\n mod_info[:threads] << invoke(prepare_vars(bot, msg, name), p, [], thread_to_await)\n $log.debug \"Running hook #{name}: #{mod_info[:threads].length}/#{MAX_MODULE_THREADS} threads.\"\n end\n rescue Exception => e\n $log.error \"Error in callback '#{name}' => #{e}\"\n $log.debug \"Backtrace: #{e.backtrace.join(\"\\n\")}\"\n end\n end\n } # /types.each\n } # /@hooks.each\n } # /synchronize\n end", "def register_command(mod, name, trigger, types = /channel/, &p)\n raise \"Please define a block\" if not block_given?\n raise \"That command is already hooked.\" if @cmds[name]\n raise \"The module given is not a module\" if not mod.is_a?(HookService)\n\n # Ensure types is an array and is full of regex\n types = [types] if not types.is_a?(Array)\n types.map!{|x| (x.is_a? Regexp) ? x : Regexp.new(x.to_s)} # convert to rx if not already\n\n @hooks_mutex.synchronize{\n # Ensure default and register \n @cmds[name] ||= {}\n @cmds[name] = {:types => types, :trigger => trigger, :proc => p, :module => mod}\n\n # register hook or command for a given module\n @modules[mod] ||= {:hooks => [], :cmds => [], :threads => [], :threaded => mod.threaded?}\n @modules[mod][:cmds] << name\n }\n\n $log.debug \"Registered command '#{name}'\"\n end", "def hook(type, options = {})\n options = {:for => [:match, :listen_to, :ctcp], :method => :hook}.merge(options)\n __hooks(type) << Hook.new(type, options[:for], options[:method])\n end", "def define_hook(name, *params)\n hooks << make_hook(name, nil, params)\n\n # We must use string evaluation in order to define a method that can\n # receive a block.\n instance_eval(<<-END)\n def #{name}(handle_or_method=nil, &block)\n add_callback(:#{name}, handle_or_method, &block)\n end\n END\n module_eval(<<-END)\n def #{name}(handle=nil, &block)\n add_external_callback(:#{name}, handle, block)\n end\n END\n end", "def define_hook(name, *params)\n fetch_or_create_hooks << make_hook(name, nil, params)\n\n # We must use string evaluation in order to define a method that can\n # receive a block.\n instance_eval(<<-END)\n def #{name}(handle_or_method=nil, &block)\n add_callback(:#{name}, handle_or_method, &block)\n end\n END\n module_eval(<<-END)\n def #{name}(handle=nil, &block)\n add_external_callback(:#{name}, handle, block)\n end\n END\n end", "def invoke_hooks!(type)\n hooks_for(type).each { |hook| hook.call }\n end", "def register_hook(name, block)\n return clear_hooks(name) if block.nil?\n\n @hooks ||= {}\n @hooks[name] ||= []\n\n block = Array(block)\n @hooks[name].concat(block)\n end", "def register_hook(name, block)\n return clear_hooks(name) if block.nil?\n\n block = Array(block)\n @hooks[name].concat(block)\n end", "def hooks_for(type)\n self.hooks[type.to_sym]\n end", "def execute_hooks_for(type, name)\n model.hooks[name][type].each { |hook| hook.call(self) }\n end", "def supported_hook_types; end", "def add_hook(*names)\n (names||[]).each{|hook_name|\n self.class_eval <<-HOOK,__FILE__,__LINE__+1\n def self.#{hook_name}(*methods,&block)\n options=methods.extract_options!\n in_hooks_scope(options[:scope]) do\n register_callback(:\"#{hook_name}\",*methods,&block)\n end\n end\n\n def #{hook_name}(*method,&block)\n self.class.#{hook_name}(*method,:scope=>self,&block)\n end\n HOOK\n register_hook(hook_name)\n }\n end", "def hook_type_name; end", "def fregister(message_type, message_subtype = nil, &listener)\n _register(message_type, message_subtype , Funnel.wrap(listener))\n end", "def callback(type, message)\n synchronize do\n @callbacks[type].call(message) if @callbacks[type]\n end\n end", "def configure_hooks(hook_type, service)\n unless VALID_HOOKS.include?(hook_type)\n raise ArgumentError, \"unknown twirp hook type received: #{hook_type}\"\n end\n\n existing_hooks = instance_variable_get(\"@#{hook_type}_hooks\")\n return if existing_hooks.nil?\n\n existing_hooks.values.each do |hook|\n service.send(hook_type, &hook)\n end\n end", "def hook(*args, &block)\n\t\t\thooks = args.last.is_a?(::Hash) ? args.pop : {}\n\n\t\t\targs.each do |method|\n\t\t\t\toriginal_method = self.instance_method(method)\n\n\t\t\t\tself.send(:define_method, method) do |*a|\n\t\t\t\t\treturn original_method.bind(self).call(*a) if \n\t\t\t\t\t\tcase\n\t\t\t\t\t\twhen hooks[:before].is_a?(Symbol)\n\t\t\t\t\t\t\thook_method(hooks[:before], *a)\n\t\t\t\t\t\twhen hooks[:before].is_a?(Class)\n\t\t\t\t\t\t\thook_class(hooks[:before], *a)\n\t\t\t\t\t\twhen hooks[:before].is_a?(Proc)\n\t\t\t\t\t\t\thook_proc(hooks[:before], *a)\n\t\t\t\t\t\twhen hooks[:before].instance_of?(hooks[:before].class)\n\t\t\t\t\t\t\thook_instance(hooks[:before], *a)\n\t\t\t\t\t\tend\n\n \t\t\t\t\tif block_given?\n\t\t\t\t\t\tif block.arity == 0\n\t\t\t\t\t\t\treturn yield\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\treturn yield(self, *a)\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\n\t\t\t\t\tfalse\n\t\t\t\tend\n\t\t\tend\n\t\tend", "def with_hooks(type, &blk)\n event = type.is_a?(Array) ? type.first : type\n run_hook :\"before_#{event}\"\n value = yield\n run_hook :\"after_#{event}\"\n value\n end", "def add_hook(event_name, hook_name, callable = T.unsafe(nil), &block); end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove a selection of hooks by name If the first argument is a number, it will be used as the timeout when waiting for any threads to end. If no timeout is given, it will wait indefinitely for threads to end.
def unregister_hooks(*names) # Load a timeout if one is given names.delete(nil) timeout = nil if names and names[0].is_a?(Numeric) then timeout = names[0].to_f names = names[1..-1] end # Then unhook things @hooks_mutex.synchronize{ names.each{|name| $log.debug "Unregistering hook: #{name}..." hook = @hooks.delete(name) mod = hook[:module] @modules[mod][:hooks].delete(name) cleanup_module(mod, timeout) } } end
[ "def unregister_commands(*names)\n # Load a timeout if one is given\n names.delete(nil)\n timeout = nil\n if names and names[0].is_a?(Numeric) then\n timeout = names[0].to_f\n names = names[1..-1]\n end\n\n # And then unhook things\n @hooks_mutex.synchronize{\n names.each{|name|\n $log.debug \"Unregistering command: #{name}...\"\n cmd = @cmds.delete(name)\n \n mod = cmd[:module]\n @modules[mod][:cmds].delete(name) \n cleanup_module(mod, timeout)\n }\n }\n end", "def unregister_modules(timeout, *mods)\n @hook_manager.unregister_modules(timeout, *mods)\n end", "def clear_hooks(name)\n @hooks[name] = []\n end", "def remove_hook_for(*names); end", "def clear_hooks(name)\n @hooks && @hooks[name] = []\n end", "def remove_hook_at(method_name, hook_index)\n hooks[method_name].delete_at(hook_index)\n end", "def unset_timer(id, name=nil)\n @timer_list_mutex.synchronize do\n if name.nil?\n timer_list.delete_if {|ti| ti.id == id }\n else\n timer_list.delete_if {|ti| ti.id == id && ti.name == name }\n end\n end\n end", "def remove_hook(method_name, hook)\n hooks[method_name].delete(hook)\n end", "def remove_timeout id\n @queue[:timeouts].reject! do |timeout|\n next timeout[:id] == id\n end\n end", "def clear_hooks(event = nil)\r\n if event\r\n hooks.delete(event.to_s) if hooks.has_key?(event.to_s)\r\n return\r\n end\r\n\r\n hooks.clear\r\n nil\r\n end", "def delete_hook(event_name, hook_name)\n @hooks[event_name] ||= []\n deleted_callable = nil\n\n @hooks[event_name].delete_if do |current_hook_name, callable|\n if current_hook_name == hook_name\n deleted_callable = callable\n true\n else\n false\n end\n end\n deleted_callable\n end", "def clear_event_hooks(event_name); end", "def remove_hook(hooks_sym, &proc)\n hooks = instance_variable_get(hooks_sym.to_sym)\n return unless hooks\n hooks.reject! {|h| h[0]==proc}\n end", "def remove_hook(event, hook)\r\n return unless hooks.has_key?(event.to_s)\r\n hook = hook.to_s unless hook.respond_to?(:call)\r\n hooks[event.to_s].delete(hook)\r\n end", "def delete_polling_thread(key)\n Thread.kill(@pool[key]) if threads_key?(key)\n @pool.delete(key)\n end", "def unwait\n @waiter_queue.push nil\n end", "def remove_hooks(repo, hook_id)\n api.remove_hook(repo, hook_id)\n end", "def clear_event_hooks(event_name)\n @hooks[event_name.to_s] = []\n end", "def remove(keys=[],&cb)\n msg = Protocol::Message.generate(:remove, keys)\n if block_given?\n job = Protocol::Parser.new(REQUEST_TIMEOUT)\n job.callback { |result|\n cb.call(result) if block_given?\n }\n job.errback { |result|\n cb.call(nil) if block_given?\n }\n @jobs << job\n send_data(msg)\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove cmd by name If the first argument is a number, it will be used as the timeout when waiting for any threads to end. If no timeout is given, it will wait indefinitely for threads to end.
def unregister_commands(*names) # Load a timeout if one is given names.delete(nil) timeout = nil if names and names[0].is_a?(Numeric) then timeout = names[0].to_f names = names[1..-1] end # And then unhook things @hooks_mutex.synchronize{ names.each{|name| $log.debug "Unregistering command: #{name}..." cmd = @cmds.delete(name) mod = cmd[:module] @modules[mod][:cmds].delete(name) cleanup_module(mod, timeout) } } end
[ "def remove_timeout id\n @queue[:timeouts].reject! do |timeout|\n next timeout[:id] == id\n end\n end", "def remove(name)\n Monitor.new(name).remove\n end", "def remove_command(name)\n @commands ||= {}\n @commands.delete name\n end", "def remove_command(name)\n @embedded_commands.delete(name.to_sym)\n end", "def remove(keys=[],&cb)\n msg = Protocol::Message.generate(:remove, keys)\n if block_given?\n job = Protocol::Parser.new(REQUEST_TIMEOUT)\n job.callback { |result|\n cb.call(result) if block_given?\n }\n job.errback { |result|\n cb.call(nil) if block_given?\n }\n @jobs << job\n send_data(msg)\n end\n end", "def remove_c(options,*names)\n command = Pre_cmd + \" \"+ \" rm \"\n containers = \"\"\n if names !=nil && names.length!=0 then\n names.each do |container|\n containers.concat(container)\n containers.concat(32)\n end\n else \n containers = \" $(docker ps -aq) \"\n end\n command.concat(options)\n command.concat(32)\n command.concat(containers)\n #puts command \n Open3.popen3(command) do |i,o,e,t|\n output = o.read.chomp\n error = e.read.chomp\n if(error.empty?)\n return output\n else\n return \"error#command:remove#reason:0:#{error}#output:#{output}\"\n end\n end\n end", "def delete_polling_thread(key)\n Thread.kill(@pool[key]) if threads_key?(key)\n @pool.delete(key)\n end", "def sub_remove _value=0\n send_cmd(\"sub_remove #{_value}\")\n end", "def remove(cmd_id)\n @front_queue << [:remove, cmd_id]\n end", "def remove_command(*names)\n options = names.last.is_a?(Hash) ? names.pop : {}\n\n names.each do |name|\n commands.delete(name.to_s)\n all_commands.delete(name.to_s)\n undef_method name if options[:undefine]\n end\n end", "def kind_kill pid, wait=1\n begin\n Process.kill 15, pid\n # Wait for process (or all group members) to\n # exit.\n Timeout.timeout wait do\n loop { Process.wait(pid) }\n end\n rescue Errno::ECHILD, Errno::ESRCH\n # Processes is dead or group has no members.\n return \n rescue Timeout::Error, StandardError\n # Process did not shutdown in time (or there\n # was an unexpected error).\n Process.kill(9, pid) rescue nil\n end\n end", "def remove_command(notification_name)\n @controller.remove_command(notification_name)\n end", "def unblock_command(cmd)\n self.blocked || return\n self.blocked.delete(cmd)\n end", "def delete_by_digest(digest) # rubocop:disable Metrics/MethodLength\n result, elapsed = timed do\n call_script(:delete_by_digest, [\n digest,\n \"#{digest}:QUEUED\",\n \"#{digest}:PRIMED\",\n \"#{digest}:LOCKED\",\n \"#{digest}:RUN\",\n \"#{digest}:RUN:QUEUED\",\n \"#{digest}:RUN:PRIMED\",\n \"#{digest}:RUN:LOCKED\",\n key,\n ])\n end\n\n log_info(\"#{__method__}(#{digest}) completed in #{elapsed}ms\")\n\n result\n end", "def remove_command(*names)\n options = names.last.is_a?(Hash) ? names.pop : {}\n\n names.each do |name|\n commands.delete(name.to_s)\n all_commands.delete(name.to_s)\n undef_method name if options[:undefine]\n end\n end", "def remove(proc)\n Thread.exclusive{ @items.delete(proc) }\n retime\n end", "def remove(name)\n raise \"No job name provided\" if name.nil?\n raise \"Couldn't find a job with name '#{name}''\" if TorqueBox::ScheduledJob.lookup(name).nil?\n\n with_schedulizer do |schedulizer|\n schedulizer.remove_job(name)\n end\n end", "def clear_timeout(id)\n `clearTimeout(#{id})`\n end", "def remove_task(*names)\n options = names.last.is_a?(Hash) ? names.pop : {}\n\n names.each do |name|\n tasks.delete(name.to_s)\n all_tasks.delete(name.to_s)\n undef_method name if options[:undefine]\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register a module by calling hook_thyself. Since modules should extend HookService, they should implement hook_thyself in order to make initial hooks.
def register_module(mod) $log.debug "Registering module: #{mod.class}..." mod.hook_thyself end
[ "def register_hooks; end", "def hook(name)\n @hook_name = name\n Container::Hook.register(name, self)\n end", "def register_hook(mod, name, trigger = nil, types = /channel/, &p)\n raise \"Please define a block\" if not block_given?\n raise \"That command is already hooked.\" if @hooks[name]\n raise \"The module given is not a module\" if not mod.is_a?(HookService)\n trigger ||= lambda{|*| return true} # set trigger if someone has allowed it to be default\n raise \"Cannot call the trigger expression (type: #{trigger.class})! Ensure it responds to call()\" if not trigger.respond_to?(:call)\n \n # Ensure types is an array and is full of regex\n types = [types] if not types.is_a?(Array)\n types.map!{|x| (x.is_a? Regexp) ? x : Regexp.new(x.to_s)} # convert to rx if not already\n \n @hooks_mutex.synchronize{\n # Ensure defaults and register \n @hooks[name] ||= {}\n @hooks[name] = {:types => types, :trigger => trigger, :proc => p, :module => mod}\n \n # Register a given hook or command for a give module\n @modules[mod] ||= {:hooks => [], :cmds => [], :threads => [], :threaded => mod.threaded?}\n @modules[mod][:hooks] << name\n }\n\n $log.debug \"Registered hook '#{name}'\"\n end", "def add_hook_context( context )\n\n case context\n when :before_include, :before_extend, :after_include, :after_extend\n case @cluster.instance\n when ::Class\n unless @cluster.instance <= ::Module\n raise ::RuntimeError, 'Include/Extend execution hooks cannot be created for classes.'\n end\n end\n when :subclass\n case @cluster.instance\n when ::Class\n when ::Module\n raise ::RuntimeError, 'Subclass execution hooks cannot be created for modules.'\n end\n end\n \n @hook_contexts[ context ] = true\n \n return self\n \n end", "def register_hook(name, block)\n return clear_hooks(name) if block.nil?\n\n block = Array(block)\n @hooks[name].concat(block)\n end", "def define(id, hook, &block)\n hooks << Hook.new(id, hook, &block)\n end", "def add_module(mod, name, file_paths)\n\t\t# Call the module set implementation of add_module\n\t\tdup = super\n\n\t\t# If the module cache is not being used, update the cache with\n\t\t# information about the files that are associated with this module.\n\t\tif (!using_cache)\n\t\t\tupdate_module_cache_info(dup.fullname, mod, file_paths)\n\t\tend\n\n\t\t# Automatically subscribe a wrapper around this module to the necessary\n\t\t# event providers based on whatever events it wishes to receive. We\n\t\t# only do this if we are the module manager instance, as individual\n\t\t# module sets need not subscribe.\n\t\tauto_subscribe_module(dup)\n\n\t\t# Notify the framework that a module was loaded\n\t\tframework.events.on_module_load(name, dup)\n\tend", "def register_hook(name, block)\n return clear_hooks(name) if block.nil?\n\n @hooks ||= {}\n @hooks[name] ||= []\n\n block = Array(block)\n @hooks[name].concat(block)\n end", "def add(hook)\n @hooks << hook\n self\n end", "def register_module_function(object); end", "def hook_require!\n @hooking_require = true\n\n # There are two independent require methods. Joy!\n ::Kernel.module_eval do\n class << self\n orig_public_require = Kernel.public_method(:require)\n define_method(:require) do |path, *args|\n ::Bumbler::Hooks.handle_require(path) do\n orig_public_require.call(path, *args)\n end\n end\n end\n\n orig_instance_require = self.instance_method(:require)\n define_method(:require) do |path, *args|\n ::Bumbler::Hooks.handle_require(path) do\n orig_instance_require.bind(self).call(path, *args)\n end\n end\n end\n\n @hooking_require = nil\n end", "def on_module_load(name, mod)\n general_event_subscribers.each { |subscriber|\n subscriber.on_module_load(name, mod)\n }\n end", "def register!(hook)\n cache_key = cache_key_for_hook(hook)\n\n ::Gitlab::Redis::SharedState.with do |redis|\n redis.multi do\n redis.sadd(cache_key, hook.id)\n redis.expire(cache_key, TOUCH_CACHE_TTL)\n end\n end\n end", "def on_module_load(mod, type, name, modinfo)\n\t\t# Payload modules require custom loading as the individual files\n\t\t# may not directly contain a logical payload that a user would \n\t\t# reference, such as would be the case with a payload stager or \n\t\t# stage. As such, when payload modules are loaded they are handed\n\t\t# off to a special payload set. The payload set, in turn, will\n\t\t# automatically create all the permutations after all the payload\n\t\t# modules have been loaded.\n\t\tif (type != MODULE_PAYLOAD)\n\t\t\t# Add the module class to the list of modules and add it to the\n\t\t\t# type separated set of module classes\n\t\t\tadd_module(mod, name, modinfo)\n\t\tend\n\n\t\tmodule_sets[type].add_module(mod, name, modinfo)\n\tend", "def on_install(*args, &block)\n register_hook :install, args, block\n end", "def inject_into_module(path, module_name, *args, &block); end", "def on_module_created(instance)\n end", "def bind!\n hooks.each { |hook| hook.bind(@context) }\n nil\n end", "def add_preplay_hook(name, &f) \n @preplay_hooks_ordered_names << name\n @preplay_hooks[name] = f \n self\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unregister all hooks and commands by unloading all modules.
def unregister_all(timeout = nil) $log.debug "Unregistering all modules..." # clone to avoid editing whilst iterating unregister_modules(timeout, *@modules.keys.clone) end
[ "def unregister_modules(timeout, *mods)\n @hook_manager.unregister_modules(timeout, *mods)\n end", "def unregister\n\n # Commands...\n klass = self.class\n @commands.each do |k,v|\n\n # Remove method.\n name = case v[0]\n when CmdFlag_Normal: 'cmd_'\n when CmdFlag_Channel: 'chan_'\n when CmdFlag_Server: 'serv_'\n end + k.to_s\n klass.remove_method name.to_sym\n\n # Remove from global maps.\n if (cmd = $commands[k])\n if cmd[0] != CmdFlag_Multiple\n $commands.delete(k) if cmd[2].class == klass\n else\n j = cmd.each_with_index do |c, i|\n next unless i > 0\n break i if c[2].class == klass\n end\n cmd.delete_at(j) if j != cmd\n end\n end\n\n end\n\n # Hooks...\n @hooks.each do |h|\n klass.remove_method \"hook_#{h[1]}\".to_sym\n if (hook = $hooks[h[1]])\n hook.delete_if { |e| e[2].class == klass }\n end\n end\n\n # Clean up.\n @commands = {}\n @hooks = []\n\n end", "def unregister_hooks(*names)\n # Load a timeout if one is given\n names.delete(nil)\n timeout = nil\n if names and names[0].is_a?(Numeric) then\n timeout = names[0].to_f\n names = names[1..-1]\n end\n\n # Then unhook things\n @hooks_mutex.synchronize{\n names.each{|name|\n $log.debug \"Unregistering hook: #{name}...\"\n hook = @hooks.delete(name)\n\n mod = hook[:module]\n @modules[mod][:hooks].delete(name) \n cleanup_module(mod, timeout)\n }\n }\n end", "def unload_all\n @last_unload = []\n loaded_safe.each do |plugin|\n unload_one plugin\n @last_unload << plugin\n end\n unload_one TWG::Core\n end", "def deregister_all(session)\n namespace = session.namespace_const\n session.modules.each do |m|\n m.deregister\n end\n session.modules = []\n @initialized = false\n true\n end", "def unload!\n event_handlers = @component.instance_variable_get('@event_handlers') || {}\n commands = @component.instance_variable_get('@commands') || {}\n buckets = @component.instance_variable_get('@buckets') || {}\n\n # Removing itself from the bot:\n bot = @hot_loader.bot\n event_handlers.values.flatten.each { |handler| bot.remove_handler(handler) }\n commands.keys.each { |name| bot.remove_command(name) }\n buckets.keys.each { |key| bot.instance_variable_get('@buckets')&.delete(key) }\n\n # Cleaning the ruby module:\n @component.remove_instance_variable('@event_handlers') rescue nil\n @component.remove_instance_variable('@commands') rescue nil\n @component.remove_instance_variable('@buckets') rescue nil\n @component.remove_instance_variable('@dependencies') rescue nil\n end", "def unregister_all\n default.unregister_all\n end", "def unload_extensions(*exts)\r\n exts.each do |ext|\r\n sym = ext_sym(ext)\r\n obj = @extensions[sym]\r\n obj.ext_unload if obj.respond_to?(:ext_unload)\r\n obj.unload\r\n Object.send(:remove_const, sym)\r\n @extensions.delete sym\r\n end\r\n end", "def clear_hooks\n @hook_objects = []\n end", "def reset_hooks\n @hooks = nil\n end", "def unregister\n Global.item.delete(@name)\n\n # remove dependency\n if @dependencies\n @dependencies.each do |dependency|\n Global.__dependencies__.delete(dependency)\n end\n end\n\n # remove accessors\n name = @name\n Global.singleton_class.module_eval do |mod|\n remove_method(name)\n remove_method(\"set_%s\" % name)\n remove_method(\"%s=\" % name)\n end\n end", "def delete_all\n @loaded_constants.each do |const_name|\n if Object.const_defined?(const_name)\n Object.send(:remove_const, const_name)\n end\n end\n Ichiban::HTMLCompiler::Context.clear_user_defined_helpers\n end", "def reset!\n @loaded_modules = {}\n end", "def unload_plugins\n @load_list.reverse.each do |plugin|\n begin\n plugin.instance.unload\n rescue\n puts \"Exception unloading plugin #{plugin.name} at #{Time.now}\"\n puts $!\n puts $!.backtrace.join(\"\\n\")\n end\n end\n end", "def clear\n @lock.synchronize{ @hooks.clear }\n end", "def unregister_commands(*names)\n # Load a timeout if one is given\n names.delete(nil)\n timeout = nil\n if names and names[0].is_a?(Numeric) then\n timeout = names[0].to_f\n names = names[1..-1]\n end\n\n # And then unhook things\n @hooks_mutex.synchronize{\n names.each{|name|\n $log.debug \"Unregistering command: #{name}...\"\n cmd = @cmds.delete(name)\n \n mod = cmd[:module]\n @modules[mod][:cmds].delete(name) \n cleanup_module(mod, timeout)\n }\n }\n end", "def unregister_commands\n # Register defined commands\n self.class.commands.each do |command|\n meth, context = command\n warn \"Unregistering #{meth} for #{self.class.name} for event #{context}\"\n \n # This allows 'auto' for commands to work in channel and private\n if context == :auto\n contexts = [:channel, :private] \n else\n contexts = [context]\n end\n contexts.each do |c|\n #Register with global $bot\n @bot.off(c.to_sym, /^\\s*!#{self.class.get_token.to_s}\\s+#{meth.to_s}\\s?(.*)$/i)\n end\n end\n # Register default command\n if (self.class.get_default_command_context == :auto) then\n contexts = [:channel, :private] \n else\n contexts = [self.class.get_default_command_context]\n end\n contexts.each do |c|\n @bot.off(c.to_sym, /^\\s*!#{self.class.get_token.to_s}(.*)$/i)\n end\n # Unregister Token\n @@global_tokens_catalog.delete(self.class.get_token)\n end", "def clear_hooks(name)\n @hooks && @hooks[name] = []\n end", "def clear_hooks(name)\n @hooks[name] = []\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Join all threads of a given module with an overall timeout
def join_module_threads(threads, timeout = nil) return if not threads threads.each{|t| # Keep track of time start = Time.now # Allow the thread to close for up to timeout seconds t.join(timeout) # Then subtract how long it took for the next one timeout -= (Time.now - start) } end
[ "def join_all_threads\n\n #Wait for test threads to complete\n Thread.list.each {|t|\n if t != Thread.current\n $test_logger.log(\"Waiting for thread '#{t}' to completed\")\n t.join\n end\n }\n end", "def join_threads(sleep_seconds_before_join: 1)\n # wait some seconds before joining the upcoming threads\n # and check that all TCPServers got one thread\n while (@tcp_server_threads.length < @tcp_servers.length) && sleep_seconds_before_join.positive?\n sleep_seconds_before_join -= 1\n sleep 1\n end\n # try to join any thread\n begin\n @tcp_server_threads.each(&:join)\n\n # catch ctrl-c to stop service\n rescue Interrupt\n end\n end", "def join\n threads.each { |t| t.join }\n end", "def join( limit = nil )\n return unless running?\n @thread.join limit\n end", "def join\n threads.list.each {|t| t.join if t.alive? }\n end", "def join(limit = INFINITE)\n limit = limit * 1000 unless limit == INFINITE\n WaitForSingleObject(@thread, limit)\n ReleaseMutex(@@mutex) \n end", "def join_threads\n Threaded.new map { |x| x.join.value }\n end", "def join\n @size.times do\n process { throw :exit }\n end\n @threads.each(&:join)\n @running = false\n puts \"finished all\"\n end", "def join(sleep_seconds_before_join: 1)\n # check already existing TCPServers\n return if @tcp_servers.empty?\n # wait some seconds before joininig the upcoming threads\n # and check that all TCPServers gots one thread\n while (@tcp_server_threads.length < @tcp_servers.length) && sleep_seconds_before_join.positive?\n sleep_seconds_before_join -= 1\n sleep 1\n end\n # try to join any thread\n begin\n @tcp_server_threads.each(&:join)\n\n # catch ctrl-c to stop service\n rescue Interrupt\n end\n end", "def wait_on_threads(threads)\n\n threads.each { |x| x.join }\n\nend", "def join_thread\n @thread.join if @thread\n @thread = nil\n end", "def join delay = nil\n # don't allow the thread to try and join itself and only worry about\n # joining for live threads\n if running? && @thread.alive? && @thread != Thread.current\n if delay\n # convert to seconds to meet the argument expectations of Thread#join\n seconds = delay / 1000.0\n @thread.join seconds\n else\n @thread.join\n end\n end\n end", "def join_until_no_more_jobs\n\n @exit_when_no_more_jobs = true\n join\n end", "def wait(limit=nil)\n @thread.join limit\n end", "def join\n @thread.join\n end", "def join_until_no_more_jobs\n\n @exit_when_no_more_jobs = true\n join\n end", "def join\n\n @run_thread.join rescue nil\n end", "def join_important_threads\n # Note: we're using this ugly accumulator to ensure that all threads have ended since IMPORTANT_THREADS will almost\n # certainly change sizes after this method is called.\n index = 0\n until index == Adhearsion::Process.important_threads.size\n begin\n Adhearsion::Process.important_threads[index].join\n rescue => e\n logger.error \"Error after joining Thread #{Thread.inspect}. #{e.message}\"\n ensure\n index = index + 1\n end\n end\n end", "def worker_boot_timeout(timeout); end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Dispatch things to hooks
def dispatch_hooks(msg, type, bot) return if @hooks.length == 0 @hooks_mutex.synchronize{ @hooks.each{|name, hook| types, trigger, p, mod, mod_info = hook[:types], hook[:trigger], hook[:proc], hook[:module], @modules[hook[:module]] # Go through and kill any old threads, purge_module_threads(mod) # If the module is not threaded, we must find the current # thread in order to let it finish before starting a new one thread_to_await = mod_info[:threads][0] if not mod_info[:threaded] # Check types match the rx types.each{|type_trigger| if type_trigger.match(type) then $log.debug "Inspecting hook '#{name}' for module #{mod.class} (threaded? #{mod_info[:threaded]}) [#{trigger.call(msg)}]" begin # Check the hook trigger works if it's of the right type if(trigger.call(msg)) then # Then invoke raise "Too many active threads for module: #{mod_info[:name]}." if mod_info[:threads].length > MAX_MODULE_THREADS $log.debug "Dispatching hook '#{name}'..." mod_info[:threads] << invoke(prepare_vars(bot, msg, name), p, [], thread_to_await) $log.debug "Running hook #{name}: #{mod_info[:threads].length}/#{MAX_MODULE_THREADS} threads." end rescue Exception => e $log.error "Error in callback '#{name}' => #{e}" $log.debug "Backtrace: #{e.backtrace.join("\n")}" end end } # /types.each } # /@hooks.each } # /synchronize end
[ "def perform_hooks!\n @perform_hooks = true\n end", "def register_hooks; end", "def hook1; end", "def pre_hook_send(handler); end", "def action_hook; end", "def around_hooks; end", "def call_hooks(*args, **kwargs)\n Hooks.call_for(self.to_s, *args, **kwargs)\n end", "def call_hooks(type, event, *args)\n hooks(type, event).each do |hook, should_exec|\n if should_exec\n instance_exec(*args, &hook)\n else\n hook.call(*args)\n end\n end\n end", "def invoke_hooks!(type)\n hooks_for(type).each { |hook| hook.call }\n end", "def process\n process_hook\n end", "def run_after_hooks\n run_hooks(self.class.after_hooks)\n end", "def run_hooks(hooks)\n hooks.each { |hook| run_hook(hook) }\n end", "def apply_hooks\n\n @hooks.each do |hook|\n \n hook_output = nil\n\n if hook.is_a?(Proc)\n hook_output = hook.call\n elsif hook.is_a?(Symbol)\n hook_output = eval(hook.to_s) # run the symbol\n elsif hook.is_a?(Hash)\n hook_output = hook # hash already? assign to output\n end\n\n @output.merge!(hook_output) if hook_output && hook_output.is_a?(Hash)\n\n\n end unless @hooks.empty?\n\n end", "def define_action_hook; end", "def _work(context)\n # pre step hook\n ret = work(context)\n # post step hook\n ret\n end", "def pre_hook_send(handler)\n\n end", "def around_hooks(job)\n get_hook_names(job, 'around_perform')\n end", "def with_hooks\n run_around_hooks do\n run_before_hooks\n yield\n run_after_hooks\n end\n end", "def post_hooks\n @to_perform.map do |hook|\n next unless hook.type.eql? :post\n hook\n end.compact\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
converts amount in float or integer into Money object
def money(amount) Money.new((amount * 100).to_i) end
[ "def coerce_money(v)\n SpookAndPuff::Money.new(v.to_s)\n end", "def return_money(amount,currency)\n return Money.new(amount*100,currency)\n end", "def instantiate amount, currency\n if amount.is_a?(BigDecimal)\n amount\n else\n BigDecimal(amount.to_s, precision_for(amount, currency))\n end\n end", "def convert_to(convert_currency)\n Money::Converter.new(amount, currency, convert_currency).convert \n end", "def convert_return_amount(money,currency)\n if(currency.nil? && params.has_key?(:account_id))\n currency = Account.find_by(params[:account_id])\n end\n\n if(currency.nil? && !params.has_key?(:account_id))\n currency = 'USD'\n end\n\n return BigDecimal(money.exchange_to(currency).fractional)\n end", "def instantiate amount, currency\n if amount.is_a?(BigDecimal)\n amount\n else\n BigDecimal.new(amount.to_s, precision_for(amount, currency))\n end\n end", "def convert(amount, currency_from, currency_to)\n return Money.new(amount, currency_from).exchange_to(currency_to).fractional\n end", "def converted_amount(other)\n (currency == other.currency ? other : other.convert_to(currency)).amount.to_f\n end", "def money\n Spree::Money.new(amount, { currency: currency })\n end", "def to_currency(amount)\n number_to_currency amount, :precision => 0\n end", "def get_value(value)\n value.instance_of?(HappyMoney::Money) ? value.convert_to(self.currency).amount : value\n end", "def amount\n return Money.new(gross_cents, currency) rescue ArgumentError\n return Money.new(gross_cents) # maybe you have an own money object which doesn't take a currency?\n end", "def Amount(value)\n return value if value.is_a? Amount\n Amount.new(value)\n end", "def convert_to(currency)\n Money.new(1, currency) + self - Money.new(1, currency)\n end", "def to_money(field_name)\n return nil unless [:min_price, :max_price, :denomination].include?(field_name)\n\n Money.new(self.send(field_name), currency_code)\n end", "def convert_to_dollars(amt)\n amt / 100.00\n end", "def amount\n amount_cents / 100.00 if amount_cents\n end", "def dollars\n amount\n end", "def convert_to(target_currency)\n fail InvalidCurrency unless Money.rates.valid_currency?(target_currency)\n\n rate = Money.rates.conversion_rate(currency, target_currency)\n Money.new(amount * rate, target_currency)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
UNIT TESTS FOR METHOD connect_angels_with_other(cities)
def test_angel_camp_connections map = Map.new # checking if Angel camp on index @cities[1] # is connected with...... # # First: with Nevada, it should be on index 0 of array connections # checking Angel camp is connected with Nevada # checking by name assert_equal 'Nevada City', map.cities[1].connections[0].name # # checking by ID assert_equal 0, map.cities[1].connections[0].id # # Second: # Checking Angel camp is connected with Sutter Creek assert_equal 'Sutter Creek', map.cities[1].connections[1].name # checking by id assert_equal 2, map.cities[1].connections[1].id # # Third: # checking Angel camp is connected with Virgina City # checking by name assert_equal 'Virginia City', map.cities[1].connections[2].name # checking by id assert_equal 3, map.cities[1].connections[2].id end
[ "def connect_virginia_with_other(cities)\n cities[3].connect cities[1]\n cities[3].connect cities[4]\n cities[3].connect cities[5]\n cities[3].connect cities[6]\n end", "def test_travel_to_random_connecting_city\n test_prospector = Prospector.new 'p1'\n options = test_prospector.map.get_city(test_prospector.location).connections\n destination = test_prospector.travel\n assert options.include?(destination)\n end", "def test_validate_cities\n skip('this is a helper method for validating location names')\n # ignored cities are ones for which I don't know the location code\n # that the API accepts\n ignored_cities = %w(chongqing koln cologne dusseldorf eugene honolulu\n milan southbay)\n cities = %w(amsterdam austin berlin calgary columbus denver firenze\n frankfurt hamburg miami montreal muenchen\n newyorkcity portland rheinland roma sandiego seattle stockholm\n stuttgart torino toronto twincities vancouver washingtondc\n wien)\n\n cities.each do |city|\n @caruby2go = Caruby2go.new(ENV['CONSUMER_KEY'], city)\n puts \"#{city}\"\n payload = @caruby2go.gasstations\n puts \"#{city}:\\n#{payload}\"\n end\n puts \"Done with valid cities (#{cities.size})\"\n puts 'Did not look for the following cities as they have previously failed validation:'\n ignored_cities.each do |city|\n puts city\n end\n end", "def test_fun_other_places\n\t\tdriver = @city.drivers[0]\n\t\tdriver.set_location @city.locations[1]\n\t\tassert_output(\"Driver 1 heading from Cathedral to Monroeville via Fourth Ave.\\n\") {@city.iterate driver, 1}\n\t\tdriver.set_location @city.locations[2]\n\t\tassert_output(\"Driver 1 heading from Hillman to Downtown via Fifth Ave.\\n\") {@city.iterate driver, 1}\n\tend", "def test_all_locations\r\n\t\toakland = City::new\r\n\t\tfour_locations = [\"Museum\", \"Cathedral\", \"Hospital\", \"Hillman\"]\r\n\t\tassert_includes four_locations, oakland.all_locations[0], oakland.all_locations[1]\r\n\t\tassert_includes four_locations, oakland.all_locations[2], oakland.all_locations[3]\r\n\tend", "def test_addCityConnection\n graph = AirGraph.new()\n sclSym = \"SCL\"\n limSym = \"LIM\"\n graph.map = {sclSym => CityNode.new(\"SCL\", \"name\", \"country\", \"continent\", \"timezone\", {\"N\"=>\"32\", \"S\" =>\"25\"}, \"population\", \"region\"), limSym =>CityNode.new(\"LIM\", \"name\", \"country\", \"continent\", \"timezone\", {\"N\"=>\"32\", \"S\" =>\"25\"}, \"population\", \"region\")}\n data = {\"routes\" => [{\"ports\"=>[\"SCL\", \"LIM\"], \"distance\"=>2453}]}\n graph.addCityConnection(data, graph.map, graph.distanceMap)\n assert_equal(graph.map[sclSym].destinations.length, 1)\n assert_equal(graph.map[sclSym].destinations.keys[0], limSym)\n assert_equal(graph.map[sclSym].destinations[limSym], 2453)\n assert_equal(graph.distanceMap[\"SCL LIM\"], 2453)\n assert_equal(graph.distanceMap[\"LIM SCL\"], 2453)\n end", "def test_coloma_to_suttercreek_virginia_city\n test_map = Map.new\n test_city = test_map.get_city('Coloma')\n test_connections = ['Sutter Creek', 'Virginia City']\n assert_equal test_city.connections.all? { |c| test_connections.include?(c) }, true\n end", "def test_connect_sutter\n map = Map.new\n # testing connect with Coloma\n assert_equal 4, map.cities[2].connections[1].id\n # testing connect angel camp\n assert_equal 1, map.cities[2].connections[0].id\n end", "def test_fun_city_locs\n\t\tassert_equal \"Hospital\", @city.get_location(0).name\n\t\tassert_equal \"Cathedral\", @city.get_location(1).name\n\t\tassert_equal \"Hillman\", @city.get_location(2).name\n\t\tassert_equal \"Museum\", @city.get_location(3).name\n\tend", "def test_valid\n test = Minitest::Mock.new\n city = City.new(\"Enumerable Canyon\", 1, 2, test)\n city2 = City.new(\"Nil Town\", 4, 2, test)\n city3 = City.new(\"Hash Crossing\", 5, 1, test)\n Array cities = [city2, city3]\n city.link_neighbors cities\n assert_equal cities, city.cities\n end", "def test_final_2_cities\n map = Map.new\n set_rule = Rules.new\n prng = Random.new 12\n id = 0\n prospectors = []\n prospectors[id] = Prospector.new id, prng\n prospectors[id].current_city = map.cities[2]\n\n set_rule.final_2_cities id, prng, prospectors\n assert_equal 5, prospectors[id].visited_num\n end", "def test_fun_end\n\t\t@city.set_drivers [@city.drivers[0], @city.drivers[1]]\n\t\t@city.drivers[0].set_location @city.other_places[0]\n\t\t@city.drivers[1].set_location @city.locations[2]\n\t\tcapture_stdout {@city.run}\n\t\tassert_includes @city.other_places, @city.drivers[0].location\n\t\tassert_includes @city.other_places, @city.drivers[0].location\n\tend", "def test_gets_new_location\n city = City.new()\n assert_equal ['Hospital', 'Cathedral', 'Fourth Avenue'], city.gets_new_location('Hospital', 'Fourth Avenue')\n end", "def test_link_neighbors_valid\n\t prng = Minitest::Mock.new\n\t def prng.rand(num); 1; end\n\t\tcity = City.new(\"Fake City\", 7, 0, prng)\n\t\tcity1 = City.new(\"Fake City 1\", 7, 0, prng)\n\t\tcity2 = City.new(\"Fake City 2\", 7, 0, prng)\n\t\tArray cities = [city1, city2]\n\t\tcity.link_neighbors cities\n\t\tassert_equal cities, city.cities\n\tend", "def test_valid\r\n test = Minitest::Mock.new\r\n city = City.new(\"Matzburg\", 6, 2, test)\r\n city2 = City.new(\"Duck Type Beach\", 10, 5, test)\r\n city3 = City.new(\"Enumerable Canyon\", 0, 1, test)\r\n Array cities = [city2, city3]\r\n city.add_neighbors cities\r\n assert_equal cities, city.cities\r\n end", "def initialize(cities)\n\t\t@aTour = []\n\t\tcities.each {|x, y| @aTour << City.new(x, y)}\n\tend", "def test_getNewLocation\n city = City::new();\n assert_equal [\"Hospital\", \"Cathedral\", \"Fourth Avenue\"], city.getNewLocation(\"Hospital\", \"Fourth Avenue\")\n end", "def test_fun_start_loc\n\t\tdriver = @city.drivers[0]\n\t\t@city.start_driver driver\n\t\tassert_includes @city.locations, driver.location\n\t\trefute_includes @city.other_places, driver.location\n\tend", "def populate\r\n DATA.each do |city_details|\r\n begin\r\n address = URI.escape \"http://www.google.com/search?q=#{city_details}\" # escape the query so things like spaces don't mess it up\r\n result = Hpricot(open address) # open the page and parse it\r\n name , state = ( result % \"#res div ol li.g h3.r a.l b\" ).innerHTML.split(', ') # find the element on the page that has the name and state\r\n city = City.new :name => name , :state => state , :country => 'US'\r\n if city.save\r\n puts \"Successfully created #{\"%20s\" % city.name} , #{city.state} , #{city.country} , (#{\"%8.2f\" % city.latitude},#{\"%8.2f\" % city.longitude})\"\r\n else\r\n puts \"#{city.inspect} failed to save from #{city_details}\"\r\n end\r\n rescue\r\n puts \"Could not generate a city from #{city_details}\"\r\n end\r\n end\r\n # end\r\n # call the above function\r\n populate\r\n \r\n # show some interesting ways to use it\r\n def show_use_cases\r\n # distance between two cities (I had to override their method to get it to do this)\r\n dallas = City.find_by_name 'Dallas'\r\n austin = City.find_by_name 'Austin'\r\n puts \"It is #{dallas.distance_to austin} miles from Austin to Dallas (as the crow flies).\"\r\n \r\n texas_cities = City.find_all_by_state('TX').map { |city| city.lat_lon }\r\n puts \"The geographic center of the cities in Texas (that are in our db) is #{Geocoder.geographic_center texas_cities}\"\r\n \r\n cities_near_sacramento = City.find_by_name('Sacramento').nearbys(100).map(&:name).join(', ')\r\n puts 'Cities within 100 miles of Sacramento: ' + cities_near_sacramento\r\n puts 'All cities in California: ' + City.find_all_by_state('CA').map { |city| city.name }.join(', ')\r\n \r\n end\r\n show_use_cases\r\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
UNIT TESTS FOR METHOD connect_sutter_with_other(cities)
def test_connect_sutter map = Map.new # testing connect with Coloma assert_equal 4, map.cities[2].connections[1].id # testing connect angel camp assert_equal 1, map.cities[2].connections[0].id end
[ "def connect_virginia_with_other(cities)\n cities[3].connect cities[1]\n cities[3].connect cities[4]\n cities[3].connect cities[5]\n cities[3].connect cities[6]\n end", "def test_coloma_to_suttercreek_virginia_city\n test_map = Map.new\n test_city = test_map.get_city('Coloma')\n test_connections = ['Sutter Creek', 'Virginia City']\n assert_equal test_city.connections.all? { |c| test_connections.include?(c) }, true\n end", "def test_fun_other_places\n\t\tdriver = @city.drivers[0]\n\t\tdriver.set_location @city.locations[1]\n\t\tassert_output(\"Driver 1 heading from Cathedral to Monroeville via Fourth Ave.\\n\") {@city.iterate driver, 1}\n\t\tdriver.set_location @city.locations[2]\n\t\tassert_output(\"Driver 1 heading from Hillman to Downtown via Fifth Ave.\\n\") {@city.iterate driver, 1}\n\tend", "def test_travel_to_random_connecting_city\n test_prospector = Prospector.new 'p1'\n options = test_prospector.map.get_city(test_prospector.location).connections\n destination = test_prospector.travel\n assert options.include?(destination)\n end", "def test_validate_cities\n skip('this is a helper method for validating location names')\n # ignored cities are ones for which I don't know the location code\n # that the API accepts\n ignored_cities = %w(chongqing koln cologne dusseldorf eugene honolulu\n milan southbay)\n cities = %w(amsterdam austin berlin calgary columbus denver firenze\n frankfurt hamburg miami montreal muenchen\n newyorkcity portland rheinland roma sandiego seattle stockholm\n stuttgart torino toronto twincities vancouver washingtondc\n wien)\n\n cities.each do |city|\n @caruby2go = Caruby2go.new(ENV['CONSUMER_KEY'], city)\n puts \"#{city}\"\n payload = @caruby2go.gasstations\n puts \"#{city}:\\n#{payload}\"\n end\n puts \"Done with valid cities (#{cities.size})\"\n puts 'Did not look for the following cities as they have previously failed validation:'\n ignored_cities.each do |city|\n puts city\n end\n end", "def test_fun_city_locs\n\t\tassert_equal \"Hospital\", @city.get_location(0).name\n\t\tassert_equal \"Cathedral\", @city.get_location(1).name\n\t\tassert_equal \"Hillman\", @city.get_location(2).name\n\t\tassert_equal \"Museum\", @city.get_location(3).name\n\tend", "def test_angel_camp_connections\n map = Map.new\n # checking if Angel camp on index @cities[1]\n # is connected with......\n #\n # First: with Nevada, it should be on index 0 of array connections\n # checking Angel camp is connected with Nevada\n # checking by name\n assert_equal 'Nevada City', map.cities[1].connections[0].name\n #\n # checking by ID\n assert_equal 0, map.cities[1].connections[0].id\n #\n # Second:\n # Checking Angel camp is connected with Sutter Creek\n assert_equal 'Sutter Creek', map.cities[1].connections[1].name\n # checking by id\n assert_equal 2, map.cities[1].connections[1].id\n #\n # Third:\n # checking Angel camp is connected with Virgina City\n # checking by name\n assert_equal 'Virginia City', map.cities[1].connections[2].name\n # checking by id\n assert_equal 3, map.cities[1].connections[2].id\n end", "def test_fun_end\n\t\t@city.set_drivers [@city.drivers[0], @city.drivers[1]]\n\t\t@city.drivers[0].set_location @city.other_places[0]\n\t\t@city.drivers[1].set_location @city.locations[2]\n\t\tcapture_stdout {@city.run}\n\t\tassert_includes @city.other_places, @city.drivers[0].location\n\t\tassert_includes @city.other_places, @city.drivers[0].location\n\tend", "def test_addCityConnection\n graph = AirGraph.new()\n sclSym = \"SCL\"\n limSym = \"LIM\"\n graph.map = {sclSym => CityNode.new(\"SCL\", \"name\", \"country\", \"continent\", \"timezone\", {\"N\"=>\"32\", \"S\" =>\"25\"}, \"population\", \"region\"), limSym =>CityNode.new(\"LIM\", \"name\", \"country\", \"continent\", \"timezone\", {\"N\"=>\"32\", \"S\" =>\"25\"}, \"population\", \"region\")}\n data = {\"routes\" => [{\"ports\"=>[\"SCL\", \"LIM\"], \"distance\"=>2453}]}\n graph.addCityConnection(data, graph.map, graph.distanceMap)\n assert_equal(graph.map[sclSym].destinations.length, 1)\n assert_equal(graph.map[sclSym].destinations.keys[0], limSym)\n assert_equal(graph.map[sclSym].destinations[limSym], 2453)\n assert_equal(graph.distanceMap[\"SCL LIM\"], 2453)\n assert_equal(graph.distanceMap[\"LIM SCL\"], 2453)\n end", "def test_add_toy_museum\n\t\t@city = CitySim::new\n\t\tdriver = Driver.new(\"Driver 1\", 1, 0, 0)\n\t\t@city.current_location = @city.museum\n\t\t@city.checkCurrentLocation(driver)\n\t\tassert_equal 1, driver.num_toys\n\tend", "def test_all_locations\r\n\t\toakland = City::new\r\n\t\tfour_locations = [\"Museum\", \"Cathedral\", \"Hospital\", \"Hillman\"]\r\n\t\tassert_includes four_locations, oakland.all_locations[0], oakland.all_locations[1]\r\n\t\tassert_includes four_locations, oakland.all_locations[2], oakland.all_locations[3]\r\n\tend", "def test_fun_start_loc\n\t\tdriver = @city.drivers[0]\n\t\t@city.start_driver driver\n\t\tassert_includes @city.locations, driver.location\n\t\trefute_includes @city.other_places, driver.location\n\tend", "def test_valid\n test = Minitest::Mock.new\n city = City.new(\"Enumerable Canyon\", 1, 2, test)\n city2 = City.new(\"Nil Town\", 4, 2, test)\n city3 = City.new(\"Hash Crossing\", 5, 1, test)\n Array cities = [city2, city3]\n city.link_neighbors cities\n assert_equal cities, city.cities\n end", "def initialize(cities)\n\t\t@aTour = []\n\t\tcities.each {|x, y| @aTour << City.new(x, y)}\n\tend", "def populate\r\n DATA.each do |city_details|\r\n begin\r\n address = URI.escape \"http://www.google.com/search?q=#{city_details}\" # escape the query so things like spaces don't mess it up\r\n result = Hpricot(open address) # open the page and parse it\r\n name , state = ( result % \"#res div ol li.g h3.r a.l b\" ).innerHTML.split(', ') # find the element on the page that has the name and state\r\n city = City.new :name => name , :state => state , :country => 'US'\r\n if city.save\r\n puts \"Successfully created #{\"%20s\" % city.name} , #{city.state} , #{city.country} , (#{\"%8.2f\" % city.latitude},#{\"%8.2f\" % city.longitude})\"\r\n else\r\n puts \"#{city.inspect} failed to save from #{city_details}\"\r\n end\r\n rescue\r\n puts \"Could not generate a city from #{city_details}\"\r\n end\r\n end\r\n # end\r\n # call the above function\r\n populate\r\n \r\n # show some interesting ways to use it\r\n def show_use_cases\r\n # distance between two cities (I had to override their method to get it to do this)\r\n dallas = City.find_by_name 'Dallas'\r\n austin = City.find_by_name 'Austin'\r\n puts \"It is #{dallas.distance_to austin} miles from Austin to Dallas (as the crow flies).\"\r\n \r\n texas_cities = City.find_all_by_state('TX').map { |city| city.lat_lon }\r\n puts \"The geographic center of the cities in Texas (that are in our db) is #{Geocoder.geographic_center texas_cities}\"\r\n \r\n cities_near_sacramento = City.find_by_name('Sacramento').nearbys(100).map(&:name).join(', ')\r\n puts 'Cities within 100 miles of Sacramento: ' + cities_near_sacramento\r\n puts 'All cities in California: ' + City.find_all_by_state('CA').map { |city| city.name }.join(', ')\r\n \r\n end\r\n show_use_cases\r\nend", "def test_valid_city\r\n test = Minitest::Mock.new\r\n city = City.new(\"Matzburg\", 6, 2, test)\r\n city2 = City.new(\"Duck Type Beach\", 10, 5, test)\r\n city3 = City.new(\"Enumerable Canyon\", 0, 1, test)\r\n Array cities = [city2, city3]\r\n check = 0\r\n city.add_neighbors check\r\n assert_nil city.cities\r\n end", "def fetch_trips(origin_city)\r\n return if origin_city.nil?\r\n\r\n airport_type = AIRPORT_TYPE_MEDIUM_KEY\r\n\r\n case\r\n when origin_city.downcase == 'helsinki'\r\n # Helsinki-Vantaa on ainoa poikkeus!\r\n airport_type = AIRPORT_TYPE_LARGE_KEY\r\n end\r\n\r\n # Suomesta tapahtuvien lähtöjen lentokentät ovat pääsääntöisesti medium-luokkaa.\r\n journey_airports = AIRPORTS.find({MUNICIPALITY_KEY => origin_city.capitalize, AIRPORT_TYPE_KEY => airport_type})\r\n unless journey_airports.nil?\r\n journey_airports.each do |airport|\r\n\r\n fetch_origin_country(airport)\r\n\r\n @trips = TRIPS.find({AIRPORT_ORIGIN_CITY => airport[MUNICIPALITY_KEY]})\r\n end\r\n end\r\n\r\n #@wikipedia_link = COUNTRIES.find(\r\n\r\nend", "def test_museum\n loc1 = @City.Museum\n road = loc1.sample\n assert_includes [\"Bar St.\",\"Fifth Ave.\"], road\nend", "def test_valid\r\n test = Minitest::Mock.new\r\n city = City.new(\"Matzburg\", 6, 2, test)\r\n city2 = City.new(\"Duck Type Beach\", 10, 5, test)\r\n city3 = City.new(\"Enumerable Canyon\", 0, 1, test)\r\n Array cities = [city2, city3]\r\n city.add_neighbors cities\r\n assert_equal cities, city.cities\r\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PUT /workout_templates/1 PUT /workout_templates/1.json
def update @workout_template = WorkoutTemplate.find(params[:id]) respond_to do |format| if @workout_template.update_attributes(params[:workout_template]) format.html { redirect_to @workout_template, notice: 'Workout template was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @workout_template.errors, status: :unprocessable_entity } end end end
[ "def update\n @workout_template = WorkoutTemplate.find(params[:id])\n\n respond_to do |format|\n if @workout_template.update_attributes(params[:workout_template])\n format.html { redirect_to(@workout_template, :notice => 'Workout template was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @workout_template.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update_report_template(args = {}) \n put(\"/reports.json/template/#{args[:templateId]}\", args)\nend", "def update\n respond_to do |format|\n if @workflow_template.update(workflow_template_params)\n format.html { redirect_to @workflow_template, notice: 'Workflow template was successfully updated.' }\n format.json { render :show, status: :ok, location: @workflow_template }\n else\n format.html { render :edit }\n format.json { render json: @workflow_template.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @workflow_template.update(workflow_template_params)\n format.html { redirect_to @workflow_template, notice: \"Workflow template was successfully updated.\" }\n format.json { render :show, status: :ok, location: @workflow_template }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @workflow_template.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @template_shift = TemplateShift.find(params[:id])\n\n respond_to do |format|\n if @template_shift.update_attributes(params[:template_shift])\n format.html { redirect_to @template_shift, notice: 'Template shift was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @template_shift.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @mytemplate = Mytemplate.get(params[:id])\n \n @mytemplate.name = params[:mytemplate][:name]\n @mytemplate.folder = params[:mytemplate][:folder]\n @mytemplate.description = params[:mytemplate][:description]\n \n respond_to do |format|\n if @mytemplate.save\n format.html { redirect_to mytemplates_path }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @mytemplate.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @exercise_template.update(exercise_template_params)\n format.html { redirect_to @exercise_template, notice: 'Exercise template was successfully updated.' }\n format.json { render :show, status: :ok, location: @exercise_template }\n format.whoa { render plain: 'success', status: :ok }\n else\n format.html { render :edit }\n format.json { render json: @exercise_template.errors, status: :unprocessable_entity }\n format.whoa { render plain: @exercise_template.errors, status: :unprocessable_entity }\n end\n end\n end", "def destroy\n @workout_template = WorkoutTemplate.find(params[:id])\n @workout_template.destroy\n\n respond_to do |format|\n format.html { redirect_to workout_templates_url }\n format.json { head :no_content }\n end\n end", "def update\n @exercise_template = ExerciseTemplate.find(params[:id])\n\n if @exercise_template.update(exercise_template_params)\n head :no_content\n else\n render json: @exercise_template.errors, status: :unprocessable_entity\n end\n end", "def create\n @workout_template = WorkoutTemplate.new(params[:workout_template])\n\n respond_to do |format|\n if @workout_template.save\n format.html { redirect_to(@workout_template, :notice => 'Workout template was successfully created.') }\n format.xml { render :xml => @workout_template, :status => :created, :location => @workout_template }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @workout_template.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @workflow_template_step.update(workflow_template_step_params)\n format.html { redirect_to @workflow_template_step, notice: 'Workflow template step was successfully updated.' }\n format.json { render :show, status: :ok, location: @workflow_template_step }\n else\n format.html { render :edit }\n format.json { render json: @workflow_template_step.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @job_template.update(job_template_params)\n format.html { redirect_to @job_template, notice: 'Job template was successfully updated.' }\n format.json { render :show, status: :ok, location: @job_template }\n else\n format.html { render :edit }\n format.json { render json: @job_template.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @milestone_template.update(milestone_template_params)\n format.html { redirect_to @milestone_template, notice: 'Milestone template was successfully updated.' }\n format.json { render :show, status: :ok, location: @milestone_template }\n else\n format.html { render :edit }\n format.json { render json: @milestone_template.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @my_template.update(my_template_params)\n format.html { redirect_to @my_template, notice: 'My template was successfully updated.' }\n format.json { render :show, status: :ok, location: @my_template }\n else\n format.html { render :edit }\n format.json { render json: @my_template.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @one_table_template =\n @one_table.\n one_table_templates.\n by_user(current_user).\n find(params[:id])\n\n respond_to do |format|\n if @one_table_template.update_attributes(params[:one_table_template])\n format.html { redirect_to [@one_table, @one_table_template], notice: t(:one_table_template_updated) }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @one_table_template.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @instruction_template = InstructionTemplate.get(params[:id])\n\n respond_to do |format|\n if @instruction_template.update(params[:instruction_template])\n format.html { redirect_to @instruction_template, notice: 'Instruction template was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @instruction_template.errors, status: :unprocessable_entity }\n end\n end\n end", "def ajax_update_template_info\n\n # Access current template being edited\n template = EmailTemplate.find(params[:template_id])\n\n template.name = params[:name]\n template.description = params[:description]\n template.email_subject = params[:email_subject]\n\n template.put('', {\n :name => template.name,\n :description => template.description,\n :email_subject => template.email_subject\n })\n\n\n response = {\n :success => true\n }\n\n # Return JSON response\n render json: response\n\n\n end", "def update\n @template = templates_keystore_params[:source_type] == 'Templates::Template' ? Templates::Template.find(templates_keystore_params[:source_id]) : Templates::Page.find(templates_keystore_params[:source_id]).try(:template)\n\n respond_to do |format|\n if @templates_keystore.update(templates_keystore_params)\n format.html { redirect_to @template, notice: 'Keystore was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @templates_keystore.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @ticket_template = TicketTemplate.find(params[:id])\n\n respond_to do |format|\n if @ticket_template.update_attributes(params[:ticket_template])\n format.html { redirect_to @ticket_template, notice: 'Ticket template was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @ticket_template.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /workout_templates/1 DELETE /workout_templates/1.json
def destroy @workout_template = WorkoutTemplate.find(params[:id]) @workout_template.destroy respond_to do |format| format.html { redirect_to workout_templates_url } format.json { head :no_content } end end
[ "def destroy\n @workout_template = WorkoutTemplate.find(params[:id])\n @workout_template.destroy\n\n respond_to do |format|\n format.html { redirect_to(workout_templates_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @customtemplate.destroy\n respond_to do |format|\n format.html { redirect_to customtemplates_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @exercise_template.destroy\n respond_to do |format|\n format.html { redirect_to exercise_templates_url, notice: 'Exercise template was successfully destroyed.' }\n format.json { head :no_content }\n format.whoa { render plain: 'success', status: :ok }\n end\n end", "def delete_report_template(args = {}) \n body_delete(\"/reports.json/template\", args[:array_of_ids])\nend", "def destroy\n @instruction_template = InstructionTemplate.get(params[:id])\n @instruction_template.destroy\n\n respond_to do |format|\n format.html { redirect_to instruction_templates_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @workflow_template.destroy\n respond_to do |format|\n format.html { redirect_to workflow_templates_url, notice: 'Workflow template was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @goal_template.destroy\n respond_to do |format|\n format.html { redirect_to goal_templates_url, notice: 'Goal template was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @use_case_template = UseCaseTemplate.find(params[:id])\n @use_case_template.destroy\n\n respond_to do |format|\n format.html { redirect_to project_use_case_templates_path @project }\n format.json { head :no_content }\n end\n end", "def destroy\n @inspection_template.destroy\n respond_to do |format|\n format.html { redirect_to inspection_templates_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @template_shift = TemplateShift.find(params[:id])\n @template_shift.destroy\n\n respond_to do |format|\n format.html { redirect_to template_shifts_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @milestone_template.destroy\n respond_to do |format|\n format.html { redirect_to milestone_templates_url, notice: 'Milestone template was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @build_template.destroy\n respond_to do |format|\n format.html { redirect_to build_templates_url }\n format.json { head :no_content }\n end\n end", "def delete_course_template(org_unit_id)\n path = \"/d2l/api/lp/#{$lp_ver}/coursetemplates/#{org_unit_id}\"\n _delete(path)\n puts '[+] Course template data deleted successfully'.green\nend", "def destroy\n @wizardcustomtemplate.destroy\n respond_to do |format|\n format.html { redirect_to wizardcustomtemplates_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @project_template = ProjectTemplate.find(params[:id])\n @project_template.destroy\n\n respond_to do |format|\n format.html { redirect_to project_templates_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @template_type.destroy\n\n respond_to do |format|\n format.html { redirect_to templates_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @template.destroy\n respond_to do |format|\n format.html { redirect_to templates_templates_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @workflow_template_step.destroy\n respond_to do |format|\n format.html { redirect_to workflow_template_steps_url, notice: 'Workflow template step was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @survey_template.destroy\n respond_to do |format|\n format.html { redirect_to organization_survey_templates_url(@organization), notice: 'Survey was successfully destroyed.' }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this could be optimized a tiny bit by only calling superclass.build_xray but i am le tired
def build_xray @build_xray ||= begin retval = Hash.new { |hash,key| hash[key] = {} } klasses = [] klass = self while klass && klass <= UIView klasses.unshift(klass) klass = klass.superclass end klasses.each do |klass| xray_props = klass.xray xray_props && xray_props.each do |key,values| values.keys.each do |check_unique| retval.each do |section, editors| editors.delete(check_unique) end end retval[key].merge!(values) end end # clean out nil-editors and empty sections retval.each do |section, editors| editors.each do |property, editor| editors.delete(property) unless editor end retval.delete(section) if editors.length == 0 end retval end end
[ "def build_xml(builder)\n super(builder)\n builder.Type { |b| self.object_type.build_xml(b) } if object_type\n end", "def inherited(subclass)\n\t\t\t# Attach instance variables to the metaclasses of newly formed child classes\n\t\t\t# clone from the root, which should always remain pristine\n\t\t\t\n\t\t\t# NOTE: This is really fragile code, built on janky assumptions.\n\t\t\t# The only reason the root is staying clean even though this is NOT a deep copy\n\t\t\t# is that the arrays that default to empty in the root hash\n\t\t\t# are being replaced by completely new arrays when the component / action list is set\n\t\t\tdep = @dependencies\n\t\t\t\n\t\t\tsubclass.class_eval do\n\t\t\t\t@dependencies = dep.clone\n\t\t\tend\n\t\tend", "def coerced_build(type, nc_array)\n\n klass = Object.const_get(\"#{type.capitalize}MDArray\")\n instance = klass.new(type, nc_array)\n instance.coerced = true\n return instance\n\n end", "def marshal_load(array)\n\t\tsuper(array[0])\n\t\t@currentLines, @currentColumns = array[1]\n\t\t@totalLines, @totalColumns, @totalSolution = array[2]\n\t\t@evolved = array[3]\n\t\treturn self\n\tend", "def init_jaxb_json_hash(_o)\n super _o\n if !_o['all'].nil?\n _oa = _o['all']\n if(_oa.is_a? Hash)\n @all = EnunciateHelpers::LAMB_CLASS_AWARE.call(_oa) if _oa['@class']\n @all = Gov::Vha::Isaac::Rest::Api1::Data::Enumerations::RestMapSetItemComponentType.from_json(_oa) unless _oa['@class']\n elsif (_oa.is_a? Array)\n #an array(of hashes hopefully) or scalar\n @all = Array.new\n _oa.each { | _item | \n if ((_item.nil? || _item['@class'].nil?)rescue true)\n @all.push Gov::Vha::Isaac::Rest::Api1::Data::Enumerations::RestMapSetItemComponentType.from_json(_item)\n else\n @all.push EnunciateHelpers::LAMB_CLASS_AWARE.call(_item)\n end\n }\n else\n @all = _oa\n end\n end\n end", "def test_view_builder_parent\nnames = %w{string int float none array}\ntypes = [String,Integer,Float,NilClass,Array]\n\nab = AnyBuilder.new.klass(ViewDef).defaults({:set_viewer => Viewer, :set_type_strict => true}).table(:set_types,types).build\nab << ViewDef.new.set_viewer(Viewer).set_type_strict(true).set_types(Object).set_auto_fields(true)\nvds = ab.collect {|c| ViewBuilder.new(c)}\n\nb = ViewBuilder.new(nil,vds)\n\nsf = SomeFields.new\nview = b.build(sf)\n\nassert view.has_members?\ntests = proc {|view|\n\t[names,types].transpose.each{|n,t|\n\tassert_equal view, view.member(n).parent\n\tassert_equal sf.method(n).call, view.member(n).get\n\tassert !view.member(n).has_members?\n\tassert_equal [t], view.member(n).types\n}}\n\ntests.call(view)\n\nb.children.each{|b_child|\nsf = SomeFields.new\nview = b.build(sf)\ntests.call(view)\n}\nend", "def init_jaxb_json_hash(_o)\n super _o\n if !_o['all'].nil?\n _oa = _o['all']\n if(_oa.is_a? Hash)\n @all = EnunciateHelpers::LAMB_CLASS_AWARE.call(_oa) if _oa['@class']\n @all = Gov::Vha::Isaac::Rest::Api1::Data::Enumerations::RestTaxonomyType.from_json(_oa) unless _oa['@class']\n elsif (_oa.is_a? Array)\n #an array(of hashes hopefully) or scalar\n @all = Array.new\n _oa.each { | _item | \n if ((_item.nil? || _item['@class'].nil?)rescue true)\n @all.push Gov::Vha::Isaac::Rest::Api1::Data::Enumerations::RestTaxonomyType.from_json(_item)\n else\n @all.push EnunciateHelpers::LAMB_CLASS_AWARE.call(_item)\n end\n }\n else\n @all = _oa\n end\n end\n end", "def init_jaxb_json_hash(_o)\n super _o\n if !_o['all'].nil?\n _oa = _o['all']\n if(_oa.is_a? Hash)\n @all = EnunciateHelpers::LAMB_CLASS_AWARE.call(_oa) if _oa['@class']\n @all = Gov::Vha::Isaac::Rest::Api1::Data::Enumerations::RestStampPrecedenceType.from_json(_oa) unless _oa['@class']\n elsif (_oa.is_a? Array)\n #an array(of hashes hopefully) or scalar\n @all = Array.new\n _oa.each { | _item | \n if ((_item.nil? || _item['@class'].nil?)rescue true)\n @all.push Gov::Vha::Isaac::Rest::Api1::Data::Enumerations::RestStampPrecedenceType.from_json(_item)\n else\n @all.push EnunciateHelpers::LAMB_CLASS_AWARE.call(_item)\n end\n }\n else\n @all = _oa\n end\n end\n end", "def flat; Flat.new(self); end", "def init_jaxb_json_hash(_o)\n super _o\n if !_o['all'].nil?\n _oa = _o['all']\n if(_oa.is_a? Hash)\n @all = EnunciateHelpers::LAMB_CLASS_AWARE.call(_oa) if _oa['@class']\n @all = Gov::Vha::Isaac::Rest::Api1::Data::Enumerations::RestConcreteDomainOperatorsType.from_json(_oa) unless _oa['@class']\n elsif (_oa.is_a? Array)\n #an array(of hashes hopefully) or scalar\n @all = Array.new\n _oa.each { | _item | \n if ((_item.nil? || _item['@class'].nil?)rescue true)\n @all.push Gov::Vha::Isaac::Rest::Api1::Data::Enumerations::RestConcreteDomainOperatorsType.from_json(_item)\n else\n @all.push EnunciateHelpers::LAMB_CLASS_AWARE.call(_item)\n end\n }\n else\n @all = _oa\n end\n end\n end", "def build\n po = ProxyObject.new(@bus, @dest, @path)\n ProxyObjectFactory.introspect_into(po, @xml)\n po\n end", "def build_xml(builder)\n super(builder)\n builder.ValidNetwork {|b| segment_config_network.build_xml(b) } if segment_config_network\n asset_on_segment_historys.each do |aosh|\n builder.AssetOnSegmentHistory {|b| aosh.build_xml(b)} if aosh\n end\n meas_locations.each do |m|\n builder.MeasurementLocation do |b|\n m.build_xml(b)\n end\n end\n end", "def append_features(base)\n if base.respond_to? :superclass\n base = base.superclass while !BASE_OBJECTS.include? base.superclass\n end\n\n super\n end", "def buildTree\n\t\t# call build method\n\t\t@root = build(@records, @attributes)\n\tend", "def make_base\r\n @map = Array.new(length) { |x_coord|\r\n Array.new(width) { |y_coord| Cell.new(:x_coord => x_coord, :y_coord => y_coord, :length => length, :width => width) }\r\n }\r\n add_map_edges\r\n @map\r\n end", "def build_array()\n @elements.dup\n end", "def init_jaxb_json_hash(_o)\n super _o\n if !_o['all'].nil?\n _oa = _o['all']\n if(_oa.is_a? Hash)\n @all = EnunciateHelpers::LAMB_CLASS_AWARE.call(_oa) if _oa['@class']\n @all = Gov::Vha::Isaac::Rest::Api1::Data::Enumerations::RestDynamicSememeValidatorType.from_json(_oa) unless _oa['@class']\n elsif (_oa.is_a? Array)\n #an array(of hashes hopefully) or scalar\n @all = Array.new\n _oa.each { | _item | \n if ((_item.nil? || _item['@class'].nil?)rescue true)\n @all.push Gov::Vha::Isaac::Rest::Api1::Data::Enumerations::RestDynamicSememeValidatorType.from_json(_item)\n else\n @all.push EnunciateHelpers::LAMB_CLASS_AWARE.call(_item)\n end\n }\n else\n @all = _oa\n end\n end\n end", "def build_array(node)\r\n return [] if node.nil?\r\n results = []\r\n results.concat build_array(node.left)\r\n results << node.payload\r\n results.concat build_array(node.right)\r\n results\r\nend", "def build\n collect_index\n init_nodes\n setup_node_dependencies\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fetch currency rates from application configuration file config/currency_rate.yml will return currency rates along with it's type
def currency_rates @currency_rates = fetch_currency_rates end
[ "def currency_rates\n response['rates'][currency.target_currency.to_s]\n end", "def currencies\n @client.make_request :get, settings_path('currencies')\n end", "def update_rates\n clear_rates\n add_currency_rate(\"EUR\", 1)\n add_currency_rates(config[\"exchange_rates\"]) # rates from bank.yml\n \n fetch_rates.each do |currency_rate|\n add_currency_rate(currency_rate[:currency], currency_rate[:rate].to_f)\n end\n @@config['exchange_rates']\n end", "def application_currency_types\n application_currency_rates.collect{ |rate| rate[:currency] }\n end", "def exchange_rates\n Currency::Exchange.exchange_rates\n end", "def getRate currency\n accounts = Account.find(:all)\n \n accounts.each do |a|\n if a.currency == currency then\n return a.exchangeRate\n end\n end\n end", "def fetch_exchange_rates(currency)\n resp = client.get('exchange-rates', { currency: currency })\n\n case resp.status\n when 200 then JSON.parse(resp.body).dig('data', 'rates')\n when 404 then raise Money::Bank::UnknownRate\n when 400\n if resp.headers['content-type'].start_with?('application/json')\n errors = JSON.parse(resp.body)&.dig('errors')\n if errors&.first&.dig('message')&.start_with?('Invalid currency')\n raise Money::Bank::UnknownRate\n end\n end\n\n raise CoinbaseExchangeFetchError\n else\n raise CoinbaseExchangeFetchError\n end\n rescue Faraday::Error, JSON::ParserError\n raise CoinbaseExchangeFetchError\n end", "def fetch_currency_rate(currency_type)\n if currency_type == \"EUR\"\n product_price_details\n else\n fetch_updated_currency_rate(currency_type)\n end\n end", "def fetch_rates\n rates = {}\n begin\n if @force_expire\n Timeout.timeout(60) do\n doc = Hpricot.XML(open('http://themoneyconverter.com/USD/rss.xml'))\n (doc/:item).each do |item|\n country = (item/:title).inner_html.split('/')[0]\n conversion_match = (item/:description).inner_html[/=.?(\\d+\\.?\\d*)/]\n # 1 USD country rate 'in USD'\n rates[country] = 1.0 / $1.to_f\n end\n rates.update({'USD' => 1.0})\n persist_rates(rates)\n end\n else\n rates = fetch_persisted_rates\n end\n rescue Exception\n rates = fetch_persisted_rates\n end\n rates\n end", "def currency_exchange_rates\n @currency_exchange_rates ||= Services::CurrencyExchangeRatesService.new(@api_service)\n end", "def all_rates\n session = Patron::Session.new\n session.timeout = 30000 # 10 secs\n session.connect_timeout = 2000 # 2 secs\n\n ExchangeRatesGenerator.logger.info \"Retrieving exchange rates from #{source}...\"\n\n http_response = session.get(source)\n\n if ['404', '405', '406', '410'].include?(http_response.status)\n # Not Found, auth failure, etc. Some form of it wasn't there.\n raise Errors::NotFoundError, \"The exchange rate source file seems to be unavailable\"\n elsif !['1', '2'].include?(http_response.status.to_s[0..0])\n # Other non-specific failures.\n raise Errors::UnexpectedError, \"Error while making a request to #{source}\\nResponse: #{http_response.inspect}\"\n end\n\n convert_to_exchange_rate_hash(http_response.body)\n end", "def currency_rates\n if session[:currency].nil?\n session[:currency] = {}\n res = JSON.parse(HTTParty.get(\"https://api.exchangeratesapi.io/latest?base=GBP\").to_json)\n\n\n session[:currency][:g2u] = res[\"rates\"][\"USD\"].round(2)\n session[:currency][:g2e] = res[\"rates\"][\"EUR\"].round(2)\n session[:currency][:g2c] = res[\"rates\"][\"CNY\"].round(2)\n session[:currency][:g2j] = res[\"rates\"][\"JPY\"].round(2)\n session[:currency][:g2r] = res[\"rates\"][\"RUB\"].round(2)\n session[:currency][:g2h] = res[\"rates\"][\"HKD\"].round(2)\n\n @g2u = res[\"rates\"][\"USD\"].round(2)\n @g2e = res[\"rates\"][\"EUR\"].round(2)\n @g2c = res[\"rates\"][\"CNY\"].round(2)\n @g2j = res[\"rates\"][\"JPY\"].round(2)\n @g2r = res[\"rates\"][\"RUB\"].round(2)\n @g2h = res[\"rates\"][\"HKD\"].round(2)\n\n else\n puts session[:currency]\n @g2u = session[:currency][\"g2u\"]\n @g2e = session[:currency][\"g2e\"]\n @g2c = session[:currency][\"g2c\"]\n @g2j = session[:currency][\"g2j\"]\n @g2r = session[:currency][\"g2r\"]\n @g2h = session[:currency][\"g2h\"]\n end\n\n end", "def currencies\n country_client.call(:get_currencies)\n end", "def rates\n fail_if_rates_missing\n @rates\n end", "def fetch_updated_currency_rate(currency_type)\n currency_rate = nil\n ApplicationController.new.fetch_currency_rates.select{ |currency| currency_rate = currency if currency[:currency] == currency_type }\n if currency_rate.present?\n actual_price = price.to_f * currency_rate[:rate].to_f\n currency_details = {:currency => currency_type, :price => actual_price.round(2)}\n else\n currency_details = product_price_details\n end\n currency_details\n end", "def find_rate()\n uri_string = \"https://free.currconv.com/api/v7/convert?q=GBP_\"\\\n \"#{@currency}&compact=ultra&apiKey=2d46a9b5b650dca0dbb1\"\n uri = URI(uri_string)\n res = Net::HTTP.get_response(uri)\n return(JSON.parse(res.body)[\"GBP_#{@currency}\"]/100.0)\n end", "def currency_codes\n @rates.keys\n end", "def rates_for(currency_code)\n # Retrieve the actual rates from the external source\n rates = all_rates\n\n adjusted_currency = currency_code.to_s.upcase.to_sym \n unless rates.include?(adjusted_currency)\n raise Errors::CurrencyNotAvailable, \"#{adjusted_currency.to_s} was not available in this Source (#{self.to_s}), please use a different Source\"\n end\n\n adjusted_rates = {}\n\n # Add the currency we are converting to...\n adjusted_rates[adjusted_currency] = 1.0\n\n # Work out the exchange from our desired currency to our base currency. So if our base was EUR and we wanted USD this would \n # be how many Euros are in one US dollar.\n adjustment_factor = 1.0 / rates[adjusted_currency]\n adjusted_rates[base_currency] = adjustment_factor\n\n # Now remove it, since we've already done it.\n rates.delete(base_currency)\n\n # Now convert the rest\n rates.each do |currency, rate|\n adjusted_rates[currency] = rate * adjustment_factor\n end\n\n adjusted_rates\n end", "def load_rates\n @rates_data_source.load_rates\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /trust_moneys GET /trust_moneys.json
def index @trust_moneys = TrustMoney.all end
[ "def show\n @trust = Trust.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @trust }\n end\n end", "def new\n @trust = Trust.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @trust }\n end\n end", "def truststore\n RubyAem::Resources::Truststore.new(@client)\n end", "def show\n ## Creating the trust object\n @trust = Trust.find(params[:id])\n\n respond_to do |format|\n format.html { get_collections and render :index }\n format.json { render json: @trust }\n format.js {}\n end\n end", "def index\n @trustees = Trustee.includes(:account_systems).all\n respond_to do |format|\n format.html { render :index }\n format.json { render json: @trustees.to_json(:include => :account_systems) }\n end\n end", "def create\n @trust = Trust.new(params[:trust])\n\n respond_to do |format|\n if @trust.save\n format.html { redirect_to @trust, notice: 'Trust was successfully created.' }\n format.json { render json: @trust, status: :created, location: @trust }\n else\n format.html { render action: \"new\" }\n format.json { render json: @trust.errors, status: :unprocessable_entity }\n end\n end\n end", "def trusts\n return unless owner?\n\n t_uris = []\n doc = xml_document(@server.read(links[:sec_trusts], \"application/xml\",\n @credentials))\n\n xpath_find(doc, @@xpaths[:sec_trust]). each do |t|\n t_uris << URI.parse(xml_node_attribute(t, \"href\"))\n end\n\n t_uris\n end", "def index\n @trust_me_nots = TrustMeNot.all\n end", "def trusts_to(selected_trustee)\n self.trusts.where(:trustee_id => selected_trustee.id)\n end", "def update\n @trust = Trust.find(params[:id])\n\n respond_to do |format|\n if @trust.update_attributes(params[:trust])\n format.html { redirect_to @trust, notice: 'Trust was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @trust.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n ## Intitializing the trust object\n @trust = Trust.new\n\n respond_to do |format|\n format.html { get_collections and render :index }\n format.json { render json: @trust }\n format.js {}\n end\n end", "def physicians\n physicians = User.physicians\n render json: { status: 200, data: physicians }\n end", "def show\n ## Creating the trust admin object\n @trust_admin = TrustAdmin.find(params[:id])\n\n respond_to do |format|\n format.html { get_collections and render :index }\n format.json { render json: @trust_admin }\n format.js {}\n end\n end", "def members\n @profile = current_user.profiles.find(params[:id], :include => :trusts)\n end", "def new\n ## Intitializing the trust admin object\n @trust_admin = TrustAdmin.new\n if params[:trust_id]\n @trust = Trust.find_by_id(params[:trust_id])\n @trust_admin.trust = @trust\n end\n\n respond_to do |format|\n format.html { get_collections and render :index }\n format.json { render json: @trust_admin }\n format.js {}\n end\n end", "def create\n @trust_me_not = TrustMeNot.new(trust_me_not_params)\n\n respond_to do |format|\n if @trust_me_not.save\n format.html { redirect_to @trust_me_not, notice: 'Trust me not was successfully created.' }\n format.json { render :show, status: :created, location: @trust_me_not }\n else\n format.html { render :new }\n format.json { render json: @trust_me_not.errors, status: :unprocessable_entity }\n end\n end\n end", "def check_trust_dbs\n # Setup query\n sql = \"SELECT d.name AS DATABASENAME\n FROM sys.server_principals r\n INNER JOIN sys.server_role_members m ON r.principal_id = m.role_principal_id\n INNER JOIN sys.server_principals p ON\n p.principal_id = m.member_principal_id\n inner join sys.databases d on suser_sname(d.owner_sid) = p.name\n WHERE is_trustworthy_on = 1 AND d.name NOT IN ('MSDB') and r.type = 'R' and r.name = N'sysadmin'\"\n\n result = mssql_query(sql)\n\n # Return on success\n return result[:rows]\n end", "def update\n respond_to do |format|\n if @trust_me_not.update(trust_me_not_params)\n format.html { redirect_to @trust_me_not, notice: 'Trust me not was successfully updated.' }\n format.json { render :show, status: :ok, location: @trust_me_not }\n else\n format.html { render :edit }\n format.json { render json: @trust_me_not.errors, status: :unprocessable_entity }\n end\n end\n end", "def request_trust(trust_url = \"http://#{request.host}/\", *args)\n trust_url = url_for(trust_url.merge(:only_path => false)) if trust_url.kind_of?(Hash)\n javascript_tag \"CCPEVE.requestTrust(#{trust_url.inspect});\", *args\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /trust_moneys/1 DELETE /trust_moneys/1.json
def destroy @trust_money.destroy respond_to do |format| format.html { redirect_to trust_moneys_url, notice: 'Trust money was successfully destroyed.' } format.json { head :no_content } end end
[ "def destroy\n @trust = Trust.find(params[:id])\n @trust.destroy\n\n respond_to do |format|\n format.html { redirect_to trusts_url }\n format.json { head :no_content }\n end\n end", "def destroy\n authorize @trust\n @trust.destroy\n respond_to do |format|\n format.html { redirect_to trusts_entities_path, notice: 'Trust was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete_tenant_circle(args = {}) \n delete(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def delete_guest_access_portal(args = {}) \n delete(\"/guestaccess.json/gap/#{args[:portalId]}\", args)\nend", "def delete_trust(uri)\n return unless owner?\n\n @server.delete(uri, @credentials)\n end", "def delete_mutant(m_id)\n\n request = API_URL + \"mutants/#{m_id}\"\n @response = RestClient.delete request\n log_mutant(\"deleted\")\n return\nend", "def destroy\n name, type = resource[:name].split('/')\n nameserver = resource[:nameserver]\n nsupdate(\"server #{nameserver}\n update delete #{name}. #{type}\n send\")\n end", "def destroy\n @moresmalltrial = Moresmalltrial.find(params[:id])\n @moresmalltrial.destroy\n\n respond_to do |format|\n format.html { redirect_to moresmalltrials_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @trustees_minute.destroy\n respond_to do |format|\n format.html { redirect_to trustees_minutes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n \n keystone.delete_tenant(keystone.get_tenant(params[:id])[:id])\n\n respond_to do |format|\n format.html { redirect_to tenants_url }\n format.json { head :ok }\n end\n end", "def destroy\n delete_obj @keystore.url\n @keystore.destroy\n respond_to do |format|\n format.html { redirect_to keystores_url, notice: 'Keystore was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete_floor_plan(args = {}) \n delete(\"/files.json/floorplan/images\", args)\nend", "def destroy\n @json.destroy\n\n head :no_content\n end", "def destroy\n @trustee.destroy\n respond_to do |format|\n format.html { redirect_to trustees_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @demand.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @capstone.destroy\n respond_to do |format|\n format.html { redirect_to capstones_url, notice: 'Capstone was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete_trust(xml) \n if current_user \n trust_root = xml.root.get_elements('TrustRoot').first.text \n unless trust_root.empty? \n @trust = current_user.trusts.find(:first, :conditions => ['trust_root = ?', trust_root]) \n if @trust \n @trust.destroy \n return render(:text => \"<Response>success</Response>\") \n end \n end \n end \n render :text => '<Response>trust root does not exist</Response>' \n end", "def destroy\n @trust_transaction.destroy\n respond_to do |format|\n format.html { redirect_to trust_transactions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @eq_maintain = EqMaintain.find(params[:id])\n @eq_maintain.destroy\n\n respond_to do |format|\n format.html { redirect_to eq_maintains_url }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /alumni_news_items POST /alumni_news_items.json
def create @alumni_news_item = AlumniNewsItem.new(alumni_news_item_params) respond_to do |format| if @alumni_news_item.save format.html { redirect_to @alumni_news_item, notice: 'Alumni news was successfully created.' } format.json { render action: 'show', status: :created, location: @alumni_news_item } else format.html { render action: 'new' } format.json { render json: @alumni_news_item.errors, status: :unprocessable_entity } end end end
[ "def create\n @newsitem = current_user.newsitems.build(newsitem_params)\n @newsitem.agreed = false\n\n respond_to do |format|\n if @newsitem.save\n format.html { redirect_to @newsitem, notice: 'Newsitem was successfully created. Please wait for the moderators to agree on your item' }\n format.json { render :json => @newsitem.as_json(include: {user: {only: :name}}, methods: [:articlephoto_url_normal, :articlephoto_url_carrousel]), status: :created}\n else\n format.html { render action: \"new\" }\n format.json { render json: @newsitem.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_news_item(org_unit_id, news_item_data, attachments = [])\n # POST /d2l/api/le/(version)/(orgUnitId)/news/\n path = \"/d2l/api/le/#{$le_ver}/#{org_unit_id}/news/\"\n json =\n {\n \"Title\" => \"Placeholder_title\",\n \"Body\" =>\n { # Composite: RichText\n \"Text\" => \"plaintext_text_here\",\n \"HTML\" => nil # OR the HTML_Formatted_version_of_text\n },\n \"StartDate\" => \"UTCDateTime\",\n \"EndDate\" => nil, # nil or UTCDateTime -- e.g. 2017-03-28T18:54:56.000Z\n \"IsGlobal\" => false,\n \"IsPublished\" => false, # sets it as a draft\n \"ShowOnlyInCourseOfferings\" => false\n }.merge!(news_item_data)\n files = attachments\n method = \"POST\"\n ap json\n ap _news_upload(path, json, files, method)\n # RETURNS a NewsItem JSON data block\nend", "def create\n respond_to do |format|\n if @news_item.save\n format.html { redirect_to @news_item, :notice => 'News item was successfully created.' }\n format.json { render :json => @news_item, :status => :created, :location => @news_item }\n else\n format.html { render action: 'new' }\n format.json { render :json => @news_item.errors, :status => :unprocessable_entity }\n end\n end\n end", "def post_data\n rss = RSS::Parser.parse(@news_url, false)\n rss.items.each do |item|\n response = HTTParty.post(\"#{@@base_uri}channels/#{@channel_id}/posts\",\n headers: {\n \"Authorization\" => @@api_key,\n \"Content-Type\" => \"application/json\"\n }, \n body:{\n \"contents\": {\n \"en_US\": {\n \"content\": \"#{item.description}\",\n \"teaser\": \"New Article!!!\",\n \"title\": \"#{item.title}\", \n \"image\": \"#{item.enclosure.url}\"\n }\n }\n }.to_json \n ) \n end\n end", "def create\n @newsitem = Newsitem.new(newsitem_params)\n\n respond_to do |format|\n if @newsitem.save\n format.html { redirect_to @newsitem, notice: 'Newsitem was successfully created.' }\n format.json { render :show, status: :created, location: @newsitem }\n else\n format.html { render :new }\n format.json { render json: @newsitem.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @news_item = NewsItem.new(news_item_params)\n\n respond_to do |format|\n if @news_item.save\n format.html { redirect_to [:admin, @news_item], notice: 'News item was successfully created.' }\n format.json { render :show, status: :created, location: @news_item }\n else\n format.html { render :new }\n format.json { render json: @news_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @stack_overflow_news_item = StackOverflowNewsItem.new(stack_overflow_news_item_params)\n\n respond_to do |format|\n if @stack_overflow_news_item.save\n format.html { redirect_to @stack_overflow_news_item, notice: 'Stack overflow news item was successfully created.' }\n format.json { render :show, status: :created, location: @stack_overflow_news_item }\n else\n format.html { render :new }\n format.json { render json: @stack_overflow_news_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @item = Item.new(item_params)\n\n if @item.save\n render json: @item\n else\n render json: { error: t('story_create_error') }, status: :unprocessable_entity\n end\n end", "def create\n item = list.items.create!(item_params)\n render json: item, status: 201\n end", "def publish_draft_news_item(org_unit_id, news_item_id)\n path = \"/d2l/api/le/#{$le_ver}/#{org_unit_id}/news/#{news_item_id}/publish\"\n _post(path, {})\nend", "def new\n @newsitem = Newsitem.new\n\n @newsitem = current_user.newsitems.build()\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @newsitem }\n end\n end", "def create\n @trending_monthly_news_item = TrendingMonthlyNewsItem.new(trending_monthly_news_item_params)\n\n respond_to do |format|\n if @trending_monthly_news_item.save\n format.html { redirect_to @trending_monthly_news_item, notice: 'Trending monthly news item was successfully created.' }\n format.json { render :show, status: :created, location: @trending_monthly_news_item }\n else\n format.html { render :new }\n format.json { render json: @trending_monthly_news_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_news_feed_item!(attributes = {})\n self.force_news_feed = true\n self.news_feed_item_attributes = attributes\n save!\n end", "def create\n @discourse_news_item = DiscourseNewsItem.new(discourse_news_item_params)\n\n respond_to do |format|\n if @discourse_news_item.save\n format.html { redirect_to @discourse_news_item, notice: 'Discourse news item was successfully created.' }\n format.json { render :show, status: :created, location: @discourse_news_item }\n else\n format.html { render :new }\n format.json { render json: @discourse_news_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @github_news_item = GithubNewsItem.new(github_news_item_params)\n\n respond_to do |format|\n if @github_news_item.save\n format.html { redirect_to @github_news_item, notice: 'Github news item was successfully created.' }\n format.json { render :show, status: :created, location: @github_news_item }\n else\n format.html { render :new }\n format.json { render json: @github_news_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_news_item(org_unit_id, news_item_id, news_item_data)\n # Example of News.NewsItemData JSON Data Block:\n # {\"Title\" => \"string\",\n # \"Body\" => {'Content' => \"content\", \"Type\" => \"type\"} # RichTextInput -- e.g. {'Content'=>'x', 'Type'=>'y'}\n # \"StartDate\": \"<string:UTCDateTime>\",\n # \"EndDate\": \"<string:UTCDateTime>\", # or nil\n # \"IsGlobal\": false,\n # \"IsPublished\": false,\n # \"ShowOnlyInCourseOfferings\": false}\n # PUT /d2l/api/le/(version)/(orgUnitId)/news/(newsItemId)\nend", "def create\n @reddit_news_item = RedditNewsItem.new(reddit_news_item_params)\n\n respond_to do |format|\n if @reddit_news_item.save\n format.html { redirect_to @reddit_news_item, notice: 'Reddit news item was successfully created.' }\n format.json { render :show, status: :created, location: @reddit_news_item }\n else\n format.html { render :new }\n format.json { render json: @reddit_news_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @trending_daily_news_item = TrendingDailyNewsItem.new(trending_daily_news_item_params)\n\n respond_to do |format|\n if @trending_daily_news_item.save\n format.html { redirect_to @trending_daily_news_item, notice: 'Trending daily news item was successfully created.' }\n format.json { render :show, status: :created, location: @trending_daily_news_item }\n else\n format.html { render :new }\n format.json { render json: @trending_daily_news_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.haml\n format.json { render :json => @news_item }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /alumni_news_items/1 PATCH/PUT /alumni_news_items/1.json
def update respond_to do |format| if @alumni_news_item.update(alumni_news_item_params) format.html { redirect_to @alumni_news_item, notice: 'Alumni news was successfully updated.' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @alumni_news_item.errors, status: :unprocessable_entity } end end end
[ "def update\n respond_to do |format|\n if @news_item.update_attributes(params[:news_item])\n format.html { redirect_to @news_item, :notice => 'News item was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: 'edit' }\n format.json { render :json => @news_item.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update_news_item(org_unit_id, news_item_id, news_item_data)\n # Example of News.NewsItemData JSON Data Block:\n # {\"Title\" => \"string\",\n # \"Body\" => {'Content' => \"content\", \"Type\" => \"type\"} # RichTextInput -- e.g. {'Content'=>'x', 'Type'=>'y'}\n # \"StartDate\": \"<string:UTCDateTime>\",\n # \"EndDate\": \"<string:UTCDateTime>\", # or nil\n # \"IsGlobal\": false,\n # \"IsPublished\": false,\n # \"ShowOnlyInCourseOfferings\": false}\n # PUT /d2l/api/le/(version)/(orgUnitId)/news/(newsItemId)\nend", "def update\n respond_to do |format|\n if @news_item.update(news_item_params)\n format.html { redirect_to [:admin, @news_item], notice: 'News item was successfully updated.' }\n format.json { render :show, status: :ok, location: @news_item }\n else\n format.html { render :edit }\n format.json { render json: @news_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @stack_overflow_news_item.update(stack_overflow_news_item_params)\n format.html { redirect_to @stack_overflow_news_item, notice: 'Stack overflow news item was successfully updated.' }\n format.json { render :show, status: :ok, location: @stack_overflow_news_item }\n else\n format.html { render :edit }\n format.json { render json: @stack_overflow_news_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @newsitem.update(newsitem_params)\n format.html { redirect_to @newsitem, notice: 'Newsitem was successfully updated.' }\n format.json { render :show, status: :ok, location: @newsitem }\n else\n format.html { render :edit }\n format.json { render json: @newsitem.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n @news.title = news_params[\"title\"]\n @news.content = news_params[\"content\"]\n @news.user_id = @current_user.id\n if @news.save\n format.html { redirect_to @news, notice: 'News was successfully updated.' }\n format.json { head :no_content }\n end\n end\n end", "def update\n @news = News.find(params[:id])\n pt = params[:news]\n @news.node_id = pt[:node_id]\n @news.title = pt[:title]\n @news.body = pt[:body]\n\n respond_to do |format|\n if @news.update_attributes(params[:news])\n format.html { redirect_to @news, notice: t(\"news.update_news_success\") }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @news.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\n respond_to do |format|\n if @news_item.update_attributes(params[:news_item])\n format.html { redirect_to(news_items_path, :notice => t(\"screens.notice.successfully_updated\")) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @news_item.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n\n #update the item of request_item\n if (params[:request_item].present?)\n @request_item.item = params[:request_item][:item].present? ? Item.new(name: params[:request_item][:item][:name]) : @request_item.item\n end\n #update all other parameters\n if @request_item.update(request_item_params)\n render json: @request_item\n else\n render json: @request_item.errors, status: :bad_request\n end\n\n end", "def update\n respond_to do |format|\n if @github_news_item.update(github_news_item_params)\n format.html { redirect_to @github_news_item, notice: 'Github news item was successfully updated.' }\n format.json { render :show, status: :ok, location: @github_news_item }\n else\n format.html { render :edit }\n format.json { render json: @github_news_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_rest\n @item = Item.find(params[:id])\n\n respond_to do |format|\n if @item.update_attributes(params[:item])\n flash[:notice] = 'Item was successfully updated.'\n format.html { redirect_to(@item) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @item.errors, :status => :unprocessable_entity }\n end\n end\n end", "def _update_item(http, headers, path, body, name)\n resp = retry_request(http, \"PATCH\", path, body, headers)\n if resp.is_a?(Net::HTTPOK)\n Chef::Log.info(\"Updated keystone item '#{name}'\")\n else\n _raise_error(resp, \"Unable to update item '#{name}'\", \"_update_item\")\n end\nend", "def update\n\t\t\t\t@api_v1_todoitem = Todoitem.find(params[:id])\n\n\t\t\t\tif @api_v1_todoitem.update(api_v1_todoitem_params)\n\t\t\t\t\thead :no_content\n\t\t\t\telse\n\t\t\t\t\trender json: @api_v1_todoitem.errors, status: :unprocessable_entity\n\t\t\t\tend\n\t\t\tend", "def update\n respond_to do |format|\n if @discourse_news_item.update(discourse_news_item_params)\n format.html { redirect_to @discourse_news_item, notice: 'Discourse news item was successfully updated.' }\n format.json { render :show, status: :ok, location: @discourse_news_item }\n else\n format.html { render :edit }\n format.json { render json: @discourse_news_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @todo = Todo.find(params[:id])\n @todo.update_attributes(params[:todo])\n render :json => @todo\n end", "def update\n article = Article.find(params[:id])\n article.update(article_params)\n render json: { article: article }\n end", "def update\n @news_item = NewsItem.find(params[:id])\n\n respond_to do |format|\n if @news_item.update_attributes(params[:news_item])\n flash[:notice] = 'News item was successfully updated.'\n format.html { redirect_to(news_path(@news_item)) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @news_item.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n\n if @api_v1_item.update(api_v1_item_params)\n render json: @api_v1_item\n else\n render json: @api_v1_item.errors\n end\n end", "def update\n respond_to do |format|\n if @trending_monthly_news_item.update(trending_monthly_news_item_params)\n format.html { redirect_to @trending_monthly_news_item, notice: 'Trending monthly news item was successfully updated.' }\n format.json { render :show, status: :ok, location: @trending_monthly_news_item }\n else\n format.html { render :edit }\n format.json { render json: @trending_monthly_news_item.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /alumni_news_items/1 DELETE /alumni_news_items/1.json
def destroy @alumni_news_item.destroy respond_to do |format| format.html { redirect_to alumni_news_items_url } format.json { head :no_content } end end
[ "def delete_news_item(org_unit_id, news_item_id)\n path = \"/d2l/api/le/#{$le_ver}/#{org_unit_id}/news/#{news_item_id}\"\n _delete(path)\nend", "def destroy\n @news_item.destroy\n respond_to do |format|\n format.html { redirect_to news_items_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @news_item.destroy\n \n respond_to do |format|\n format.html { redirect_to news_items_url }\n format.json { head :ok }\n end\n end", "def destroy\n @stack_overflow_news_item.destroy\n respond_to do |format|\n format.html { redirect_to stack_overflow_news_items_url, notice: 'Stack overflow news item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @discourse_news_item.destroy\n respond_to do |format|\n format.html { redirect_to discourse_news_items_url, notice: 'Discourse news item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @news_items = NewsItem.find(params[:id])\n @news_items.destroy\n\n respond_to do |format|\n format.html { redirect_to(news_items_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @news_item = NewsItem.find(params[:id])\n @news_item.destroy\n\n respond_to do |format|\n format.html { redirect_to(news_items_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @github_news_item.destroy\n respond_to do |format|\n format.html { redirect_to github_news_items_url, notice: 'Github news item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @iseincnews.destroy\n respond_to do |format|\n format.html { redirect_to iseincnews_index_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @trending_daily_news_item.destroy\n respond_to do |format|\n format.html { redirect_to trending_daily_news_items_url, notice: 'Trending daily news item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @news.destroy\n\n respond_to do |format|\n format.html { redirect_to news_index_url }\n format.json { head :ok }\n end\n end", "def destroy\n @manage_news.destroy\n respond_to do |format|\n format.html { redirect_to manage_news_index_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @news.destroy\n respond_to do |format|\n format.html { redirect_to news_index_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @trending_monthly_news_item.destroy\n respond_to do |format|\n format.html { redirect_to trending_monthly_news_items_url, notice: 'Trending monthly news item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @news.destroy\n respond_to do |format|\n format.html { redirect_to admin_news_index_path }\n format.json { head :no_content }\n end\n end", "def destroy\n @api_v1_item.destroy\n render json: {message: 'deletado com sucesso'}\n end", "def destroy\n @latest_news.destroy\n respond_to do |format|\n format.html { redirect_to latest_news_index_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @admin_useful_news = Admin::UsefulNews.find(params[:id])\n @admin_useful_news.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_useful_news_index_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @trending_weekly_news_item.destroy\n respond_to do |format|\n format.html { redirect_to trending_weekly_news_items_url, notice: 'Trending weekly news item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Callback called after initialization.
def after_initialize end
[ "def post_init\n end", "def callback; end", "def during_after_load; end", "def on_setup_callbacks; end", "def after_generate_callbacks; end", "def postReady()\n\t\t\t#does nothing. extend in subclasses\n\t\tend", "def after_pin_initialization\n end", "def after_initialize\n configuration.after_initialize_block.call if configuration.after_initialize_block\n end", "def on_startup\n end", "def process_init\n end", "def after_initialize\n self.class.after_initialize_hooks.each{ |hook| instance_exec(&hook) }\n end", "def after_initialize_callback\n # The 'self.' bits below are needed, do not remove.\n self.internal = unique_id unless self.internal?\n end", "def post_init(&block)\n @hooks[:post_init] = block\n end", "def preReady()\n\t\t\t#does nothing. extend in subclasses\n\t\tend", "def initialize(callback)\n @callback = callback\n end", "def after_loaded(o={}, &block)\n end", "def before_callback_phase=(_arg0); end", "def after_setting_value_callback; end", "def after_initialize_blocks\n @after_initialize_blocks ||= []\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Callback before begin assertions.
def before_assert end
[ "def before_assert(symbol=nil, &block)\n if block_given?\n @before_assert_callbacks << block\n elsif symbol\n @before_assert_callbacks << symbol\n end\n end", "def before_assert(*symbols, &block)\n if block_given?\n @before_assert_callbacks << block\n else\n @before_assert_callbacks += symbols\n end\n end", "def before_test(test); end", "def assert_callback_before(configuration, task_name, before_task_name, msg = nil)\n msg ||= \"Expected configuration to callback #{task_name.inspect} before #{before_task_name.inspect} but did not\"\n test_callback_on(true, configuration, task_name, :before, before_task_name, msg)\n end", "def setupBeforeTestTest\n assert @setup, 'setup instance method MUST be run before test'\n end", "def precondition(&block)\n SimpleContracts::simple_contract_assert(\"precondition\", &block)\nend", "def before_assert\n @subject = get_instance_of(@subject)\n end", "def before(&blk)\n self.before_block = blk\n end", "def __wrap_assertion &block # :nodoc:\n @@assertions += 1\n yield\n end", "def before(hook=:all, &block)\n setting_callback(hook, \n :all => :@before_callback, \n :each_ruby => :@before_each_ruby_callback, \n :env => :@before_environment_callback, &block)\n end", "def before_setup(&block)\n pre_setup_actions.unshift block\n end", "def preRun\n end", "def super_before(&b)\n @expectation.super_before(&b)\n self\n end", "def before_run(&block)\n @before_run_block = block\n end", "def add_assertion\n @assertion_count += 1\n end", "def before(*args, &block)\n if block_given?\n Thread.current[:before_hook] = block\n else\n Thread.current[:before_hook].call(*args) if Thread.current[:before_hook]\n end\n end", "def pre_execute(&block)\n @hooks[:pre_execute] = block\n end", "def assert(truthy=false)\n unless truthy || (block_given? && yield)\n file, line = caller[0].split(\":\")\n error_message = \"Assertion Failed! < #{file}:#{line}:#{ SCRIPT_LINES__[file][line.to_i - 1][0..-2] rescue ''} >\"\n raise AssertionException.new(error_message)\n end\n end", "def before(&block)\n opts[:before_hook] = if b = opts[:before_hook]\n proc do\n instance_exec(&block)\n instance_exec(&b)\n end\n else\n block\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The list of attributes that are permitted to be used as data attributes in tables and in the tag on show pages.
def html_data_attributes data_attributes = record.class.columns.select do |column| column.type.in?(%i[integer boolean datetime float uuid interval]) && !column.array? end.map(&:name).map(&:to_sym) api_attributes & data_attributes end
[ "def attributes\n attrs = sort_members(@context.attributes).find_all{|a| @options.show_all || a.visibility == :public || a.visibility == :protected}\n attrs.collect{|a| {:name=>a.name, :visibility=>a.visibility, :rw=>a.rw, :description=>markup(a.comment, true)}}\n end", "def attributes\n map(&:attribute)\n end", "def attribute_names; end", "def allowed_sort_attributes\n @scope.attribute_names\n end", "def requested_attributes; end", "def attributes\n @_attributes ||= page.definition.fetch(\"fixed_attributes\", {}).symbolize_keys\n end", "def showable_attributes\n return attributes if permitted_to?(WriteAllPrivilege)\n attributes.reject do |k,v|\n !allowed?(:read, k, true)\n end\n end", "def attributes(*) end", "def vendor_all_attribute_names\n return ATTRIBUTES.values\n end", "def values\n @attrs.values\n end", "def getAttrs\n @attrs\n end", "def to_attr_list\n AttrList.new attributes.keys\n end", "def attribs\n\t\t@attributes\n\tend", "def attributes\n data.require(:attributes)\n end", "def attributes_to_show\n\t\t\tself.class.attribute_names.keep_if{|c| !self.field_names_to_skip_while_making_form.include? c.to_s}\n\t\tend", "def attributes\n @record.attributes.tap do |attributes|\n attributes.keys.each do |key|\n unless @restrictions.allowed_fields[:view].include? key.to_sym\n attributes[key] = nil\n end\n end\n end\n end", "def symbolized_list_attributes\n %w(fact_attributes)\n end", "def accessible_attributes\n read_inheritable_attribute(:attr_accessible) || []\n end", "def predefined_attributes\n @@predefined_attributes ||= []\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Executes a command in the Heroku Toolbelt
def heroku(command) system("GEM_HOME='' BUNDLE_GEMFILE='' GEM_PATH='' RUBYOPT='' /usr/local/heroku/bin/heroku #{command}") end
[ "def heroku(command, options = {}, &block)\n run \"heroku #{command} -a #{app}\", options, &block\n end", "def cmd(app_name, args)\n execute \"heroku #{args} --app #{Shellwords.escape app_name}\"\n end", "def deploy!\n puts \"Adding and committing compiled output for deployment..\"\n puts %x[git add .]\n puts %x[git commit -a -m \"temporary commit for deployment\"]\n puts 'Deploying to Heroku..'\n puts %x[git push heroku HEAD:master --force]\nend", "def scm_run(command, filter = nil)\n deployment.invoke_command(command, filter)\n end", "def rake\n deprecate(\"`heroku #{current_command}` has been deprecated. Please use `heroku run rake` instead.\")\n command = \"rake #{args.join(' ')}\"\n run_attached(command)\n end", "def heroku\n name = shift_argument || options[:app] || ENV['HEROKU_APP']\n validate_arguments!\n no_remote = !options[:no_remote].nil?\n remote = options[:remote]\n remote = \"heroku\" if remote == nil\n addons = options[:addons]\n password = options[:password]\n password = newpass if password == nil\n info = api.post_app({\n \"name\" => name,\n \"stack\" => \"cedar\"\n }).body\n begin\n action(\"Creating #{info['name']}\") do\n if info['create_status'] == 'creating'\n Timeout::timeout(options[:timeout].to_i) do\n loop do\n break if api.get_app(info['name']).body['create_status'] == 'complete'\n sleep 1\n end\n end\n end\n if info['region']\n status(\"region is #{info['region']}\")\n else\n status(\"stack is #{info['stack']}\")\n end\n end\n \n (addons || \"\").split(\",\").each do |addon|\n addon.strip!\n action(\"Adding #{addon} to #{info[\"name\"]}\") do\n api.post_addon(info[\"name\"], addon)\n end\n end\n\n api.put_config_vars(info[\"name\"], \"BUILDPACK_URL\" => \"http://github.com/heathprovost/openbd-heroku.git\")\n api.put_config_vars(info[\"name\"], \"OPENBD_PASSWORD\" => password)\n hputs([ info[\"web_url\"], info[\"git_url\"] ].join(\" | \"))\n \n rescue Timeout::Error\n \n hputs(\"Timed Out! Run `heroku status` to check for known platform issues.\")\n \n end\n\n unless no_remote\n create_git_remote(remote, info[\"git_url\"])\n end\n\n feature = api.get_features.body.detect { |f| f[\"name\"] == \"user-env-compile\" }\n throw \"Heroku labs feature \\\"user-env-compile\\\" is not available\" unless feature\n api.post_feature(\"user-env-compile\", info['name'])\n\n end", "def cli_command(command)\n do_action({:action => :command, :command => command})\n end", "def execute(command)\n Softcover.test? ? system(command) : exec(command)\n end", "def thor(command, *args); end", "def run_app(command, arguments)\nend", "def exec(command_name, args)\n puts \"You called \" + command_name + \" with args: \" + args.inspect\n end", "def git(command)\n run \"cd #{deploy_to} && umask 002 && sg #{application_group} -c \\\"git #{command}\\\"\"\n end", "def run_locally(cmd)\n logger.trace \"executing locally: #{cmd.inspect}\" if logger\n `#{cmd}`\nend", "def run(release, command)\n ENV['RBENV_VERSION'] = release\n shims = \"#{RBenv.root}/shims\"\n unless ENV['PATH'].split(':').first == shims\n ENV['PATH'] = \"#{shims}:#{ENV['PATH']}\"\n end\n command = command.join(\"\\n\") if command.respond_to? :join\n command.lines.each do |line|\n system line.chomp\n end\n end", "def exec(command)\n environment.exec(command)\n end", "def run_command(command)\n %x(#{@python} -c '#{command}').chomp if @python\n end", "def remote\n Heroku::JSPlugin.install('heroku-git')\n Heroku::JSPlugin.run('git', 'remote', ARGV[1..-1])\n end", "def execute\n parse_command\n run_command(command)\n end", "def perform(server, username, app_path, command, environment, app_name, channel, config)\n slack_message(config, \"#{app_name} : Deploying #{environment} environment to #{server}.\", channel)\n cmd = \"ssh #{username}@#{server} 'cd -- #{app_path} && #{command.gsub('{environment}', environment)}'\"\n o, s = Open3.capture2e(cmd)\n gist = post_gist(config, app_name, o)\n status_message = set_deploy_status(o, s)\n status_text = \"#{app_name} : #{status_message} See gist for logs: #{gist['html_url']}\"\n slack_message(config, status_text, channel)\n puts \"Deployed #{app_name} to #{s}, command=#{cmd}, gist=#{gist['html_url']}, result: output=#{o}, status=#{s}\"\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /flickr_accounts GET /flickr_accounts.json
def index @flickr_accounts = FlickrAccount.all end
[ "def index\n @accounts = current_user.person.facebook_accounts\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @accounts }\n end\n end", "def social_accounts_for_a_project\n uri = \"#{@api_url}/#{@project_id}/accounts?access_token=#{@access_token}\"\n get uri\n end", "def get_account\n as_json(get_results('/account'))\n end", "def index\n @accounts = current_user.person.twitter_accounts\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @accounts }\n end\n end", "def index\n @accounts = current_user.person.blackberry_accounts\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @accounts }\n end\n end", "def accounts\n get_collection 'accounts', :class => Buxfer::Account\n end", "def list\n token = SocialService::Facebook.renew_token(token_params)\n\n accounts =\n SocialService::Facebook\n .accounts(token)\n .reject { |a| a[:id].in?(facebook_account_ids) }\n\n render json: { accounts: accounts }\n end", "def get_folio_data\n netid = params['netid']\n url = ENV['OKAPI_URL']\n tenant = ENV['OKAPI_TENANT']\n account = CUL::FOLIO::Edge.patron_account(url, tenant, folio_token, { username: netid })\n # Rails.logger.debug(\"mjc12test: Got FOLIO account #{account.inspect}\")\n render json: account\n end", "def show\n @account = current_user.person.facebook_accounts.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @account }\n end\n end", "def index\n @accounts = current_user.person.gmail_accounts\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @accounts }\n end\n end", "def url(perms = :read, options = {})\n options.merge!(:api_key => @flickr.api_key, :perms => perms, :frob => self.frob)\n @flickr.sign_request(options)\n Flickr::Base::AUTH_ENDPOINT + \"?\" + options.collect{|k,v| \"#{k}=#{CGI.escape(v.to_s)}\"}.join('&')\n end", "def accounts\n make_promise(@core.web3.JS[:personal], 'getListAccounts')\n end", "def get_flickr_pics (photoset)\n\n api_key = '0dd1537c46575cf8b7b2a2df94156fd9'\n method = 'flickr.photosets.getPhotos'\n format = 'json'\n\n #for testing\n user_id = '128529405@N05'\n photoset_id = '72157648179656437' #ladder pics\n\n base_url = 'https://api.flickr.com/services/rest/'\n\n response = RestClient.get base_url, {\n :params => {\n 'api_key' => api_key,\n 'photoset_id' => photoset,\n 'method' => method,\n 'format' => format,\n 'nojsoncallback' => 1,\n 'extras' => 'original_format'\n }\n }\n\n return response\n\n end", "def flickr_url\n get_url(:flickr)\n end", "def portfolio_accounts\n data = call_api(method: \"get\", url: \"/portfolio/accounts\" )\n @accountId = data.first[\"accountId\"]\n @accountId\n end", "def index\n @accounts = current_user.person.linked_in_accounts\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @accounts }\n end\n end", "def getAllAccounts(type)\n\turl = \"http://api.reimaginebanking.com:80/accounts?type=#{type}&key=#{APIkey}\"\n\tresp = Net::HTTP.get_response(URI.parse(url))\n\tdata = resp.body\n\tputs(data)\nend", "def login_url(perms)\n \"https://flickr.com/services/auth/?api_key=#{@api_key}&perms=#{perms}&api_sig=#{signature_from('api_key'=>@api_key, 'perms' => perms)}\"\n end", "def flickrAuthentication\n if not session[:username]\n render :text => \"Error, failed to authenticate user!\", :status => 401\n return\n end\n \n @user = User.find_by_username(session[:username])\n\n if @user == nil\n render :text => \"Error, failed to find user!\", :status => 401\n return\n end\n\n\n @receivedToken = false\n \n if params[:frob] && params[:frob] != \"\"\n\n frob = params[:frob]\n method = \"flickr.auth.getToken\"\n \n api_sig = Digest::MD5.hexdigest(\"#{@@flickr_secret}api_key#{@@flickr_api_key}frob#{frob}method#{method}\")\n\n flickr_url = \"http://api.flickr.com\"\n flickr_params = \"/services/rest?api_key=#{@@flickr_api_key}&api_sig=#{api_sig}&method=#{method}&frob=#{frob}\"\n \n begin\n url = URI.parse(flickr_url)\n res = Net::HTTP.start(url.host, url.port) {|http|\n http.get(flickr_params)\n }\n xml = res.body\n doc = XML::Document.string(xml) \n \n token = doc.find_first('//auth/token').content\n nsid = doc.find_first('//auth/user')['nsid']\n flickr_username = doc.find_first('//auth/user')['username']\n \n if token != nil && nsid != nil && flickr_username != nil\n puts \"Token: #{token}\"\n puts \"NSID: #{nsid}\"\n puts \"Username: #{flickr_username}\"\n @receivedToken = true\n flickr_data = ServiceInformation.find_or_create_by_user_id_and_service_type(@user.id, \"flickr\")\n flickr_data.update_attribute(:s_token, token)\n flickr_data.update_attribute(:s_id, nsid)\n flickr_data.update_attribute(:s_username, flickr_username)\n end\n rescue => e\n putsE(e)\n end \n \n end\n \n \n \n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /flickr_accounts POST /flickr_accounts.json
def create @flickr_account = FlickrAccount.new(flickr_account_params) if @flickr_account.save redirect_to flickr_accounts_path else render :new end # respond_to do |format| # if @flickr_account.save # format.html { redirect_to @flickr_account, notice: 'Flickr account was successfully created.' } # format.json { render :show, status: :created, location: @flickr_account } # else # format.html { render :new } # format.json { render json: @flickr_account.errors, status: :unprocessable_entity } # end # end end
[ "def add_social_account(social_account = {}); JSON[Api::post_social_accounts(social_account, self)]; end", "def create\n @account = current_user.accounts.new(account_params)\n\n if @account.save\n render json: @account, status: :created, location: @account\n else\n render json: @account.errors, status: :unprocessable_entity\n end\n end", "def index\n @flickr_accounts = FlickrAccount.all\n end", "def create\n @oauth_account = OauthAccount.new(oauth_account_params)\n\n respond_to do |format|\n if @oauth_account.save\n format.html { redirect_to login_oauth_accounts_url(redirect_uri: params[:redirect_uri]) }\n format.json { render :show, status: :created, location: @oauth_account }\n else\n format.html { render :new }\n format.json { render json: @oauth_account.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @flickr_photo = FlickrPhoto.new(flickr_photo_params)\n\n respond_to do |format|\n if @flickr_photo.save\n format.html { redirect_to @flickr_photo, notice: 'Flickr photo was successfully created.' }\n format.json { render action: 'show', status: :created, location: @flickr_photo }\n else\n format.html { render action: 'new' }\n format.json { render json: @flickr_photo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @account = BlackberryAccount.new(params[:blackberry_account])\n current_user.person.blackberry_accounts << @account\n\n respond_to do |format|\n if @account.save\n format.html { redirect_to( accounts_path, :notice => 'Account was successfully created.') }\n format.json { render :json => @account, :status => :created, :location => @account }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @account.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @flickr_user = FlickrUser.new(params[:flickr_user])\n if @flickr_user.populate\n redirect_to flickr_user_photosets_url(@flickr_user)\n else\n flash[:notice] = \"User not found\"\n redirect_to :controller => :home\n end\n end", "def login_url(perms)\n \"https://flickr.com/services/auth/?api_key=#{@api_key}&perms=#{perms}&api_sig=#{signature_from('api_key'=>@api_key, 'perms' => perms)}\"\n end", "def create\n @spotify_account = SpotifyAccount.new(spotify_account_params)\n\n respond_to do |format|\n if @spotify_account.save\n format.html { redirect_to @spotify_account, notice: 'Spotify account was successfully created.' }\n format.json { render :show, status: :created, location: @spotify_account }\n else\n format.html { render :new }\n format.json { render json: @spotify_account.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\n @twitter_account = TwitterAccount.new(params[\"twitter_account\"])\n\n success = @twitter_account.save\n\n respond_to do |format|\n if success\n format.html { redirect_to twitter_accounts_url }\n format.json { render json: @twitter_account, status: :created, location: @twitter_account }\n else\n format.html { render action: \"new\" }\n format.json { render json: @twitter_account.errors, status: :unprocessable_entity }\n end\n end\n end", "def flickrAuthentication\n if not session[:username]\n render :text => \"Error, failed to authenticate user!\", :status => 401\n return\n end\n \n @user = User.find_by_username(session[:username])\n\n if @user == nil\n render :text => \"Error, failed to find user!\", :status => 401\n return\n end\n\n\n @receivedToken = false\n \n if params[:frob] && params[:frob] != \"\"\n\n frob = params[:frob]\n method = \"flickr.auth.getToken\"\n \n api_sig = Digest::MD5.hexdigest(\"#{@@flickr_secret}api_key#{@@flickr_api_key}frob#{frob}method#{method}\")\n\n flickr_url = \"http://api.flickr.com\"\n flickr_params = \"/services/rest?api_key=#{@@flickr_api_key}&api_sig=#{api_sig}&method=#{method}&frob=#{frob}\"\n \n begin\n url = URI.parse(flickr_url)\n res = Net::HTTP.start(url.host, url.port) {|http|\n http.get(flickr_params)\n }\n xml = res.body\n doc = XML::Document.string(xml) \n \n token = doc.find_first('//auth/token').content\n nsid = doc.find_first('//auth/user')['nsid']\n flickr_username = doc.find_first('//auth/user')['username']\n \n if token != nil && nsid != nil && flickr_username != nil\n puts \"Token: #{token}\"\n puts \"NSID: #{nsid}\"\n puts \"Username: #{flickr_username}\"\n @receivedToken = true\n flickr_data = ServiceInformation.find_or_create_by_user_id_and_service_type(@user.id, \"flickr\")\n flickr_data.update_attribute(:s_token, token)\n flickr_data.update_attribute(:s_id, nsid)\n flickr_data.update_attribute(:s_username, flickr_username)\n end\n rescue => e\n putsE(e)\n end \n \n end\n \n \n \n end", "def create_account(opts)\n HelloSign::Resource::Account.new post('/account/create', :body => opts)\n end", "def create\n @account = YahooAccount.new(params[:yahoo_account])\n current_user.person.yahoo_accounts << @account\n\n respond_to do |format|\n if @account.save\n format.html { redirect_to( accounts_path, :notice => 'Account was successfully created.') }\n format.json { render :json => @account, :status => :created, :location => @account }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @account.errors, :status => :unprocessable_entity }\n end\n end\n end", "def add_accounttttttttttttttttttttttttttt\n\n res = {\n :success => false,\n :msg => '',\n :data => []\n }\n\n begin\n params[\"account\"][:company_id] = params[:id]\n account = Account.create(params[\"account\"])\n\n res[:msg] = 'Created new company account'\n res[:data] = {:account => {:id => account.id, :name => account.first.capitalize + ' ' + account.last.capitalize}}\n res[:success] = true\n rescue AccountCreateError => e\n res[:msg] = e.errors[0]\n res[:data][:errors] = e.errors[1]\n end\n\n render :json => res.to_json, :layout => false\n end", "def create_albums\n url = 'https://stg-resque.hakuapp.com/albums.json'\n uri = URI(url)\n response = Net::HTTP.get(uri)\n albums = JSON.parse(response)\n\n albums.each do |album|\n Album.create!(album.except('id'))\n end\nend", "def create_account(options)\n form_data = options.merge({ 'action' => 'createaccount' })\n res, dummy = make_api_request(form_data)\n res\n end", "def user_account_data\n \n render :json => {\n :csrf => form_authenticity_token,\n :burntAfter => Time.now + 30.days, # Current recommended max life\n :canPost => user_signed_in?,\n :signedIn => user_signed_in?\n }, \n :callback => params[:callback]\n end", "def add_favorite username, password, slideshow_id\n do_request 'add_favorite', username: username, password: password, slideshow_id: slideshow_id\n end", "def create\n @account = PhoneAccount.new(params[:phone_account])\n current_user.person.phone_accounts << @account\n\n respond_to do |format|\n if @account.save\n format.html { redirect_to( accounts_path, :notice => 'Account was successfully created.') }\n format.json { render :json => @account, :status => :created, :location => @account }\n else\n format.html { render :action => 'new' }\n format.json { render :json => @account.errors, :status => :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /flickr_accounts/1 PATCH/PUT /flickr_accounts/1.json
def update # respond_to do |format| # if @flickr_account.update(flickr_account_params) # format.html { redirect_to @flickr_account, notice: 'Flickr account was successfully updated.' } # format.json { render :show, status: :ok, location: @flickr_account } # else # format.html { render :edit } # format.json { render json: @flickr_account.errors, status: :unprocessable_entity } # end # end end
[ "def update\n respond_to do |format|\n if @flickr_photo.update(flickr_photo_params)\n format.html { redirect_to @flickr_photo, notice: 'Flickr photo was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @flickr_photo.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @flickr_photo = FlickrPhoto.find(params[:id])\n\n respond_to do |format|\n if @flickr_photo.update_attributes(params[:flickr_photo])\n format.html { redirect_to(@flickr_photo, :notice => 'FlickrPhoto was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @flickr_photo.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update_tenant_circle(args = {}) \n put(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def update *_\n @future = users_futures.find(params[:id])\n\n if @future.update_attributes(params[:future])\n render json: @future\n else\n render json: @future.errors, status: :unprocessable_entity\n end\n end", "def favorite\n url = Addressable::URI.new(\n scheme: 'http',\n host: 'localhost',\n port: 3000,\n path: '/contacts/2/favorite'\n ).to_s\n\n puts RestClient.patch(\n url,{}\n )\nend", "def update \n begin\n @resource = Account.find(params[:id])\n @resource.update_attributes!(params[:account])\n render :response => :PUT\n rescue Exception => e\n @error = process_exception(e)\n render :response => :error\n end\n end", "def update_current_logged_in_users_password(args = {}) \n put(\"/users.json/current/password\", args)\nend", "def put\n request_method('PUT')\n end", "def update\n spice = Spice.find_by(id: params[:id])\n spice.update(spice_params)\n render json: spice\nend", "def update\n \n if @api_v1_person.update(api_v1_person_params) \n render json: @api_v1_person\n else\n render json: @api_v1_person.errors, status: 400\n end\n \n end", "def update\n json_update(factType,factType_params, FactType)\n end", "def update\n account = current_organization.accounts.find(params[:id])\n return forbidden unless account && current_account.allowed_to_edit_account?(account, current_organization)\n return json(account) unless account.update_attributes pick(params, :first_name, :last_name, :email,:language, :document_language)\n\n role = pick(params, :role)\n #account.update_attributes(role) if !role.empty? && current_account.admin?\n membership = current_organization.role_of(account)\n membership.update_attributes(role) if !role.empty? && current_account.admin?\n password = pick(params, :password)[:password]\n if (current_account.id == account.id) && password\n account.update(password: password)\n end\n json account.canonical(membership: membership)\n end", "def update\n @account = current_user.accounts.find(params[:id])\n\n if @account.update(account_params)\n head :no_content\n else\n render json: @account.errors, status: :unprocessable_entity\n end\n end", "def update(info)\n\t\tresponse = @client.put(\n\t\t\t@session[\"resources\"][\"account\"][\"url\"],\n\t\t\t:body => info.to_json,\n\t\t\t:headers => {\n\t\t\t\t\"Accept\" => mediaType(\"account\"),\"Content-Type\" => mediaType(\"account\"),\n\t\t\t\t\"Authorization\" => \"Capability #{@session[\"resources\"][\"account\"][\"capability\"]}\"\t\n\t\t\t})\n\t\traise \"Error attempting to update account: (#{response.status}) #{response.body}\" if response.status != 200\n\t\t@session[\"resources\"][\"account\"] = JSON.parse(response.body)\n\t\tself\n\tend", "def update\n uri = \"#{API_BASE_URL}/products/#{params[:id]}\"\n payload = params.to_json\n rest_resource = RestClient::Resource.new(uri, USERNAME, PASSWORD)\n begin\n rest_resource.put payload , :content_type => \"application/json\"\n flash[:notice] = \"Product Updated successfully\"\n rescue Exception => e\n flash[:error] = \"Product Failed to Update\"\n end\n redirect_to users_path\n\n end", "def update\n respond_to do |format|\n if @spotify_account.update(spotify_account_params)\n format.html { redirect_to @spotify_account, notice: 'Spotify account was successfully updated.' }\n format.json { render :show, status: :ok, location: @spotify_account }\n else\n format.html { render :edit }\n format.json { render json: @spotify_account.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @oauth_account.update(oauth_account_params)\n format.html { redirect_to @oauth_account, notice: 'Oauth account was successfully updated.' }\n format.json { render :show, status: :ok, location: @oauth_account }\n else\n format.html { render :edit }\n format.json { render json: @oauth_account.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @user = User.find(params[:id])\n @user.name = params[:name]\n @user.email = params[:email]\n @user.password = params[:password]\n @user.photo = params[:photo]\n @user.role = params[:type]\n @user.save\n render json:@user\n end", "def patch(data, options={})\n raise NotImplementedError, \"We only patchs to singular resources.\" if count > 1\n first.patch(data, options)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /flickr_accounts/1 DELETE /flickr_accounts/1.json
def destroy # @flickr_account.destroy # respond_to do |format| # format.html { redirect_to flickr_accounts_url, notice: 'Flickr account was successfully destroyed.' } # format.json { head :no_content } # end end
[ "def destroy\n @flickr_photo.destroy\n respond_to do |format|\n format.html { redirect_to flickr_photos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @flickr_photo = FlickrPhoto.find(params[:id])\n @flickr_photo.destroy\n\n respond_to do |format|\n format.html { redirect_to(flickr_photos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @account = current_user.person.facebook_accounts.find(params[:id])\n @account.destroy\n\n respond_to do |format|\n format.html { redirect_to accounts_path }\n format.json { head :ok }\n end\n end", "def unlink_flickr_account\n if @user.flickr_identity\n @user.flickr_identity.destroy\n flash[:notice] = \"We've dissassociated your Flickr account from your NatureWatch NZ account.\"\n redirect_to :action => 'options'\n else\n flash[:notice] = \"Your Flickr account has not been linked before!\"\n redirect_to :action => 'options'\n end\n end", "def delete photo_id\n @flickr.photos.delete(photo_id: photo_id)\n end", "def unlink_flickr_account\n if current_user.flickr_identity\n current_user.flickr_identity.destroy\n flash[:notice] = \"We've dissassociated your Flickr account from your #{@site.name} account.\"\n redirect_to :action => 'options'\n else\n flash[:notice] = \"Your Flickr account has not been linked before!\"\n redirect_to :action => 'options'\n end\n end", "def destroy\n @flickr_search = FlickrSearch.find(params[:id])\n @flickr_search.destroy\n\n respond_to do |format|\n format.html { redirect_to(flickr_searches_url) }\n format.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 account_photos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @oauth.destroy\n respond_to do |format|\n format.html { redirect_to oauths_url }\n format.json { head :no_content }\n end\n end", "def destroy\n if @api_v1_person.destroy\n render json: 'deletado'\n end\n \n end", "def destroy\n @account_album = Account::Album.find(params[:id])\n @account_album.destroy\n\n respond_to do |format|\n format.html { redirect_to account_albums_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @oauth_account.destroy\n respond_to do |format|\n format.html { redirect_to oauth_accounts_url, notice: 'Oauth account was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @fotosresposta = Fotosresposta.find(params[:id])\n @fotosresposta.destroy\n\n respond_to do |format|\n format.html { redirect_to fotosresposta_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @spotify_account.destroy\n respond_to do |format|\n format.html { redirect_to spotify_accounts_url, notice: 'Spotify account was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @flick.destroy\n respond_to do |format|\n format.html { redirect_to flicks_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @account = current_user.person.twitter_accounts.find(params[:id])\n @account.destroy\n\n respond_to do |format|\n format.html { redirect_to accounts_path }\n format.json { head :ok }\n end\n end", "def destroy\n @auth_person = Auth::Person.find(params[:id])\n @auth_person.destroy\n\n respond_to do |format|\n format.html { redirect_to auth_people_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @fotos_in.destroy\n respond_to do |format|\n format.html { redirect_to fotos_ins_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @account = current_user.person.gmail_accounts.find(params[:id])\n @account.destroy\n\n respond_to do |format|\n format.html { redirect_to accounts_path }\n format.json { head :ok }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a special version of popen which captures stdout, stdin and stdout and the PID of the executing process
def custom_popen(*cmd) pw = IO::pipe # pipe[0] for read, pipe[1] for write pr = IO::pipe pe = IO::pipe pid_pipe = IO::pipe # pipe for communicating the process id of the started process executing_proc_pid = nil pid = fork{ # child executing_proc_pid = fork{ # grandchild pw[1].close STDIN.reopen(pw[0]) pw[0].close pr[0].close STDOUT.reopen(pr[1]) pr[1].close pe[0].close STDERR.reopen(pe[1]) pe[1].close exec(*cmd) } pid_pipe[1].write(executing_proc_pid.to_s + "\n") pid_pipe[1].close exit!(0) } pw[0].close pr[1].close pe[1].close executing_proc_pid = pid_pipe[0].gets.to_i puts "from pipe: executing_proc_pid=#{executing_proc_pid}" pid_pipe[0].close Process.waitpid(pid) pi = [pw[1], pr[0], pe[0], executing_proc_pid] pw[1].sync = true if defined? yield begin return yield(*pi) ensure pi.each{|p| p.close unless p.closed?} end end pi end
[ "def to_stdout_from_any_process; end", "def spawn_process(command_line)\n host_stdout, cmd_stdout = IO.pipe\n host_stderr, cmd_stderr = IO.pipe\n\n pid = Process.spawn(command_line.command_environment, command_line.command, :out => cmd_stdout, :err => cmd_stderr)\n cmd_stdout.close\n cmd_stderr.close\n\n return pid, host_stdout, host_stderr\n end", "def subprocess\n\tif not pid = Process.fork\n\t\tyield\n\t\texit!\n\tend\n\tpid\nend", "def popen_command(*args)\n cmd = command_str(*args)\n IO.popen(\"#{cmd} 2>&1\", \"r\")\n end", "def popen4(*argv)\n # create some pipes (see pipe(2) manual -- the ruby docs suck)\n ird, iwr = IO.pipe\n ord, owr = IO.pipe\n erd, ewr = IO.pipe\n\n # spawn the child process with either end of pipes hooked together\n opts =\n ((argv.pop if argv[-1].is_a?(Hash)) || {}).merge(\n # redirect fds # close other sides\n :in => ird, iwr => :close,\n :out => owr, ord => :close,\n :err => ewr, erd => :close\n )\n pid = spawn(*(argv + [opts]))\n\n [pid, iwr, ord, erd]\n ensure\n # we're in the parent, close child-side fds\n [ird, owr, ewr].each { |fd| fd.close if fd }\n end", "def popen4(*argv)\n # create some pipes (see pipe(2) manual -- the ruby docs suck)\n ird, iwr = IO.pipe\n ord, owr = IO.pipe\n erd, ewr = IO.pipe\n\n # spawn the child process with either end of pipes hooked together\n opts =\n ((argv.pop if argv[-1].is_a?(Hash)) || {}).merge(\n # redirect fds # close other sides\n :in => ird, iwr => :close,\n :out => owr, ord => :close,\n :err => ewr, erd => :close\n )\n pid = spawn(*(argv + [opts]))\n\n [pid, iwr, ord, erd]\n ensure\n # we're in the parent, close child-side fds\n [ird, owr, ewr].each { |fd| fd.close }\n end", "def run_shell(cmd)\n cmd_result = {\"stdout\" => \"\",\"stderr\" => \"\", \"pid\" => \"\"}\n begin\n status = IO.popen4(cmd) do |pid, stdin, stdout, stderr|\n stdin.close\n [\n Thread.new(stdout) {|stdout_io|\n stdout_io.each_line do |l|\n cmd_result[\"stdout\"] += l\n end\n stdout_io.close\n },\n \n Thread.new(stderr) {|stderr_io|\n stderr_io.each_line do |l|\n cmd_result[\"stderr\"] += l\n end\n }\n ].each( &:join )\n cmd_result[\"pid\"] = pid\n end\n rescue Exception => e\n cmd_result[\"stderr\"] += \"#{e.message}\\n#{e.backtrace}\"\n end\n cmd_result\n end", "def popen2(bin)\n in_r, in_w = IO.pipe\n out_r, out_w = IO.pipe\n pid = Process.spawn(bin, in: in_r, out: out_w)\n begin\n yield(in_w, out_r, pid)\n ensure\n Process.wait(pid)\n end\n end", "def capture_subprocess_io\n _synchronize do\n begin\n require \"tempfile\"\n\n captured_stdout, captured_stderr = Tempfile.new(\"out\"), Tempfile.new(\"err\")\n\n orig_stdout, orig_stderr = $stdout.dup, $stderr.dup\n $stdout.reopen captured_stdout\n $stderr.reopen captured_stderr\n\n yield\n\n $stdout.rewind\n $stderr.rewind\n\n return captured_stdout.read, captured_stderr.read\n ensure\n $stdout.reopen orig_stdout\n $stderr.reopen orig_stderr\n\n orig_stdout.close\n orig_stderr.close\n captured_stdout.close!\n captured_stderr.close!\n end\n end\n end", "def get_from_shell_cmd(cmd, proc_id)\n stdout, stderr, status = Open3.capture3(cmd)\n if not status.success?\n cancel_job(\"error executing command '#{cmd}' - #{stderr}\", proc_id)\n end\n return stdout.strip!\nend", "def spawn_process(args = nil)\n #Used for printing debug-stuff.\n @main = true\n\n if args && args[:exec]\n cmd = \"#{args[:exec]}\"\n else\n if RbConfig::CONFIG[\"bindir\"]\n cmd = \"#{RbConfig::CONFIG[\"bindir\"]}/ruby\"\n else\n cmd = \"ruby\"\n end\n end\n\n cmd << \" \\\"#{File.realpath(File.dirname(__FILE__))}/../scripts/ruby_process_script.rb\\\" --pid=#{@my_pid}\"\n cmd << \" --debug\" if @args[:debug]\n cmd << \" \\\"--title=#{@args[:title]}\\\"\" unless @args[:title].to_s.strip.empty?\n\n #Start process and set IO variables.\n require \"open3\"\n @io_out, @io_in, @io_err = Open3.popen3(cmd)\n @io_out = Tsafe::Proxy.new(obj: @io_out)\n @io_out.sync = true\n @io_in.sync = true\n @io_err.sync = true\n\n started = false\n @io_in.each_line do |str|\n if str == \"ruby_process_started\\n\"\n started = true\n break\n end\n\n debug \"Ruby-process-debug from stdout before started: '#{str}'\\n\" if @debug\n end\n\n raise \"Ruby-sub-process couldnt start: '#{@io_err.read}'.\" unless started\n self.listen\n\n #Start by getting the PID of the process.\n begin\n @pid = self.static(:Process, :pid).__rp_marshal\n raise \"Unexpected PID: '#{@pid}'.\" if !@pid.is_a?(Fixnum) && !@pid.is_a?(Integer)\n rescue => e\n self.destroy\n raise e\n end\n\n if block_given?\n begin\n yield(self)\n ensure\n self.destroy\n end\n\n return self\n else\n return self\n end\n end", "def right_popen(command, stdin, &block)\n\n RightScale.popen3(\n :command => command,\n :target => RightTarget.new(block),\n :stdout_handler => :on_out,\n :stderr_handler => :on_err,\n :exit_handler => :on_exit,\n :input => stdin)\n end", "def do_fork(arg)\n r, w = IO.pipe\n pid = Process.spawn(arg, out: w)\n Process.detach pid\n puts 'spawned process under pid: ' + pid.to_s\n w.close\n r.close\n false\n end", "def spawn(cmd, target)\n super(cmd, target)\n\n # garbage collect any open file descriptors from past executions before\n # forking to prevent them being inherited. also reduces memory footprint\n # since forking will duplicate everything in memory for child process.\n ::GC.start\n\n # create pipes.\n stdin_r, stdin_w = IO.pipe\n stdout_r, stdout_w = IO.pipe\n stderr_r, stderr_w = IO.pipe\n status_r, status_w = IO.pipe\n\n [stdin_r, stdin_w, stdout_r, stdout_w,\n stderr_r, stderr_w, status_r, status_w].each {|fdes| fdes.sync = true}\n\n @pid = ::Kernel::fork do\n begin\n stdin_w.close\n ::STDIN.reopen stdin_r\n\n stdout_r.close\n ::STDOUT.reopen stdout_w\n\n stderr_r.close\n ::STDERR.reopen stderr_w\n\n status_r.close\n status_w.fcntl(::Fcntl::F_SETFD, ::Fcntl::FD_CLOEXEC)\n\n unless @options[:inherit_io]\n ::ObjectSpace.each_object(IO) do |io|\n if ![::STDIN, ::STDOUT, ::STDERR, status_w].include?(io)\n # be careful to not allow streams in a bad state from the\n # parent process to prevent child process running.\n (io.close rescue nil) unless (io.closed? rescue true)\n end\n end\n end\n\n if group = get_group\n ::Process.egid = group\n ::Process.gid = group\n end\n\n if user = get_user\n ::Process.euid = user\n ::Process.uid = user\n end\n\n if umask = get_umask\n ::File.umask(umask)\n end\n\n # avoid chdir when pwd is already correct due to asinine printed\n # warning from chdir block for what is basically a no-op.\n working_directory = @options[:directory]\n if working_directory &&\n ::File.expand_path(working_directory) != ::File.expand_path(::Dir.pwd)\n ::Dir.chdir(working_directory)\n end\n\n environment_hash = {}\n environment_hash['LC_ALL'] = 'C' if @options[:locale]\n environment_hash.merge!(@options[:environment]) if @options[:environment]\n environment_hash.each do |key, value|\n ::ENV[key.to_s] = value.nil? ? nil: value.to_s\n end\n\n if cmd.kind_of?(Array)\n cmd = cmd.map { |c| c.to_s } #exec only likes string arguments\n exec(*cmd)\n else\n exec('sh', '-c', cmd.to_s) # allows shell commands for cmd string\n end\n raise 'Unreachable code'\n rescue ::Exception => e\n # note that Marshal.dump/load isn't reliable for all kinds of\n # exceptions or else can be truncated by I/O buffering.\n error_data = {\n 'class' => e.class.name,\n 'message' => e.message,\n 'backtrace' => e.backtrace\n }\n status_w.puts(::YAML.dump(error_data))\n end\n status_w.close\n exit!\n end\n\n stdin_r.close\n stdout_w.close\n stderr_w.close\n status_w.close\n @stdin = stdin_w\n @stdout = stdout_r\n @stderr = stderr_r\n @status_fd = status_r\n start_timer\n true\n rescue\n # catch-all for failure to spawn process ensuring a non-nil status. the\n # PID most likely is nil but the exit handler can be invoked for async.\n safe_close_io\n @status = ::RightScale::RightPopen::ProcessStatus.new(@pid, 1)\n raise\n end", "def run(*args)\n stdin, stdout, stderr, process = Open3.popen3(*args)\n out = stdout.read.strip\n err = stderr.read.strip\n\n [stdin, stdout, stderr].each(&:close)\n [process.value, out + err]\n end", "def start(command_and_args = [], output_to_wait_for = nil, wait_timeout = nil, env = {}, opts = {})\n out_r, out_w = IO.pipe\n @out_log = ProcessLog.new(out_r, @opts).start\n if opts[:stderr]\n err_r, err_w = IO.pipe\n @err_log = ProcessLog.new(err_r, @opts).start\n else\n err_w = out_w\n end\n @pid = spawn(env, *command_and_args, :out => out_w, :err => err_w)\n out_w.close\n err_w.close if opts[:stderr]\n @out_log.wait_for_output(output_to_wait_for, :timeout => wait_timeout) unless output_to_wait_for.nil?\n end", "def get_shell_pid\n cmd_exec(\"echo $$\").to_s\n end", "def stdout_pipe; end", "def get_pid\n\t\tEventMachine::get_subprocess_pid @signature\n\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
does crazy things on arrays : The magic_array function takes an array of number or an array of array of number as parameter and return the same array : flattened (i.e. no more arrays in array) reversed with each number multiplicated by 2 with each multiple of 3 removed with each number duplicate removed (any number should appear only once) sorted
def magic_array(array) array.flatten.reverse.map! {|i| i = i*2}.delete_if {|i| i.modulo(3) == 0}.uniq.sort end
[ "def magic_array(array)\n return array.flatten.sort.map { |i| i*2 }.delete_if { |i| i % 3 == 0}.uniq\nend", "def double_array(array)\n result = []\n 2.times { result << array }\n result.flatten\nend", "def double_array(arr)\n arr_div_three = []\n arr_not_div_three = []\n arr.each do |number|\n if div_three(number)\n arr_div_three.push(number)\n else\n arr_not_div_three.push(number)\n end\n end\n result = [arr_div_three, arr_not_div_three]\n result\nend", "def products_of_all_other_nums(array)\n\n\tresult = Array.new() { [] }", "def mod_three my_array\n\t@my_array = my_array\n\tto_return = []\n\tto_return = @my_array.map { |nr| nr % 3 }\n\tto_return = to_return.reject { |nr| nr == 0 }\n\tp to_return\nend", "def triplify(array)\n \t \n \t new_array = array.map { |i| i * 3 }\n \t p new_array\n end", "def remove_con_dups(arr)\n arr.map(&:squeeze)\nend", "def bitonic_sort(array)\n return array if array.length <= 1\n\n length = array.length\n num = nearest_power_of_2(array.length)\n\n # add place holder values\n array << Float::INFINITY until array.length == num\n\n array = bitonic_recurse(array, 0, array.length, 1)\n\n # remove place holder values\n array.pop until array.length == length\n\n array\nend", "def cubed_values (array)\n\n cubed_array = array.map { | number | number ** 3 }\n return cubed_array\n\nend", "def sorted_triples(array)\n sort_array = []\n array.each_slice(3) do |group|\n sort_array << group.sort\n end\n return sort_array\nend", "def using_flatten (arrays)\n arrays.flatten\nend", "def flat(a)\n\tnew_arr = []\n\ta.each do |el|\n\t\tif el.is_a? Array\n\t\t\tel.each do |n|\n\t\t\t\tif el.is_a? Array\n\t\t\t\t\ta << n\n\t\t\t\telse\n\t\t\t\t\tnew_arr << n\n\t\t\t\tend\n\t\t\tend\n\t\telse\n\t\t\tnew_arr << el\t\n\t\tend\n\tend\n\tp new_arr\nend", "def flatten_and_sort(array)\n array.flatten.sort\nend", "def flatten(arr)\n return arr if arr.count == 0\n answer = []\n (arr.count).times do |counter|\n if arr[counter].respond_to? :each # Duck typing preferred in Ruby?\n inner_array = flatten(arr[counter])\n (inner_array.count).times do |counter_inner|\n answer << inner_array[counter_inner]\n end\n else\n answer << arr[counter]\n end\n end\n answer\nend", "def flatten(array)\nend", "def make_pattern(array = [], number) # Define a method with two paremeter one array which will be the output and another one which is the given number.\r\n if number <= 0 # This is our base case it will stop if the number is 0 or less than that.\r\n array << number #Then we will push the number in to the array.\r\n\t\tarray << array.reverse #Now we will push the array in to it self, But in reverse order.\r\n\t\tarray.flatten! # At this two point we have a nested array it should be turn to one array.\r\n array.delete_at(array.length / 2) # Now there is a problem in our array the middle element of the array is repeated twice.So we delete one.\r\n return array # The array is ready to be called.\r\n end\r\n array << number # It pushes the number in to array \r\n make_pattern(array , number - 5) # This will make our method recursive.It will deduct 5 from our number at each time the method execute.\r\nend", "def simplifyErgArray(array)\n current=0 #the \"start\" element\n lookingAt=1 #the element we're looking at to decide if it's the same as current\n toRemove=[] #duplicate elements to remove\n\n while (current<array.length && lookingAt<array.length) do\n if (array[current][2]==array[current][3] && \n array[current][2]==array[lookingAt][2] &&\n array[current][2]==array[lookingAt][3]\n ) #if elements are the same, remove them, look at next element.\n toRemove << array[lookingAt]\n lookingAt+=1\n elsif (current<(lookingAt-1)) # end of run and there's something to remove\n #current to lookingAt-1 can be merged\n array[current][1]=array[lookingAt][0]\n current=lookingAt\n lookingAt=current+1\n else #we've found nothing to remove, go to next element and repeat\n current=lookingAt\n lookingAt=current+1\n end\n end\n array=array-toRemove\n return array\n end", "def flatten_and_sort(array)\n array.flatten.sort\nend", "def mod_three(numbers)\n\tnew_array = numbers.reject {|x| x % 3 == 0}.map {|x| x % 3}\n\treturn new_array\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
merges sections by prefering other's attributes FIXME: needs specing
def +(other) fail "Unmergable sections:\n1) #{self.inspect}\n2) #{other.inspect}\nReason: values must differ." unless self.value == other.value @attrs.each do |a| case a when Attribute other.attrs << a unless other.attrs.map(&:name).include?(a.name) when Section other.attrs << a end end other end
[ "def merge_metadata(existing_metadata, section, new_metadata); end", "def merge_attributes\n attrs = self.attributes.dup.reject{ |k,v| ignored_merge_attributes.include?(k) }\n attrs.merge!(address_attributes) # we want addresses to be shown in the UI\n sorted = attrs.sort do |a,b|\n (ordered_merge_attributes.index(a.first) || 1000) <=> (ordered_merge_attributes.index(b.first) || 1000)\n end\n sorted.inject({}) do |h, item|\n h[item.first] = item.second\n h\n end\n end", "def merge_sections cm # :nodoc:\n my_sections = sections.group_by { |section| section.title }\n other_sections = cm.sections.group_by { |section| section.title }\n\n other_files = cm.in_files\n\n remove_things my_sections, other_files do |_, section|\n @sections.delete section.title\n end\n\n other_sections.each do |group, sections|\n if my_sections.include? group\n my_sections[group].each do |my_section|\n other_section = cm.sections_hash[group]\n\n my_comments = my_section.comments\n other_comments = other_section.comments\n\n other_files = other_section.in_files\n\n merge_collections my_comments, other_comments, other_files do |add, comment|\n if add then\n my_section.add_comment comment\n else\n my_section.remove_comment comment\n end\n end\n end\n else\n sections.each do |section|\n add_section group, section.comments\n end\n end\n end\n end", "def tag_section_mapping; end", "def merge!(other)\n return self if other.nil?\n\n my_keys = @ini.keys\n other_keys = case other\n when IniFile\n other.instance_variable_get(:@ini).keys\n when Hash\n other.keys\n else\n raise Error, \"cannot merge contents from '#{other.class.name}'\"\n end\n\n (my_keys & other_keys).each do |key|\n case other[key]\n when Hash\n @ini[key].merge!(other[key])\n when nil\n nil\n else\n raise Error, \"cannot merge section #{key.inspect} - unsupported type: #{other[key].class.name}\"\n end\n end\n\n (other_keys - my_keys).each do |key|\n @ini[key] = case other[key]\n when Hash\n other[key].dup\n when nil\n {}\n else\n raise Error, \"cannot merge section #{key.inspect} - unsupported type: #{other[key].class.name}\"\n end\n end\n\n self\n end", "def merge_attrs\n REXML::XPath.first(node, \".//*[@merge|@merge-attrs]\")._?.name\n end", "def merge_attributes(child, parent_attributes); end", "def merge_attributes\n return @assertions,\n @setup,\n @teardown,\n @provides,\n @depends_on,\n @skipped,\n @reason,\n @suites\n end", "def merged_attributes(*path)\n merge_all(path)\n end", "def merge(args)\n source = YAML.load_file args[:source]\n target = YAML.load_file args[:target]\n target.each do |et|\n source.each do |es|\n if et['name'] == es[args[:electorate]]\n et['members'] ||= []\n member = Hash.new\n es.each do |key,val|\n member[key] = val\n end\n et['members'].push member\n end\n end \n end\n target.to_yaml\n end", "def groupbysection()\n merge(notgroupbysection: 'true')\n end", "def merge_attributes(block, attributes) # :nodoc:\n defaults = DEFAULT_ATTRIBUTES[nil].dup\n defaults.merge!(DEFAULT_ATTRIBUTES[block]) if block\n defaults.merge!(attributes)\n \n # register with Lazydoc\n defaults[:desc] ||= Lazydoc.register_caller(Lazydoc::Trailer, 2)\n \n defaults\n end", "def merge! other\n self.attributes.each do |attr, val|\n next unless val.blank?\n self.send(\"#{attr}=\".to_sym, other.send(attr))\n end\n end", "def merge(source); end", "def linktosections()\n merge(linktosections: 'true')\n end", "def merge_attributes(new)\n merge = Student.new(attributes).attributes\n new.stringify_keys.each do |key, value|\n case key\n when 'guid' ; puts 'guid: skipped'\n when 'id' ; puts 'id: skipped'\n when 'gpa'\n merge[key] = value\n merge['gpa_updated'] = DateTime.current\n else\n merge[key] = value if merge.key?(key)\n end\n end\n merge\n end", "def merge_configurations cfg,cfg2\n cfg['prefix']||=cfg2['prefix']\n raise \"Attempting to merge configurations with differing prefixes: '#{cfg['prefix']}' vs. '#{cfg2['prefix']}' \" if cfg['prefix']!=cfg2['prefix']\n cfg['include']||=[]\n cfg['depend']||=[]\n cfg['interface']||=[]\n cfg['include']+=cfg2['include'] if cfg2['include']\n cfg['depend']+=cfg2['depend'] if cfg2['depend']\n cfg['interface']+=cfg2['interface'] if cfg2['interface']\n return cfg\nend", "def merge_node_properties(node, tag, parent_properties); end", "def union(other)\n merged = attributes.merge(other){|k,t1,t2|\n if t1 == t2 \n t1 \n else\n Object\n end\n }\n Heading.new(merged)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /facility_items GET /facility_items.json
def index @facility_items = FacilityItem.where("true").order(:facility_name).page params[:page] end
[ "def index\n if facility_params[:facility_id]\n @facility_items = FacilityItem.where(facility_id: @facility.id).order(:name).page params[:page]\n else \n @facility_items = [] \n for value in @template.template_facility_item do\n @facility_items.push(FacilityItem.find(value.facility_item_id))\n end \n end\n end", "def show\n @facility = Facility.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @facility }\n end\n end", "def index\n @facility_cost_items = FacilityCostItem.all\n end", "def show\n @facility_total = FacilityTotal.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @facility_total }\n end\n end", "def index\n @facilities = Facility.all\n respond_with @facilities\n end", "def show\n @facility_code = FacilityCode.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @facility_code }\n end\n end", "def index\n @users_facilities = UsersFacility.all\n end", "def get_facilities\n list = organizations.map { |org| org.resource.identifier.last.value }\n facilities_ids = list.join(',')\n\n facilities_request.get(facilities_ids)\n end", "def create\n @facility_item = FacilityItem.new(facility_item_params)\n\n respond_to do |format|\n if @facility_item.save\n format.html { redirect_to @facility_item, notice: 'Facility item was successfully created.' }\n format.json { render :show, status: :created, location: @facility_item }\n else\n format.html { render :new }\n format.json { render json: @facility_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n rooms = Array.new\n if params[:facility].nil?\n # 自分の施設情報だけを返す\n facilities = current_user.facilities\n facilities.each do |facility|\n rooms.concat(facility.rooms)\n end\n else\n # facility=[facility_id]\n facility = Facility.find_by(id: params[:facility].to_i)\n # 施設IDが存在しない場合\n if facility.nil?\n response = {\n status: 'NotFound',\n message: 'rooms not found'\n }\n return render json: response, status: 404\n end\n # ユーザーの施設IDでない場合\n if facility.user_id != current_user.id\n response = {\n status: 'NotFound',\n message: 'rooms not found'\n }\n return render json: response, status: 404\n end\n rooms.concat(facility.rooms)\n end\n\n render json: {\n status: 'Success',\n message: '',\n rooms: rooms.as_json(except: [\n :created_at,\n :updated_at\n ], include: [\n :ota_rooms\n ])\n }, status: 200\n end", "def get_facility(facility_id)\n params = {}\n with_monitoring do\n response = perform(:get, facilities_url_with_id(facility_id), params, headers)\n OpenStruct.new(response[:body])\n end\n end", "def index\n @facilities = Facility.all\n end", "def create\n @facility_item = FacilityItem.new(facility_item_params)\n\n respond_to do |format|\n if @facility_item.save\n format.html { redirect_to '/facilities/'+@facility_item.facility_id.to_s+'/facility_items', notice: 'Facility item was successfully created.' }\n format.json { render :show, status: :created, location: @facility_item }\n else\n format.html { render :new }\n format.json { render json: @facility_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @facility = Facility.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @facility }\n end\n end", "def index\n @facility_totals = FacilityTotal.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @facility_totals }\n end\n end", "def list\n facilities.map do |facility|\n {\n 'pH_AMT_DUE' => 0,\n 'pS_STATEMENT_DATE' => Time.zone.today.strftime('%m%d%Y'),\n 'station' => {\n 'facilitY_NUM' => facility['id'].sub('vha_', ''),\n 'city' => facility['address']['physical']['city'].upcase\n }\n }\n end\n end", "def index\n @other_facilities = OtherFacility.all\n end", "def show\n @central_facility = CentralFacility.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @central_facility }\n end\n end", "def index\n @facility_types = FacilityType.all\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /facility_items POST /facility_items.json
def create @facility_item = FacilityItem.new(facility_item_params) respond_to do |format| if @facility_item.save format.html { redirect_to @facility_item, notice: 'Facility item was successfully created.' } format.json { render :show, status: :created, location: @facility_item } else format.html { render :new } format.json { render json: @facility_item.errors, status: :unprocessable_entity } end end end
[ "def create\n @facility_item = FacilityItem.new(facility_item_params)\n\n respond_to do |format|\n if @facility_item.save\n format.html { redirect_to '/facilities/'+@facility_item.facility_id.to_s+'/facility_items', notice: 'Facility item was successfully created.' }\n format.json { render :show, status: :created, location: @facility_item }\n else\n format.html { render :new }\n format.json { render json: @facility_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @facility = Facility.new(params[:facility])\n\n respond_to do |format|\n if @facility.save\n format.html { redirect_to @facility, notice: 'Facility was successfully created.' }\n format.json { render json: @facility, status: :created, location: @facility }\n else\n format.html { render action: \"new\" }\n format.json { render json: @facility.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @facility_cost_item = FacilityCostItem.new(facility_cost_item_params)\n\n respond_to do |format|\n if @facility_cost_item.save\n format.html { redirect_to @facility_cost_item, notice: 'Facility cost item was successfully created.' }\n format.json { render action: 'show', status: :created, location: @facility_cost_item }\n else\n format.html { render action: 'new' }\n format.json { render json: @facility_cost_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @users_facility = UsersFacility.new(users_facility_params)\n\n respond_to do |format|\n if @users_facility.save\n format.html { redirect_to @users_facility, notice: 'Users facility was successfully created.' }\n format.json { render :show, status: :created, location: @users_facility }\n else\n format.html { render :new }\n format.json { render json: @users_facility.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n json_response(current_restaurant.restaurant_food_items.create!(food_item_params), :created)\n end", "def update\n respond_to do |format|\n if @facility_item.update(facility_item_params)\n format.html { redirect_to facility_facility_items_path(@facility_item.facility_id), notice: 'Facility item was successfully updated.' }\n format.json { render :show, status: :ok, location: @facility_item }\n else\n format.html { render :edit }\n format.json { render json: @facility_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n item = list.items.create!(item_params)\n render json: item, status: 201\n end", "def create\n @other_facility = OtherFacility.new(other_facility_params)\n\n respond_to do |format|\n if @other_facility.save\n format.html { redirect_to @other_facility, notice: 'Other facility was successfully created.' }\n format.json { render :show, status: :created, location: @other_facility }\n else\n format.html { render :new }\n format.json { render json: @other_facility.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @facility_type = FacilityType.new(facility_type_params)\n\n respond_to do |format|\n if @facility_type.save\n format.html { redirect_to @facility_type, notice: \"Facility type was successfully created.\" }\n format.json { render :show, status: :created, location: @facility_type }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @facility_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @offshore_facility = OffshoreFacility.new(offshore_facility_params)\n\n respond_to do |format|\n if @offshore_facility.save\n format.html { redirect_to @offshore_facility, notice: 'Offshore facility was successfully created.' }\n format.json { render :show, status: :created, location: @offshore_facility }\n else\n format.html { render :new }\n format.json { render json: @offshore_facility.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @facility_item.update(facility_item_params)\n format.html { redirect_to @facility_item, notice: 'Facility item was successfully updated.' }\n format.json { render :show, status: :ok, location: @facility_item }\n else\n format.html { render :edit }\n format.json { render json: @facility_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n if facility_params[:facility_id]\n @facility_items = FacilityItem.where(facility_id: @facility.id).order(:name).page params[:page]\n else \n @facility_items = [] \n for value in @template.template_facility_item do\n @facility_items.push(FacilityItem.find(value.facility_item_id))\n end \n end\n end", "def create\n @facility_category = FacilityCategory.new(facility_category_params)\n\n respond_to do |format|\n if @facility_category.save\n format.html { redirect_to @facility_category, notice: 'Facility category was successfully created.' }\n format.json { render :show, status: :created, location: @facility_category }\n else\n format.html { render :new }\n format.json { render json: @facility_category.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @request_item = RequestItem.new(request_item_params)\n @request_item.item = Item.new(name: params[:request_item][:item][:name])\n\n if @request_item.save\n render json: @request_item \n else\n render json: @request_item.errors, status: :bad_request\n end\n end", "def create\n @facility_instance = FacilityInstance.new(facility_instance_params)\n\n respond_to do |format|\n if @facility_instance.save\n format.html { redirect_to @facility_instance, notice: 'Facility instance was successfully created.' }\n format.json { render :show, status: :created, location: @facility_instance }\n else\n format.html { render :new }\n format.json { render json: @facility_instance.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @facility = Facility.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @facility }\n end\n end", "def create\n @facility_total = FacilityTotal.new(params[:facility_total])\n\n respond_to do |format|\n if @facility_total.save\n format.html { redirect_to @facility_total, notice: 'Facility total was successfully created.' }\n format.json { render json: @facility_total, status: :created, location: @facility_total }\n else\n format.html { render action: \"new\" }\n format.json { render json: @facility_total.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @feature_item = FeatureItem.new(feature_item_params)\n\n respond_to do |format|\n if @feature_item.save\n format.html { redirect_to @feature_item, notice: \"Feature item was successfully created.\" }\n format.json { render :show, status: :created, location: @feature_item }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @feature_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @ft_item = FtItem.new(ft_item_params)\n\n respond_to do |format|\n if @ft_item.save\n format.html { redirect_to @ft_item, notice: 'Ft item was successfully created.' }\n format.json { render :show, status: :created, location: @ft_item }\n else\n format.html { render :new }\n format.json { render json: @ft_item.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /facility_items/1 PATCH/PUT /facility_items/1.json
def update respond_to do |format| if @facility_item.update(facility_item_params) format.html { redirect_to @facility_item, notice: 'Facility item was successfully updated.' } format.json { render :show, status: :ok, location: @facility_item } else format.html { render :edit } format.json { render json: @facility_item.errors, status: :unprocessable_entity } end end end
[ "def update\n respond_to do |format|\n if @facility_item.update(facility_item_params)\n format.html { redirect_to facility_facility_items_path(@facility_item.facility_id), notice: 'Facility item was successfully updated.' }\n format.json { render :show, status: :ok, location: @facility_item }\n else\n format.html { render :edit }\n format.json { render json: @facility_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @facility.update(facility_params)\n format.html { redirect_to facilities_path, notice: 'Facility was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @facility.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @facility = Facility.find(params[:id])\n\n respond_to do |format|\n if @facility.update_attributes(params[:facility])\n format.html { redirect_to @facility, notice: 'Facility was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @facility.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @facility = Facility.find(params[:id])\n\n respond_to do |format|\n if @facility.update_attributes(params[:facility])\n format.html { redirect_to @facility, notice: 'Facility was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @facility.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @offshore_facility.update(offshore_facility_params)\n format.html { redirect_to @offshore_facility, notice: 'Offshore facility was successfully updated.' }\n format.json { render :show, status: :ok, location: @offshore_facility }\n else\n format.html { render :edit }\n format.json { render json: @offshore_facility.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @facility_cost_item.update(facility_cost_item_params)\n format.html { redirect_to @facility_cost_item, notice: 'Facility cost item was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @facility_cost_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @users_facility.update(users_facility_params)\n format.html { redirect_to @users_facility, notice: 'Users facility was successfully updated.' }\n format.json { render :show, status: :ok, location: @users_facility }\n else\n format.html { render :edit }\n format.json { render json: @users_facility.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @other_facility.update(other_facility_params)\n format.html { redirect_to @other_facility, notice: 'Other facility was successfully updated.' }\n format.json { render :show, status: :ok, location: @other_facility }\n else\n format.html { render :edit }\n format.json { render json: @other_facility.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n json_response(@food_item.update!(food_item_params))\n end", "def update\n @item_feature = ItemFeature.find(params[:id])\n\n respond_to do |format|\n if @item_feature.update_attributes(params[:item_feature])\n format.html { redirect_to @item_feature, notice: 'Item feature was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @item_feature.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n coffeeshop_facilities = params[:coffeeshop].delete(:facilities)\n @coffeeshop.facility_ids = coffeeshop_facilities\n\n respond_to do |format|\n if @coffeeshop.update(coffeeshop_params)\n format.html { redirect_to @coffeeshop, notice: 'Coffeeshop was successfully updated.' }\n format.json { render :show, status: :ok, location: @coffeeshop }\n else\n format.html { render :edit }\n format.json { render json: @coffeeshop.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @facility_type.update(facility_type_params)\n format.html { redirect_to @facility_type, notice: \"Facility type was successfully updated.\" }\n format.json { render :show, status: :ok, location: @facility_type }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @facility_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\n #update the item of request_item\n if (params[:request_item].present?)\n @request_item.item = params[:request_item][:item].present? ? Item.new(name: params[:request_item][:item][:name]) : @request_item.item\n end\n #update all other parameters\n if @request_item.update(request_item_params)\n render json: @request_item\n else\n render json: @request_item.errors, status: :bad_request\n end\n\n end", "def update\n respond_to do |format|\n if @feature_item.update(feature_item_params)\n format.html { redirect_to @feature_item, notice: \"Feature item was successfully updated.\" }\n format.json { render :show, status: :ok, location: @feature_item }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @feature_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def _update_item(http, headers, path, body, name)\n resp = retry_request(http, \"PATCH\", path, body, headers)\n if resp.is_a?(Net::HTTPOK)\n Chef::Log.info(\"Updated keystone item '#{name}'\")\n else\n _raise_error(resp, \"Unable to update item '#{name}'\", \"_update_item\")\n end\nend", "def update\n respond_to do |format|\n if @place_facility.update(place_facility_params)\n format.html { redirect_to @place_facility, notice: 'Place facility was successfully updated.' }\n format.json { render :show, status: :ok, location: @place_facility }\n else\n format.html { render :edit }\n format.json { render json: @place_facility.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n json_update(factType,factType_params, FactType)\n end", "def update\n @scheduled_facility = ScheduledFacility.find(params[:id])\n\n respond_to do |format|\n if @scheduled_facility.update_attributes(params[:scheduled_facility])\n format.html { redirect_to @scheduled_facility, notice: 'Scheduled facility was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @scheduled_facility.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @room_facility.update(room_facility_params)\n format.html { redirect_to @room_facility, notice: 'Room facility was successfully updated.' }\n format.json { render :show, status: :ok, location: @room_facility }\n else\n format.html { render :edit }\n format.json { render json: @room_facility.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /facility_items/1 DELETE /facility_items/1.json
def destroy @facility_item.destroy respond_to do |format| format.html { redirect_to facility_items_url, notice: 'Facility item was successfully destroyed.' } format.json { head :no_content } end end
[ "def destroy\n @facility_item.destroy\n respond_to do |format|\n format.html { redirect_to facility_facility_items_path(facility_params), notice: 'Facility item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n\n @facility = Facility.find(params[:id])\n @facility.destroy\n\n respond_to do |format|\n format.html { redirect_to facilities_url }\n format.json { head :ok }\n end\n end", "def destroy\n @facility = Facility.find(params[:id])\n @facility.destroy\n\n respond_to do |format|\n format.html { redirect_to facilities_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @facility_cost_item.destroy\n respond_to do |format|\n format.html { redirect_to facility_cost_items_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @offshore_facility.destroy\n respond_to do |format|\n format.html { redirect_to offshore_facilities_url, notice: 'Offshore facility was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @central_facility = CentralFacility.find(params[:id])\n @central_facility.destroy\n\n respond_to do |format|\n format.html { redirect_to central_facilities_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @facility_total = FacilityTotal.find(params[:id])\n @facility_total.destroy\n\n respond_to do |format|\n format.html { redirect_to facility_totals_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @users_facility.destroy\n respond_to do |format|\n format.html { redirect_to users_facilities_url, notice: 'Users facility was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @facility_type.destroy\n respond_to do |format|\n format.html { redirect_to facility_types_url, notice: \"Facility type was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\r\n @facility = Facility.find(params[:facility_id])\r\n @facility_custody = FacilityCustody.find(params[:id])\r\n @facility_custody.destroy\r\n\r\n respond_to do |format|\r\n format.html { redirect_to facility_url(@facility) }\r\n format.xml { head :ok }\r\n end\r\n end", "def destroy\n @scheduled_facility = ScheduledFacility.find(params[:id])\n @scheduled_facility.destroy\n\n respond_to do |format|\n format.html { redirect_to scheduled_facilities_url }\n format.json { head :no_content }\n end\n end", "def delete_item\n item_id = params[\"item_id\"]\n\n item = TextItem.find_by_id(item_id)\n item = Image.find_by_id(item_id) if item.nil?\n item = Collection.find_by_id(item_id) if item.nil?\n render_json :status => :not_found, :messages => \"Could not find the item with id #{item_id}.\" and return if item.nil?\n\n if item.class == Collection\n if params[\"id\"].nil?\n render_json :status => :bad_request, :messages => \"Can't delete a collection reference without providing the parent collection id. Please use the longer url for item deletion.\" and return\n end\n collection = Collection.find_by_id(params[\"id\"])\n else\n collection = Ownership.find_by_item_id(item_id).parent\n end\n;\n render_json :status => :not_found, :messages => \"Could not find parent collection for the item.\" and return if (collection.nil?)\n render_json :status => :forbidden, :messages => \"The user is not allowed to delete from this collection.\" and return if (!collection.delete?(@user, @client))\n\n collection.delete_item(item_id)\n render_json :entry => {} and return\n end", "def destroy\n @facility = Facility.find(params[:id])\n @facility.destroy\n redirect_to admins_url\n end", "def destroy\n @health_facility.destroy\n respond_to do |format|\n format.html { redirect_to health_facilities_url, notice: 'Health facility was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @medical_facility.destroy\n respond_to do |format|\n format.html { redirect_to medical_facilities_url, notice: 'Medical facility was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @backlog_item.destroy\n respond_to do |format|\n format.html { redirect_to backlog_items_url }\n format.json { head :no_content }\n end\n end", "def destroy\n render status: 200, json: @request_item.destroy\n end", "def destroy\n @other_facility.destroy\n respond_to do |format|\n format.html { redirect_to other_facilities_url, notice: 'Other facility was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n request = RestClient.delete File.join(API_SERVER,\"rest-api/departments\",params['id'])\n redirect_to :action => :index\t\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This should contain expected class of the returning message. Might be overwritten in child class
def expected_messages_class self.class.name.sub("Lookups", "Messages").constantize end
[ "def message_expectation_class; end", "def message_class\n return Scene_Battle::Message\n end", "def message_class\n @message_class || get_model_class(:Message)\n end", "def message_for(test); end", "def validates_type_error_message(m, klass)\n # SEQUEL6: Make this the default behavior in validation_helpers\n if OVERRIDE_PROC.equal?(m)\n TYPE_ERROR_STRINGS[klass]\n else\n super\n end\n end", "def may_have_messages?; true; end", "def message\n m = super.dup\n m << \" #{text}\" if text\n m << \" (#{code}, #{description.inspect})\"\n end", "def message\n str = super\n self.class.get_reason + (str.empty? ? \"\" : \": #{str}\")\n end", "def get_message_specifications\n\t\tend", "def get_message_factory\n\t\tend", "def expected_message(*phrases) new_message.expected(*phrases); end", "def message\n m = super\n m << \" (#{code}, #{description.inspect})\"\n end", "def human_msg_type\n self[:msg_type].to_human\n end", "def new_message\n end", "def validate_base_message(message)\n\n unless has_subject(message)\n SendResult.enum[\"MessageValidationEmptySubject\"]\n end\n unless has_from_email_address(message)\n SendResult.enum[\"EmailAddressValidationMissingFrom\"]\n end\n unless message.from_email_address.is_valid\n SendResult.enum[\"EmailAddressValidationInvalidFrom\"]\n end\n unless has_valid_reply_to(message)\n SendResult.enum[\"RecipientValidationInvalidReplyTo\"]\n end\n unless has_message_body(message)\n SendResult.enum[\"MessageValidationEmptyMessage\"]\n end\n unless has_valid_custom_headers(message.custom_headers)\n SendResult.enum[\"MessageValidationInvalidCustomHeaders\"]\n end\n\n SendResult.enum[\"Success\"]\n\n end", "def want_msg?\r\n msg_type == 'want'\r\n end", "def expectation_description\n\t\t\tif @expected_message.is_a?( Regexp )\n\t\t\t\treturn \"finish_with %d (%s) status and a message which matches %p\" % [\n\t\t\t\t\t@expected_status,\n\t\t\t\t\tSTATUS_NAMES[@expected_status],\n\t\t\t\t\t@expected_message\n\t\t\t\t]\n\t\t\telse\n\t\t\t\treturn \"finish_with %d (%s) status and a message which is %p\" % [\n\t\t\t\t\t@expected_status,\n\t\t\t\t\tSTATUS_NAMES[@expected_status],\n\t\t\t\t\t@expected_message\n\t\t\t\t]\n\t\t\tend\n\t\tend", "def initialize(message, expected_type, actual_type)\n super(message)\n @expected_type = expected_type\n @actual_type = actual_type\n end", "def message_type\n return @message_type\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate the last part of the breadcrumb for a static page within a unit
def getPageBreadcrumb(unit, pageName) (!pageName || pageName == "home" || pageName == "campus_landing") and return [] pageName == "search" and return [{ name: "Search", id: unit.id + ":" + pageName}] pageName == "profile" and return [{ name: "Profile", id: unit.id + ":" + pageName}] pageName == "sidebar" and return [{ name: "Sidebars", id: unit.id + ":" + pageName}] p = Page.where(unit_id: unit.id, slug: pageName).first p or halt(404, "Unknown page #{pageName} in #{unit.id}") return [{ name: p[:name], id: unit.id + ":" + pageName, url: "/#{unit.id}/#{pageName}" }] end
[ "def extract_breadcrumb\n end", "def max_breadcrumbs; end", "def extract_breadcrumb\n\n end", "def breadcrumbs\n breadcrumbs = link_to this_webapp.webapp_name, root_path, :class => 'first-breadcrumb'\n unless @breadcrumb.nil?\n breadcrumbs += content_tag(:label, \" > \")\n if @breadcrumb.kind_of? Picture\n picture = @breadcrumb\n @breadcrumb = @breadcrumb.gallery\n end\n breadcrumbs += parent_breadcrumbs_gallery(@breadcrumb)\n\n unless picture.nil?\n breadcrumbs += content_tag(:label, \" > \")\n breadcrumbs += content_tag(:label, picture.title, :class => 'end-breadcrumb')\n end\n end\n if @finish_breadcrumb\n breadcrumbs + \" > \" + @finish_breadcrumb\n else\n breadcrumbs\n end\n end", "def the_breadcrumb(add_post_type = true)\n generate_breadcrumb(add_post_type)\n h.breadcrumb_draw\n end", "def hardcoded_breadcrumbs\n [\n {\n title: \"Home\",\n url: \"/\",\n },\n {\n title: subtopic.parent.title,\n url: subtopic.parent.base_path,\n },\n {\n title: subtopic.title,\n url: subtopic.base_path,\n },\n ]\n end", "def breadcrumb_trail(controller, action)\n begin\n trail = link_to(\"Home\", \"/forge\", :class => \"crumb no-arrow\")\n trail += link_to(display_controller(controller), url_for(:controller => params[:controller]), :class => \"crumb\") if controller != \"forge/index\"\n trail += content_tag(:span, display_action(action), :class => \"crumb\") if action != \"index\"\n return trail\n rescue\n return \"\"\n end\n end", "def breadcrumb_name\n title\n end", "def rails_activesupport_breadcrumbs; end", "def breadcrumb(page_slug)\n page_slug.split('/')\n .map { |dir_or_page| WikiPage.unhyphenize(dir_or_page).capitalize }\n .join(' / ')\n end", "def build_breadcrumbs\n @breadcrumbs = [\n { :title => I18n.t(\"admin.sections.#{resource_collection_name}\"), :url => collection_path }\n ]\n @breadcrumbs << { :title => params[:action] } unless params[:action] == 'index'\n end", "def trail(delimiter = nil)\n return @breadcrumbs.collect{ |c| c[:title] }.join(delimiter) if delimiter\n @breadcrumbs\n end", "def member_breadcrumbs\n collection_breadcrumbs\n add_breadcrumb(@report.date.strftime('%b %e Report'), url_for(@report), true, 'Report')\n end", "def member_breadcrumbs\n add_breadcrumb(@period.name, url_for(@period), true, 'Coaching Period')\n end", "def breadcrumb_label(page)\n if ( page != nil )\n (page.abspath == '/') ? 'Home' : ( page.metadata('menu').nil? ? page.heading : page.metadata('menu') )\n else\n 'Home'\n end\n end", "def build_crumb(title, url)\n str = \"\"\n xtitle = CGI::escapeHTML(truncate(title, breadcrumb_size_limit))\n if is_external_breadcrumb?(url)\n str += \"<a href=\\\"#{url}\\\" class=\\\"bt_external\\\">#{xtitle}</a>\"\n else\n str += \"<a href='#{url}'>#{xtitle}</a>\"\n end\n str\n end", "def breadcrumb_as_string\n @@breadcrumb ||= {}\n @@breadcrumb[self.id] ||= breadcrumb(include_self: true).map{|x| x[:name]}.join(\" / \")\n end", "def breadcrumb\n attributes['breadcrumb'] || title\n end", "def home_breadcrumbs(action=\"\")\n crumbs = []\n\n crumbs.push({ \"text\": t(\"defaults.home\"), \"link\": root_path })\n\n case action\n when \"api\"\n crumbs.push({ \"text\": \"API\" })\n\n when \"conferences\"\n crumbs.push({ \"text\": t(\"views.conference.list\") })\n end\n\n render \"partials/breadcrumbs\", crumbs: crumbs\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get recent items (with author info) for a unit, by most recent eschol_date
def getRecentItems(unit) items = Item.join(:unit_items, :item_id => :id).where(unit_id: unit.id) .where(Sequel.lit("attrs->\"$.suppress_content\" is null")) .reverse(:eschol_date).limit(5) return items.map { |item| { id: item.id, title: item.title, authors: getItemAuthors(item.id) } } end
[ "def getRecentItems(unitID, limit=5, item_id=nil)\n items = item_id ? Item.join(:unit_items, :item_id => :id).where(unit_id: unitID)\n .where(status: 'published')\n .exclude(id: item_id)\n .reverse(:added).limit(limit)\n : Item.join(:unit_items, :item_id => :id).where(unit_id: unitID)\n .where(status: 'published')\n .reverse(:added).limit(limit)\n return items.map { |item|\n { id: item.id, title: item.title, authors: getItemAuthors(item.id), genre: item.genre, \n author_hide: JSON.parse(item.attrs)[\"author_hide\"] }\n }\nend", "def latest_items\n self.feed_items.find(:all, :conditions => ['created_on >= ?', self.updated_on.ago(1.second)])\n end", "def articles_for_year(year, kind)\n @items.select { |item| item[:kind] == kind && Time.parse(item[:created_at]).year == year }.sort_by { |item| Time.parse(item[:created_at]) }.reverse\nend", "def by_volume(opts={})\n opts.to_options!\n\n q = Esquire.new\n q.configure(opts)\n q.source_filter(@project, @track)\n q.date_filter(opts[:start_date], opts[:end_date])\n q.aggregations[:top_authors] = {terms: {field: 'interaction.author.username', size: 50}}\n\n result = self.MeasuredQuery(q.build, \"authors.#{__method__}\", opts)\n unless result.nil? || result.empty?\n list = result['aggregations']['top_authors']['buckets']\n list = self.normalize_keys(list, ['key', 'doc_count'], ['screen_name', 'count'])\n return list\n end\n\n return result\n end", "def mentioned_by_top_authors(opts={})\n opts.to_options!\n\n top_authors = self.by_volume(opts).map{|bucket| bucket['screen_name']}\n\n q = Esquire.new\n q.configure(opts)\n q.source_filter(@project, @track)\n q.date_filter(opts[:start_date], opts[:end_date])\n q.qfilters << {terms: {'interaction.author.username' => top_authors}}\n q.facets[:top_authors] = {terms: {field: 'interaction.mentions', size: 50, shard_size: 50}}\n\n result = self.MeasuredQuery(q.build, \"authors.#{__method__}\", opts)\n unless result.nil? || result.empty?\n list = result['facets']['top_authors']['terms']\n list = self.normalize_keys(list, ['term'], ['screen_name'])\n list\n end\n end", "def recent_item\n raise MsdApi::Exception::InvalidParameter.new(_('errors.missing_param', key: :date)) unless params[:date]\n\n begin\n data = MsdApi::RedisRecentAnalytics.hgetall(epoch_date)\n @item = OpenStruct.new(data)\n rescue Exception => e\n render_error_json(_('errors.invalid_date'))\n end\n end", "def get_org_unit_news_items(org_unit_id, since = \"\")\n path = \"/d2l/api/le/#{$le_ver}/#{org_unit_id}/news/\"\n path += \"?since=#{since}\" if since != \"\"\n _get(path)\nend", "def last_summary\n\t\t@db[:gold_summary].reverse_order(:summary_date).get(:created_date)\n\tend", "def recent_updated_titles(name)\n\tissues = Octokit.search_repositories name, {:sort => :updated}\n\t\n\t# filter for newer issues\n\tissues.items.reject!{|issue_item| issue_item.updated_at < @last_updated} unless @last_updated.nil?\n\t@last_updated = issues.items.first.updated_at\n\t\n\tissues.items.map{|issue_item| issue_item.name}\n\t\nend", "def recent_items\n items.where([\"DATE(created_at) = DATE(?)\", Time.now]).all\n end", "def artists_abrv(item)\n item.artists_last\n end", "def latest\n @latest = apiQuery(\"items(first:1, order:UPDATED_DESC, include:[PUBLISHED,EMBARGOED]) { nodes { updated } }\").\n dig(\"items\", \"nodes\", 0, \"updated\")\n end", "def get_most_recently_visited_topics(org_unit_id) # GET\n query_string = \"/d2l/api/le/#{$le_ver}/#{org_unit_id}/content/recent\"\n _get(query_string)\n # Returns: a JSON array of Topic ToC entries.\nend", "def latest_in_unit\n package_branch.packages.unit(self.unit).order(\"version DESC\").first\n end", "def get_recent_dub_list\n #to be scraped\n @asc_date_list = CliDub::User.get_recent_dub_list\n end", "def most_recent_recipe\n my_recipes=recipe_cards.each do |recipe|\n recipe.user\n end\n my_recipes_sorted = my_recipes.sort_by { |recipe| recipe.date_of_entry}\n my_most_recent = my_recipes_sorted[-1]\n end", "def get_top_artists(period: '1month')\n query_params = { period: period }\n params = lastfm_params('user.gettopartists', query_params)\n response = RestClient.get(BASE, params: params)\n handle_response(response)\n end", "def recent\n [\n app.blog(:episodes).articles.first(2),\n app.blog(:blog).articles.first(2)\n ].flatten.sort_by { |e|\n e.data.date\n }\n end", "def latest_dosage\n dosages.order(date_given: :desc).first\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Traverse the nav bar, including subfolders, yielding each item in turn to the supplied block.
def travNav(navBar, &block) navBar.each { |nav| block.yield(nav) if nav['type'] == 'folder' travNav(nav['sub_nav'], &block) end } end
[ "def bootstrap_nav(*args, &block)\n levels = { :primary => 1, :secondary => 2, :tertiary => 3 }\n options = args.extract_options!\n level = levels[options[:level]] || (options[:level] || 1).to_i\n\n\n # If there are no arguments, use the current page\n args.unshift page if args.empty? && !page.nil?\n \n current_page = page\n \n contents = \"\".tap do |str|\n\n page = current_page # TODO: Can't call page within tap, so we've passed it as a variable. Can we do this better?\n\n # Opening HTML for Twitter Bootstrap Navigation\n if level == 1\n str << '<ul class=\"nav\">'\n else\n str << '<ul class=\"dropdown-menu\">'\n end\n \n pages = args.map do |arg|\n if arg.root?\n arg.children.first\n else \n case arg\n when Breeze::Content::NavigationItem then arg\n else Breeze::Content::NavigationItem.where(:permalink => arg.to_s).first\n end\n end\n end.flatten.compact\n \n ancestry = pages.first ? pages.first.self_and_ancestors.to_a : [ page ]\n\n # If page is undefined, there's no active page\n # This is used for example on the Breeze Commerce Cart and Checkout pages\n # In the longer term, this should be removed, in favour of making the cart a proper page, with checkout as a view\n page ||= nil\n \n active = page ? (page.root? ? [page] : ancestry.dup) : []\n ancestry << ancestry.last.children.first if ancestry.last\n ancestry.compact!\n \n if level <= ancestry.length && ancestry[level].present?\n siblings = ancestry[level].self_and_siblings.to_a.select(&:show_in_navigation?) \n # siblings = page.self_and_siblings.to_a.select(&:show_in_navigation?) \n siblings.unshift ancestry[level - 1] if options[:home] || (level == 1 && options[:home] != false)\n siblings.each_with_index do |p, i|\n page_title = if (options[:home] && options[:home] != true) && (p.level < level || p.root?)\n options[:home]\n case options[:home]\n when true then p.title\n when Symbol then p.send options[:home]\n when Proc then options[:home].call(p)\n else options[:home].to_s\n end\n else\n p.title\n end\n page_title = p.title if page_title.blank?\n \n link_options = ({}).tap do |o|\n o[:class] = [ p.root? ? \"home\" : p.slug ].tap do |classes|\n classes << \"active\" if p == page || (active.index(p).to_i > 0 && p.level == level)\n classes << \"first\" if i == 0\n classes << \"last\" if i == siblings.length - 1\n end.join(\" \")\n end\n \n link = if block_given?\n capture p, link_options, &block\n else\n permalink = p.class.name == \"Breeze::Content::Placeholder\" ? 'javascript:void(0)' : p.permalink\n link_to content_tag(:span, \"#{page_title}\".html_safe), permalink, link_options\n end\n \n recurse = case options[:recurse]\n when true then 3\n when :active then ancestry.include?(p) ? 1 : 0\n when Numeric, /^\\d+$/ then options[:recurse].to_i\n else 0\n end\n \n if recurse > 0 && p.level == level && !p.root?\n unless (child = p.children.first).nil?\n link << bootstrap_nav(child, options.merge(:level => level + 1, :recurse => recurse - 1), &block)\n end\n end\n \n # if options[:full] && p.children\n # p.children.each do |child|\n # link << navigation_bootstrap(child, options.merge(:full => true), &block)\n # end\n # end\n\n li_options = ({}).tap do |o|\n o[:class] = [ p.root? ? \"home\" : p.slug ].tap do |classes|\n classes << \"active\" if p == page || (active.index(p).to_i > 0 && p.level == level)\n classes << \"first\" if i == 0\n classes << \"last\" if i == siblings.length - 1\n classes << \"dropdown\" if p.children.length > 0\n classes << 'level-' + level.to_s\n end.join(\" \")\n end\n \n str << content_tag(:li, link.html_safe, li_options)\n end\n end\n \n # Opening HTML for Twitter Bootstrap Navigation\n str << '</ul>'\n \n end\n # content_tag :div, contents.html_safe, options.except(:level, :recurse).reverse_merge(:class => \"#{levels.invert[level] || \"level-#{level}\"} navigation\")\n contents.html_safe\n \n end", "def traverse_nav_markdown(node)\n\t\n\t\t# traverse subfolders, go deep\n\t\tif node_has_children(node)\n\t\t\t node.children.items.each_with_index do |child|\n\n\t\t\t\t items = traverse_nav_markdown(child)\n\t\t\t\t child.children = Map.new unless child.children?\n\t\t\t\t child.children.count = 0 unless child.children.count?\n\t\t\t\t child.children.items = [] unless child.children.items?\n\t\t \n\t\t\t\t child.children.count = items.size\n\t\t\t\t child.children.items = items\t\t\t\t\n\n\t\t\t end\n\t\tend\n\t\n\t\tnode_list = nil\n\t\tif node.children? and node.children.items?\n\t\t\tnode_list = node.children.items\n\t\tend\n\t\n\t\tmarkdowns = Dir.glob(\"#{node.source_path}/*.markdown\")\n\t\n\t\t# if we are at the root node (content source), don't process markdowns here (home.markdown handled separately, special)\n\t\tmarkdowns = [] if node.nav_level == 0\n\t\n\n\t\tif markdowns.size > 0 and node.nav_level > 0\n\n\t\t\t#puts\n\t\t\t#puts \"#{node.source} - #{node.children?}\"\n\t\t\tnode.children = Map.new unless node.children?\n\t\t\tnode.children.count = 0 unless node.children.count?\n\t\t\tnode.children.items = [] unless node.children.items?\n\t\t\t#puts \"#{node.source} - #{node.children?} - #{node.children.count?}\"\n\t\t\n\t\t\tnode_list = node.children.items\n\t\t\t\n\t\t\tmarkdowns.each do |md|\t\t\t\t\t\t\n\t\t\t\tsource = md.gsub(/#{node.source_path}\\//, \"\").gsub(/.markdown/, \"\")\n\t\t\t\n\t\t\t\tis_cbdoc_special_file = source.start_with? \"aaab-\"\n\t\t\t\n\t\t\t\tunless is_cbdoc_special_file\t\t\t\t\n\t\t\t\t\n\t\t\t\t\tif node.link?\n\t\t\t\t\t\tlink = node.link + \"/\" + source \n\t\t\t\t\telse\t\t \n\t\t\t\t\t\tnode.link = \"undefined\"\n\t\t\t\t\t\tputs node.nav_type\n\t\t\t\t\t\texit\n\t\t\t\t\tend\n\t\t\t\t\n\t\t\t\t\tsource_path = node.source_path + \"/\" + source\t\t\t \n\n\t\t\t\t\tis_markdown_and_folder = (File.exist?(\"#{source_path}\") && File.directory?(\"#{source_path}\"))\n\t\t\t\n\t\t\t\t\tunless is_markdown_and_folder\t\t \n\t\t\t\t\t\n\t\t\t\t\t\tfull_link = (node.link.start_with?(\"/#{CONTENT_LINK_PREFIX}/\") ?\tlink : \"/#{CONTENT_LINK_PREFIX}/\" + link )\n\t\t\t\t\t\tparent_path = node.source_path\n\t\t\t\t\t\tparent_full_link = (node.link.start_with?(\"/#{CONTENT_LINK_PREFIX}/\") ?\t node.link : \"/#{CONTENT_LINK_PREFIX}/\" + node.link )\n\t\t\t\t\n\t\t\t\t\t\titem = Map.new({\n\t\t\t\t\t\t\tdoctype: \"nav\",\n\t\t\t\t\t\t\tsubtype: \"nav_\" + (node.nav_level + 1).to_s,\n\t\t\t\t\t\t\tnav_type: \"markdown\",\n\t\t\t\t\t\t\tnav_level: node.nav_level + 1,\t\t\t\t\n\t\t\t\t\t\t\tnav_order: 9000,\n\t\t\t\t\t\t\tnav_title: process_navigation_name(source),\n\t\t\t\t\t\t\tsource: source,\n\t\t\t\t\t\t\tlink: link,\n\t\t\t\t\t\t\tfull_link: full_link,\n\t\t\t\t\t\t\tparent: node.source,\n\t\t\t\t\t\t\tparent_nav_title: node.nav_title,\n\t\t\t\t\t\t\tparent_link: node.link,\n\t\t\t\t\t\t\tparent_full_link: parent_full_link,\n\t\t\t\t\t\t\tparent_path: parent_path,\n\t\t\t\t\t\t\tsource_path: source_path,\n\t\t\t\t\t\t\tancestors: [],\n\t\t\t\t\t\t\tancestors_links: [],\n\t\t\t\t\t\t\tsiblings: [],\n\t\t\t\t\t\t\tsiblings_links: [],\n\t\t\t\t\t\t\tdescendants: [],\n\t\t\t\t\t\t\tdescendants_links: []\t\t\t\t \n\t\t\t\t\t\t})\n\t\t\t\t\t\n\t\t\t\t\t\tnode_list << item \n\t\t\t\t\tend\t\t \n\t\t\t\tend\n\t\t\tend\t\t \n\t\tend\n\t\n\t\t#ap node_list\n\t\n\t\tnode_list\n\tend", "def traverse_page_hierarchy( from=nil, &builder ) # :yields: type, title, path\n\t\t\traise LocalJumpError, \"no block given\" unless builder\n\t\t\tself.traverse_hierarchy( Pathname.new(''), self.hierarchy, from, &builder )\n\t\tend", "def setup_nav_items\n dir = Rails.root.join('app', 'views', 'reports', 'categories').to_s\n @nav_items = {}\n cats = %W(\n the_churches\n developing_localities\n cities_we_are_burdened_for\n various_works\n building_projects\n archives\n )\n cats.each do |cat|\n @nav_items[cat] = Dir.glob(\"#{dir}/#{cat}/*\").map do |path|\n next unless path['.slim']\n path.remove(\".slim\").split(\"/\").last\n end.compact.sort\n end\n @current_page = request.env['PATH_INFO']\n end", "def render_nav( current_user, params, nav ) \n # nav blocks is array of blocks' navigation element (without the divider yet)\n nav_blocks = []\n nav_blocks_string = \"\"\n @is_nav_active = false \n \n nav[:blocks].each do |nav_block|\n # nav block has_many nav elements \n puts \"the nav[:header] = #{nav[:header]}, gonna render nav block\"\n result = render_nav_block( current_user, params, nav_block) \n nav_blocks << result if not result.nil? and not result.length == 0\n end\n \n return nil if nav_blocks.length == 0 \n \n \n nav_blocks_count = nav_blocks.length \n counter = 0\n \n nav_blocks.each do |nav_block|\n nav_blocks_string << nav_block\n if counter != nav_blocks_count - 1 \n nav_blocks_string << draw_block_divider \n end\n counter += 1 \n end\n \n \n # <li class=\"dropdown active\">\n nav_blocks_string = draw_nav( nav_blocks_string, @is_nav_active , nav)\n \n return nav_blocks_string \n \n end", "def page_nav(&proc)\n opening = \"<div class=\\\"page_nav\\\">\"\n concat(opening)\n yield\n closing = \"</div>\"\n concat(closing)\n end", "def navigation_for( nav_name, options = {}, &block )\n raise ArgumentError, \"Missing block\" unless block_given?\n\n builder = options[:builder] || ActionView::Base.default_navigation_builder\n\n options.reverse_merge!(\n :wrapper_tag => :ul,\n :nav_item_tag => :li,\n :selected_class => 'selected',\n :html => {}\n )\n\n start_tag( options ) if navigation_has_wrapper?( options )\n body_content( builder, nav_name, options, &block )\n close_tag( options ) if navigation_has_wrapper?( options )\n\n # Mark the navigation block has having been rendered\n navigation_builder[nav_name] = true\n end", "def build\n yield self if block_given?\n @item_builders.each { |b| @nav.items << b.item }\n @nav\n end", "def nav_item\n h.content_tag :li, :class => 'pull-right' do\n yield\n end\n end", "def output_nav(items)\n html = Array.new\n items.each do |text, path|\n item_path = Rails.application.routes.recognize_path(path)\n current_path = {:action => params[:action], :controller => params[:controller]}\n class_name = text.downcase\n if item_path[:controller] == current_path[:controller] && item_path[:action] == current_path[:action]\n class_name << \" active\"\n end\n html << content_tag(:li, link_to(text, path), :class => class_name)\n end\n html.join(\"\\n\").html_safe\n end", "def main_menu(include_children=true,&block)\n menu_items = []\n \n if (root_menus=SiteMenu.roots).any?\n # load menu from database\n root_menus.each do |menu|\n menu_items << yield(menu.name, \n render( 'home/menu/with_children', \n :menu => menu, \n :recursive=>include_children,\n :force => true\n )\n ) if menu && (menu.role_needed||0) <= current_role\n end\n else\n # Use default menu\n \n # home\n menu_items = [ ]\n \n # Top pages\n menu_items << top_pages.map { |page|\n yield( page.id.to_s.to_sym, menu_link_to( page.short_title, \"/p/#{page.link_to_title}\" ))\n } if can? :read, Page\n \n # Blogs, Userlist, Comments\n menu_items << yield(:blogs, menu_link_to( t(:blogs), blogs_path )) if can? :read, Blog\n menu_items << yield(:userlist, menu_link_to( t(\"menu.userlist\"), registrations_path)) if can? :read, Page\n menu_items << yield(:comments, menu_link_to( t(\"menu.comments\"), comments_path)) if can? :read, Comment.new\n end\n \n menu_items\n end", "def buildNavigation(navHash, parentSection='')\n if (navHash != nil && !navHash.empty?)\n navHash.each do |k, arr|\n\n itemKey = $CfeUtils.removeUnvantedChars(k)\n \n $leftNavigation[itemKey] ||= {}\n \n if (arr.has_key?('own_url') && !arr['own_url'].empty?)\n $breadcrumbsNavigation[itemKey] ||= {}\n $breadcrumbsNavigation[itemKey]['title'] = arr['own_url']['title']\n $breadcrumbsNavigation[itemKey]['alias'] = arr['own_url']['alias']\n else\n puts \"--------------------------------------------------------\"\n puts \"WARNING: Page: \" + k + \". Full path: \" + itemKey + \" doesn't have right meta tags\" \n puts \"--------------------------------------------------------\"\n end\n \n $leftNavigation[itemKey]['level1'] ||= {}\n \n navHash.each do |pageKey, pages|\n # create first level pages\n $leftNavigation[itemKey]['level1'][pageKey] ||= {}\n $leftNavigation[itemKey]['level1'][pageKey]['alias'] = pages['own_url']['alias']\n $leftNavigation[itemKey]['level1'][pageKey]['title'] = pages['own_url']['title']\n \n # check if page has children\n if ( pageKey == k && arr.has_key?('childrens') && !arr['childrens'].empty?)\n $leftNavigation[itemKey]['level1'][pageKey]['childrens'] ||= {}\n pages['childrens'].each do |level2Key, level2Pages|\n $leftNavigation[itemKey]['level1'][pageKey]['childrens'][level2Key] ||= {}\n $leftNavigation[itemKey]['level1'][pageKey]['childrens'][level2Key]['alias'] = level2Pages['own_url']['alias']\n $leftNavigation[itemKey]['level1'][pageKey]['childrens'][level2Key]['title'] = level2Pages['own_url']['title']\n end \n buildNavigation(pages['childrens'], itemKey) \n \n else \n # if this is last level page - we will show his parent as first level, and this page as children\n # we set level0 as parent array, and remove leve1, because we don't need it anymore\n if (parentSection != '' && pageKey == k) \n $leftNavigation[itemKey]['level0'] ||= {}\n $leftNavigation[itemKey]['level0'] = $leftNavigation[parentSection]['level1']\n $leftNavigation[itemKey].delete('level1')\n break;\n end\n end\n end #navhash pages loop \n end \n end #navhash arr loop \n end", "def navigation(start=1, descendants=1, breadcrumb=false)\n setup\n reset(start, descendants, breadcrumb)\n nav = unordered_list(navigation_origin)\n reset\n return nav\n end", "def each(&block)\n files, subdirectories = @children.partition do |child|\n child.is_a?(File)\n end\n\n files.each(&block)\n\n subdirectories.each do |subdirectory|\n block.call(subdirectory)\n\n subdirectory.each(&block)\n end\n end", "def navigation_list\n w.partial(\"navigation_list\", \n :locals => { :current_level => \"1\" })\n end", "def items(&block)\n @primary_navigation = ItemContainer.new\n block.call @primary_navigation\n end", "def buildNavigation(navHash, parentItemKey = '')\n if (navHash == nil && navHash.empty?)\n #puts \"Empty hash \"\n return\n end\n\n\n navHash.each do |pageId, pageData|\n\n itemKey = $CfeUtils.removeUnvantedChars(pageId)\n\n $leftNavigation[itemKey] ||= {}\n\n if (pageData.has_key?('alias') && !pageData['alias'].empty?)\n $breadcrumbsNavigation[itemKey] ||= {}\n $breadcrumbsNavigation[itemKey]['title'] = pageData['title']\n $breadcrumbsNavigation[itemKey]['alias'] = pageData['alias']\n else\n puts \"--------------------------------------------------------\"\n puts \"WARNING: Page: \" + k + \". Full path: \" + itemKey + \" doesn't have right meta tags\"\n puts \"--------------------------------------------------------\"\n end\n\n\n $leftNavigation[itemKey] ||= {}\n $leftNavigation[itemKey]['childrens'] ||= {}\n\n if (parentItemKey != '')\n # we need pages which are in the same lavel as current,\n # best way to do this is to get parent level page children\n $leftNavigation[itemKey]['uncles'] ||= {}\n\n if (!$leftNavigation[parentItemKey].empty?)\n $leftNavigation[itemKey]['uncles'] = $leftNavigation[parentItemKey]['childrens']\n end\n\n\n # also for pages with level 2+ we need information about parents\n $leftNavigation[itemKey]['parents'] ||= {}\n $leftNavigation[itemKey]['parents'] = $leftNavigation[parentItemKey]['uncles']\n\n\n end\n\n\n # current page properties\n $leftNavigation[itemKey]['alias'] = pageData['alias']\n $leftNavigation[itemKey]['title'] = pageData['title']\n $leftNavigation[itemKey]['level'] = pageData['level']\n $leftNavigation[itemKey]['parent_page'] = parentItemKey\n\n\n\n if (!pageData.empty? && !pageData.has_key?('childrens'))\n # for the 3-rd and 4-th level pages we must set their parent reference\n if (pageData['level'] == (CONST_MaxSubLevels - 2) || pageData['level'] == (CONST_MaxSubLevels - 1))\n $leftNavigation[itemKey]['parentReference'] ||= {}\n $leftNavigation[itemKey]['parentReference']['parentKey'] = parentItemKey\n $leftNavigation[itemKey]['parentReference']['parentData'] ||= {}\n $leftNavigation[itemKey]['parentReference']['parentData'][parentItemKey] = $leftNavigation[parentItemKey]\n end\n\n next\n end\n\n\n # level 1\n pageData['childrens'].each do |pageKey, pages|\n pageKey = $CfeUtils.removeUnvantedChars(pageKey)\n $leftNavigation[itemKey]['childrens'][pageKey] ||= {}\n $leftNavigation[itemKey]['childrens'][pageKey]['alias'] = pages['alias']\n $leftNavigation[itemKey]['childrens'][pageKey]['title'] = pages['title']\n $leftNavigation[itemKey]['childrens'][pageKey]['level'] = pages['level']\n $leftNavigation[itemKey]['childrens'][pageKey]['parent_page'] = itemKey\n end\n\n #recursively call for all 2 level pages\n buildNavigation(pageData['childrens'], itemKey)\n end\n end", "def walk(block)\r\n raise \"Must be passed a block\" unless block.kind_of?(Proc)\r\n all_children.map do |nr| block.call(nr) end\r\n end", "def cms_navigation\n nav = AdminController.cms_nav.map do |section|\n # First element is the title, second element is array of children.\n if section.is_a?(Array)\n render :partial => \"/admin/nav_section\",\n :locals => {:title => section[0], :children => section[1]}\n # Class should contain a partial override.\n elsif section.is_a?(Class)\n render_partial_for_controller(section)\n else\n raise RuntimeError, \"Unexpected CMS nav value: #{section}\"\n end\n end\n\n nav.compact.join(\"\\n\")\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For Displaying all The Shop Profiles
def index @shops = current_user.shop_profiles end
[ "def index\n @shopper_profiles = ShopperProfile.all\n end", "def index\n @shop_profiles = ShopProfile.all\n end", "def index\n @product_profiles = ProductProfile.all\n end", "def index\n @professional_profiles = ProfessionalProfile.all\n end", "def index\n @profs = Prof.all\n end", "def index\n @profiles = CertProfile.all\n end", "def index\n @proccs = Procc.all\n end", "def index\n @org_profiles = OrgProfile.all\n end", "def show\n\t\t@shop_profile = ShopProfile.find(params[:id])\n\t\t@items = @shop_profile.shop_products.where(shop_profile_id: @shop_profile.id)\n\t\t.paginate(page: params[:page], per_page: 6).search(params[:search])\n\t\tif !params[:category_id].nil?\n\t\t\t@items = @shop_profile.shop_products.where(category_id: params[:category_id])\n\t\t\t.paginate(page: params[:page], per_page: 6)\n\t\tend\n\tend", "def index\n @general_profiles = GeneralProfile.all\n end", "def index\n @gear_profiles = GearProfile.all\n end", "def index\n @cert_profiles = CertProfile.all\n end", "def index\n @progs = Prog.all\n end", "def index\n @order_profiles = current_user.order_profiles.all\n end", "def index\n @produits = Produit.all\n end", "def index\n @profils = Profil.all\n end", "def index\n @organisation_profiles = OrganisationProfile.all\n end", "def show\n @provisioning_profile = current_user.provisioning_profiles.find(params[:id])\n end", "def index\n @propperties = Propperty.all\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For Displaying all the Shop Products for a particular Shop Profile
def show @shop_profile = ShopProfile.find(params[:id]) @items = @shop_profile.shop_products.where(shop_profile_id: @shop_profile.id) .paginate(page: params[:page], per_page: 6).search(params[:search]) if !params[:category_id].nil? @items = @shop_profile.shop_products.where(category_id: params[:category_id]) .paginate(page: params[:page], per_page: 6) end end
[ "def index\n @shopper_profiles = ShopperProfile.all\n end", "def index\n @shop_profiles = ShopProfile.all\n end", "def index\n @product_profiles = ProductProfile.all\n end", "def index\n\t\t@shops = current_user.shop_profiles\n\tend", "def shop_products\n products.shop_products\n end", "def index\n @shop_physical_products = Shop::PhysicalProduct.all\n end", "def showSellerProduct\n @products = Product.where(:customer_id => session[:user_id], active: true)\n render 'sellerproducts'\n end", "def index\n @professional_profiles = ProfessionalProfile.all\n end", "def show\n @business_profile = BusinessProfile.find(params[:id])\n @products = Product.where(owner_id: @business_profile.id)\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @business_profile }\n end\n end", "def index\n @sproducts = Sproduct.where(\"vendor = ?\", current_user.shopify_product_vendor)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @sproducts }\n end\n end", "def get_all_products\n @products_arr = @product.get_products\n display_products\n end", "def create\r\n @products = Product.pluck :id\r\n @products = Product.all\r\n @shop_profile = ShopProfile.new(shop_profile_params)\r\n\r\n respond_to do |format|\r\n if @shop_profile.save\r\n format.html { redirect_to @shop_profile, notice: \"Shop profile was successfully created.\" }\r\n format.json { render :show, status: :created, location: @shop_profile }\r\n else\r\n format.html { render :new, status: :unprocessable_entity }\r\n format.json { render json: @shop_profile.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def index\n @has_products = HasProduct.all\n end", "def products(params = {})\n @products ||= Product.find_all_by_shop_id(user_id.to_s, params)\n end", "def get_product_list\r\n if params[:user_id] && user = User.find(params[:user_id])\r\n user.products.all\r\n else\r\n Product.all #kaminari needs a scope\r\n end\r\n end", "def list_my_products\n if signed_in?\n @products = Product.find(:all, :conditions => { :user_id => current_user.id} )\n @search = Hash.new\n render 'list_my_products'\n else\n redirect_to root_url\n end\n end", "def show\n @product_core = @store.product_cores.find(params[:id])\n @categories = Category.all\n @allinstances = ProductInstance.find_all_by_sku(@product_core.sku)\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @product_core }\n end\n end", "def products\n # Find merchant id\n # Find products linked to that merchant\n # Show them\n id = params[:user_id].to_i\n @merchant = User.find_by(id: id)\n\n if @merchant.nil?\n render :notfound, status: :not_found\n end\n @products = @merchant.products.all\n\n end", "def all_products\n # Retrieve all of the active products\n @products = Product.active_products\n\n # Check to see if we have a query parameter. This is used for the product search bar\n if params[:query]\n @products = @products.search(params[:query])\n end\n\n # Scope the products to only display the ones available based on country selection\n @products = @products.country_specific(session[:site_country])\n\n # Check to see if we have to display a filtered list\n if !params[:category_id].nil?\n # A category filter exists, we will further filter the products\n @products = @products.category_specific(Category.find(params[:category_id]).descendents)\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For Creating a New Shop Profile for a Shopkeeper
def create authorize ShopProfile @shop = ShopProfile.new(shop_params) @shop.build_address(address_params_shopkeeper) if @shop.valid? and ! current_user.user_profile.nil? current_user.shop_profiles << @shop flash[:success] = 'Shop Details added' redirect_to root_path elsif current_user.user_profile.nil? flash[:danger] = 'Please enter Personal Details before adding a Shop' redirect_to new_user_profile_path else flash[:error] = 'Shop Details not added' render 'new' end end
[ "def create\n @shopper_profile = ShopperProfile.new(shopper_profile_params)\n\n respond_to do |format|\n if @shopper_profile.save\n format.html { redirect_to @shopper_profile, notice: 'Shopper profile was successfully created.' }\n format.json { render action: 'show', status: :created, location: @shopper_profile }\n else\n format.html { render action: 'new' }\n format.json { render json: @shopper_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_profile!\n bundle_id = Sigh.config[:app_identifier]\n name = Sigh.config[:provisioning_name]\n if !name\n name = Sigh.config[:app_identifier].gsub '.' ,''\n end\n\n UI.important \"Creating new provisioning profile for '#{Sigh.config[:app_identifier]}' with name '#{name}'\"\n profile = profile_type.create!(name: name,\n bundle_id: bundle_id)\n profile\n end", "def create\r\n @products = Product.pluck :id\r\n @products = Product.all\r\n @shop_profile = ShopProfile.new(shop_profile_params)\r\n\r\n respond_to do |format|\r\n if @shop_profile.save\r\n format.html { redirect_to @shop_profile, notice: \"Shop profile was successfully created.\" }\r\n format.json { render :show, status: :created, location: @shop_profile }\r\n else\r\n format.html { render :new, status: :unprocessable_entity }\r\n format.json { render json: @shop_profile.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def create\n @shop = Shop.find(current_owner.id)\n @user = User.find_for_authentication(:email => params[:loyalty][:name])\n @loyalty = @shop.loyalties.create({:profile_id => @user.id, :points => params[:loyalty][:points]})\n redirect_to shop_path(@shop)\n end", "def create_profile\n new_profile = Profile.new\n new_profile.user_id = self.id\n new_profile.save!\n end", "def create\n @profile = Profile.find(params[:profile_id])\n @shelf = @profile.shelves.create(params[:shelf])\n \n respond_to do |format|\n if @shelf.save\n format.html { redirect_to profile_shelves_path(@profile), notice: 'Shelf was successfully created.' }\n format.json { render json: @shelf, status: :created, location: @shelf }\n else\n format.html { render action: \"new\" }\n format.json { render json: @shelf.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_profile\n self.profile = Profile.create(user_id: id)\n end", "def save_and_create_profile\n self.profile = Profile.new\n self.save\n end", "def create_DB_profile\n \n @profile = ProfileId.new\n @profile.user_name = params[:user_name]\n @profile.profile_id = @parsed[\"profileId\"]\n @profile.save\n end", "def create\n @profile = current_user.profiles.build(profile_params)\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render action: 'show', status: :created, location: @profile }\n else\n format.html { render action: 'new' }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = Profile.new(profile_params)\n\n if @profile.save\n render json: @profile, status: :created, location: [:web, @profile]\n else\n render json: @profile.errors, status: :unprocessable_entity\n end\n end", "def create_customer_profile(options)\n requires!(options, :profile)\n requires!(options[:profile], :email) unless options[:profile][:merchant_customer_id] || options[:profile][:description]\n requires!(options[:profile], :description) unless options[:profile][:email] || options[:profile][:merchant_customer_id]\n requires!(options[:profile], :merchant_customer_id) unless options[:profile][:description] || options[:profile][:email]\n\n request = build_request(:create_customer_profile, options)\n commit(:create_customer_profile, request)\n end", "def create\n @security_profile = Security::Profile.new(security_profile_params)\n @security_profile.user_created_id = current_user.id\n respond_to do |format|\n if @security_profile.save\n format.html { redirect_to security_profiles_path, notice: I18n.t('profiles.controller.create')}\n format.json { render :show, status: :created, location: @security_profile }\n else\n format.html { render :new }\n format.json { render json: @security_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = current_user.profiles.create(params[:profile])\n @profile.add_properties(params[:property])\n\n if @profile.save\n flash[:notice] = 'Profile was successfully created.'\n redirect_to :action => 'list'\n else\n render :action => 'new' \n end\n end", "def create\n @user = current_user()\n @profile = @user.profiles.new(params[:profile])\n\n respond_to do |format|\n if @profile.save\n flash[:notice] = 'Profile was successfully created.'\n format.html { redirect_to(@profile) }\n format.xml { render :xml => @profile, :status => :created, :location => @profile }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @profile.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @provisioning_profile = current_user.provisioning_profiles.new(params[:provisioning_profile])\n\n if @provisioning_profile.save\n redirect_to provisioning_profiles_url, notice: 'Provisioning profile was successfully created.'\n else\n render action: \"new\"\n end\n end", "def create_profile\n\t\t# update the last created profile to associate with user\n\t\tProfile.last.update(user_id: User.last.id, fname: User.last.name.split[0], lname: User.last.name.split[1])\n\tend", "def create\n @profile = current_user.profiles.new(params[:profile])\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render json: @profile, status: 201, location: @profile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @profile.errors, status: 422 }\n end\n end\n end", "def create\n @professional_profile = ProfessionalProfile.new(professional_profile_params)\n @professional_profile.user = current_user\n\n respond_to do |format|\n if @professional_profile.save\n format.html { redirect_to @professional_profile, notice: 'Professional profile was successfully created.' }\n format.json { render :show, status: :created, location: @professional_profile }\n else\n format.html { render :new }\n format.json { render json: @professional_profile.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For Updating a Shop Profile Details
def update @shop = current_user.shop_profiles.find(params[:id]) authorize @shop if @shop.update_attributes(shop_params) and @shop.address.update_attributes(address_params_shopkeeper) flash[:success] = 'Updated Successfully' redirect_to shop_profiles_path else flash[:danger] = 'Shop Details not Updated' render 'edit' end end
[ "def update\r\n respond_to do |format|\r\n if @shop_profile.update(shop_profile_params)\r\n format.html { redirect_to @shop_profile, notice: \"Shop profile was successfully updated.\" }\r\n format.json { render :show, status: :ok, location: @shop_profile }\r\n else\r\n format.html { render :edit, status: :unprocessable_entity }\r\n format.json { render json: @shop_profile.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def update\n respond_to do |format|\n if @shopper_profile.update(shopper_profile_params)\n format.html { redirect_to @shopper_profile, notice: 'Shopper profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @shopper_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n\t\t# Updating the details according the that particular profile\n\t\t@profile.update_attributes(profile_params)\n\t\t# Redirect to the particular surgeon profile show page\n\t\tredirect_to profile_path(@profile)\n\tend", "def update_profile\n @profile = @account.employee\n \n if params[:profile].present?\n @profile.assign_attributes(profile_params)\n @profile.save\n redirect_to gns_core.my_profile_backend_accounts_path, flash: {success: 'Profile has been updated successfully.'}\n else\n redirect_to gns_core.my_profile_backend_accounts_path, flash: {error: 'Profile update failed. Please try again!'}\n end\n end", "def update_profile\n @update_profile = User.find(current_user.id)\n current_email = @update_profile.update(email: user_profile_params[:email])\n current_name = @update_profile.update(name: user_profile_params[:name])\n current_mobile = @update_profile.update(mobile: user_profile_params[:mobile])\n @update_profile.save\n redirect_to root_path\n end", "def update\n profile = self.bookalope.http_get('/api/profile')['user']\n self.firstname = profile['firstname']\n self.lastname = profile['lastname']\n end", "def update_profession\n @general_info = GeneralInfo.find_by(userKey: session[:current_user_key])\n \n if @general_info.update_attribute(specific_profile_id, :specific_profile_id)\n redirect_to '/show_profile'\n else\n render :action => 'edit_profession'\n end\n end", "def update\n respond_to do |format|\n if @profile.update(quoter_profile_params)\n # format.html { redirect_to @profile.user, notice: 'Profile was successfully updated.' }\n format.html { redirect_to users_url }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_profile(options = {}) \n # query profile info\n response = HTTP.auth('Bearer ' + Asca::Tools::Token.new_token).get(URI_PROFILES, :params => { 'filter[name]' => options[:name] })\n if response.status.success?\n responseObj = JSON.parse(response.body)\n queried_profile_list = responseObj[\"data\"]\n if queried_profile_list.length() > 0\n profile = queried_profile_list[0]\n end\n else\n Asca::Tools::Log.error(response.body)\n return\n end\n \n if !profile\n Asca::Tools::Log.error(\"No profile named #{options[:name]} found\")\n return\n end\n # create new profile\n profile_type = profile[\"attributes\"][\"profileType\"]\n \n # get bundle id\n response = HTTP.auth('Bearer ' + Asca::Tools::Token.new_token).get(profile[\"relationships\"][\"bundleId\"][\"links\"][\"self\"])\n bundle_id = JSON.parse(response.body)[\"data\"][\"id\"]\n response = HTTP.auth('Bearer ' + Asca::Tools::Token.new_token).get(profile[\"relationships\"][\"certificates\"][\"links\"][\"self\"])\n certificate_ids = JSON.parse(response.body)[\"data\"].map { |cer| cer[\"id\"] }\n \n # get all device ids\n device_ids = Asca::REST::Provisioning::Devices.list_devices.map { |device|\n device[\"id\"]\n }\n \n # delete old prifile\n delete_profile :name => options[:name]\n \n if profile_type.include? 'APP_STORE'\n create_new_profile :name => options[:name], :type => profile_type, :bundle_id => bundle_id, :certificate_ids => certificate_ids\n else\n create_new_profile :name => options[:name], :type => profile_type, :bundle_id => bundle_id, :device_ids => device_ids, :certificate_ids => certificate_ids\n end\n \n return true\n end", "def update\n respond_to do |format|\n if @profile.update(customer_profile_params)\n # format.html { redirect_to @profile.user, notice: 'Profile was successfully updated.' }\n format.html { redirect_to users_url }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def profile\r\n if request.post?\r\n @customer.update_attributes :email => params[:customer][:email], :phone => params[:customer][:phone]\r\n @store_user.my_account_log(@customer,\"Update Profile Email: #{@customer.email} Phone: #{@customer.phone}\")\r\n @customer.update_ax\r\n end\r\n end", "def profile_update(profile,user)\n @profile=profile\n @user=user\n mail to: @user.email, subject: \"Profile updated (Socail Trip App)\", from:'test@example.com'\n end", "def update\n @profile = current_user.profiles.find(params[:id])\n\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n format.html { redirect_to(@profile, :notice => 'Profile was successfully updated.') }\n format.xml { head :ok }\n format.json { render :json => @profile }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @profile.errors, :status => :unprocessable_entity }\n format.json { render :json => {:error => @profile.errors.full_messages} }\n end\n end\n end", "def updateProfile(profile_params)\n user = getUserById(profile_params.id)\n isUpdateProfile = UserRepository.updateProfile(user, profile_params)\n end", "def update\n @profile = current_user.profiles\n\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n flash[:notice] = 'Profile was successfully updated.'\n format.html { redirect_to(@profile) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @profile.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @profile = User.find( params[:user_id] ).profile\n \n # Mass assign edited profile attributes and save\n if @profile.update_attributes(profile_params)\n flash[:success] = \"Profile updated\"\n # Redirect user to their profile page\n redirect_to user_path( id: params[:user_id] )\n else\n render action :edit\n end\n end", "def update\n # Retrieve user from db\n @user = User.find(params[:user_id])\n # Retrieve that user's profile\n @profile = @user.profile\n \n # Mass assign edited profile attributes from whitelisting below\n if @profile.update_attributes(profile_params)\n flash[:success] = \"Profile has been updated!\"\n redirect_to user_path(id: params[:user_id])\n else\n render action: :edit\n end\n \n end", "def update_profile(profile)\n @type = Type::CIM_UPDATE_PROFILE\n @fields.merge!(profile.to_hash)\n make_request\n end", "def edit_profile\n\t\t# prepopulates form with current profile info\n\t\tprofile = Profile.find_by(user_id: params[:id])\n\t\t@alias = profile.user_name\n\t\t@bio = profile.bio\n\t\t@image = profile.image\n\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Changing Status of a Shop Profile to Approved or Disapproved
def change_status authorize ShopProfile @shop = ShopProfile.find(params[:shop_profile_id]) #Calling method approve_shop from Model ShopProfile.approve_shop(@shop, flash) redirect_to request.referrer || root_path end
[ "def change_status\n self.status = USER_STATUS_ACTIVE if (self.status == USER_STATUS_PENDING && self.confirmed?)\n end", "def check_status\n\t\t@shop = ShopProfile.find_by(id: params[:shop_profile_id])\n\t\tif @shop.is_approved == false\n\t\t\tflash[:danger] = 'You are not approved to add products'\n\t\t\tredirect_to root_path\n\t\tend\n\tend", "def set_profile_active_and_save!\n self.status = 'active'\n self.save\n end", "def approve\n #get profile, and profile owner\n presenter = find_presenter\n profile = presenter.presenter_profile\n \n #check status of profile\n #if waiting for admin approval\n if profile.status == \"pending_admin\"\n #check if logged in user is an admin\n if current_user.user_type == \"admin\"\n if profile.approve\n flash[:info] = \"This profile has been approved\"\n Notification.send_message(presenter.user, \"Your profile changes have been approved.\", presenter_profile_path(presenter), :system)\n redirect_to presenter_profile_path(presenter)\n else\n flash[:danger] = \"Something went wrong\"\n redirect_to presenter_profile_path(presenter)\n end\n \n else #Incorrect user\n flash[:info] = \"Profile changes are waiting for approval from admin.\"\n redirect_to root_url\n end\n\n #if waiting for profile owner approval\n elsif profile.status == \"pending_presenter\"\n #check if logged in presenter is profile owner\n if presenter == current_user.presenter\n if profile.approve\n flash[:info] = \"Your profile has been approved\"\n redirect_to presenter_profile_path(presenter)\n else\n flash[:danger] = \"Something went wrong\"\n redirect_to presenter_profile_path(presenter)\n end\n else #incorrect user\n flash[:info] = \"Profile changes are waiting approval from presenter\"\n redirect_to presenter_profile_path(presenter)\n end\n\n else #profile is already approved\n flash[:warning] = \"Profile is already approved\"\n redirect_to root_url\n end\n end", "def approved=(is_approved)\n if is_approved && is_approved != 0 && is_approved != \"0\"\n self.status = Status::ACTIVE\n else\n self.status = Status::UNAPPROVED\n end\n end", "def compliance_approved\n approve = true\n self.asins.each do |asin|\n approve = approve and asin.status.eql?(\"compliance_approved\")\n end\n self.status = \"compliance_approved\" if approve\n self.save\n end", "def alter_status(params = {})\n req = WebPay::ShopRequestAlterStatus.create(params)\n raw_response = @client._request(:post, 'shops' + '/' + req.id.to_s + '/' + 'alter_status', req)\n WebPay::ShopResponse.new(raw_response)\n end", "def approve!\n self.update_attribute(:state, 'approved')\n end", "def approve!\n self.update_attribute(:status, APPROVED)\n self.stock_entries.update_all(status: StockEntry::ACTIVE)\n true\n end", "def approve\n @organization.status = 'active'\n @organization.save\n redirect_to admin_organizations_path\n end", "def update_status_after_moderation\n if order_items.customized.detect { |item| item.approved == false }\n Core.log(\"=== SETTING ORDER STATUS TO REJECTED: #{id}\")\n set_status('Asset(s) Rejected')\n OrderStatus.create(:order_id => id, :status => 'Asset(s) Rejected')\n elsif !order_items.customized.detect { |item| item.approved.nil? }\n if self.order_items.detect{|i| i.orderable_type == \"NonCustomizableProduct\"} && self.order_items.select{|i| i.orderable_type == \"NonCustomizableProduct\"}.length == self.order_items.length\n Core.log(\"=== SETTING ORDER STATUS TO READY TO SHIP: #{id}\")\n self.set_status('Ready to Ship') \n else\n Core.log(\"=== SETTING ORDER STATUS TO ASSETS APPROVED: #{id}\")\n self.set_status('Asset(s) Approved')\n OrderStatus.create(:order_id => self.id, :status => 'Asset(s) Approved')\n end\n end\n end", "def approve!\n\t\tif self.status == \"active\"\n\t\t\traise \"ERROR in approving an already active member\"\n\t\telsif self.status == \"rejected\"\n\t\t\traise \"ERROR cannot approve rejected member\"\n\t\telse\n\t\t\tself.update!(status: \"active\")\n\t\tend\n\tend", "def modify_status\n if params[:status]\n @article.declined!\n else\n if current_user.admin?\n @article.approved!\n elsif current_user.moderator?\n @article.moderator_approved!\n end\n end\n redirect_to(:back)\n end", "def approval_status\n self.approved? ? 'Approved ' : 'Pending '\n end", "def update_status!(stripe_account, new_status)\n stripe_account.reload\n stripe_account.status = new_status if stripe_account.status != \"active\"\n stripe_account.save!\n end", "def approve\n update_attribute :needs_review, false\n end", "def unapprove!\n self.update_attribute :approved, false\n end", "def approve\n profile = Profile.find(params[:profile][:id]) if params[:profile]\n current_profile.approves!(@submission, for_profile: profile)\n respond_to do |format|\n format.html { redirect_to @submission }\n format.json { head :no_content }\n end\n end", "def admin_approve_user\n @user.update(approved: true)\n redirect_to admin_path, notice: \"User Approved\"\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns next wednesday from current date
def next_wednesday date = self while !date.wednesday? date = date.next end date end
[ "def next_weekday(weekday = 2)\n date = Date.today\n unless date.strftime(\"%w\") == weekday.to_s\n date += 1 + ((weekday -1 -date.wday) % 7)\n end\n date\n end", "def next_weekday\n if next_day.on_weekend?\n next_week(:monday, same_time: true)\n else\n next_day\n end\n end", "def next_weekday\n next_wday = base_wday < weekdays.max ? next_time_value(weekdays, base_wday) : weekdays.min\n Date.parse(Date::DAYNAMES[next_wday]) + week_adjustment(next_wday)\n end", "def wednesday\n day(:wednesday)\n end", "def next_occurring(day_of_week); end", "def next_week(day = :monday)\n days_into_week = { :monday => 0, :tuesday => 1, :wednesday => 2,\n :thursday => 3, :friday => 4, :saturday => 5,\n :sunday => 6 }\n since(1.week).beginning_of_week.since(days_into_week[day].day).change(:hour => 0)\n end", "def next_week(day = :monday)\r\n days_into_week = { :monday => 0, :tuesday => 1, :wednesday => 2, :thursday => 3, :friday => 4, :saturday => 5, :sunday => 6}\r\n result = (self + 7).beginning_of_week + days_into_week[day]\r\n self.acts_like?(:time) ? result.change(:hour => 0) : result\r\n end", "def next_monday(date)\n date += ((1-date.wday) % 7).days\n end", "def find_next_week\n if @schedule.days == 0\n date = @date + ((@schedule.start_date.wday - @date.wday) % 7) + (7 * ((@schedule.start_date - @date) % @schedule.period_num))\n return date\n else\n date = @date + find_next_in_bitmask(@schedule.days, @date.wday, 7)\n\n if @date.wday >= bitmask(@schedule.days).length\n date += periods_to_add * 7\n end\n\n return date\n end\n end", "def next_day\r\n if @next_day.nil?\r\n @next_day = convert_day_to_date(current_day).tomorrow.strftime('%Y%m%d')\r\n end\r\n @next_day\r\n end", "def date_of_next(day)\n date = Date.parse(day)\n delta = date > Date.today ? 0 : 7\n date + delta\nend", "def next_occurring(day_of_week)\n from_now = DAYS_INTO_WEEK.fetch(day_of_week) - wday\n from_now += 7 unless from_now > 0\n advance(days: from_now)\n end", "def next_schedule_day\n date = self\n while date.weekend? or date.ca_holiday?\n date = date.next\n end\n return date\n end", "def next_working_date(date)\n cwday = date.cwday\n days = 0\n while non_working_week_days.include?(((cwday + days - 1) % 7) + 1)\n days += 1\n end\n date + days\n end", "def find_next_day\n day = @date.to_date + ((@schedule.start_date - @date.to_date) % @schedule.period_num)\n return day\n end", "def getNextSaturday(dateToday)\n nextSaturday = dateToday + ((6 - dateToday.wday) % 7)\n if dateToday == nextSaturday\n nextSaturday + 7\n else\n nextSaturday\n end\n end", "def next_show_date\n interval = SATURDAY - Date.today().wday\n interval = SATURDAY if (interval < 0)\n\n Date.today + interval\n end", "def next_sunday(due_to_date)\n right_now = Time.zone.now\n right_now += 6.days if right_now <= due_to_date # approximation should be fine, ignore edge cases for now\n return right_now + (7 - right_now.wday).days + (22 - right_now.hour).hours + (0 - right_now.min).minutes + (0 - right_now.sec).second\n end", "def next_sunday(due_to_date)\n\t\t\tright_now = Time.zone.now\n\t\t\tright_now += 6.days if right_now <= due_to_date # approximation should be fine, ignore edge cases for now\n return right_now + (7 - right_now.wday).days + (22 - right_now.hour).hours + (0 - right_now.min).minutes + (0 - right_now.sec).second\n\t end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Store data to memcache using the specified key ==== Parameters key:: The key identifying the cache entry data:: The data to be put in cache from_now:: The number of minutes (from now) the cache should persist
def cache_set(key, data, from_now = nil) _expire = from_now ? from_now.minutes.from_now.to_i : 0 @memcache.set(key, data, _expire) cache_start_tracking(key) Merb.logger.info("cache: set (#{key})") true end
[ "def cache_set(key, data, from_now = nil)\n cache_file = @config[:cache_directory] / \"#{key}.cache\"\n cache_directory = File.dirname(cache_file)\n FileUtils.mkdir_p(cache_directory)\n _expire = from_now ? from_now.minutes.from_now : nil\n cache_write(cache_file, Marshal.dump([data, _expire]))\n Merb.logger.info(\"cache: set (#{key})\")\n true\n end", "def cache_set(key, data, from_now = nil)\n _expire = from_now ? from_now.minutes.from_now : nil\n CacheModel.cache_set(key, Marshal.dump(data), _expire)\n Merb.logger.info(\"cache: set (#{key})\")\n true\n end", "def cache_set(key, data, from_now = nil)\n _expire = from_now ? from_now.minutes.from_now : nil\n cache_write(key, [data, _expire])\n Merb.logger.info(\"cache: set (#{key})\")\n true\n end", "def write(key, value, expires_in: nil)\n @cache[key] = value\n @expires[key] = Faulty.current_time + expires_in unless expires_in.nil?\n end", "def set_into_cache(key, value, expiry = 0)\n cache_class.set(key, value, expiry)\n end", "def write(key, data = nil, parameters = {}, conditions = {})\n if writable?(key, parameters, conditions)\n begin\n @memcached.set(normalize(key, parameters), data, expire_time(conditions))\n true\n rescue\n nil\n end\n end\n end", "def store(key, value, options = {})\n # todo What's the best way to run these two calls at once, given that it's very much one-at-a-time\n exp = options[:expires_in] ? (Time.now + options[:expires_in]) : nil\n @mongo_collection.update({ '_id' => key }, { '_id' => key, 'data' => value, 'expires' => exp }, { :upsert => true }) # upsert is the best technical term ever.\n \n unless options.has_key?(:bypass_memcache)\n args = [key, value, options[:expires_in] || @options[:memcache_default_expire]].compact\n @memcache.set(*args)\n end\n \n value\n end", "def store(key, data)\n @data[key] = data\n flush\n end", "def store(value, *key)\n @cache[key] = value\n end", "def put(namespace, key, entry)\n @lock.synchronize do\n now = Time.now.utc.to_i\n prune_expired(now)\n @entries[full_key(namespace, key)] = entry\n prune_size\n end\n end", "def write(key, data)\n return false if data.blank?\n return false unless store(key, data)\n @cache.write(key, data)\n end", "def set_keycache(key,encoded_key,expires = 3600)\n @keycache = {\n :expires => Time.now.to_i + expires,\n :key => key,\n :encoded_key => encoded_key\n }\n write_settings\n end", "def set(key, val, timeout = nil)\n @pstore.transaction do\n # calculate expiration time\n expires = timeout ? (Time.now.to_i + timeout) : nil\n\n # save entry\n @pstore[key] = ::WeatherSage::CacheEntry.new(expires, val)\n\n # purge any expired entries\n flush\n end\n\n # return value\n val\n end", "def save(key, value)\n return if @capacity <= 0\n\n @cache_mutex.synchronize do\n @map.delete(key) if @map.key?(key)\n\n @map[key] = CacheElement.new(value)\n\n @map.delete(@map.first[0]) if @map.size > @capacity\n nil\n end\n end", "def ping_key(key)\n return nil if invalid_key?(key)\n @mutex.synchronize do\n @keys[key]['time_stamp'] = Time.new\n end\n end", "def add_key key\n @keystore.add_key(key)\n @storage.add_watched_address(key[:addr])\n end", "def save_data(key, data, expire_on = nil)\n raise 'The save_data method must be implemented'\n end", "def set(key, value, expires: nil)\n validate_key(key)\n validate_value(value)\n\n mset({ key => value }, expires: expires)\n end", "def put(token, expires_in, data={})\n @store.write(key_for(token), data, expires_in: expires_in)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Expire the cache entries matching the given key ==== Parameter key:: The key matching the cache entries ==== Additional info In memcache this requires to keep track of all keys (on by default). If you don't need this, set :no_tracking => true in the config.
def expire_match(key) if @tracking_key for _key in get_tracked_keys expire(_key) if /#{key}/ =~ _key end else Merb.logger.info("cache: expire_match is not supported with memcache (set :no_tracking => false in your config") end true end
[ "def expire_cached(key:)\n Stockpile::CachedValueExpirer.expire_cached(key: key)\n end", "def expire_cache!(key)\n raise 'The expire_cache method must be implemented'\n end", "def cache_expire(key:)\n begin\n CACHE.delete(key)\n rescue Redis::CannotConnectError || Redis::ConnectionError || Redis::TimeoutError\n exit\n end\n end", "def invalidate( key )\n\t\tself.log.debug \"invalidating cache key '%p' for %s\" % [key, self.name]\n\t\tsuper\n\tend", "def expire_cache_keys *keys\r\n keys.each { |k| @cache.delete k.to_sym }\r\n end", "def invalidate(key)\n full_key = namespaced(key)\n announce_cache_invalidate(full_key)\n\n storage.delete(full_key)\n end", "def delete_from_cache(key)\n cache_class.delete(key)\n end", "def expire_counts(key)\n # The oldest day we want to keep, like 20130317\n oldest_date = (Date.today() - days_to_store - 1).strftime('%Y%m%d').to_i\n fields_to_delete = []\n\n # Each of the fields is like '20130317'.\n redis.hkeys(key).sort!.each do |field|\n if field.to_i < oldest_date\n fields_to_delete.push(field)\n else\n break\n end\n end\n\n if fields_to_delete.length > 0\n redis.hdel('a', fields_to_delete)\n end\n end", "def expire_all\n adapter.expire_all\n logger.info('', '', :expired, cache_name)\n end", "def expire(key, seconds); end", "def cache_delete(key)\n @cache_store.delete(key)\n nil\n end", "def expire_cache(*args)\n Rails.cache.delete(cache_id(*args))\n end", "def evict(key)\n @cache.delete(key) unless key.nil?\n end", "def reset!(key)\n # If $redis is not available, it tries to create the redis connection\n $redis ||= Redis.new(:url => 'redis://127.0.0.1:6379')\n\n prepend = (defined?(Rails) ? Rails.env + '_' : '')\n\n # Used for 'when' happened\n key_for_time = prepend + key + '_time'\n # Used for actual data\n key_for_value = prepend + key + '_values'\n\n $redis.del(key_for_value, key_for_time)\n end", "def evict(key)\n @data_expires_at.delete(key)\n cache_value = @data.delete(key)\n @current_size_bytes -= size_of(key, cache_value)\n end", "def pexpire(key, milliseconds); end", "def clear_all_expired\n t = Time.now\n\n @cache.each_pair do |name, entry|\n clear_if_expired(name, entry, t)\n end\n end", "def set_expiry(key, time)\n cache.set_expiry(key, time)\n end", "def expire_time(key)\n @store[key].expires_at\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gives info on the current cache store ==== Returns The type of the current cache store
def cache_store_type "memcache" end
[ "def type\n @config[:caching][:type]\n end", "def retrieve_store_class(store)\n require \"active_support/cache/#{store}\"\n rescue LoadError => e\n raise \"Could not find cache store adapter for #{store} (#{e})\"\n else\n ActiveSupport::Cache.const_get(store.to_s.camelize)\n end", "def cache_store_type\n \"database\"\n end", "def session_store_type\n \"memcache\"\n end", "def retrieve_store_class(store)\n # require_relative cannot be used here because the class might be\n # provided by another gem, like redis-activesupport for example.\n require \"active_support/cache/#{store}\"\n rescue LoadError => e\n raise \"Could not find cache store adapter for #{store} (#{e})\"\n else\n ActiveSupport::Cache.const_get(store.to_s.camelize)\n end", "def store_info\n @params[:stores].collect { |store| store.class.name }\n end", "def store_information\n get('store')\n end", "def cache_store\n ActionController::Base.cache_store\n end", "def store\n current_store =\n if store_key\n Spree::Store.find_by(code: store_key) ||\n Store.where(\"url like ?\", \"%#{store_key}%\").first\n end\n\n current_store || Spree::Store.default\n end", "def cache_store\n Rails.cache\n end", "def store\n backends[\"store\"]\n end", "def is_store?\n @type == :store\n end", "def storage_type\n @storage_type\n end", "def storage_class\n data[:storage_class]\n end", "def storage_type\n @dbi.storage_type\n end", "def adapter\n if @@adapter == :cache_store\n Cashier::Adapters::CacheStore\n else\n Cashier::Adapters::RedisStore\n end\n end", "def object_cache_info\n communicate(type: :object_cache_info)\n end", "def current_store_id\n Thread.current[REQUEST_STORE_ID]\n end", "def storage_class\n data.storage_class\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Store the tracked keys in memcache (used by expire_match) ==== Parameter keys:: The keys to keep track of
def set_tracked_keys(keys) @memcache.set(@tracking_key, keys) end
[ "def expire_cache_keys *keys\r\n keys.each { |k| @cache.delete k.to_sym }\r\n end", "def cache_all(keys, values, options = {})\n keys.zip(values) { |k, v| @cache.write(cache_key(k), v, options) }\n end", "def _store(*key_elements, value)\n cache.put(_key(*key_elements), value)\n end", "def mexists(keys)\n validate_key_array(keys)\n\n Result.new {\n existing_keys = GitHub::SQL.values(<<-SQL, :keys => keys, :now => now, :connection => connection).to_set\n SELECT `key` FROM key_values WHERE `key` IN :keys AND (`expires_at` IS NULL OR `expires_at` > :now)\n SQL\n\n keys.map { |key| existing_keys.include?(key) }\n }\n end", "def mexists(keys)\n validate_key_array(keys)\n\n Result.new {\n existing_keys = GitHub::SQL.values(<<-SQL, :keys => keys, :now => now, :connection => connection).to_set\n SELECT `key` FROM #{@table_name} WHERE `key` IN :keys AND (`expires_at` IS NULL OR `expires_at` > :now)\n SQL\n\n keys.map { |key| existing_keys.include?(key) }\n }\n end", "def update(hash, keys)\n\tnow=Time.now.to_i\n\tkeys.each { |key|\n\t\tnext unless hash.key?(key)\n\t\thash[key]=now\n\t}\nend", "def add_keys(new_keys)\n if new_keys.is_a? KeySet\n add_keys(new_keys.keys)\n else\n [*new_keys].each { |new_key| @key_map[new_key.kid] = new_key }\n end\n end", "def hydrate_store(keys, iss)\n keys.each do |key|\n store.set(\n iss, key['kid'],\n JSON::JWK.new(\n kty: key['kty'],\n e: key['e'],\n n: key['n'],\n kid: key['kid']\n )\n )\n end\n end", "def keys=(keys)\n extend ArrayKeys::KeyAccess if keys\n @keys = keys.frozen? ? keys.dup : keys\n unless @keys.respond_to?(:key_pos)\n @keys.extend(ArrayKeys::KeySet)\n end\n end", "def set_key_files( files )\n @key_manager.clear!\n files.each { |file| @key_manager << file }\n end", "def cache_keys(identifiers)\n identifiers.map { |identifier| cache_key(identifier) }\n end", "def session_keys=(keys) #:nodoc:\n @@session_keys=keys\n end", "def add_keys(keys)\n keys.each { |key| @counts[key] = 0 }\n end", "def fetch_multi(*keys, &block)\n return {} if keys.size == 0\n result = {}\n result = cache.read_multi(*keys) if should_cache?\n\n missed_keys = keys - result.select {|key, value| value.present? }.keys\n\n if missed_keys.size > 0\n if block_given?\n replacement_results = nil\n ActiveRecord::Base.connection.with_master do\n replacement_results = yield missed_keys\n end\n missed_keys.zip(replacement_results) do |(key, replacement_result)|\n if should_cache?\n replacement_result = map_cached_nil_for(replacement_result )\n cache.write(key, replacement_result)\n logger.debug \"[IdentityCache] cache miss for #{key} (multi)\"\n end\n result[key] = replacement_result\n end\n end\n else\n result.keys.each do |key|\n logger.debug \"[IdentityCache] cache hit for #{key} (multi)\"\n end\n end\n\n result.keys.each do |key|\n result[key] = unmap_cached_nil_for(result[key])\n end\n\n result\n end", "def cache_delete(*keys)\n keys.each {|key| @moneta.delete(key) }\n end", "def save_fetched_keys(params)\n if Commands::RETRIEVAL_COMMANDS.include?(params[:command])\n params[:keys].each { |key| fetched_records_time[key.to_sym] = Time.now }\n end\n end", "def store_paths_to_visit(paths)\n return if paths.empty?\n redis.sadd paths_to_visit_key, paths\n end", "def store(value, *key)\n @cache[key] = value\n end", "def import_by_using_cached_keys\n CommitKeyCreator.update_key_associations @blob.keys.to_a, @commit\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve tracked keys from memcache ==== Returns keys:: The tracked keys
def get_tracked_keys @memcache.get(@tracking_key) || [] end
[ "def keys\n cache.keys\n end", "def keys\n redis.hkeys(key)\n end", "def getallkeys\t\t\t\t\n\t\t\treturn $redis.keys\"*\"\n\t\tend", "def cache_objects_keys\n @object_data[].keys\n end", "def key_ids\n @keys.keys\n end", "def keys\n db = open_db\n begin\n keys = db.keys\n ensure\n db.close\n end\n return keys\n end", "def get_keys\n @store.keys\n end", "def keys\n storage_hash.keys\n rescue\n nil\n end", "def keys\n @store.keys\n end", "def keys\n @store.keys\n end", "def keys\n dict.keys\n end", "def key_ids\n return @key_ids\n end", "def keys\n list = []\n each_key{|key| list << key}\n list\n end", "def each\n kys = @cache.keys\n @db.execute(\"select id from tmud;\") do |k|\n kys << k.to_i\n end\n kys.uniq!\n kys.each {|k| yield @cache.get(k)}\n end", "def cached_files()\n @@file_cache.keys\n end", "def list\n @keychain.keys\n end", "def all_keys\n self.key_list_set.members.to_a\n end", "def keys\n @counts.keys\n end", "def list_keys()\n # TODO\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Seed an image by passing its file name, imageable type (e.g. Banner, Product) and imageable id (the id of the object being the image belongs to)
def seed_image(filename, imageable_type, imageable_id) Picture.create!( :id => $image_id, :image => image(filename), :imageable_type => imageable_type, :imageable_id => imageable_id ) $image_id += 1 end
[ "def create(image)\n @image = image # Image\n end", "def load_imageable\n klass = [Entree, Review].detect { |c| params[\"#{c.name.underscore}_id\"] }\n @imageable = klass.find(params[\"#{klass.name.underscore}_id\"])\n end", "def add_sponsor_covenant_image(candidate)\n filename = 'actions.png'\n sponsor_covenant = candidate.sponsor_covenant\n candidate.sponsor_covenant.build_scanned_covenant\n sponsor_covenant.scanned_covenant.filename = filename\n sponsor_covenant.scanned_covenant.content_type = 'image/png'\n File.open(File.join('spec/fixtures/files/', filename), 'rb') do |f|\n sponsor_covenant.scanned_covenant.content = f.read\n end\n candidate.save\nend", "def add_sponsor_eligibility_image(candidate)\n filename = 'actions.png'\n sponsor_eligibility = candidate.sponsor_eligibility\n sponsor_eligibility.build_scanned_eligibility\n sponsor_eligibility.scanned_eligibility.filename = filename\n sponsor_eligibility.scanned_eligibility.content_type = 'image/png'\n File.open(File.join('spec/fixtures/files/', filename), 'rb') do |f|\n sponsor_eligibility.scanned_eligibility.content = f.read\n end\n candidate.save\nend", "def create_images(product)\n self.image_labels.each_with_index do |label, position|\n\n self.image_file_extensions.each do |extension|\n file_name = self.image_path + value('image') + '_' + label + extension\n next unless File.exist?(file_name)\n\n types = []\n\n unless self.image_types[position].nil?\n types = product_attribute_set.asset_types.where(code: self.image_types[position].split(',').map(&:strip))\n end\n\n image = Asset.new\n image.product = product\n image.store = self.store\n image.position = position\n image.label = label\n image.set_file(File.open(file_name))\n\n types.each do |type|\n image.asset_types << type\n end\n\n # save without sync to format with paperclip\n image.sync_needed = false\n image.save\n\n # save with sync to push to magento\n image.sync_needed = true\n image.save\n end\n end\n end", "def create_weapons \n weapon = Weapon.create(name: 'Steel Sword', damage: 8, cost: 0, :merchant_id => self.id)\n # weapon.picture.attach(io: File.open('app/assets/images/weapons/steel sword.PNG'),\n # filename: 'steel sword.PNG')\n\n weapon1 = Weapon.create(name: 'Orcish Sword', damage: 15, cost: 15, :merchant_id => self.id )\n # weapon1.picture.attach(io: File.open('app/assets/images/weapons/orcish sword.PNG'),\n # filename: 'orcish sword.PNG')\n\n weapon2 = Weapon.create(name: 'Dawnbreaker', damage: 25, cost: 30, :merchant_id => self.id )\n # weapon2.picture.attach(io: File.open('app/assets/images/weapons/dawnbreaker.PNG'),\n # filename: 'dawnbreaker.PNG')\n end", "def create_image_with_local(name, type, container_uuid, path)\n @logger.debug(\"Creating image from file path #{path}\")\n container_id = JSON.parse(\n @client.get('v2.0', \"storage_containers/#{container_uuid}\")\n )['id'].split('::').last\n @logger.debug(\"Container ID is #{container_id}\")\n spec = { name: name, image_type: type, annotation: name }\n @logger.debug(\"Image creation specs => #{spec}\")\n task = JSON.parse(@client.post('v2.0', 'images', spec.to_json))\n task_uuid = task['task_uuid']\n image_uuid = TaskManager.wait_on_task(task_uuid, @client, @logger)\n task = JSON.parse(\n @client.put('v0.8', \"images/#{image_uuid}/upload\",\n File.open(path), nil,\n { 'X-Nutanix-Destination-Container' => container_id })\n )\n task_uuid = task['task_uuid']\n # Timeout is set to 60 minutes as image upload may take time\n TaskManager.wait_on_task(task_uuid, @client, @logger, 60 * 60)\n image_uuid\n rescue => e\n raise e\n end", "def create\n # Check this before the real creation TODO: Bit of a hack\n Image.new.creatable_by?(current_user) or raise Hobo::PermissionDeniedError, \"#{self.class.name}#create\"\n img = Image.create_with_file(params[:image][:name], params[:image][:file])\n %w{auto_ana auto_img_1 auto_img_2 auto_text_1 auto_text_2 auto_capo}.each do |f|\n if (params[f] == \"on\") \n img.add_zone!(I18n.t(\"image.auto_zone_names.#{f}\"))\n end\n end\n if(img.save)\n flash[:notice] = \"Image #{img.name} succesfully created\"\n else\n flash[:notice] = \"Error creating the image\"\n end\n redirect_to :controller => :images, :action => :index\n end", "def load_imageable\n\t\tklass = [User].detect { |c| params [\"#{c.name.underscore}_id\"]} \n\t\t@imageable = klass.find(params[\"#{klass.name.underescore}_id\"])\n\tend", "def image_for(id, size=:source)\n image_tag \"https://spoonacular.com/recipeImages/#{id}-#{IMAGE_SIZES[size]}\"\n end", "def create_side\n raise \"no fog images without an id\" if new_record?\n @assembly = true\n\n #puts \"apu=>#{adjusted_picture_url}\"\n #puts \"portrait=>#{portrait.inspect}\"\n\n file_url = if adjusted_picture_url\n adjusted_picture_url # the adjusted picture url\n elsif portrait\n # grab a copy of the sessions portrait using the face sized image\n portrait.image_url(:face)\n else\n # no portrait must just be a charm so use the merchandise.parts image\n part.image_part_url\n end\n\n raise \"no item_side image? customer_item_side id:#{id} file:#{file_url}\" if file_url.blank?\n\n # LDB:? i think this url stores the file into image_stock\n self.remote_image_stock_url = file_url\n\n # end up being the custom piece with portrait and background\n self.remote_image_custom_url = part.image_part_url\n\n # this writes our remote image_custom and image_stock to the S3 server\n save\n\n # finished using the incoming adjusted picture url\n self.adjusted_picture_url = nil\n\n end", "def save_image_types type_of_image,image\n @image = ImageType.new\n @image.image_type = type_of_image\n @image.images_for_job_id = image.id\n @image.image_page_number = image.image_number\n @image.save\n end", "def add_img(id, file)\n @server.call(\"addImg\",db_id,id,file)\n end", "def create_images\n # find the correct image file name and path\n self.image_labels.each_with_index do |label, position|\n\n self.image_file_extensions.each do |extension|\n file_name = self.image_path + value('image') + '_' + label + extension\n next unless File.exist?(file_name)\n\n types = []\n\n unless self.image_types[position].nil?\n types = Gemgento::AssetType.where(product_attribute_set: self.product.product_attribute_set, code: self.image_types[position])\n end\n\n unless types.is_a? Array\n types = [types]\n end\n\n create_image(file_name, types, position, label)\n end\n end\n\n # clear the cache\n Rails.cache.clear\n end", "def create\n thing_image = ThingImage.new(thing_image_create_params.merge({\n :image_id => params[:image_id],\n :thing_id => params[:thing_id]}))\n thing = Thing.where(id: thing_image.thing_id).first\n if !thing\n full_message_error \"cannot find thing[#{params[:thing_id]}]\", :bad_request\n skip_authorization\n return\n elsif !Image.where(id: thing_image.image_id).exists?\n full_message_error \"cannnot find image[#{params[:image_id]}]\", :bad_request\n skip_authorization\n return\n end\n\n authorize thing, :add_image?\n\n thing_image.creator_id = current_user.id\n if thing_image.save\n head :no_content\n else\n render json: {errors: thing_image.errors.messages}, status: :unprocessable_entity\n end\n end", "def image_create # rubocop:disable Metrics/AbcSize\n attrcheck = {\n 'REST end point' => @options[:rest_endpoint],\n 'Create JSON' => @options[:create_json]\n }\n @validate.attrvalidate(@options, attrcheck)\n file = File.read(@options[:create_json])\n create_data = JSON.parse(file)\n instanceconfig = ImageList.new(@options[:id_domain], @options[:user_name], @options[:passwd], @options[:rest_endpoint])\n instanceconfig = instanceconfig.create(create_data)\n # error checking response\n @util.response_handler(instanceconfig)\n return JSON.pretty_generate(JSON.parse(instanceconfig.body))\n end", "def create_listing_image(params)\n image = self.listing_images.create!(params)\n image.update_attributes(publicly_visible: false, category: 'home', caption: '')\n\n image\n end", "def show_image\n\t\t@product = Product.find(params[:id])\n\t\tif @product.image.nil?\n\t\t\tsend_data open(\"#{Rails.root}/lib/seeds/images/no_image.jpg\", \"rb\").read, type: 'image/jpg'\n\t\telse\n\t\t\tsend_data @product.image, type: 'image/jpg'\n\t\tend\n\tend", "def create_image(instance_id, create_opts={})\n create_resource :image, { :instance_id => instance_id }.merge(create_opts)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
recipient (string) sms recipient in general format; e.g. '+886912345678' message (string) message content options (hash) optional config options.ignore_cert (boolean) Ignore SSL certificate or not options.insecure (boolean) Use plain HTTP or HTTPS options.mode (string) delivery mode 'bit' instant delivery (default) 'bulk' bulk delivery
def deliver(recipient, message, options={}) protocol = options[:insecure] ? "http" : "https" uri = URI.parse "#{protocol}://#{API_HOST}" uri.path = case (options[:mode].to_sym rescue nil) when nil, :bit SMS_ENDPOINT when :bulk BULK_SMS_ENDPOINT else raise StandardError.new "Bad delivering mode!" end uri.query = URI.encode_www_form({ username: @username, password: @password, dstaddr: recipient, smbody: Iconv.new("big5", "utf-8").iconv(message), dlvtime: (options[:dlvtime] rescue 0), vldtime: (options[:vldtime] rescue nil), response: (options[:response] rescue nil) }) response = Net::HTTP.start(uri.host, use_ssl: uri.scheme == 'https') do |http| http.verify_mode = OpenSSL::SSL::VERIFY_NONE if options[:ignore_cert] req = Net::HTTP::Get.new uri http.request(req) end parse_response(response.body)["kmsgid"].to_i end
[ "def deliver_sms(params)\n#puts \"**** Message#deliver_sms; params=#{params}\"\n sms_gateway = params[:sms_gateway]\n phone_number_array = @contact_info.map {|c| c[:phone]}.compact.uniq\n phone_numbers = phone_number_array.join(',')\n assemble_sms()\n#puts \"**** sms_gateway.deliver #{sms_gateway} w #{phone_numbers}: #{sms_only}\"\n #******* CONNECT TO GATEWAY AND DELIVER MESSAGES \n gateway_reply = \n sms_gateway.deliver(phone_numbers, sms_only)\n#puts \"**** gateway_reply=#{gateway_reply}\"\n #******* PROCESS GATEWAY REPLY (INITIAL STATUSES OF SENT MESSAGES) \n gtw_msg_id = nil\n if phone_number_array.size == 1\n # SINGLE PHONE NUMBER \n if gateway_reply =~ /ID: (\\w+)/\n gtw_msg_id = $1\n gtw_msg_id = gateway_reply[4..99] # Temporary workaround as $1 doesn't work on Heroku\n msg_status = MessagesHelper::MsgSentToGateway\n else\n gtw_msg_id = gateway_reply # Will include error message\n msg_status = MessagesHelper::MsgError\n end\n # Mark the message to this member as being sent\n self.sent_messages[0].update_attributes(:gateway_message_id => gtw_msg_id, \n :msg_status => msg_status)\n else\n # MULTIPLE PHONE NUMBERS\n # Get the Clickatell reply and parse into array of hash like {:id=>'asebi9xxke...', :phone => '2345552228372'}\n#puts \"**** gateway_reply=#{gateway_reply}\"\n msg_statuses = gateway_reply.split(\"\\n\").map do |s|\n if s =~ /ID:\\s+(\\w+)\\s+To:\\s+([0-9]+)/\n {:id => $1, :phone => $2} \n else\n {:id => nil, :phone => nil, :error => s}\n end\n end\n # Make array to associate members with their numbers\n @member_phones = self.members.map {|m| {:phone => m.primary_phone, :member => m} }\n # Update the sent_message records to indicate which have been accepted at Gateway \n msg_statuses.each do |s|\n#puts \"**** s[:id]=#{s[:id]}, s[:phone]=#{s[:phone]}\"\n if s[:id] && s[:phone]\n # Find the right member by matching phone numbers\n member = @member_phones.find{|m| m[:phone]==s[:phone]}[:member]\n # Find the right sent_message by matching member & message\n sent_message = SentMessage.where(:member_id=>member.id, :message_id=>self.id).first\n # Update the sent_message\n sent_message.update_attributes(\n :gateway_message_id => s[:id], \n :msg_status=> MessagesHelper::MsgSentToGateway\n )\n end\n end\n # Any sent_messages not now marked with gateway_message_id and msg_status must have errors\n sent_messages.each do |m| \n m.update_attributes(:msg_status=> MessagesHelper::MsgError) if m.msg_status.nil?\n end\n end\n end", "def send_sms(options = {})\n # Check for login\n login = options[:login] || @@login\n raise ArgumentError, \"Login must be present\" unless login and not login.blank?\n\n # Check for password\n password = options[:password] || @@password\n raise ArgumentError, \"Password must be present\" unless password and not password.blank?\n\n # Multiple destinations support\n options[:destination] = [options[:destination]] unless options[:destination].kind_of?(Array)\n\n # Check for max destinations\n raise ArgumentError, \"Max of 5000 destinations exceeded\" if (options[:destination].size > 5000)\n\n destinations = []\n options[:destination].each do |phone|\n raise ArgumentError, \"Recipient must be a telephone number with international format: #{phone.to_s}\" unless parsed = GlobalPhone.parse(phone.to_s)\n if parsed.international_string.to_s =~ /^\\+1/\n destinations << parsed.international_string.gsub(/^\\+1/, \"01\") # Replace initial +1 with 01 for IT Cloud requirements\n else\n destinations << parsed.international_string.gsub(\"+\", \"\") # Remove + from international string\n end\n end\n\n message = options[:message].to_s\n raise ArgumentError, \"Message must be present\" if message.blank?\n raise ArgumentError, \"Message is 765 chars maximum\" if message.size > 765\n\n http = Net::HTTP.new(APIUri.host, APIUri.port)\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n request = Net::HTTP::Post.new(APIUri.request_uri)\n request.set_form_data({'user' => login,\n 'token' => password,\n 'GSM' => destinations.join(\",\"),\n 'SMSText' => message,\n 'metodo_envio' => '1via'})\n\n response = http.request(request)\n if response.code == \"200\"\n begin\n result = response.body.split(\"<br>\").map{ |a| a.split(\",\") }.map{ |res| {:telephone => res[0].strip, :code => res[1].strip }}\n rescue\n # Try to get petition result\n result = [{:code => response.body}]\n end\n result.each do |destination|\n case destination[:code]\n when \"-1\" then\n destination[:description] = \"Authentication failed\"\n when \"-2\" then\n destination[:description] = \"Out of hours\"\n when \"-3\" then\n destination[:description] = \"No credit\"\n when \"-4\" then\n destination[:description] = \"Wrong number\"\n when \"-5\" then\n destination[:description] = \"Wrong message\"\n when \"-6\" then\n destination[:description] = \"System under maintenance\"\n when \"-7\" then\n destination[:description] = \"Max cellphones reached\"\n when \"-8\" then\n destination[:description] = \"Cellphone number in black list\"\n when \"-9\" then\n destination[:description] = \"message rejected for content\"\n when \"-10\" then\n destination[:description] = \"Message with no link authorized\"\n when \"-11\" then\n destination[:description] = \"Error in metodo_envio variable\"\n else\n if destination[:code].to_i > 0\n destination[:description] = \"OK\"\n else\n destination[:description] = \"Unknown error\"\n end\n end\n end\n return result\n else\n raise RuntimeError, \"Server responded with code #{response.code}: #{response.body}\"\n end\n end", "def deliver_sms(options={})\n#puts \"**** Message#deliver_sms; options=#{options}\"\n sms_gateway = options[:sms_gateway] || SmsGateway.default_sms_gateway\n @phones ||= options[:phone_numbers] || sent_messages.map {|sm| sm.phone}.compact.uniq\n @phones = @phones.split(',') if @phones.is_a? String \n if @phones.empty?\n AppLog.create(:code => 'Message.deliver_sms', :severity=> 'warning', \n :description => \"Attempting to send SMS for message ##{self.id} but no phone numbers found\")\n return\n end\n assemble_sms()\n#puts \"**** sms_gateway.deliver #{sms_gateway} w #{phone_numbers}: #{sms_only}\"\n #******* CONNECT TO GATEWAY AND DELIVER MESSAGES \n gateway_reply = sms_gateway.deliver(@phones, sms_only, self.id)\n#puts \"**** sms_gateway=#{sms_gateway}\"\n#puts \"**** gateway_reply=#{gateway_reply}\"\n #******* PROCESS GATEWAY REPLY (INITIAL STATUSES OF SENT MESSAGES) \n update_sent_messages_w_status(gateway_reply) if options[:news_update].nil? && gateway_reply # The IF is there just to make testing simpler.\n # In production, a reply will always be present?\n end", "def send_sms!\n msg = \"You have a new message in HereStay: #{mobile_booking_messages_url(self.booking_id, :host => ActionMailer::Base.default_url_options[:host])}\"\n if recipient\n recipient.deliver_message!(msg) if !recipient.online? and recipient.available_by_phone?\n end\n end", "def send_message(recipient, message_text, opts={})\n valid_options = { :sender => \"\", :messagetype => \"Text\" }\n valid_options.merge!(:sender => opts[:sender]) if opts[:sender]\n valid_options.merge!(:messagetype => opts[:msg_type]) if opts[:msg_type]\n valid_options.merge!(:referencenumber => opts[:ref_number]) if opts[:ref_number]\n recipient = recipient.join(\",\")if recipient.is_a?(Array)\n response = execute_command('sms',\n { :mobilenumber => recipient, :message => message_text}.merge(valid_options)\n )\n response = parse_response(:sms, response)\n response.is_a?(Array) ? response.map { |r| r[:status] } : response[:status]\n end", "def deliver(message, options = {})\n options = options.reverse_merge default_options\n to = recipient.respond_to?(:call) ? recipient.call(message) : recipient\n message.body message.body.encode(options[:charset]) if options[:charset].presence\n ActionMailerSMSMailer.forward_sms(to, message, options.compact).deliver_now\n message.to\n end", "def send(txt, to, options = {})\n options.default = nil\n api_request(\"sendSms.php\", {\n txt: txt,\n to: to,\n idGroup: options[:idGroup],\n source: options[:source],\n flash: options[:flash],\n dateTimeSend: options[:dateTimeSend],\n onlydelivery: options[:onlydelivery],\n use_alfasource: options[:use_alfasource],\n discountID: options[:discountID],\n channel: options[:channel]\n })\n end", "def deliver(message, _options = {})\n raise ServiceError, \"too many recipients, max. is #{MAX_RECIPIENT} (current: #{message.to.length})\" if message.to.length > MAX_RECIPIENT\n\n # Prepare request\n request = Net::HTTP::Post.new('/messaging/sms').tap do |request|\n request.body = post_params(message)\n request.content_type = 'application/json'\n request['Accept'] = 'application/json'\n request['client_id'] = api_key\n request['SCS-Version'] = 2\n end\n\n # Log as `curl` request\n self.class.logger.debug \"curl -X#{request.method} '#{endpoint}' -d '#{request.body}'\"\n\n # Perform request\n resp = http_client.request(request)\n\n # Handle errors\n raise ServiceError, \"endpoint did respond with #{resp.code} and #{resp.body}\" unless resp.code.to_i == 201\n self.class.logger.debug resp.body\n\n # Return numbers message send to\n message.to\n end", "def deliver_message_via_carrier(text, to, from)\n SMS_CARRIER.deliver_message(text, to, from)\nend", "def recipient_contact\n @recipient_contact ||= SimpleShipping::Contact.new(\n :person_name => \"John Recipient Smith\",\n :phone_number => \"1234567890\"\n )\n end", "def recipient=(value)\n @recipient = value\n end", "def security_notification(user, sender, options={})\n @sender = sender\n redmine_headers 'Sender' => sender.login\n @message =\n l(options[:message],\n field: (options[:field] && l(options[:field])),\n value: options[:value])\n @title = options[:title] && l(options[:title])\n @remote_ip = options[:remote_ip] || @sender.remote_ip\n @url = options[:url] && (options[:url].is_a?(Hash) ? url_for(options[:url]) : options[:url])\n redmine_headers 'Url' => @url\n mail :to => [user, *options[:recipients]].uniq,\n :subject => \"[#{Setting.app_title}] #{l(:mail_subject_security_notification)}\"\n end", "def security_notification(sender, options={})\n @sender = sender\n redmine_headers 'Sender' => sender.login\n @message = l(options[:message],\n field: (options[:field] && l(options[:field])),\n value: options[:value]\n )\n @title = options[:title] && l(options[:title])\n @originator = options[:originator] || sender\n @remote_ip = options[:remote_ip] || @originator.remote_ip\n @url = options[:url] && (options[:url].is_a?(Hash) ? url_for(options[:url]) : options[:url])\n redmine_headers 'Sender' => @originator.login\n redmine_headers 'Url' => @url\n mail :to => [User.current, *options[:recipients]].uniq,\n :subject => \"[#{Setting.app_title}] #{l(:mail_subject_security_notification)}\"\n end", "def message(options)\n return if config.message.empty?\n if batch == true\n receipients << options\n else\n if options[:type] == :user\n send_message(options[:user])\n else\n group, password = split_password(options[:user])\n send_muc_message(group, password)\n end\n end\n end", "def set_recipient_data\n return if recipient_data\n return unless recipient_user_ids&.present?\n\n self.recipient_data = if email?\n recipient_users_email\n elsif sms?\n recipient_users_sms\n end\n end", "def giftcoupon_recipient_mail(coupon_number,name,email,message,fname,lname,payment_type)\r\n\r\n load_settings\r\n @recipients =email\r\n @from = \"admin@holdmymemories.com\"\r\n @bcc=\"seth.johnson@holdmymemories.com,bob@s121.com\"\r\n @subject = \"Gift Membership from Holdmymemories\"\r\n @sent_on = Time.now\r\n @content_type = \"text/html\"\r\n\r\n body[:coupon_number] = coupon_number\r\n body[:fname] = fname\r\n body[:lname]=lname\r\n body[:payment_type]=payment_type\r\n body[:name]=name\r\n body[:message]=message\r\n\r\n end", "def recipient=(value)\n @recipient = value\n end", "def process_and_send_for_one (recipient)\n mail_payload = MailPayload.new(\n :subject => subject(recipient),\n :body => message(recipient),\n :recipient_record => recipient,\n :recipient_type => (recipient_type == 'parent' ? 'guardian' : recipient_type),\n :sender => User.find_by_id(sender_id),\n :hostname => Fedena.hostname,\n :mail_type => :alert,\n :alert_name => alert_name,\n :mail_logger => mail_logger\n )\n mail_payload.send_mail # TODO: handle response\n recipient\n end", "def recipient_address\n @recipient_address ||= SimpleShipping::Address.new(\n :country_code => 'US',\n :state_code => 'MN',\n :city => 'Minneapolis',\n :street_line => 'Nightmare Avenue 13',\n :postal_code => '55411'\n )\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET Modifies the starting location passed via URL (QR Codes) Passes starting location as the room number Redirects immediately to Map
def start unless params[:origin].blank? params[:origin].slice!(0) if params[:origin][0].upcase == "R" # Remove proceeding R if present origin = params[:origin].to_s.rjust(4, '0').prepend("R") # Add zero padding and Prepend R session[:start] = origin.upcase end redirect_to "/map" end
[ "def qr\n @qrLink = nil\n @targetURL = nil\n\n room = Room.find(params[:originID]).first\n if room == nil\n raise ActionController::RoutingError.new('Origin Room Not Found')\n #render :status => 404, :layout => false\n else\n originRoom = room.room_number\n\n unless params[:destinationID].blank? # Origin and destination supplied\n destinationRoom = Room.find(params[:destinationID]).room_number\n\n # Hardcoding this for now because it's weird\n @targetURL = root_url + \"start/\" + originRoom + \"/end/\" + destinationRoom\n\n @qrLink = generateQRLink(@targetURL)\n else\n @targetURL = url_for(action: 'start', controller: 'administration', origin: originRoom)\n @qrLink = generateQRLink(@targetURL)\n end\n\n render :layout => true\n end\n end", "def get_location(location_mode, request_location_mode); end", "def map_call(lat, long)\n location = google_map + lat + \",\" + long + \"&zoom=14&size=600x800\" + @@api_key[\"map_key\"]\nend", "def url location\n \"http://api.local.yahoo.com/MapsService/V1/geocode?appid=#{@appid}&location=#{CGI.escape location}\"\n end", "def show_map(lat, long, path)\n map_params = {\n :settings => {:map_type => \"standard\",:region => [lat, long, 0.2, 0.2],\n :zoom_enabled => true,:scroll_enabled => true,:shows_user_location => false,\n :api_key => GOOGLE_MAPS_API_KEY},\n \n :annotations => [{\n :latitude => lat, \n :longitude => long, \n :title => Localization::Request[:address], \n :subtitle => \"I am here\",\n :url => url_for(:action => :request_rental)\n }]\n }\n MapView.create map_params\n WebView.navigate url_for :action => :request\n end", "def embedded_map_url\n \"http://snippets.mapmycdn.com/routes/view/embedded/#{map_my_run_id}?width=600&height=400&&line_color=E60f0bdb&rgbhex=DB0B0E&distance_markers=0&unit_type=imperial&map_mode=ROADMAP\"\n end", "def decode(params = {})\n raise Error unless params.has_key? :location\n remove_unavailable_params! params\n api_method = {\n :location => API_LOCATION,\n :version => '1',\n :call => 'address'\n }\n mapquest.request api_method, params, Response\n end", "def ajax_go_to\n \tresults = Geocoding::get(params[:location])\n \t\n \tif results.status == Geocoding::GEO_SUCCESS\n \t\tcoords = results[0].latlon\n render :update do |page|\n @map = Variable.new(\"map\")\n page << @map.set_center(GLatLng.new(coords), 4)\n end\n end \n end", "def static_page\n url = Addressable::URI.new(\n :scheme => \"https\",\n :host => \"maps.googleapis.com\",\n :path => \"/maps/api/staticmap\",\n :query_values => {\n :center => \"#{self.latitude},#{self.longitude}\",\n :zoom => 17,\n :markers => \"markerStyles|#{self.latitude},#{self.longitude}|\",\n :size => \"500x400\",\n :sensor => \"false\"\n }).to_s\n end", "def nearby_geo_callback1\n\t\twebview_navigate_for_type(:index) if @params[\"known_position\"].to_i != 0 && @params[\"status\"] == \"ok\"\n \t# Try again if the first call failed, seems to be needed on the simulator...\n \tif @params[\"known_position\"].to_i == 0 || @params[\"status\"] != \"ok\" \n\t\t\tGeoLocation.set_notification( url_for_type(:action => :nearby_geo_callback2), default_query_hash_str, GeoTimeout) \n\t\t\tredirect_for_type :action => :wait, :query => { :message => \"Finding location...\" }\n\t\tend\n\tend", "def viewMapByAddress(address, callback)\n puts \"viewMapByAddress(address:#{address}, callback:#{callback}\"\n\n url = \"http://maps.google.com/maps/api/geocode/json?\" +\n \"address=#{address}&\" +\n \"sensor=true\"\n #puts url\n\n res = Rho::AsyncHttp.get(\n :url => url,\n #:headers => {\"Cookie\" => cookie},\n )\n #puts res.inspect\n\n if res[\"status\"] == \"ok\" # && res[\"body\"][\"status\"] == \"OK\"\n #puts res[\"body\"].inspect\n #puts res[\"body\"][\"results\"][0][\"geometry\"][\"location\"][\"lat\"]\n #puts res[\"body\"][\"results\"][0][\"geometry\"][\"location\"][\"lng\"]\n\n to_lat = res[\"body\"][\"results\"][0][\"geometry\"][\"location\"][\"lat\"]\n to_lng = res[\"body\"][\"results\"][0][\"geometry\"][\"location\"][\"lng\"]\n else\n to_lat = '34.4893270'\n to_lng = '133.3614320'\n end\n\n viewMap address, to_lat, to_lng, callback\n end", "def geocoder\n begin\n render(:json => open(\"#{GEOCODER_URL}&#{request.query_string}\"){|f| f.read})\n rescue SocketError\n render(:text => $!.to_s, :status => 500)\n end\n end", "def coordinates_url latitude, longitude\n \"https://www.google.com/maps/search/?api=1&query=#{latitude}%2C#{longitude}\"\n end", "def show\n @location_url_map = LocationUrlMap.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @location_url_map }\n end\n end", "def index\n puts 'getting geo queries'\n @geo_queries = GeoQuery.where('id > 238') #prior queries were test results from me\n\t#@geo_queries = GeoQuery.where('id > 10') #prior queries were test results from me\n\t\n\t@final_url = 'http://maps.google.com/maps/api/staticmap?zoom=1&size=1024x1024&sensor=false&markers=size:tiny'\n\t@geo_queries.each do |qry|\n\t @final_url = @final_url + '|' + qry.lat.to_s.slice(0,7) + ',' +qry.lon.to_s.slice(0,7)\t\n\tend\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @geo_queries }\n end\n end", "def event_get_location_details\n @loc = Apis::HereApi.new(\"\").get_location_details(params[:locationid])\n render json: @loc\n end", "def show\n location = params[:search_location] || session[:location]\n testing = Geocoder.search(location)\n if testing.empty?\n redirect_to root_path\n else\n coordinates = params[:lat_lon] || session[:lat_lon]\n radius = params[:radius]\n # puts \"Radius in controller #{radius}\"\n if location != nil && coordinates != nil\n @locations = Location.get_search_results(location, coordinates, radius)\n else\n render 'index'\n end\n end\nend", "def url\n if value['latitude'].present? and value['longitude'].present?\n if value['type'] == MAP_TYPE_GOOGLE\n sprintf(\n 'http://maps.google.com/maps?%s&t=m&q=%s+%s',\n value['zoom'].present? ? 'z=' + value['zoom'] : '',\n value['latitude'],\n value['longitude']\n )\n else # yandex\n sprintf(\n 'http://maps.yandex.ru/?l=map&text=%s&ll=%s%s',\n [value['latitude'], value['longitude']].join(','),\n [value['longitude'], value['latitude']].join(','),\n value['zoom'].present? ? '&z=' + value['zoom'] : nil\n )\n end\n end\n end", "def marker \n lat = params[:lat]\n lon = params[:lon]\n api = WeatherApi.new(lat, lon)\n response = api.query\n if response[:code] != 200\n payload = {\n error: \"Error calling Open Weather API\", \n code: response[:code]\n }\n else \n payload = response\n end\n\n render json: payload\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /logvisitor Logs a visitor. Called from redirect.js, which redirects to home after 2 minutes of inactivity. Logs a visitor after one minute of inactivity.
def logvisitor @visitor.end = DateTime.current @visitor.save render :nothing => true end
[ "def log_visit\n session_id = request.session_options[:id]\n client = DeviceDetector.new(request.env[\"HTTP_USER_AGENT\"])\n client_os = client.os_name\n if !VisitorLog.find_by_session_id(session_id)\n VisitorLog.create(:session_id => session_id, :logged_in => false, :device_type => client_os)\n end\n\n if VisitorLog.find_by_session_id(session_id)\n log = VisitorLog.find_by_session_id(session_id)\n if !log.logged_in && logged_in?\n log.update_attribute(\"logged_in\", true)\n log.save\n end\n\n if logged_in? && current_user.department_id.present? && log.department_id.nil?\n log.update_attribute(\"department_id\", current_user.department_id)\n log.save\n end\n end\n\n end", "def dc_log_visit\r\n if request.env[\"HTTP_USER_AGENT\"] and request.env[\"HTTP_USER_AGENT\"].match(/\\(.*https?:\\/\\/.*\\)/)\r\n logger.info \"ROBOT: #{Time.now.strftime('%Y.%m.%d %H:%M:%S')} id=#{@page.id} ip=#{request.remote_ip}.\"\r\n session[:is_robot] = true\r\n else\r\n DcVisit.create(site_id: @site.id, \r\n user_id: session[:user_id], \r\n page_id: @page.id, \r\n ip: request.remote_ip,\r\n session_id: request.session_options[:id],\r\n time: Time.now )\r\n end\r\nend", "def dc_log_visit()\r\n if request.env[\"HTTP_USER_AGENT\"] and request.env[\"HTTP_USER_AGENT\"].match(/\\(.*https?:\\/\\/.*\\)/)\r\n logger.info \"ROBOT: #{Time.now.strftime('%Y.%m.%d %H:%M:%S')} id=#{@page.id} ip=#{request.remote_ip}.\"\r\n session[:is_robot] = true\r\n else\r\n DcVisit.create(site_id: @site.id, \r\n user_id: session[:user_id], \r\n page_id: @page.id, \r\n ip: request.remote_ip,\r\n session_id: request.session_options[:id],\r\n time: Time.now )\r\n end\r\nend", "def logVisit record=nil, rateable=false\n return if !valid_browser?(request.user_agent) or valid_robot?(request.user_agent)\n\n user_id = user_signed_in? ? current_user.id : nil\n record_class = record_id = nil\n record_class = record.class.to_s unless record.nil?\n record_id = record.id unless record.nil?\n LogVisitWorker.perform_async(request.user_agent, request.remote_ip, user_id, Time.now, record_class, record_id, rateable)\n \n# Thread.new do\n# #Wait 10 seconds to allow the request to be returned before starting. This saves the request some time.\n# #On development using Webrick, if we wait too long and another thread gets created this one gets killed.\n# #Should be good on production.\n# sleep 10\n\n# ip_address = logIpAddress #First log IpAddress\n \n# record.register_visit_by(ip_address)\n\n# return unless rateable\n# #If the user is not the author then record statistics about how much they viewed the record\n# if user_signed_in? && record.user != current_user\n#\trecord.register_view_by(current_user)\n# end\n# end\n end", "def visited\n set_cors_headers\n geo = check_geo(request.remote_ip)\n location = geo['city']+', '+geo['region_code']\n referer = URI(request.referer)\n if !params[:visitor]\n params[:visitor] = \"Anon User\"\n end\n @site = Site.find_by_name_and_user_id(referer.host, params[:id])\n if @site\n @visitor = Visitor.find_by_name_and_site_id(params[:visitor], @site.id)\n if !@visitor\n @visitor = Visitor.new(:site_id => @site.id, :name => params[:visitor])\n @visitor.save\n end\n @visit = Visit.new(:visitor_id => @visitor.id, :url => referer.path, :ip_address => request.remote_ip, :location => location, :event => params[:event], :data => params[:data])\n @visit.save\n else\n user_id = params[:id]\n @site = Site.new(:name => referer.host, :user_id => user_id)\n @site.save\n @visitor = Visitor.new(:site_id => @site.id, :name => params[:visitor])\n @visitor.save\n @visit = Visit.new(:visitor_id => @visitor.id, :url => referer.path,:ip_address => request.remote_ip, :location => location, :event => params[:event], :data => params[:data])\n @visit.save\n end\n render :text => \"visit recorded\", :content_type => \"text/plain\"\n end", "def perform(user_agent, remote_ip, user_id, timestamp, record_class, record_id)\n logForemVisit(user_agent, remote_ip, user_id, timestamp, record_class, record_id)\n end", "def register_visit\r\n if @debug\r\n puts \"REQUEST IN REGISTER VISIT: #{request}\"\r\n puts \"BODY REQUEST: #{request.body}\"\r\n puts \"AUTH REQUEST: #{request.authorization}\"\r\n puts \"LENGTH REQUEST: #{request.content_length}\"\r\n puts \"FORM DATA REQUEST: #{request.form_data?}\"\r\n puts \"FULLPATH REQUEST: #{request.fullpath}\"\r\n puts \"HEADERS REQUEST: #{request.headers}\"\r\n puts \"IP REQUEST: #{request.ip}\"\r\n puts \"REQUEST IP ADDRESS: #{request['ip_address']}\"\r\n puts \"REQUEST REMOTE IP: #{request['remote_ip']}\"\r\n end\r\n response = @mints_pub.register_visit(request)\r\n if @debug\r\n puts \"RESPONSE IN REGISTER VISIT: #{response}\"\r\n end\r\n @contact_token = response['contact_token'] ? response['contact_token'] : response['user_token']\r\n @visit_id = response['visit_id']\r\n if @debug\r\n puts \"VISIT ID: #{@visit_id}\"\r\n end\r\n cookies.permanent[:mints_contact_id] = { value: @contact_token, secure: true, httponly: true }\r\n cookies.permanent[:mints_visit_id] = { value: @visit_id, secure: true, httponly: true }\r\n end", "def register_visit\r\n if @debug\r\n puts \"REQUEST IN REGISTER VISIT: #{request}\"\r\n puts \"BODY REQUEST: #{request.body}\"\r\n puts \"AUTH REQUEST: #{request.authorization}\"\r\n puts \"LENGTH REQUEST: #{request.content_length}\"\r\n puts \"FORM DATA REQUEST: #{request.form_data?}\"\r\n puts \"FULLPATH REQUEST: #{request.fullpath}\"\r\n puts \"HEADERS REQUEST: #{request.headers}\"\r\n puts \"IP REQUEST: #{request.ip}\"\r\n puts \"REQUEST IP ADDRESS: #{request['ip_address']}\"\r\n puts \"REQUEST REMOTE IP: #{request['remote_ip']}\"\r\n end\r\n\r\n response = @mints_pub.register_visit(request)\r\n\r\n puts \"RESPONSE IN REGISTER VISIT: #{response}\" if @debug\r\n\r\n @contact_token = response['contact_token'] || response['user_token']\r\n @visit_id = response['visit_id']\r\n\r\n puts \"VISIT ID: #{@visit_id}\" if @debug\r\n\r\n cookies.permanent[:mints_contact_id] = { value: @contact_token, secure: true, httponly: true }\r\n cookies.permanent[:mints_visit_id] = { value: @visit_id, secure: true, httponly: true }\r\n end", "def visit!\n self.duration = [(Time.now - self.updated_at).to_i, 15 * 30].min # if user stay on page more than 15 min\n self.visits += 1\n self.save!\n end", "def create\n @visitor_log = VisitorLog.new(visitor_log_params)\n\n respond_to do |format|\n if @visitor_log.save\n format.html { redirect_to @visitor_log, notice: 'Visitor log was successfully created.' }\n format.json { render :show, status: :created, location: @visitor_log }\n else\n format.html { render :new }\n format.json { render json: @visitor_log.errors, status: :unprocessable_entity }\n end\n end\n end", "def establish_session(request)\n #puts \"Request for: #{request.url} - running before...\"\n if ((session[:ip_address] != request.ip) or\n (session[:created_at] < (Time.now() - 60 * 20))) # Session older than 20 minutes?\n #puts \"This looks like a new user!\"\n session[:ip_address] = request.ip\n session[:created_at] = Time.now()\n user_id = DB[:users].insert(:ip_address => request.ip,\n :referrer => request.referrer,\n :created_at => session[:created_at])\n session[:user_id] = user_id\n redirect \"/survey/step/1\", 302\n end\nend", "def logForemVisit(user_agent, remote_ip, user_id, timestamp, record_class, record_id)\n ip_address = logForemIpAddress(user_agent, remote_ip, user_id, timestamp)\n return if record_id.nil? or ip_address.nil?\n record = record_class.constantize.find(record_id)\n record.register_visit_by(ip_address)\n end", "def log_activity(params)\n post_call(\"user/#{user_id}/activities.json\", params)\n end", "def log_time_and_user\n ActivityLog.create(\n requested_url: request.original_url,\n shortened_url: request.original_url.split('?').first,\n user_ip: request.remote_ip,\n initial_request_time: @initial_time,\n page_generation_time: (Time.now - @initial_time) * 1000,\n current_user: current_user ? current_user.email : nil\n )\n end", "def log_funnel_page_visit\n log_funnel_event(:view_page)\n end", "def record_session_activity\n return unless Ermahgerd.configuration.record_session_activity\n\n browser = Browser.new(request.headers['User-Agent'])\n\n RecordSessionActivityWorker.perform_async(\n authorization_from_header!,\n browser.name,\n browser.full_version,\n Time.zone.now.iso8601,\n browser.device.name,\n access_token[:device_key],\n request.remote_ip,\n Time.zone.at(access_token[:auth_time]).iso8601,\n request.path,\n browser.platform.name,\n browser.platform.version,\n current_user.id,\n access_token[:jti]\n )\n end", "def log_view(url, manual_expiration: false)\n record = {}\n\n # 0 - standard user view\n # 1 - manual expiration\n record[:kind] = manual_expiration ? 1 : 0\n\n record[:user_id] = current_user.id if user_signed_in?\n record[:ip] = request.env['HTTP_X_FORWARDED_FOR'].nil? ? request.env['REMOTE_ADDR'] : request.env['HTTP_X_FORWARDED_FOR']\n\n # Limit retrieved values to 256 characters\n record[:user_agent] = request.env['HTTP_USER_AGENT'].to_s[0, 255]\n record[:referrer] = request.env['HTTP_REFERER'].to_s[0, 255]\n\n record[:successful] = url.expired ? false : true\n\n url.views.create(record)\n url\n end", "def register_visit_timer(visit, time)\n @client.raw('get', \"/register-visit-timer?visit=#{visit}&time=#{time}\")\n end", "def create\n @visitlog = Visitlog.new(params[:visitlog])\n\n respond_to do |format|\n if @visitlog.save\n flash[:notice] = 'Visitlog was successfully created.'\n format.html { redirect_to(@visitlog) }\n format.xml { render :xml => @visitlog, :status => :created, :location => @visitlog }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @visitlog.errors, :status => :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST Upload an SVG map
def map_upload unless params[:uploaded_map].blank? require 'fileutils' # Ensure public/maps exists FileUtils::mkdir_p "public/maps" directory = "public/maps.tmp" # Ensure a blank maps.tmp directory exists FileUtils.rm_rf directory FileUtils::mkdir_p directory # Copy the existing maps into that directory # (to support the case where the user is updating maps and doesn't specify # all of the existing maps.) FileUtils.cp_r 'public/maps/.', directory # Copy uploaded files to maps.tmp, overriding any old maps that were # just copied in the line above. params[:uploaded_map].each do |map| path = File.join(directory, "floor" + map[0].to_s + ".svg") File.open(path, "wb") { |f| f.write(map[1].read) } end notice = "Maps were successfully uploaded." $MAP_DATE = Time.now.to_i else error = "Error uploading SVG map" end # unless uploaded_map.blank? respond_to do |format| format.html { redirect_to action: "index", error: error, notice: notice } end end
[ "def map=(svg)\n svg_to_img_to_s3 \"tripmap/#{self.id}.jpg\", svg\n map # return value is map, see below\n# rescue\n# map\n end", "def export\n\t\t# create the file name: map title - indicator - event\n\t\tfilename = params[:hidden_form_map_title].clone()\n\t\tfilename << \"-\"\n\t\tfilename << params[:hidden_form_indicator_name_abbrv]\n\t\tfilename << \"-\"\n\t\tfilename << params[:hidden_form_event_name]\n\t\tfilename << \"-#{l Time.now, :format => :file}\"\n\n\t\theaders['Content-Type'] = \"image/svg+xml; charset=utf-8\"\n headers['Content-Disposition'] = \"attachment; filename=#{clean_filename(filename)}.svg\"\n end", "def create_modified_svg(request)\n http_request = request.to_http_info(@api_client.config)\n make_request(http_request, :POST, 'File')\n end", "def map=(svg)\n svg_to_img_to_s3 \"map/#{self.id}.jpg\", svg\n map # return value is map, see below\n rescue\n map\n end", "def export_svg\n # @mySVG = \"some svg content here\"\n send_data @mySVG,\n :type => 'text/xml; charset=UTF-8;',\n :disposition => \"attachment; filename=#{@seatmap.title}.svg\"\n end", "def create\n @svgpost = Svgpost.new(params[:svgpost])\n\n respond_to do |format|\n if @svgpost.save\n format.html { redirect_to @svgpost, notice: 'Svgpost was successfully created.' }\n format.json { render json: @svgpost, status: :created, location: @svgpost }\n else\n format.html { render action: \"new\" }\n format.json { render json: @svgpost.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @svg_image = SvgImage.new(svg_image_params)\n\n respond_to do |format|\n if @svg_image.save\n format.html { redirect_to @svg_image, notice: 'Svg image was successfully created.' }\n format.json { render :show, status: :created, location: @svg_image }\n else\n format.html { render :new }\n format.json { render json: @svg_image.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_svg\n @project = Project.find params[:id]\n filename = params[:filename].squish.downcase.tr(\" \",\"_\") + '.svg'\n file = File.open(File.join(@project.path, filename), 'w+') {|f| f.write(params[:sketch]) }\n if file\n commit @project.path, filename, Base64.decode64(params[:sketch]), \"Create #{filename}\"\n flash[:notice] = \"Your new image was added successfully! How sparkly!\"\n else\n flash[:alert] = \"Your new image didn't get saved! How sad :(\"\n end\n redirect_to url_for(@project)\n end", "def create\n @svg_file = Cmtool::SvgFile.new(svg_file_params)\n\n respond_to do |format|\n if @svg_file.save\n format.html { redirect_to(cmtool.svg_files_path, :notice => I18n.t('cmtool.action.create.successful', :model => Cmtool::SvgFile.model_name.human)) }\n format.xml { render :xml => @svg_file, :status => :created, :location => @svg_file }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @svg_file.errors, :status => :unprocessable_entity }\n end\n end\n end", "def modify_svg(request)\n http_request = request.to_http_info(@api_client.config)\n make_request(http_request, :GET, 'File')\n end", "def create\n @upload_map = current_user.upload_maps.new(upload_map_params)\n @upload_map = update_attributes(params[\"upload_map\"][\"file\"], @upload_map)\n\n respond_to do |format|\n if @upload_map.save\n message = \"上傳成功,新增了 #{@upload_map.dots.size} 個點\"\n @upload_map.dots.size > 0 ? flash[:notice] = message : flash[:warning] = \"#{message},建議改用其他格式匯入\"\n format.html { redirect_to @map }\n format.json { render :show, status: :created, location: @upload_map }\n else\n format.html { render :new }\n format.json { render json: @upload_map.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @svg_image.update(svg_image_params)\n format.html { redirect_to @svg_image, notice: 'Svg image was successfully updated.' }\n format.json { render :show, status: :ok, location: @svg_image }\n else\n format.html { render :edit }\n format.json { render json: @svg_image.errors, status: :unprocessable_entity }\n end\n end\n end", "def svg_shape!\n svg = File.read shape_svg_file\n # Get rid of the XML doctype.\n svg.sub! /\\<\\?xml.*\\?\\>/, ''\n svg.strip!\n\n # Get rid of namespaces, version, and scaling.\n tag = /\\<svg[^\\>]*\\>/.match(svg)[0]\n tag.gsub! /xmlns\\:?\\w*\\=\"[^\"]*\"/, ''\n tag.gsub! /version=\"[^\"]*\"/, ''\n svg.sub! /\\<svg[^\\>]*\\>/, tag\n \n svg\n end", "def edit_svg\n project = Project.find params[:id]\n @filename = params[:image_name]\n @path= (File.join project.path, @filename).gsub(\"public\",\"\")\n end", "def to_svg\n if (@fullscreen or @layout.fullscreenmap)\n #then we can skip the subscreen rendering with tempfiles and dump the map's svg\n funkygps.map.to_svg\n else\n out = %{<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\\n}\n out << %{<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\\n}\n out << %{<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"#{width}px\" height=\"#{height}px\">\\n}\n @layout.subscreens.each do |subscreen|\n out << add_svg(x: @layout.x(of:subscreen), y: @layout.y(of:subscreen), width: @layout.width(of:subscreen), height: @layout.height(of: subscreen), svg: funkygps.instance_variable_get(subscreen).to_svg) if @layout.is_visible(screen: subscreen)\n end\n out << %{</svg>}\n out\n end\n end", "def create\n # TODO: If they have a shareable link, verify that it is acceptable\n @errors = Array.new\n params = map_params\n\n @map = Map.create(map_params)\n @okay = @map.valid?\n if @okay\n redirect_to @map, format: :json\n else\n render json: @map.errors, status: :unprocessable_entity\n end\n\n end", "def new\n @svgpost = Svgpost.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @svgpost }\n end\n end", "def put_pdf_in_request_to_svg_with_http_info(out_path, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: PdfApi.put_pdf_in_request_to_svg ...\"\n end\n # verify the required parameter 'out_path' is set\n if @api_client.config.client_side_validation && out_path.nil?\n fail ArgumentError, \"Missing the required parameter 'out_path' when calling PdfApi.put_pdf_in_request_to_svg\"\n end\n # resource path\n local_var_path = \"/pdf/convert/svg\"\n\n # query parameters\n query_params = {}\n query_params[:'outPath'] = out_path\n query_params[:'storage'] = opts[:'storage'] if !opts[:'storage'].nil?\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])\n\n # form parameters\n form_params = {}\n # Fix header in file\n post_body = nil\n post_body = opts[:'file'] if !opts[:'file'].nil?\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/octet-stream'])\n\n # http body (model)\n # Fix header in file\n # post_body = nil\n auth_names = ['JWT']\n data, status_code, headers = @api_client.call_api(:PUT, 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 => 'AsposeResponse')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PdfApi#put_pdf_in_request_to_svg\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def save_svg(svg)\n # invoke plot in background, return pid\n bg('/dev/null', [\n # absolute path to python\n '/usr/bin/python3',\n\n # build path to plot.py\n '%s/plot.py' % [__dir__],\n\n # build chart json data\n JSON.unparse(svg),\n ])\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
currently a noop method. If a format other than mongo query format is used for prefilters, this method would do the appropriate conversion
def convert_filter_to_mongo_query(filter) filter end
[ "def queryAndConvert() \n\t\tres = self.query()\n\t\treturn res.convert()\n end", "def mongoize(object)\n case object\n when AnyType then object.mongoize\n when Hash \n v = object[:value]\n case object[:type].downcase\n when 'integer', 'decimal', 'boolean'\n v = YAML.load(v)\n when 'datetime', 'date', 'instant'\n v = PartialDateTime.mongoize(v)\n end\n convertType(v)\n else\n convertType(object)\n end\n end", "def typecast_query_param( param_value, field )\n #This is a stub, used for indexing\n end", "def convert(obj)\n ret = convert_proc.call(obj)\n filters.execute(ret)\n end", "def to_json(query)\n res = query\n # conversion for fieldname\n res = res.gsub(/( [^ ]+?: )/) {|fieldname| fieldname_format(fieldname)}\n # conversion for ObjectId\n res = res.gsub(/ObjectId\\([^ ]+?\\)/) {|objectid| to_string(objectid)}\n # conversion for Timestamp\n res = res.gsub(/Timestamp \\d+\\|\\d+/) {|timestamp| to_string(timestamp)}\n # conversion for Date\n res = res.gsub(/new Date\\(\\d+\\)/) {|date| to_string(date)}\n # filter regex\n res = res.gsub(/\\/\\^.*\\//) {|pattern| to_string(pattern)}\n return res\n end", "def convert!(preferred_formats=nil)\n raise ArgumentError unless (preferred_formats && preferred_formats.size > 0)\n\n # why convert if we are already there?\n # (except in the case that the serivce excepts coordinates and we have a\n # a geocode ... the google geocode results are superior)\n #\n skip_conversion = false\n unless (@format.to_sym == Query::Format::Geocode.format) &&\n preferred_formats.include?(Query::Format::Coordinates.format)\n if preferred_formats.include?(@format.to_sym)\n skip_conversion = true\n converted_query = self.dup\n end\n end\n\n unless skip_conversion\n # go through each acceptable format and try to convert to that\n converted = false\n converted_query = Barometer::Query.new\n preferred_formats.each do |preferred_format|\n klass = FORMAT_MAP[preferred_format.to_sym]\n # if we discover that the format we have is the preferred format, return it\n if preferred_format == @format\n converted = true\n converted_query = Barometer::Query.new(@q)\n end\n unless converted\n unless converted_query = get_conversion(preferred_format)\n converted_query = Query::Format.const_get(klass.to_s).to(self)\n end\n converted = true if converted_query\n end\n if converted\n converted_query.country_code ||= Query::Format.const_get(klass.to_s).country_code(converted_query.q)\n post_conversion(converted_query)\n break\n end\n end\n end\n\n # force geocode?, unless we already did\n #\n if Barometer.force_geocode && !@geo\n if converted_query && converted_query.geo\n @geo = converted_query.geo\n elsif converted_query\n puts \"enhance geocode: #{converted_query.q}\" if Barometer::debug?\n geo_query = Query::Format::Coordinates.to(converted_query)\n @geo = geo_query.geo if (geo_query && geo_query.geo)\n converted_query.geo = @geo.dup\n end\n end\n\n converted_query\n end", "def mongoize\n value\n end", "def type_cast_for_solr(value, dest_type = nil)\n return nil if value.nil?\n return coder.dump(value) if encoded?\n\n case (dest_type || type)\n when :boolean then value ? 'true' : 'false'\n when :date, :time, :datetime, :timestamp then value.to_time.utc.strftime(Format::SOLR_TIME_FORMAT)\n when :list, :set then list_to_solr_value(value)\n when :map then map_to_solr_value(value)\n when :uuid, :timeuuid then value.to_s\n else value\n end\n end", "def convert (val)\n return nil if val.blank? and val != false\n if @type == String\n return val.to_s\n elsif @type == Integer\n return Kernel.Integer(val) rescue val\n elsif @type == Float\n return Kernel.Float(val) rescue val\n elsif @type == Boolean\n v = BOOLEAN_MAPPING[val]\n v = val.to_s.downcase == 'true' if v.nil? # Check all mixed case spellings for true\n return v\n elsif @type == Date\n if val.is_a?(Date)\n return val\n elsif val.is_a?(Time)\n return val.to_date\n else\n return Date.parse(val.to_s) rescue val\n end\n elsif @type == Time\n if val.is_a?(Time)\n return Time.at((val.to_i / 60) * 60).utc\n else\n return Time.parse(val).utc rescue val\n end\n elsif @type == DateTime\n if val.is_a?(DateTime)\n return val.utc\n else\n return DateTime.parse(val).utc rescue val\n end\n elsif @type == Array\n val = [val] unless val.is_a?(Array)\n raise ArgumentError.new(\"#{name} must be an Array\") unless val.is_a?(Array)\n return val\n elsif @type == Hash\n raise ArgumentError.new(\"#{name} must be a Hash\") unless val.is_a?(Hash)\n return val\n elsif @type == BigDecimal\n \treturn BigDecimal.new(val.to_s)\n else\n if val.is_a?(@type)\n val\n elsif val.is_a?(Hash) and (@type < EmbeddedDocument)\n return @type.new(val)\n else\n raise ArgumentError.new(\"#{name} must be a #{@type}\")\n end\n end\n end", "def objectified_param_value\n @objectified_param_value ||= case @filter.type\n when :date\n format = I18n.t(\"date.formats.#{QueryReport.config.date_format}\")\n param_value.kind_of?(String) ? (Date.strptime(param_value, format) rescue param_value) : param_value\n when :datetime\n param_value.kind_of?(String) ? Time.zone.parse(param_value) : param_value\n when :boolean\n param_value.to_boolean\n else\n param_value\n end\n end", "def query_string_normalizer; end", "def coerce(value)\n return nil if value.nil? || value == ''\n \n case type\n when :date\n Date.strptime(value, @result_set.date_format) unless @empty_ok\n when :time\n DateTime.strptime(\"1/1/-4712 #{value}\", @result_set.time_format) unless @empty_ok\n when :timestamp\n DateTime.strptime(value, @result_set.time_format) unless @empty_ok\n when :number\n if value.include?('.')\n value.to_f\n elsif value.include?(',')\n value.gsub(/,/, '.').to_f\n else\n value.to_i\n end\n else\n value.to_s\n end\n end", "def mongoize(object)\n case object\n when TranslatedString then object.mongoize\n else object\n end\n end", "def mongoize(object)\n if object.is_a?(SS::Extensions::Decimal128)\n object.mongoize\n elsif object.is_a?(::BigDecimal) || object.is_a?(BSON::Decimal128) || object.numeric?\n new(object).mongoize\n end\n end", "def mongoize(object)\n object.mongoize\n end", "def format_value(key, val, data_type = nil)\n # if data_type wasn't passed, then get the data_type from the fields hash\n data_type ||= self.fields[key]\n\n val = format_operation(key, val, data_type)\n\n case data_type\n when :object\n val = val.with_indifferent_access if val.is_a?(Hash)\n when :array\n # All \"array\" types use a collection proxy\n val = val.to_a if val.is_a?(Parse::CollectionProxy) #all objects must be in array form\n val = [val] unless val.is_a?(Array) #all objects must be in array form\n val.compact! #remove any nil\n val = Parse::CollectionProxy.new val, delegate: self, key: key\n when :geopoint\n val = Parse::GeoPoint.new(val) unless val.blank?\n when :file\n val = Parse::File.new(val) unless val.blank?\n when :bytes\n val = Parse::Bytes.new(val) unless val.blank?\n when :integer\n if val.nil? || val.respond_to?(:to_i) == false\n val = nil\n else\n val = val.to_i\n end\n when :boolean\n if val.nil?\n val = nil\n else\n val = val ? true : false\n end\n when :string\n val = val.to_s unless val.blank?\n when :float\n val = val.to_f unless val.blank?\n when :acl\n # ACL types go through a special conversion\n val = ACL.typecast(val, self)\n when :date\n # if it respond to parse_date, then use that as the conversion.\n if val.respond_to?(:parse_date) && val.is_a?(Parse::Date) == false\n val = val.parse_date\n # if the value is a hash, then it may be the Parse hash format for an iso date.\n elsif val.is_a?(Hash) # val.respond_to?(:iso8601)\n val = Parse::Date.parse(val[\"iso\"] || val[:iso])\n elsif val.is_a?(String)\n # if it's a string, try parsing the date\n val = Parse::Date.parse val\n #elsif val.present?\n # pus \"[Parse::Stack] Invalid date value '#{val}' assigned to #{self.class}##{key}, it should be a Parse::Date or DateTime.\"\n # raise ValueError, \"Invalid date value '#{val}' assigned to #{self.class}##{key}, it should be a Parse::Date or DateTime.\"\n end\n when :timezone\n val = Parse::TimeZone.new(val) if val.present?\n else\n # You can provide a specific class instead of a symbol format\n if data_type.respond_to?(:typecast)\n val = data_type.typecast(val)\n else\n warn \"Property :#{key}: :#{data_type} has no valid data type\"\n val = val #default\n end\n end\n val\n end", "def convert_fields_for_query(fields)\n case fields\n when String, Symbol\n {fields => 1}\n when Array\n return nil if fields.length.zero?\n fields.each_with_object({}) { |field, hash| hash[field] = 1 }\n when Hash\n return fields\n end\n end", "def coerce(value)\n return nil if (value == nil || value == '') && @result != \"text\"\n case @result\n when \"text\"\n return value\n when \"number\"\n return BigDecimal.new(value)\n when \"date\"\n return Date.strptime(value, @result_set.date_format)\n when \"time\"\n return DateTime.strptime(\"1/1/-4712 \" + value, \"%m/%d/%Y #{@result_set.time_format}\")\n when \"timestamp\"\n return DateTime.strptime(value, @result_set.timestamp_format)\n when \"container\"\n return URI.parse(\"#{@result_set.server.scheme}://#{@result_set.server.host_name}:#{@result_set.server.port}#{value}\")\n end\n end", "def convert!\n # Appends the resource type to the Solr Document\n to_h.merge(Valkyrie::Persistence::Solr::Queries::MODEL.to_sym => [resource.internal_resource])\n .merge(indexer_solr(resource))\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the git channel for the specific IRC channel
def git_channel(channel) return @channels[channel] if @channels[channel] @channels[channel] = Git::Channel.new(@config[channel.server.name][channel.nname]) end
[ "def get_channel(build)\n channel = ''\n if build.is_branch_build\n channel = get_slack_channel(build.project)\n elsif !build.username.blank?\n channel = \"@#{build.username}\"\n end\n channel\n end", "def get_channel(arg)\n server.get_channel(arg)\n end", "def get_channel_by_name(client, channel_name)\n channel_data = client.channels_info(channel: \"#\" + channel_name.to_s)\n channel_data.channel.id\nend", "def channel\n Channel.get(@name)\n end", "def channel\n @channels[BASE_PATH]\n end", "def channel\n @query.channels.get(@name)\n end", "def get_slack_channel(project)\n get_plugin_setting_value(project, :slack_channel)\n end", "def get_chibi_channel\n send_request(FUNCTION_GET_CHIBI_CHANNEL, [], '', 1, 'C')\n end", "def get_channel(channel)\n channel = channel.to_s if channel.kind_of?(Symbol)\n raise \"Channel not found: #{channel} (expected one of #{self.keys.inspect})\" unless self.keys.include?(channel)\n self[channel]\n end", "def channel_name\n @channel_name ||= SlackUtils::SingletonClient.instance.find_channel_name(@channel_id)\n end", "def channel\n return @channel\n end", "def find_channel(cid)\n return self.channels[cid]\n end", "def get_channel(bone, channel)\n channel_data_for(bone).get_channel(channel)\n end", "def get_channel hash, to\n if config.recipient then\n make_channel config.recipient\n elsif to then\n make_channel to\n elsif hash[:channel]\n make_channel hash[:channel]\n else\n raise CollinsNotify::ConfigurationError.new \"No slack.channel or config.recipient specified\"\n end\n end", "def find_channel\n debug 'Looking for channel...'\n _response = self.signed_request'/api/v1/channels.list.joined', 'GET'\n _channels = _response['channels']\n\n _channels.each { |ch|\n if ch['name'] == $config.get_channel\n @channel_id = ch['_id']\n break\n end\n }\n\n if @channel_id\n debug \"Channel found! Channel ID is #{@channel_id}\"\n else\n puts \"Channel not found. Check if channel ##{$config.get_channel} exists and bot user is added to the channel.\"\n exit 1\n end\n end", "def channel_name\r\n return for_context(false) { |c| c.channel_name } \r\n end", "def channel_to\n Channel.find(channel_id_to)\n end", "def channel_by_name name\n @channels.find { |channel| channel.name == name }\n end", "def channel\n attributes[:channel]\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simply make sure that `opts` can be converted into a Hash, then does so. Then returns `opts` as a HashWithIndifferentAccess.
def sanitize_options(opts) opts = opts.to_hsh rescue opts.to_h HashWithIndifferentAccess.new(opts) end
[ "def convert_options(options)\n\t\tHashWithIndifferentAccess.new(options)\n\tend", "def to_hash_opts_with_defaults(opts, defaults = nil)\n if opts.is_a?(Hash)\n opts.dup\n elsif opts.is_a?(ActionController::Parameters)\n opts.to_h\n elsif defaults.is_a?(Hash)\n defaults.dup\n else\n {}\n end\n end", "def opts\n params = {}\n @opts.each { |opt, opts| params[opt.to_sym] = opt_value(opt, *opts[0, 2]) }\n params\n end", "def to_hash_merge_opts(opts, defaults = {})\n if opts.is_a?(Hash)\n defaults.merge(opts)\n else\n defaults.dup\n end\n end", "def parse_options(opts)\n JSON.parse(opts, { symbolize_names: true })\n end", "def options_as_hash\n options.inject({}) do |memo, option|\n memo[option.name.to_s] = option\n memo\n end\n end", "def to_hash_options_for_verbosity(actor, verbosity, opts)\n if (verbosity != :id) && (verbosity != :ignore)\n if verbosity == :minimal\n {\n :include => MINIMAL_HASH_KEYS\n }\n elsif verbosity == :standard\n {\n :include => MINIMAL_HASH_KEYS | STANDARD_HASH_KEYS\n }\n elsif (verbosity == :verbose) || (verbosity == :complete)\n {\n :include => MINIMAL_HASH_KEYS | STANDARD_HASH_KEYS | VERBOSE_HASH_KEYS\n }\n else\n {}\n end\n else\n {}\n end\n end", "def with_opts(opts)\n orig_opts = @opts\n @opts = orig_opts.merge(opts)\n copy_inputs_wrapper_from_wrapper(opts, @opts)\n yield\n ensure\n @opts = orig_opts if orig_opts\n end", "def to_hash\n unless @indifferent_access\n indifferent_access!\n end\n @settings\n end", "def parsed_opts\n ActiveSupport::JSON.decode conv_opts\n end", "def opts=(o=nil)\n raise \"opts must be a hash\" unless (o ||= {}).is_a? Hash\n @opts = o\n end", "def updateOpts(opts = nil)\n\t\t\tif !opts\n\t\t\t\topts = {}\n\t\t\tend\n\n\t\t\tif !opts.is_a? Hash\n\t\t\t\traise SDKInvalidArgException, '`opts` must be a hash'\n\t\t\telsif opts.has_key? 'params' && !opts['params'].is_a?(Hash)\n\t\t\t\traise SDKInvalidArgException '`opts[\\'params\\']` must be a hash'\n\t\t\tend\n\n\t\t\t@opts.merge!(opts)\n\t\tend", "def to_hash_options_for_verbosity(actor, verbosity, opts)\n if (verbosity == :minimal) || (verbosity == :standard)\n {\n :include => DEFAULT_HASH_KEYS\n }\n elsif (verbosity == :verbose) || (verbosity == :complete)\n {\n :include => DEFAULT_HASH_KEYS | VERBOSE_HASH_KEYS\n }\n else\n {}\n end\n end", "def with_opts(opts)\n orig_opts = @opts\n @opts = orig_opts.merge(opts)\n copy_inputs_wrapper_from_wrapper(opts, @opts)\n yield\n ensure\n # :nocov:\n @opts = orig_opts if orig_opts\n # :nocov:\n end", "def extract_options(args)\n options = args.last\n options.respond_to?(:to_hash) ? options.to_hash.dup : {}\n end", "def standardize_opts(opts)\n opts ||= {}\n opts[:mode] = :rails\n opts[:symbol_keys] = opts[:symbolize_keys] || opts[:symbolize_names]\n\n opts\n end", "def awesome_hash_with_indifferent_access(object)\n awesome_hash(object)\n end", "def extractable_options?\n instance_of?(Hash)\n end", "def extract_options(*args)\n args = args.dup\n index = args.rindex { |e| e.is_a?(Hash) } || args.length\n args[-1] = args[index] || {}\n args[index] = nil if index < args.length - 1\n args\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Raises an error if `opts` does not contain the `key`
def validate_option_key(opts, key) raise "opts[:#{key}] or opts['#{key}'] must be given" unless opts.has_key?(key) end
[ "def check_keys(*args)\n options = args.shift\n args.each do |key|\n raise MissingParameter.new(key) unless options.key?(key)\n end\n end", "def required_option(options, key)\n result = get_option(options, key)\n raise ArgumentError, \"Missing required option: #{key}\" if result == \"\"\n result\n end", "def assert_bad_or_good_if_key(key, value, missing, message_key = :message)\n return true unless @options.key? key\n\n if @options[key]\n return true if bad?(value, message_key)\n else\n return true if good?(value, message_key)\n missing = 'not ' + missing\n end\n\n @missing = missing\n false\n end", "def assert_good_or_bad_if_key(key, value, missing, message_key = :message)\n return true unless @options.key? key\n\n if @options[key]\n return true if good?(value, message_key)\n missing = 'not ' + missing\n else\n return true if bad?(value, message_key)\n end\n\n @missing = missing\n false\n end", "def check_for_missing_value\n @options.each do |key, value|\n raise OptionParser::MissingArgument, key if value =~ /^--/\n end\n end", "def fetch_option(key)\n options.find { |option| [option.long, option.short].include?(clean(key)) }\n end", "def validate_option(key, value)\n return if !TidyFFI::Tidy.validate_options? || TidyFFI::Interface.option_valid?(key, value)\n\n if TidyFFI::Interface.default_options[key]\n raise TidyFFI::Tidy::InvalidOptionValue, \"#{value} is not a valid value for key #{key}\"\n else\n raise TidyFFI::Tidy::InvalidOptionName, \"#{key} is an invalid option name\"\n end\n end", "def fetch_option(key); end", "def has_key!(hash, key)\n unless hash.has_key?(key)\n raise ArgError, \"#{hash} should have '#{key}' key\"\n end\n end", "def check_keys\n @options.keys.each do |key|\n if DEFAULT_OPTIONS.keys.index(key).nil?\n raise \"#{key} is not a valid configuration option.\"\n end\n end\n end", "def option_defined?( key )\n options.has_key?(key) and options[key]\n end", "def has_option?(k)\n raise ParseError.new(\"`nil' cannot be an option key\") if (k.nil?)\n @options.has_key?(k.to_sym)\n end", "def strict_operations_option(operations:, key:)\n val = options_as_planned(operations: operations, key: key)\n unless val.uniq.length == 1\n msg = \"More than one value given in Operation Options for #{key}:\" \\\n \" #{val}\"\n raise IncompatibleParametersError, msg\n end\n val.first\n end", "def valid_option? opt_sym\n @options_with_short_keys.key? opt_sym\n end", "def check_for_illegal_keys!(options)\n if any_unrecognized_keys?(ALLOWED_KEYS, options)\n raise \"Unrecognized options in add_method_tracer_call: #{unrecognized_keys(ALLOWED_KEYS, options).join(', ')}\"\n end\n end", "def arguement_check(options)\n args = [\"access_key_id\", \"secret_access_key\", \"bucket_name\"] \n args.each do |arg|\n begin\n options.fetch(arg)\n rescue KeyError\n raise ArgumentError, \"Argument #{arg} is required.\"\n end\n end\n end", "def remove(key)\n return_value = nil\n\n @opts = @opts.delete_if do |item|\n head, tail = split.call item\n\n return_value = tail if head == key.to_s\n end\n\n return_value\n end", "def option(key)\n option_set[key]\n end", "def requireParameterForOption(opt, options)\n if 0 == options.count\n log(ErrorLabel, \"Parameter for option #{opt} is missing!\")\n else\n if options[0][0].eql?(\"-\")\n log(ErrorLabel, \"Parameter for option #{opt} may not begin with a hyphen.\")\n end\n end\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts the input entertrack (probably from barcode scanner) into the computer_id
def track_to_id self.computer_id = (entertrack - 10000000) end
[ "def rom_id\n read_bytes(0x3C, 2)\n end", "def device_id\n response = meta(nil,:info).first\n manufacturer = response[/^Manufacturer: (.*)/,1].strip\n model = response[/^Model: (.*)/,1].strip\n revision = response[/^Revision: (.*)/,1].strip\n imei = response[/^IMEI: (.*)/,1].strip\n return '%s %s, IMEI: %s' % [manufacturer.capitalize,model,imei]\n end", "def to_id(summoner)\n \tsummoner = summoner.to_s\n summoner=~/[0-9]{2,8}/ ? summoner.to_i : get_id(summoner)\n end", "def return_character_id(result_hash)\n result_hash[:id]\n end", "def interface_eni_id(interface)\n mac = interface_mac_address(interface)\n eni_id = node['ec2']['network_interfaces_macs'][mac]['interface_id']\n Chef::Log.debug(\"#{interface} eni id is #{eni_id}\")\n eni_id\n end", "def hw_id\n ifaces = Facter::Util::IP.get_interfaces.select do |iface|\n # @todo danielp 2013-07-25: Razor would previously limit this to only\n # Ethernet interfaces, which seems (a) limited, and (b) likely to fail\n # in Fedora 20 and beyond, when they rename the interfaces based\n # on topology. IMO, we should have a more sensible policy than this.\n #\n # @todo lutter 2013-08-18: add 'emNNN' to the list of interfaces as a\n # stopgap since that's what Fedora 18 uses. Most likely, we will need\n # to make this regexp configurable to allow people to adapt it to\n # various kernel's naming conventions\n iface =~ /^(eth|em)\\d+$/\n end\n\n # Since we might have eliminated the only interfaces present on this\n # machine, this needs to apply *after* the filtering is done.\n ifaces.empty? and\n raise \"no network interfaces detected; cannot generate a hardware ID\"\n\n # @todo danielp 2013-07-25: Razor did nothing to normalize case in the\n # hardware identifier, depending on either the server doing that, or\n # simple chance to ensure that they matched. We currently follow...\n ifaces.map do |iface|\n Facter::Util::IP.get_interface_value(iface, 'macaddress')\n end.compact.join('_').gsub(':', '')\n end", "def char_to_button_id(char); end", "def id\n m = /ether\\s+(\\S+)/.match(`ifconfig wlan0`)\n return nil if m.nil?\n mac = m[1] # WLAN mac address\n return nil if mac.nil?\n MAC2ID[mac.downcase]\n end", "def parse_human_id_formatted(input)\n parse_human_ids_formatted(input).first\n end", "def usercode\n \n #Put the device into IDCode retrival mode.\n self.instruction = :usercode\n\n #And attempt to retrieve the 32-bit IDcode.\n usercode_packed = receive_data(32).reverse\n\n #Return the usercode as a hex string.\n usercode_packed.unpack(\"H*\").first.upcase\n\n end", "def machine_id(timeout=nil)\n request = Packet.create_request(COMMAND_ID_CORE_MACHINE_ID)\n\n args = [request]\n args << timeout if timeout\n\n response = client.send_request(*args)\n\n mid = response.get_tlv_value(TLV_TYPE_MACHINE_ID)\n\n # Normalise the format of the incoming machine id so that it's consistent\n # regardless of case and leading/trailing spaces. This means that the\n # individual meterpreters don't have to care.\n\n # Note that the machine ID may be blank or nil and that is OK\n Rex::Text.md5(mid.to_s.downcase.strip)\n end", "def card_identification\n message.fields[6].strip\n end", "def find_unique_id(line)\n\t\ttemp = line =~ /\\w{11}:/\n\t\tif (temp != nil)\n\t\t\ttemp = line[temp..temp+10]\n\t\tend\n\t\treturn temp\n\tend", "def get_id(data)\n result = get_full_data(data)\n screenid = nil\n result.each { |screen| screenid = screen['screenid'].to_i if screen['name'] == data[:name] }\n screenid\n end", "def fetch_id(char_name)\n char = Character.find_by_name(char_name)\n char.id\n end", "def build_hw_id(mac_addresses)\n mac_addresses.map { |mac| mac.downcase.gsub(\":\", \"\") }.join(\"_\")\n end", "def enter_id_number(data)\n logger.debug \"Entering ID number information\"\n prefix = data[BAMPFAObjectData::ID_PREFIX.name]\n year = data[BAMPFAObjectData::ID_YEAR.name]\n gift_1 = data[BAMPFAObjectData::ID_GIFT_1.name]\n gift_2 = data[BAMPFAObjectData::ID_GIFT_2.name]\n gift_3 = data[BAMPFAObjectData::ID_GIFT_3.name]\n alpha = data[BAMPFAObjectData::ID_ALPHA.name]\n wait_for_element_and_type(id_prefix_input_locator, prefix) if prefix\n wait_for_element_and_type(id_year_input_locator, year) if year\n wait_for_element_and_type(id_prefix_input_locator, gift_1) if gift_1\n wait_for_element_and_type(id_prefix_input_locator, gift_2) if gift_2\n wait_for_element_and_type(id_prefix_input_locator, gift_3) if gift_3\n wait_for_element_and_type(id_prefix_input_locator, alpha) if alpha\n end", "def make_track_number()\n\t\tnumber = @storage.get_total_track_count + 1\n\t\t# Convert number to string, so that in @storage, track number is stored as a string\n\t\treturn number.to_s\n\tend", "def server_to_id(server)\r\n if server.kind_of? String\r\n puts \"forward lookup\"\r\n id = @server_alias_to_id[server]\r\n else\r\n puts \"reverse lookup\"\r\n id = @cinch_bot_to_id[server] #If it's not a string, assume it's a bot object, reverse lookup id\r\n end\r\n id\r\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensures that a computer's status can only be either scrapped or sold
def scrapped_or_sold if (scrapped.blank? and sold.blank?) # Do nothing elsif !(scrapped.blank? ^ sold.blank?) errors.add(:base, "Please indicate whether a computer has been scrapped or sold, not both.") end end
[ "def can_be_assigned?\n\t\t(!status.include? STATUS[\"Assigned\"]) && (!status.include? STATUS[\"Repair\"])\n\tend", "def check_book_availability\n if self.book.book_copies.unassigned_copies.where(is_active: true).count < 1\n errors.add(:base, \"Book out of stock\")\n end\n end", "def player_1_wins_with_scissors\n @player_1_weapon == \"scissors\" && @player_2_weapon != \"rock\"\n end", "def is_computer?\n false\n end", "def been_sold\n if (customer.present? or price.present?) and sold != true\n errors.add(:base, \"Only sold computers can have customers or prices.\")\n end\n end", "def status\n return 0 unless has_been_approved_for_this_season?\n return 1 if all_primary_picks_are_wins?\n if first_loss_before_second_chance_start? && all_secondary_picks_are_wins?\n return 2\n end\n if first_loss_before_second_chance_start? == false || all_secondary_picks_are_wins? == false\n return 3\n end\n raise \"error determining status\"\n end", "def can_be_fulfilled?\n has_inventory = (quantity <= item.inventory)\n # status == \"unfulfilled\"\n (has_inventory) && (status == \"unfulfilled\")\n end", "def can_rent_books?\n @rented_books.each do |b|\n if b.status == \"overdue\"\n return false\n end\n end\n @rented_books.count < 2\n end", "def enable_disable_inventory?\n active? && !delivered? && !is_draft?\n end", "def cannot_save_inprod_verify(state)\n act_state = cannot_save_inprod_checkbox['checked'].to_s\n if (state.downcase == 'checked' and act_state.match(/(true)$/i)) or (state.downcase == 'unchecked' and act_state.empty?)\n print_to_output (\"VERIFIED: 'Cannot Save in Production' is #{state} in Rave.\")\n else\n raise \"'Cannot Save in Production' is NOT #{state} in Rave.\"\n end\n end", "def status_change_allowed?\n !event.application_status_locked\n end", "def cannot_withdraw?\n cannot_withdraw = false\n case status\n when InventoryItem::OUT_OF_STOCK\n cannot_withdraw = true\n when InventoryItem::PENDING_ENTRY\n cannot_withdraw = true\n when InventoryItem::EXPIRED\n cannot_withdraw = true\n end\n\n cannot_withdraw\n end", "def check_status\n #puts (\"Checking Status for \" + self.user.name + \" on \" + self.challenge.title)\n #logger.debug(\"Checking Status for \" + self.user.name + \" on \" + self.challenge.title)\n remaining_misses <= 0 ? set_status(:Disqualified) : set_status(:Active)\n end", "def sold?(product)\n product.status == 'Sold'\n end", "def strong?\r\n @health > 100\r\n end", "def can_rent_books?\n @books_rented.each do |b|\n if b.status == \"Overdue\"\n return false\n end\n end\n\n if @books_rented.count >= 2\n return false\n else\n return true\n end\n end", "def computer_choice!(display_in)\n # try to win\n winner_square = can_computer_win?(display_in)\n puts winner_square\n if winner_square != 0 # can win, pick the winner\n add_piece_to_boaard(display_in, COMPUTER_MARK, winner_square)\n else\n # try to avoid loss\n protect_square = computer_can_lose(display_in) \n puts \"Avoid Loss::: #{protect_square}\"\n if protect_square != 0 # about to lose, so pick the protecting square\n add_piece_to_boaard(display_in, COMPUTER_MARK, protect_square)\n else\n # find a free square since I can't win and I am not about to lose\n free_square_value = free_square(display_in)\n if free_square_value.nonzero? # not empty board\n add_piece_to_boaard(display_in, COMPUTER_MARK, free_square_value)\n end\n end\n end\n end", "def billed_or_paid?\n status == PAID || status == BILLED\n end", "def can_use_super?\n return @stored_energy == @officer.scop_rate\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensures that a customer and price can only be assigned for sold computers
def been_sold if (customer.present? or price.present?) and sold != true errors.add(:base, "Only sold computers can have customers or prices.") end end
[ "def customer_can_afford_pet(customer, new_pet)\n customer[:cash] >= 100\nend", "def customer_can_afford_pet(customer, cost_of_pet)\n customer[:cash] >= cost_of_pet[:price] ? true : false\nend", "def customer_can_afford_pet(customer, new_pet)\nreturn customer[:cash] >= new_pet[:price]\nend", "def restrict_purchase\n return false unless price_group && product\n !can_purchase?\n end", "def validate_consumption_and_production_prices\n %i[marginal_costs max_consumption_price].each do |price_attribute|\n value = public_send(price_attribute)\n\n next if value.nil?\n\n if merit_order&.type != :flex\n errors.add(price_attribute, 'is only allowed when the merit_order type is \"flex\"')\n next\n end\n\n errors.add(price_attribute, 'must not be less than zero') if value.negative?\n end\n end", "def customer_can_afford_pet(customer, pet)\n if customer[:cash] >= pet[:price]\n return true\n else\n return false\n end\nend", "def scrapped_or_sold\n if (scrapped.blank? and sold.blank?)\n # Do nothing\n elsif !(scrapped.blank? ^ sold.blank?)\n errors.add(:base, \"Please indicate whether a computer has been scrapped or sold, not both.\")\n end\n end", "def user_cant_be_product_seller\n if product.merchant.user_id == user_id\n errors.add(:product_id, \"can't review your own products\")\n end\n end", "def customer_can_afford_pet?(customer_hash, wanted_pet)\n if customer_hash[:cash] >= wanted_pet[:price]\n true\n else\n false\n end\nend", "def company_responsible_for_customer?(company_id: nil)\n self.carrier_product.company_id == company_id\n end", "def customer_can_afford_pet(customer, new_pet)\n return customer[:cash] >= new_pet[:price]\n\n # if customer[:cash] >= new_pet[:price]\n # return true\n # elsif customer[:cash] < new_pet[:price]\n # return false\n # end\nend", "def validate\n price_cents <= 0 ? raise(InvalidProductPriceCents) : true\n end", "def ensure_sufficient_credit\n if user.store_credits_total < store_credit_amount\n # user's credit does not cover all adjustments.\n adjustments.store_credits.destroy_all\n\n update!\n end\n end", "def is_customer_facing?\n self.company_type.price_set?\n end", "def validate_ownership\n buyer_items.each { |item| item.validate_owner seller }\n seller_items.each { |item| item.validate_owner buyer }\n end", "def ensure_customer!\n unless current_customer\n # TODO: clean up customer not authorized\n render text: \"Not allowed\", status: :unauthorized\n false\n end\n end", "def sell_pet_to_customer(pet_shop, pet, customer)\n\n # check if pet exists and if customer can afford to buy the pet\n if find_pet_by_name(pet_shop, pet) != nil && (customer_can_afford_pet(customer, pet) == true)\n\n # add pet to customer\n add_pet_to_customer(customer, pet)\n\n # remove pet from store\n remove_pet_by_name(pet_shop, pet)\n\n sold = customer_pet_count(customer)\n # increase pets sold in petshop\n increase_pets_sold(pet_shop, sold)\n\n # changing total cash in store\n amount = pet[:price]\n add_or_remove_cash(pet_shop, amount)\n end\nend", "def valid_assign(course_id,current_user)\n if current_user.typeofuser == \"admin\" then\n if current_user.tenant.pricing_plan.plan_group == \"assessment_only_plan\" then\n #uncomment the below code if we want to stop the admin while assigning only\n # if current_user.tenant.remaining_learner_credit > 0 then\n # return true\n # else\n # return false\n # end\n return true\n else\n max_learners_to_be_assigned = current_user.tenant.pricing_plan.no_of_users\n total_leaners_assigned = current_user.user.find(:all,:conditions=>[\"deactivated_at IS ?\",nil]).length\n\n if total_leaners_assigned <= max_learners_to_be_assigned\n return true\n else\n return false\n end\n end\n\n elsif current_user.typeofuser == \"individual buyer\" or current_user.typeofuser == \"corporate buyer\" then\n max_learners_to_be_assigned = BuyerSeller.find_by_course_id_and_buyer_user_id(course_id,current_user.id).no_of_license\n total_leaners_assigned = Learner.find_all_by_admin_id_and_course_id(current_user.id,course_id).length\n if total_leaners_assigned < max_learners_to_be_assigned - 1\n return true\n else\n return false\n end\n end\n end", "def sell_pet_to_customer(pet_shop, pet, customer)\n if pet != nil && customer_can_afford_pet(customer, pet) #basically enter if true # could refractor this to if pet != nil\n add_pet_to_customer(customer, pet)\n customer[:cash] -= pet[:price]\n remove_pet_by_name(pet_shop, pet)\n increase_pets_sold(pet_shop, 1)\n add_or_remove_cash(pet_shop, pet[:price])\n end\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns boolean for user being/not being considered a military person, by eMIS, based on their Title 38 Status Code.
def military_person? title38_status == 'V3' || title38_status == 'V6' end
[ "def status\n return :not_authorized unless user_loa3\n\n mvi_response&.status\n end", "def status\n return MVI::Responses::FindProfileResponse::RESPONSE_STATUS[:not_authorized] unless user.loa3?\n\n mvi_response.status\n end", "def status\n return MPI::Responses::FindProfileResponse::RESPONSE_STATUS[:not_authorized] unless user_identity.loa3?\n\n mvi_response.status\n end", "def detect_protect_on_status(pkmn, check_status = true)\n return true if check_status and pkmn.status != 0\n return true if pkmn.battle_effect.has_substitute_effect? and pkmn != @IA_Info[:launcher]\n return true if pkmn.battle_effect.has_safe_guard_effect?\n return false\n end", "def served_in_military?\n edipi.present? && veteran? || military_person?\n end", "def check_status\n #puts (\"Checking Status for \" + self.user.name + \" on \" + self.challenge.title)\n #logger.debug(\"Checking Status for \" + self.user.name + \" on \" + self.challenge.title)\n remaining_misses <= 0 ? set_status(:Disqualified) : set_status(:Active)\n end", "def marital_status; end", "def rehabilitation_ali?\n team_ali_code.rehabilitation_code?\n end", "def status_ok?\n current_user.status if current_user\n end", "def status\n refund? ? 3 : redeemed? ? 1 : (used_status? ? 2 : 0)\n end", "def status\n return VAProfile::ContactInformation::PersonResponse::RESPONSE_STATUS[:not_authorized] unless @user.loa3?\n\n response.status\n end", "def enrolled?\n ['A','C','R'].include?(request_status)\n end", "def marital_status\n fetch('demographic.marital_status')\n end", "def guardian_with_correct_status?\r\n return true if guardian_verified?\r\n return false if guardian_token.nil?\r\n\r\n guardian_token == self.guardian&.get_bungie_account({}, {:cached => false})&.bungieNetUser&.statusText\r\n end", "def granted?\n deg_status == 9\n end", "def is_moderator?\n self.user_status == 'moderator'\n end", "def status\n participant = Participant.where(\"user_id = ? and school_id = ?\",self.id,self.school).first\n if participant\n return participant.accepted\n else\n return false\n end\n end", "def is_lunch_status(status_text, status_emoji)\n return true if is_lunch_emoji(status_emoji)\n \n case status_text\n when /[M,m]ahlzeit/ then\n return true\n end\n \n false\nend", "def status_getuser?()\n return true if (@status == TAC_PLUS_AUTHEN_STATUS_GETUSER)\n return false\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This action is used to retrieve data to be display on the IDSR MONTHLY REPORT Is called by Ajax and renders results in json
def idsr_monthly_report_summary date = params[:year_month].split('-') @start_date = Date.new(date[0].to_i,date[1].to_i) @end_date = @start_date + 1.month - 1.day @disaggregated_diagnosis = {} idsr_monthly_set = ConceptName.where(["name IN (?)",["Idsr Monthly Summary"]]).map(&:concept_id) idsr_monthly_set_members = ConceptSet.where(["concept_set IN (?)",idsr_monthly_set]).map(&:concept_id) concept_ids = ConceptName.where(["concept_name.concept_id IN (?)", idsr_monthly_set_members]).map(&:concept_id) observation = Observation.where(["obs.obs_datetime >= ? AND obs.obs_datetime <= ? AND obs.value_coded IN (?)",@start_date, @end_date,concept_ids]).includes({:person=>{}}) observation.each do | obs| next if obs.person.blank? next if obs.answer_concept.blank? previous_date = obs.obs_datetime.strftime('%Y-%m-%d').to_date sex = obs.person.gender age = PatientService.age(obs.person, previous_date) diagnosis_name = obs.answer_concept.fullname rescue '' @disaggregated_diagnosis[diagnosis_name]={ "=<4" =>0, "=>5" =>0 } # if @disaggregated_diagnosis[diagnosis_name] != nil if age.to_i < 5 @disaggregated_diagnosis[diagnosis_name]["=<4"]+=1 else @disaggregated_diagnosis[diagnosis_name]["=>5"]+=1 end # end # end @diaggregated_paginated = [] @disaggregated_diagnosis.each { | diag, value | @diaggregated_paginated << [diag, value] } end #raise @diaggregated_paginated.inspect render :json=> @diaggregated_paginated end
[ "def index\n @monthly_details = MonthlyDetail.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @monthly_details }\n end\n end", "def get_month\n @by_months = ByMonth.where(initials: params[:initials])\n render json: @by_months\n end", "def index\n @attendance_reports = AttendanceReport.all\n\n render json: @attendance_reports\n end", "def index\n @monthlies = Monthly.where(user: current_user)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @monthlies }\n end\n end", "def index\n @monthly_reports = MonthlyReport.all\n end", "def show\n @extract_monthly = ExtractMonthly.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @extract_monthly }\n end\n end", "def show\n @monthly_retail = MonthlyRetail.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @monthly_retail }\n end\n end", "def index\n respond_with @workmonths = Workmonth.all\n end", "def show\n @monthlydatum = Monthlydatum.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @monthlydatum }\n end\n end", "def index\n @monthly_balances = MonthlyBalance.all\n\n render json: @monthly_balances\n end", "def index\n @monthly_targets = MonthlyTarget.where(target_year: Date.today.year)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @monthly_targets } == nil\n end\n end", "def index\n @mpi_statistics_reports = MpiStatisticsReport.includes({:batch => [:client, :facility]}, :user, {:eob => :check_information}).limit(20).order(\"id desc\")\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @mpi_statistics_reports }\n end\n end", "def index\n @monthly_finances = MonthlyFinance.all\n # respond_to do |format|\n # format.html # index.html.erb\n # format.json { render json: @monthly_finances }\n # end\n end", "def index\n @report = Report.find(params[:report_id])\n @report_lines = @report.report_lines\n @title = @report.report_title\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @report_lines }\n end\n end", "def index\n @monthly_interests = MonthlyInterest.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @monthly_interests }\n end\n end", "def index\n @lines = ReportingForms::LaborLine.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @lines }\n end\n end", "def index\n billing_logs = Atmosphere::BillingLog.last_year\n\n @user = Atmosphere::User.find params[:user_id] if params[:user_id]\n billing_logs = billing_logs.where(user: @user) if @user\n\n billing_logs = billing_logs.sum_currency_by_month\n billing_logs = billing_logs.group_by { |x| x[0][0] }\n\n @data_series =\n if billing_logs.present?\n billing_logs.map do |bl_currency|\n {\n name: bl_currency.first,\n data: Atmosphere::BillingLog.month_data_series(bl_currency.second)\n }\n end\n else\n [{\n name: 'No consumption',\n data: [0] * 12\n }]\n end.to_json\n\n render partial: 'atmosphere/admin/funds/billing', format: :html\n end", "def idsr_monthly_summary\n @report_name = 'IDSR Monthly Summary'\n @logo = CoreService.get_global_property_value('logo').to_s\n @current_location_name =Location.current_health_center.name\n @obs_start_year = Observation.first.obs_datetime.year\n\n render :layout => 'report'\n end", "def index\n @mint_dates = @mint.mint_dates\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @mint_dates }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This action is used to display form content on the IDSR MONTHLY REPORT
def idsr_monthly_summary @report_name = 'IDSR Monthly Summary' @logo = CoreService.get_global_property_value('logo').to_s @current_location_name =Location.current_health_center.name @obs_start_year = Observation.first.obs_datetime.year render :layout => 'report' end
[ "def index\n\t\tcollaborator_ids = User.get_collaborator_ids(current_user.id)\n\t\t@my_forms = ExtractionFormTemplate.get_user_forms(current_user.id)\n\t\t@collab_forms = ExtractionFormTemplate.get_collaborator_forms(current_user.id, collaborator_ids)\n\t\t@world_forms = ExtractionFormTemplate.get_world_forms(current_user.id, collaborator_ids)\n\t\t@page_title = \"The Extraction Form Bank\"\n\tend", "def accounting\n redirect_to admin_list_path and return if params[:selected].nil?\n @date = get_date()\n @num_days = Time.days_in_month(@date.month, @date.year)\n name_accounting_forms(render_accounting_html())\n end", "def month_report\n redirect_to tickets_path(status: 'resolved', date: '1', format: request.format.symbol)\n end", "def index\n @report_forms = Supplier::ReportForm.includes(:editor).own(current_user.id).order(id: :desc).page(params[:page] || 1)\n end", "def index\n unless params[:all].nil?\n @extraction_forms = ExtractionForm.all\n @title = \"Listing All Extraction Forms\"\n else\n available = User.get_available_extraction_form_ids(current_user.id)\n @extraction_forms = ExtractionForm.find(available).paginate(:page=>params[:page])\n @title = \"Your Extraction Forms\"\n end\n end", "def index\n @monthly_reports = MonthlyReport.all\n end", "def new\n @monthly_detail = MonthlyDetail.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @monthly_detail }\n end\n end", "def this_month\n\t\t@concerts = Concert.where(\"extract(month from date) = ? and extract(year from date) = ?\", DateTime.now.month, DateTime.now.year)\n\t\trender(\"index\")\n\tend", "def index\n @monthly_details = MonthlyDetail.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @monthly_details }\n end\n end", "def index\n @n400_forms = N400Form.all\n end", "def new\n @extract_monthly = ExtractMonthly.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @extract_monthly }\n end\n end", "def new\n @incident_report = IncidentReport.new\n\n respond_to do |format|\n format.html # new.html.erb\n end\n end", "def index\n @morning_forms = MorningForm.all\n end", "def time_form\n @index = Index.find(params[:id])\n @form_url = {:action => params['form_action'], :id => params['id']}\n @form_url[:controller] = params['form_controller'] || 'students'\n @date = params[:date] ? Time.parse(params[:date]) : Date.today\n @day = params[:day]\n @form_action = params[:form_action]\n end", "def index\n @control_list_months = ControlListMonth.all\n end", "def all_forms\n self.forms.each_index { |x| puts \"[#{x.to_s}]-------\"; self.forms[x].report }\n nil\n end", "def new\n @sys_export = SysExport.new\n render :layout => 'moban_edit'\n end", "def index\n @loan_forms = LoanForm.all\n end", "def new\n @monthly = current_user.monthlies.new\n if current_user.monthlies.empty?\n today = Date.today\n @monthly.year = today.year\n @monthly.month = today.month\n else\n latest = current_user.monthlies[0]\n if 12 == latest.month\n @monthly.year = latest.year + 1\n @monthly.month = 1\n else\n @monthly.year = latest.year\n @monthly.month = latest.month + 1\n end\n end\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @monthly }\n # show modal form in time_records index\n format.js { render :partial => 'new_modal'}\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse out a teamweek file and return an array of players
def get_team_for_week(team, week) file = "#{@teamweek_dir}/#{team}_#{week}.html" n = Nokogiri.HTML(File.open(file)) players = [] [0,1,2].each do |i| t0 = n.css("#statTable#{i}") t0.css('tr').each do |tr| opts = {} next unless tr.css('td.pos').text =~ /\S/ opts[:name] = tr.css('td.player a.name').text (pteam, ppos) = tr.css('li.ysf-player-team-pos span').text.gsub(/[() ]/, '').split('-') ppos ||= '' ppos.gsub! /,.*/, '' ppos.gsub! /(IR|NA)/, '' opts[:pos] = ppos opts[:points] = tr.css('td.pts').text.to_i slot = tr.css('td.pos').text slot = 'WRRB' if slot == 'W/R' opts[:slot] = slot players.push(YahooFF::Player.new(opts)) end end return YahooFF::Team.new(team, week, players) end
[ "def by_season_team_parser\n by_season_team_data = []\n target_dir = by_season_team_dir\n Dir.foreach(target_dir) do |file|\n next if file == '.' or file == '..'\n json_file = File.open(target_dir + file)\n parsed_file = JSON.parse(File.read(json_file))\n player_values = parsed_file[\"api\"][\"players\"]\n\n player_values.each do |value|\n # Add team_id to parsed value\n value[:team_id] = file.split(\"_\")[0].to_i\n # Add season to parsed value\n value[:season] = file.split(\"_\")[1].to_i\n # Add coaches to parsed value\n value[:coaches] = parsed_file[\"api\"][\"coachs\"] # sic (as spelled in API)\n by_season_team_data.push(value.deep_symbolize_keys!)\n end\n end\n\n by_season_team_data\n end", "def read_players\n\n file_data = File.read(PLAYERS_DATABASE)\n\n if file_data.empty?\n []\n else\n JSON.parse(file_data).map do |player|\n Player.new(\n player['name'],\n player['short_description'],\n player['stats'],\n player['profession'],\n player['location']\n )\n end\n end\n\n end", "def opponents(week)\n return @opponents[week] if @opponents[week]\n \n filename = \"#{@schedule_dir}/#{week}.html\"\n n = Nokogiri.HTML(File.open(filename))\n\n @opponents[week] = []\n\n t = n.css('#scheduletable')\n games = t.css('table table tr').each_slice(2)\n games.each do |g|\n first, second = *g\n t1 = first.css('td.team a')[0]\n t1num = t1.attr('href').split('/')[-1]\n t1name = t1.text\n\n t2 = second.css('td.team a')[0]\n t2num = t2.attr('href').split('/')[-1]\n t2name = t2.text\n \n @opponents[week] << [t1num, t2num]\n end\n \n return @opponents[week]\n end", "def fetch_data_from_xml_file\n\t\tplayers = []\n\t\tdoc = File.open(\"./app/assets/data/1998statistics.xml\") { |f| Nokogiri::XML(f) }\n\t\t\n\t\t# traversing the xml tree using css path\n\t\tdoc.css(\"SEASON\").each do |season|\n\t\t\tseason.css(\"LEAGUE\").each do |league|\n\t\t\t\tleague.css(\"DIVISION\").each do |division|\n\t\t\t\t\tdivision.css(\"TEAM\").each do |team|\n\t\t\t\t\t\tteam.css(\"PLAYER\").each do |xml_player|\n\t\t\t\t\t\t\t# create a new Player Hash \n\t\t\t\t\t\t\tplayer = Hash.new(nil)\n\t\t\t\t\t\t\tplayer[:year] = assign_if_null season.at_css(\"YEAR\")\n\t\t\t\t\t\t\tplayer[:league_name] = assign_if_null league.at_css(\"LEAGUE_NAME\")\n\t\t\t\t\t\t\tplayer[:division_name] = assign_if_null division.at_css(\"DIVISION_NAME\")\n\t\t\t\t\t\t\tplayer[:team_name] = assign_if_null team.at_css(\"TEAM_NAME\")\n\t\t\t\t\t\t\tplayer[:team_city] = assign_if_null team.at_css(\"TEAM_CITY\")\n\t\t\t\t\t\t\tplayer[:surname] = assign_if_null xml_player.at_css(\"SURNAME\")\n\t\t\t\t\t\t\tplayer[:given_name] = assign_if_null xml_player.at_css(\"GIVEN_NAME\")\n\t\t\t\t\t\t\tplayer[:position] = assign_if_null xml_player.at_css(\"POSITION\")\n\t\t\t\t\t\t\tplayer[:home_runs] = assign_if_null xml_player.at_css(\"HOME_RUNS\")\n\t\t\t\t\t\t\tplayer[:rbi] = assign_if_null xml_player.at_css(\"RBI\")\n\t\t\t\t\t\t\tplayer[:runs] = assign_if_null xml_player.at_css(\"RUNS\")\n\t\t\t\t\t\t\t# calculate batting average \n\t\t\t\t\t\t\thits = assign_if_null xml_player.at_css(\"HITS\")\n\t\t\t\t\t\t\tat_bats = assign_if_null xml_player.at_css(\"AT_BATS\")\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tplayer[:avg] = (hits.to_f/at_bats.to_f).round(4) if hits != \"\" && at_bats!= \"\" && at_bats.to_f != 0\n\t\t\t\t\t\t\t# calculate Stolen Base %age\n\t\t\t\t\t\t\tsteals = assign_if_null xml_player.at_css(\"STEALS\")\n\t\t\t\t\t\t\tcaught_stealing = assign_if_null xml_player.at_css(\"CAUGHT_STEALING\")\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tplayer[:sbp] = (steals.to_f * 100/(steals.to_f + \n\t\t\t\t\t\t\t\t(caught_stealing != \"\"? caught_stealing.to_f : 0))).round(2) if steals!=\"\" && steals.to_f != 0\n\t\t\t\t\t\t\t# Calculate OPS (HITS + WALKS + HIT_BY_PITCH)/(AT_BATS + WALKS + HIT_BY_PITCH + SACRIFICE_FLIES)\n\t\t\t\t\t\t\twalks = assign_if_null xml_player.at_css(\"WALKS\")\n\t\t\t\t\t\t\thit_by_pitch = assign_if_null xml_player.at_css(\"HIT_BY_PITCH\")\n\t\t\t\t\t\t\tsacrifice_flies = assign_if_null xml_player.at_css(\"SACRIFICE_FLIES\")\n\t\t\t\t\t\t\tif (hits!=\"\" || walks!=\"\" || hit_by_pitch!=\"\") && \n\t\t\t\t\t\t\t(at_bats!=\"\" || walks!=\"\" || hit_by_pitch!=\"\" || sacrifice_flies!=\"\")\n\t\t\t\t\t\t\t\t$numerator = (hits!=\"\"? hits.to_f : 0) +\n\t\t\t\t\t\t\t\t\t(walks!=\"\"? walks.to_f : 0) +\n\t\t\t\t\t\t\t\t\t(hit_by_pitch!=\"\"? hit_by_pitch.to_f : 0)\n\t\t\t\t\t\t\t\t$denominator = (at_bats!=\"\"? at_bats.to_f : 0) +\n\t\t\t\t\t\t\t\t\t(walks!=\"\"? walks.to_f : 0) +\n\t\t\t\t\t\t\t\t\t(hit_by_pitch!=\"\"? hit_by_pitch.to_f : 0) + \n\t\t\t\t\t\t\t\t\t(sacrifice_flies!=\"\"? sacrifice_flies.to_f : 0)\n\t\t\t\t\t\t\t\tif $denominator > 0\n\t\t\t\t\t\t\t\t\tplayer[:ops] = ($numerator/$denominator).round(4)\n\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\t# push these into the players array\n\t\t\t\t\t\t\tplayers << player\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t\n\t\treturn players\n\tend", "def scrape_team(team_num)\n # page = @agent.get(team_page(team_num))\n # For all players\n # Create player score in DB for given week/team/league\n # Players are a row on table starting with id=\"plyr\" followed by digits.\n # Inside this row, there is a td with class \"playertablePlayerName\"\n # Position is in same td as name immediately after a ;nbsp\n # 1st instance of class=\"playertableStatappliedPoints\" is points\n # 1st TD in tr contains the position played or \"BENCH\"\n\n end", "def by_league_team_parser\n by_league_team_data = []\n target_dir = by_league_team_dir\n Dir.foreach(target_dir) do |file|\n next if file == '.' or file == '..'\n json_file = File.open(target_dir + file)\n parsed_file = JSON.parse(File.read(json_file))\n stat_values = parsed_file[\"api\"][\"stats\"]\n stat_values[:league_id] = file.split(\"_\")[1].to_i\n stat_values[:team_id] = file.split(\"_\")[3].to_i\n by_league_team_data.push(stat_values.deep_symbolize_keys!)\n end\n\n by_league_team_data\n end", "def parsePlayerData(data)\n played = Set.new\n notPlayed = Set.new\n data['games'].each do |game_stats|\n appid = game_stats['appid']\n forever = game_stats['playtime_forever']\n if forever && forever >= 30\n played.add(appid)\n else\n notPlayed.add(appid)\n end\n end\n [played, notPlayed]\n end", "def readData(tournament)\r\n\topen(\"tournament.txt\", \"r\") do |f|\r\n\t\twhile line = f.gets.chomp\r\n\t\t\tarr = line.split(\",\")\r\n\t\t\tteam = Team.new(arr[1], arr[0].to_i)\r\n\t\t\ttournament.push(team)\r\n\t\tend\r\n\tend\r\nend", "def playersXML\n doc = Nokogiri::XML(File.open(Rails.root.to_s+\"/1998statistics.xml\"))\n \n @players = []\n doc.xpath('//PLAYER').map do |i| \n # Data needed to determine batting average\n @atbats = i.xpath('AT_BATS').text\n @hits = i.xpath('HITS').text\n #calling the batting average method\n \n \n @player = Player.new\n @player.surname = i.xpath('SURNAME').text\n @player.givenname = i.xpath('GIVEN_NAME').text\n @player.games = i.xpath('GAMES').text \n @player.atbats = @atbats\n @player.runs = i.xpath('RUNS').text\n @player.hits = @hits\n @player.rbi = i.xpath('RBI').text\n @player.pb = i.xpath('PB').text\n @player.walks = i.xpath('WALKS').text\n @player.struckout = i.xpath('STRUCK_OUT').text\n @player.hitbypitch = i.xpath('HIT_BY_PITCH').text\n @players << @player\n end\n \n return @players\n \n end", "def by_country_season_parser\n by_country_season_data = []\n target_dir = by_country_season_dir\n Dir.foreach(target_dir) do |file|\n next if file == '.' or file == '..'\n json_file = File.open(target_dir + file)\n parsed_file = JSON.parse(File.read(json_file))\n league_values = parsed_file[\"api\"][\"leagues\"].values\n league_values.each {|v| by_country_season_data.push(v.deep_symbolize_keys!)}\n end\n\n by_country_season_data\n end", "def load_teams\n tell \"Loading teams...\" unless options.quiet?\n teams = []\n\n doc = Nokogiri::HTML(open(TEAMS_URL))\n div1a = doc.css('div.mod-container > div.span-2').first\n list = div1a.css('div.mod-teams-list-medium ul li')\n \n list.each do |t|\n a_tag = t.search('h5 > a').first\n id = a_tag['href'].match(/_\\/id\\/([\\d]+)\\/.+\\Z/)[1]\n name = a_tag.content\n teams.push({:id => id, :name => name})\n end\n\n teams.sort_by { |team| team[:name] }\n end", "def by_league_parser\n by_league_data = []\n target_dir = by_league_dir\n Dir.foreach(target_dir) do |file|\n next if file == '.' or file == '..'\n json_file = File.open(target_dir + file)\n parsed_file = JSON.parse(File.read(json_file))\n @team_values = parsed_file[\"api\"][\"teams\"].values\n\n end\n\n @team_values.each { |v| by_league_data.push(v.deep_symbolize_keys!)}\n\n by_league_data\n end", "def parse_players\n s0 = @scanner.pos\n parse_comments\n s2 = @scanner.pos\n if match_str('N+') == :failed\n @scanner.pos = s2\n s2 = :failed\n else\n s4 = parse_nonls\n if parse_nl == :failed\n @scanner.pos = s2\n s2 = :failed\n else\n @reported_pos = s2\n s2 = s4\n end\n end\n s2 = nil if s2 == :failed\n parse_comments\n s4 = @scanner.pos\n if match_str('N-') == :failed\n @scanner.pos = s4\n s4 = :failed\n else\n s6 = parse_nonls\n if parse_nl == :failed\n @scanner.pos = s4\n s4 = :failed\n else\n @reported_pos = s4\n s4 = s6\n end\n end\n s4 = nil if s4 == :failed\n @reported_pos = s0\n [s2&.join, s4&.join]\n end", "def parse_season_file s_file\n #Now, create the season_record if we haven't done this one.\n s_file=t_file.gsub(/\\.xml\\z/,year_records.last[\"season\"].to_s<<\".xml\")\n next if $log.index(File.basename(s_file))\n season_record = {}\n season_record.merge!(team_record)\n season_record.store(\"season\",y.xpath('./@year')[0].value.to_i)\n season_record.store(\"league\",y.xpath('./@league')[0].value)\n y.xpath('./postSeasonSeriesWins')[0].attributes.each{|k,v|\n season_record.store(k,v.value.to_i)}\n y.xpath('./teamStats')[0].attributes.each{|k,v|\n #Warning: this will work so long as any of the averages and percentages contain a decimal place, which *should* be true for every number in the dataset.\n if (v.value.index('.'))\n season_record.store(k,v.value.to_f)\n else\n season_record.store(k,v.value.to_i)\n end\n }\n y.xpath('./leagueComparison')[0].attributes.each{|k,v|\n #These should all be floats, so no warning here.\n season_record.store(\"relative_\"+k,v.value.to_f)\n }\n \n #Division, league rank, and division rank all need to be pulled out of the standings file for this season.\n s = Nokogiri::XML.parse(File.read(File.join(path_to(:rawd_dir),\"standings\",season_record[\"season\"].to_s << \".xml\")))\n #Divisions only exist from 1969 onward.\n if season_record[\"season\"]>1968\n season_record.store(\"league_rank\",s.xpath(\"//team[contains(@id,'#{team_record[\"team_id\"]}')]\")[-2][\"rank\"].to_i)\n season_record.store(\"division_rank\",s.xpath(\"//team[contains(@id,'#{team_record[\"team_id\"]}')]\")[-1][\"rank\"].to_i)\n season_record.store(\"division\",s.xpath(\"//team[contains(@id,'#{team_record[\"team_id\"]}')]\")[-1].parent.name)\n year_records.last.store(\"division_rank\",season_record[\"division_rank\"])\n else\n season_record.store(\"league_rank\",s.xpath(\"//team[contains(@id,'#{team_record[\"team_id\"]}')]\")[-1][\"rank\"].to_i)\n end\n year_records.last.store(\"league_rank\",season_record[\"league_rank\"])\n #Now all that's left for the season_record is pulling the list of game_ids from the season file.\n z = Nokogiri::XML.parse(File.read(s_file))\n s_game_records=[]\n p_game_records=[]\n z.xpath('/team/games')[0].children.each{ |w|\n game_id=w[\"id\"]\n gr = Hash[\"game_date\",game_id[3..-1],\n \"game_type\",w[\"homeaway\"],\n \"game_result\",w.xpath('./results/@result')[0].value,\n \"home_score\",w.xpath('./results/@homescore')[0].value,\n \"away_score\",w.xpath('./results/@awayscore')[0].value,\n \"opponent\",w.xpath('./opponentinfo/@opponentid')[0].value]\n if game_id[-1]==48 #\"0\"[0]\n gr.store(\"double_header\",\"false\")\n else\n gr.store(\"double_header\",\"true\")\n end\n if w[\"playoffgame\"]==\"0\"\n s_game_records.push(gr)\n else\n p_game_records.push(gr)\n end\n #Now is the best time to parse the game files, since we've got both the relevant season and standing fields open, in z and s.\n #Since each game file has two participants, only parse home games.\n g_file = File.join($datasource,game_id+\".xml\")\n if gr[\"game_type\"]==\"home\" and !$log.index(File.basename(g_file))\n g = Nokogiri::XML.parse(File.read(g_file))\n game_record = {}\n game_record.store(\"game_id\",game_id)\n game_record.store(\"date\",g.xpath('/gamedata/game/@date')[0].value)\n game_record.store(\"day_of_the_week\",g.xpath('/gamedata/game/@dayofweek')[0].value)\n game_record.store(\"attendance\",g.xpath('/gamedata/game/@attendance')[0].value.to_i)\n game_record.store(\"location\",g.xpath('/gamedata/game/stadium/@location')[0].value.gsub(/,([A-Z]{2})/,', \\1'))\n #The start time needs to be processed.\n game_record.store(\"start_time\",w[\"starttime\"].insert(1,\":\") << \" PM\")\n #The stadium name needs to be processed.\n stadium=g.xpath('/gamedata/game/stadium/@name')[0].value.gsub(/ \\(P.*\\)/,'')\n city = game_record[\"location\"].gsub(/, ?[A-Z]{2}/,'')\n stadium << \" in \" << city unless stadium.index(city)\n game_record.store(\"stadium\",stadium)\n season_record.store(\"home_stadium\",stadium) unless season_record[\"home_stadium\"]\n #Process the home team's stats.\n home_record = {}\n home_record.store(\"team_id\",g.xpath('/gamedata/game/home/info/@teamID')[0].value)\n home_record.store(\"team_name\",g.xpath('/gamedata/game/home/info/@name')[0].value)\n home_record.store(\"team_location\",g.xpath('/gamedata/game/home/info/@location')[0].value)\n #League rank and division rank both come from the standings file s.\n ranks=s.xpath(\"//day[contains(@date,'#{game_record['date']}')]//team[contains(@id,'#{home_record['team_id']}')]\")\n if ranks[0]\n home_record.store(\"league_rank\",ranks[0][\"rank\"].to_i)\n home_record.store(\"division_rank\",ranks[1][\"rank\"].to_i) if ranks[1]\n else\n #This is a postseason game.\n if season_record[\"season\"]>1968\n home_record.store(\"league_rank\",s.xpath(\"//team[contains(@id,'#{home_record['team_id']}')]\")[-2][\"rank\"].to_i)\n home_record.store(\"division_rank\",s.xpath(\"//team[contains(@id,'#{home_record['team_id']}')]\")[-1][\"rank\"].to_i)\n else\n home_record.store(\"league_rank\",s.xpath(\"//team[contains(@id,'#{home_record['team_id']}')]\")[-1][\"rank\"].to_i)\n end\n end\n home_record.store(\"runs\",g.xpath('/gamedata/game/home/@runs')[0].value.to_i)\n home_record.store(\"hits\",g.xpath('/gamedata/game/home/@hits')[0].value.to_i)\n home_record.store(\"errors\",g.xpath('/gamedata/game/home/@errors')[0].value.to_i)\n home_record.store(\"left_on_base\",g.xpath('/gamedata/game/home/@leftOnBase')[0].value.to_i)\n pitchers = []\n g.xpath('/gamedata/finalstats/home/pitching')[0].children.each{|p|\n pitchers.push(Hash[\"player_id\",p[\"id\"],\n \"first_name\",p[\"firstname\"],\n \"last_name\",p[\"lastname\"],\n \"batters_faced\",p[\"battersFaced\"].to_i,\n \"hits\",p[\"hits\"].to_i,\n \"walks\",p[\"walks\"].to_i,\n \"rbi\",p[\"rbi\"].to_i])}\n home_record.store(\"pitching\",pitchers)\n batters = []\n g.xpath('/gamedata/finalstats/home/batting')[0].children.each{|p|\n batters.push(Hash[\"player_id\",p[\"id\"],\n \"first_name\",p[\"firstname\"],\n \"last_name\",p[\"lastname\"],\n \"at_bats\",p[\"atbats\"].to_i,\n \"hits\",p[\"hits\"].to_i,\n \"walks\",p[\"walks\"].to_i,\n \"rbi\",p[\"rbi\"].to_i])}\n home_record.store(\"batting\",batters)\n game_record.store(\"home_team_stats\",home_record)\n #Process the away team's stats.\n away_record = {}\n away_record.store(\"team_id\",g.xpath('/gamedata/game/away/info/@teamID')[0].value)\n away_record.store(\"team_name\",g.xpath('/gamedata/game/away/info/@name')[0].value)\n away_record.store(\"team_location\",g.xpath('/gamedata/game/away/info/@location')[0].value)\n #League rank and division rank both come from the standings file s.\n ranks=s.xpath(\"//day[contains(@date,'#{game_record['date']}')]//team[contains(@id,'#{away_record['team_id']}')]\")\n if ranks[0]\n away_record.store(\"league_rank\",ranks[0][\"rank\"].to_i)\n away_record.store(\"division_rank\",ranks[1][\"rank\"].to_i) if ranks[1]\n else\n #This is a postseason game.\n if season_record[\"season\"]>1968\n away_record.store(\"league_rank\",s.xpath(\"//team[contains(@id,'#{away_record['team_id']}')]\")[-2][\"rank\"].to_i)\n away_record.store(\"division_rank\",s.xpath(\"//team[contains(@id,'#{away_record['team_id']}')]\")[-1][\"rank\"].to_i)\n else\n away_record.store(\"league_rank\",s.xpath(\"//team[contains(@id,'#{away_record['team_id']}')]\")[-1][\"rank\"].to_i)\n end\n end\n away_record.store(\"runs\",g.xpath('/gamedata/game/away/@runs')[0].value.to_i)\n away_record.store(\"hits\",g.xpath('/gamedata/game/away/@hits')[0].value.to_i)\n away_record.store(\"errors\",g.xpath('/gamedata/game/away/@errors')[0].value.to_i)\n away_record.store(\"left_on_base\",g.xpath('/gamedata/game/away/@leftOnBase')[0].value.to_i)\n pitchers = []\n g.xpath('/gamedata/finalstats/away/pitching')[0].children.each{|p|\n pitchers.push(Hash[\"player_id\",p[\"id\"],\n \"first_name\",p[\"firstname\"],\n \"last_name\",p[\"lastname\"],\n \"batters_faced\",p[\"battersFaced\"].to_i,\n \"hits\",p[\"hits\"].to_i,\n \"walks\",p[\"walks\"].to_i,\n \"rbi\",p[\"rbi\"].to_i])}\n away_record.store(\"pitching\",pitchers)\n batters = []\n g.xpath('/gamedata/finalstats/away/batting')[0].children.each{|p|\n batters.push(Hash[\"player_id\",p[\"id\"],\n \"first_name\",p[\"firstname\"],\n \"last_name\",p[\"lastname\"],\n \"at_bats\",p[\"atbats\"].to_i,\n \"hits\",p[\"hits\"].to_i,\n \"walks\",p[\"walks\"].to_i,\n \"rbi\",p[\"rbi\"].to_i])}\n away_record.store(\"batting\",batters)\n game_record.store(\"away_team_stats\",away_record)\n #Process the inning records.\n inning_records = []\n g.xpath('/gamedata/playbyplay').children.each { |y|\n inning_record = {\"number\"=>y.xpath('./@num')[0].value}\n a_event_records = []\n y.xpath('./away').children.each {|z|\n a_event_records.push(Hash[\"player_id\",z.xpath('./@playerid')[0].value,\n \"pitcher_id\",z.xpath('./@pitcherid')[0].value,\n \"balls\",z.xpath('./@balls')[0].value.to_i,\n \"strikes\",z.xpath('./@strikes')[0].value.to_i,\n \"result\",z.xpath('./@result')[0].value,\n \"description\",z.xpath('./@pbp')[0].value,\n \"home_score\",z.xpath('./score/@homescore')[0].value.to_i,\n \"away_score\",z.xpath('./score/@awayscore')[0].value.to_i])}\n h_event_records=[]\n y.xpath('./home').children.each {|z|\n h_event_records.push(Hash[\"player_id\",z.xpath('./@playerid')[0].value,\n \"pitcher_id\",z.xpath('./@pitcherid')[0].value,\n \"balls\",z.xpath('./@balls')[0].value.to_i,\n \"strikes\",z.xpath('./@strikes')[0].value.to_i,\n \"result\",z.xpath('./@result')[0].value,\n \"description\",z.xpath('./@pbp')[0].value,\n \"home_score\",z.xpath('./score/@homescore')[0].value.to_i,\n \"away_score\",z.xpath('./score/@awayscore')[0].value.to_i])}\n inning_record.store(\"away_play_by_play\",a_event_records)\n inning_record.store(\"home_play_by_play\",h_event_records)\n inning_records.push(inning_record)\n }\n game_record.store(\"innings\",inning_records)\n #Append the game_record to the file.\n $game_out.puts(game_record.to_json)\n #Finally, add the file to the log.\n $log_file.puts(File.basename(g_file))\n end \n }\n season_record.store(\"regular_season_games\",s_game_records)\n season_record.store(\"post_season_games\",p_game_records)\n #We now have a complete season_record! Let's write it.\n $season_out.puts(season_record.to_json)\n #and write in the log that we finished this file.\n $log_file.puts(File.basename(s_file)) \nend\n\n\ntask :copy_icss do\n Dir[\"#{path_to(:hb_config)}/*icss.yaml\"].each{ |icss|\n sh \"cp #{icss} #{path_to(:fixd_dir)}\"}\nend\n\ntask :copy_endpoint do\n FileUtils.mkdir_p(File.join(path_to(:fixd_dir),\"code\"))\n Dir[\"#{path_to(:hb_engine)}/*endpoint.rb\"].each{ |endpoint|\n sh \"cp #{endpoint} #{File.join(path_to(:fixd_dir),\"code\")}\"}\nend\n\ntask :run => [:parse_team_files, :copy_icss, :copy_endpoint]\n\n#If we've read in all of the files, we shouldn't need to do anything.\n#But, if the user forgot to delete the log file, we should remind them.\nputs \"The log file contains #{$log.size} files, as many as the input directory. Remember to remove /log if you want to restart the hackbox.\" if $log.size==Dir[File.join($datasource,\"*\")].size\n\nRake::Task[:run].invoke unless $log.size==Dir[File.join($datasource,\"*\")].size\n\n", "def player_numbers(team_name)\n hash = get_team(team_name)\n player_array = hash[:players]\n player_numbers = []\n len = player_array.length()\n i = 0\n while i < len\n player = player_array[i]\n number = player[:number]\n player_numbers.push(number)\n i += 1\n end\n return player_numbers\nend", "def by_league_parser\n by_league_data = []\n target_dir = by_league_dir\n Dir.foreach(target_dir) do |file|\n next if file == '.' or file == '..'\n json_file = File.open(target_dir + file)\n parsed_file = JSON.parse(File.read(json_file))\n standing_values = parsed_file[\"api\"][\"standings\"]\n standing_values.each do |value|\n value[1][:rank] = value[0]\n by_league_data.push(value[1].deep_symbolize_keys!)\n end\n end\n\n by_league_data\n end", "def player_data_by_team(team)\n players = []\n if team == game_hash[:home][:team_name]\n players << game_hash[:home][:players]\n else\n players << game_hash[:away][:players]\n end\n return players.flatten\nend", "def player_numbers(team_name)\n team = all_team_info(team_name)\n team[:players].map do |player|\n player[:number]\n end\nend", "def players\n results = get_parts(\"status\", 2..-1)\n results.map do |player|\n player = player.split(\" \", 3)\n {\n :name => player[2][1..-2],\n :ping => player[1].to_i,\n :score => player[0].to_i\n }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
reset session and other
def reset reset_session redirect_to root_path end
[ "def reset_session!; end", "def reset\n @session = nil\n end", "def session_reset!\n session[:file_id] = nil\n session[:row_error] = nil\n session[:file_error] = nil\n session[:sr_error] = nil\n session[:mp_error] = nil\n session[:mp_warning] = nil\n end", "def sessions_reset\n self.sessions_flush\n @sessions = {}\n end", "def reset_current_session\n\n pop_session_frame\n push_session_frame\n\n end", "def reset_sessions!\n # reset in reverse so sessions that started servers are reset last\n session_pool.reverse_each { |_mode, session| session.reset! }\n end", "def reset_sessions!\n session_pool.each { |mode, session| session.reset! }\n end", "def reset_session\n super\n user_session.try(:destroy)\n end", "def reload\n @session_id = nil\n login\n end", "def kill_session\n session[:session] = false\n session[:sessionToken] = \"\"\n session[:sessionMember] = \"\"\n session[:sessionMV] = \"\"\n session[:sessionOffer] = \"\"\n end", "def _clear_session\n session[:_order] = nil\n end", "def clear_sessions \n sessions.each do |key, session|\n logger.info \"Closing: #{key}\"\n session.close\n end \n sessions.clear \n reset_password\n end", "def reset_session_stack\n\n # remove existing reference in persistence\n if persistence_id\n cease!\n end\n \n \tself.persistence_id = nil\n\n @session_stack.clear\n\n push_session_frame\n\n end", "def kill_session\n session[:session] = false\n session[:sessionToken] = \"\"\n session[:sessionMember] = \"\"\n session[:sessionMV] = \"\"\n end", "def clear_session\n session[:int_key] = nil\n session[:email] = nil\n session[:password] = nil\n session[:account_id] = nil\n redirect_to root_url\n end", "def invalidate_session\n @sequence = 0\n @session_id = nil\n end", "def reset_session_counts\n self.session_count = 0\n end", "def clear_session\n session.clear\n end", "def reset\n log_out_and_disconnect\n @imap = nil\n @logged_in = false\n @idling = false\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For example: the summation of 3 is 6 because 1 + 2 + 3 = 6, the summation of 6 is 21 because 1 + 2 + 3 + 4 + 5 + 6 = 21. Write a method summation_sequence that takes in a two numbers: start and length. The method should return an array containing length total elements. The first number of the sequence should be the start number. At any point, to generate the next element of the sequence we take the summation of the previous element. You can assume that length is not zero.
def summation_sequence(start, length) arr = [start] i = 1 while i < length arr << summation(arr[i-1]) i += 1 end return arr end
[ "def summation_sequence(start, length)\n array = [start]\n (length - 1).times do |i|\n current_element = array[-1]\n next_element = summation(current_element)\n array << next_element\n end\n\n array\nend", "def summation_sequence(start, length)\n summation = [start]\n (length - 1).times { summation << get_summation(summation[-1]) }\n return summation\nend", "def summation_sequence(start, length)\n return [] if length <= 0\n seq = [start]\n\n while seq.length < length\n sum = 0\n (1..seq[-1]).each { |n| sum += n }\n seq << sum\n end\n\n return seq\nend", "def sum_of_sequence(begin_number, end_number, step)\n begin_number.step(end_number, step).reduce(0, :+)\nend", "def sequence_sum(begin_number, end_number, step)\n return 0 if end_number < begin_number\n \n x = begin_number\n sum = 0\n \n while x <= end_number\n sum += x\n x += step\n end\n \n sum\nend", "def sequence_sum(begin_number, end_number, step)\n return 0 if begin_number > end_number\n (begin_number..end_number).step(step).reduce(:+)\nend", "def sequence_sum(begin_number, end_number, step)\n return 0 if begin_number > end_number\n sum = 0\n until begin_number > end_number\n \tsum += step\n end\nend", "def sequence_sum(begin_number, end_number, step)\n result = 0\n return result if begin_number > end_number\n return end_number if begin_number == end_number\n steps_taken = (end_number / step.to_f).ceil\n steps_taken.times do |n|\n result += (begin_number)+(step*n)\n end\n if begin_number == 0\n result += end_number\n end \n return result\nend", "def sum_of_sums(array)\n sequence_total = 0\n sum = 0\n array.each do |n|\n sequence_total += n\n sum += sequence_total\n end\n sum\nend", "def xbonacci(starting_sequence, number_of_xbonacci_numbers_to_return)\n sequence = starting_sequence\n # length of array to return\n n = number_of_xbonacci_numbers_to_return\n # numbers of elements before to sum\n x = starting_sequence.length\n # numbers to add to array\n i = n - x\n (0...i).each do |i|\n s = sequence[i...(x + i)].sum\n sequence << s\n end\n\n sequence\nend", "def arithmetic_sequence_sum(a, r, n)\n a*n + r*n*(n-1)/2\nend", "def sequence_sum(begin_number, end_number, step)\n #your code here\nend", "def total_product_sequence(n)\n return n if n < 4\n\n arr = [1, 2, 3, 6]\n\n while arr.length < n\n arr << sum_array(arr)\n end\n\n arr.last\nend", "def sequence_sum\n reduce(:+)\n end", "def sum_of_sums(array)\n \n total_sum = 0\n subsequence_sum = 0\n array.each do |num|\n subsequence_sum += num\n total_sum += subsequence_sum\n end\n total_sum\nend", "def sum_of_sums(arr)\n subsequences = []\n arr.each_with_index do |num, index|\n subsequences << arr.slice(0, index + 1)\n end\n \n subsequences.flatten.sum\nend", "def sequence(count, start_number)\n array = []\n count.times { |i| array << (start_number * (i + 1)) }\n array\nend", "def sequence(count, start)\n sequence = []\n 1.upto(count) do |index|\n sequence.push(start * index)\n end\n sequence\nend", "def fibonacci(length)\n sequence = []\n prev1 = 1\n prev2 = 0\n while sequence.length < length\n if sequence.length == 1\n sequence << prev1\n else\n sequence << prev1 + prev2\n prev2 = prev1\n prev1 = sequence[-1]\n end\n end\n return sequence\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve the RASD item that specifies memory properties of a VM.
def get_memory_rasd_item(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/virtualHardwareSection/memory" ) end
[ "def memory\n get_memory_info\n end", "def read_mem addr\n @mem[addr]\n end", "def determine_memory\n result = @info[:memory] = {}\n\n free_cmd = \"free -m|awk '$1 ~ /Mem/ {print $2, $2-$6-$7}; $1 ~ /Swap/ \" \\\n \"{print $3}'|xargs\"\n mem = @shell.query('MEMORY', free_cmd)\n total, used, swap = mem.split(/\\s+/)\n\n result[:total] = total.to_i\n result[:mem_used] = used.to_i\n result[:swap_used] = swap.to_i\n result[:swapping?] = swqp.to_i > 0\n end", "def read_memory_size\n\t\tdata = command(:read_special)\n\t\tdata << 0x23.chr\n\t\tsend_command data\n\tend", "def memory\n domain_info[:memory]\n end", "def get_vm_memory(vm_name, default_value) \n require_string(vm_name)\n require_integer(default_value)\n\n return get_env_variable(\"UPLF_#{vm_name}_MEMORY\", default_value)\n end", "def ramdisk_id\n data[:ramdisk_id]\n end", "def memory\n self.resource_records.first(:order => [:created_at.desc]).memory\n end", "def ram\n @ram ||= Memory.new(2 ** (8 * address_size), \"RAM\")\n end", "def ram_disks\n rd = []\n rec = Plist::parse_xml(`hdiutil info -plist`)['images'].reject do |e|\n e['image-path'] !~ /^ram:\\/\\//\n end\n rec.each do |r|\n ramdisk = Rbb::Device.new(r['system-entities'][0]['dev-entry'])\n rd << ramdisk\n end\n return rd\nend", "def get_cpu_rasd_item(id)\n request(\n :expects => 200,\n :idempotent => true,\n :method => 'GET',\n :parser => Fog::ToHashDocument.new,\n :path => \"vApp/#{id}/virtualHardwareSection/cpu\"\n )\n end", "def resident_memory(pid = $$)\n\t\t\t\t_vm_rss = IO.readlines(\"/proc/#{pid}/status\")\n\t\t\t\t\t.find { |x| x.start_with?('VmRSS') }\n\n\t\t\t\t_vm_rss ? _vm_rss.split[1].to_i : nil\n\t\t\tend", "def vmsize\n object.vmsize.id\n end", "def memory_info_ex\n info = File.new(\"/proc/#{@pid}/statm\").readline.split[0...7]\n vms, rss, shared, text, lib, data, dirty = info.map {|i| i.to_i * PAGE_SIZE}\n OpenStruct.new(vms: vms, rss: rss, shared: shared, text: text, lib: lib,\n data: data, dirty: dirty)\n end", "def memory(opts = {})\n opts = opts.transform_keys(&:to_sym)\n val = bit_value(opts[:argmem]) | (bit_value(opts[:inaccessiblemem]) << 2) | (bit_value(opts[:memory]) << 4)\n enum(:memory, val)\n end", "def read_definition\n content = Cheetah.run([\"VBoxManage\", \"showvminfo\",\n \"--machinereadable\", name], stdout: :capture)\n @definition = content.split(\"\\n\").reduce({}) do |definition, line|\n key, value = line.split(\"=\")\n definition[unquote(key)] = unquote(value)\n definition\n end\n end", "def read_memory(address)\n # nes.memory.readWord(address)\n # Memory Manager readWord above\n # return read(address) | (read(address + 1) << 8);\n end", "def raw_available_memory\n (mob.hardware.memory_size - mob.summary.quick_stats.overall_memory_usage)/BYTES_IN_MB\n end", "def get(name)\n return @material[name]\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /skill_user_profiles GET /skill_user_profiles.json
def index @skill_user_profiles = SkillUserProfile.all render json: @skill_user_profiles end
[ "def show\n render json: @skill_user_profile\n end", "def profiles\n hash = {:username => @username}\n @api.request(\"users/profiles/?#{build_query_string(hash)}\")\n end", "def get_profile_skills\n profile_skills = find_elements PROFILE_SKILLS_LOCATOR\n get_skills profile_skills\n end", "def getProfileInfo *args\n options=fill_args [:userid],[:userid],*args\n request \"/Profile/getProfileInfo.json\",options\n end", "def getMyProfile\n if(request.post?)\n cSocialID = self.findKeyInJSON(params[:params], \"SocialID\", 2)\n cSocialType = self.findKeyInJSON(params[:params], \"SocialType\", 2)\n \n rData = {}\n \n # find this player's highest scene number, if not, just return 0\n a = Sbdbindexing.find(\"ongame_\" + cSocialType + \"_myscene_\" + cSocialID)\n arrayValue = a.arrayvalue\n \n case arrayValue.size\n when 1\n highestSceneNo = 1\n when 0\n highestSceneNo = 0\n else\n b = arrayValue[1].sort.reverse\n highestSceneNo = b[0][\"sceneNo\"]\n end\n \n # return this player's information\n begin\n u = Player.findUser(cSocialID, cSocialType)\n rData = {\n \"Coins\" => u.coins, \n \"RedRockets\" => u.redRockets, \n \"RWBRockets\" => u.rwbRockets,\n \"HighestSceneNo\" => highestSceneNo\n }\n rStatus = \"100\"\n rescue Exception => e\n rStatus = \"101\"\n end\n \n # Return JSON response\n cRequestID = self.findKeyInJSON(params[:params], \"RequestID\", 1)\n self.jsonRender(rData, 'User Profile', cRequestID, rStatus)\n end\n end", "def get_user_profile_by_user_id(user_id)\n path = \"/d2l/api/lp/#{$lp_ver}/profile/user/#{user_id}\"\n _get(path)\n # Returns UserProfile JSON data block\nend", "def index\n @skills_to_profiles = SkillsToProfile.all\n end", "def show\n if params[:user_id]\n @user = User.find(params[:user_id])\n @skill = @user.skills.where(id:params[:id])\n render json: @skill\n elsif params[:id]\n @skill = Skill.where(id:params[:id])\n render json: @skill\n elsif params[:name]\n @skill = Skill.where(name:params[:name])\n render json: @skill\n else\n render json: {result:'nothing found'}\n end\n end", "def index\n @personal_skills = @user.personal_skills\n end", "def test_get_skills_route\n render :json => get_profile_skills_for_profile(\"https://www.linkedin.com/in/marissamayer\").to_json\n end", "def json_show_users_profile_tutorial_step_by_user_id\n\n respond_to do |format|\n if UsersProfile.exists?(user_id: params[:user_id])\n @user_profile = UsersProfile.find_by_user_id(params[:user_id])\n format.json { render json: @user_profile.as_json(only: [:user_id, :tutorial_step]), status: :ok }\n\n end\n end\n end", "def get_current_user_profile\n path = \"/d2l/api/lp/#{$lp_ver}/profile/myProfile\"\n _get(path)\n # Returns: UserProfile JSON data block\nend", "def get_user_profile_by_profile_id(profile_id)\n path = \"/d2l/api/lp/#{$lp_ver}/profile/#{profile_id}\"\n _get(path)\n # Returns UserProfile JSON data block\nend", "def create\n byebug\n @skill_user_profile = SkillUserProfile.new(skill_user_profile_params)\n\n if @skill_user_profile.save\n render json: @skill_user_profile, status: :created, location: @skill_user_profile\n else\n render json: @skill_user_profile.errors, status: :unprocessable_entity\n end\n end", "def profile\n @user = UsersService.getUserById(params[:id])\n end", "def index\n @profil = Profil.find(params[:user_id])\n render json: @profil\n end", "def user_skills\n respond_to do |format|\n format.json { render json: @skill_category_service.get_hierarchy_checked(params[:user_id], SkillCategoryService::SKILL_SET_TYPES[:custom]) }\n end\n end", "def profile_detail()\n get(\"profile\")\n end", "def get_default_profile \n get(\"/profiles.json/default\")\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /skill_user_profiles/1 GET /skill_user_profiles/1.json
def show render json: @skill_user_profile end
[ "def index\n @skill_user_profiles = SkillUserProfile.all\n\n render json: @skill_user_profiles\n end", "def profiles\n hash = {:username => @username}\n @api.request(\"users/profiles/?#{build_query_string(hash)}\")\n end", "def getMyProfile\n if(request.post?)\n cSocialID = self.findKeyInJSON(params[:params], \"SocialID\", 2)\n cSocialType = self.findKeyInJSON(params[:params], \"SocialType\", 2)\n \n rData = {}\n \n # find this player's highest scene number, if not, just return 0\n a = Sbdbindexing.find(\"ongame_\" + cSocialType + \"_myscene_\" + cSocialID)\n arrayValue = a.arrayvalue\n \n case arrayValue.size\n when 1\n highestSceneNo = 1\n when 0\n highestSceneNo = 0\n else\n b = arrayValue[1].sort.reverse\n highestSceneNo = b[0][\"sceneNo\"]\n end\n \n # return this player's information\n begin\n u = Player.findUser(cSocialID, cSocialType)\n rData = {\n \"Coins\" => u.coins, \n \"RedRockets\" => u.redRockets, \n \"RWBRockets\" => u.rwbRockets,\n \"HighestSceneNo\" => highestSceneNo\n }\n rStatus = \"100\"\n rescue Exception => e\n rStatus = \"101\"\n end\n \n # Return JSON response\n cRequestID = self.findKeyInJSON(params[:params], \"RequestID\", 1)\n self.jsonRender(rData, 'User Profile', cRequestID, rStatus)\n end\n end", "def get_current_user_profile\n path = \"/d2l/api/lp/#{$lp_ver}/profile/myProfile\"\n _get(path)\n # Returns: UserProfile JSON data block\nend", "def get_user_profile_by_user_id(user_id)\n path = \"/d2l/api/lp/#{$lp_ver}/profile/user/#{user_id}\"\n _get(path)\n # Returns UserProfile JSON data block\nend", "def getProfileInfo *args\n options=fill_args [:userid],[:userid],*args\n request \"/Profile/getProfileInfo.json\",options\n end", "def show\n if params[:user_id]\n @user = User.find(params[:user_id])\n @skill = @user.skills.where(id:params[:id])\n render json: @skill\n elsif params[:id]\n @skill = Skill.where(id:params[:id])\n render json: @skill\n elsif params[:name]\n @skill = Skill.where(name:params[:name])\n render json: @skill\n else\n render json: {result:'nothing found'}\n end\n end", "def get_user_profile_by_profile_id(profile_id)\n path = \"/d2l/api/lp/#{$lp_ver}/profile/#{profile_id}\"\n _get(path)\n # Returns UserProfile JSON data block\nend", "def json_show_users_profile_tutorial_step_by_user_id\n\n respond_to do |format|\n if UsersProfile.exists?(user_id: params[:user_id])\n @user_profile = UsersProfile.find_by_user_id(params[:user_id])\n format.json { render json: @user_profile.as_json(only: [:user_id, :tutorial_step]), status: :ok }\n\n end\n end\n end", "def get_profile_skills\n profile_skills = find_elements PROFILE_SKILLS_LOCATOR\n get_skills profile_skills\n end", "def profile\n @user = UsersService.getUserById(params[:id])\n end", "def update\n @skill_user_profile = SkillUserProfile.find(params[:id])\n\n if @skill_user_profile.update(skill_user_profile_params)\n head :no_content\n else\n render json: @skill_user_profile.errors, status: :unprocessable_entity\n end\n end", "def profile\n return nil unless user.loa3?\n\n mvi_response&.profile\n end", "def create\n byebug\n @skill_user_profile = SkillUserProfile.new(skill_user_profile_params)\n\n if @skill_user_profile.save\n render json: @skill_user_profile, status: :created, location: @skill_user_profile\n else\n render json: @skill_user_profile.errors, status: :unprocessable_entity\n end\n end", "def get_default_profile \n get(\"/profiles.json/default\")\nend", "def profile_detail()\n get(\"profile\")\n end", "def index\n @personal_skills = @user.personal_skills\n end", "def profile\n return nil unless user_loa3\n\n mvi_response&.profile\n end", "def profile\n return nil unless user_identity.loa3?\n\n mvi_response&.profile\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /skill_user_profiles POST /skill_user_profiles.json
def create byebug @skill_user_profile = SkillUserProfile.new(skill_user_profile_params) if @skill_user_profile.save render json: @skill_user_profile, status: :created, location: @skill_user_profile else render json: @skill_user_profile.errors, status: :unprocessable_entity end end
[ "def create\n user_skill_params[:skill_ids].map do |skill_id|\n @user_skill = UserSkill.create(user_id: params[:user_id], skill_id: skill_id)\n unless @user_skill.save\n json_response(@user_skill.errors, 422) and return\n end\n end\n json_response(\"Skills added\".to_json, 200)\n end", "def create\n @skills_to_profile = SkillsToProfile.new(skills_to_profile_params)\n\n respond_to do |format|\n if @skills_to_profile.save\n format.html { redirect_to @skills_to_profile, notice: 'Skills to profile was successfully created.' }\n format.json { render :show, status: :created, location: @skills_to_profile }\n else\n format.html { render :new }\n format.json { render json: @skills_to_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n respond_to do |format|\n begin\n if params[\"skills_user\"][\"user_id\"]\n skill_id = params[\"skills_user\"][\"skill_id\"]\n user_ids = params[\"skills_user\"][\"user_id\"].reject{ |c| c.empty? }\n user_ids.each do |user_id|\n SkillsUser.create(skill_id: skill_id, user_id: user_id)\n end\n format.html { redirect_to skills_users_path, notice: 'Skills user was successfully created.' }\n end\n rescue\n format.html { render :new }\n format.json { render json: @skills_user.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @professional_skill = current_profile.professional_skills.create(professional_skill_params)\n\n respond_to do |format|\n if @professional_skill.save\n format.html { redirect_to profile_professional_skills_path, notice: 'Professional skill was successfully created.' }\n format.json { render :show, status: :created, location: @professional_skill }\n else\n format.html { render :new }\n format.json { render json: @professional_skill.errors, status: :unprocessable_entity }\n end\n end\n end", "def user_params\n params.require(:profile).permit(\n user_attributes: [:first_name,\n :last_name,\n :skill_names,\n :interest_ids =>[]]\n )['user_attributes']\n end", "def create\n @user_skill = UserSkill.new(user_skill_params)\n\n respond_to do |format|\n if @user_skill.save\n format.html { redirect_to @user_skill, notice: \"User skill was successfully created.\" }\n format.json { render :show, status: :created, location: @user_skill }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @user_skill.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = current_user.profiles.build(profile_params)\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render action: 'show', status: :created, location: @profile }\n else\n format.html { render action: 'new' }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile_sub_skill = ProfileSubSkill.new(profile_sub_skill_params)\n\n respond_to do |format|\n if @profile_sub_skill.save\n format.html { redirect_to @profile_sub_skill, notice: 'Profile sub skill was successfully created.' }\n format.json { render :show, status: :created, location: @profile_sub_skill }\n else\n format.html { render :new }\n format.json { render json: @profile_sub_skill.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @profile = current_user.profiles.new(params[:profile])\n\n respond_to do |format|\n if @profile.save\n format.html { redirect_to @profile, notice: 'Profile was successfully created.' }\n format.json { render json: @profile, status: 201, location: @profile }\n else\n format.html { render action: \"new\" }\n format.json { render json: @profile.errors, status: 422 }\n end\n end\n end", "def create\n @user_to_skill = UserToSkill.new(user_to_skill_params)\n\n respond_to do |format|\n if @user_to_skill.save\n format.html { redirect_to @user_to_skill, notice: 'User to skill was successfully created.' }\n format.json { render :show, status: :created, location: @user_to_skill }\n else\n format.html { render :new }\n format.json { render json: @user_to_skill.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @skill_user_profiles = SkillUserProfile.all\n\n render json: @skill_user_profiles\n end", "def create\n @skill_profile = SkillProfile.new(params[:skill_profile])\n\n respond_to do |format|\n if @skill_profile.save\n format.html { redirect_to(@skill_profile, :notice => 'Skill profile was successfully created.') }\n format.xml { render :xml => @skill_profile, :status => :created, :location => @skill_profile }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @skill_profile.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @skill = @user.skills.new(params[:skill])\n\n respond_to do |format|\n if @skill.save\n flash[:notice] = 'Skill was successfully created.'\n format.html { redirect_to(user_skills_path(@user)) }\n else\n format.html { render :action => \"new\" }\n end\n end\n end", "def create\n @profile_user = ProfileUser.new(profile_user_params)\n\n respond_to do |format|\n if @profile_user.save\n format.html { redirect_to @profile_user, notice: 'Profile user was successfully created.' }\n format.json { render :show, status: :created, location: @profile_user }\n else\n format.html { render :new }\n format.json { render json: @profile_user.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @user = current_user()\n @profile = @user.profiles.new(params[:profile])\n\n respond_to do |format|\n if @profile.save\n flash[:notice] = 'Profile was successfully created.'\n format.html { redirect_to(@profile) }\n format.xml { render :xml => @profile, :status => :created, :location => @profile }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @profile.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @personal_profile = PersonalProfile.new(personal_profile_params)\n @personal_profile.user_id=current_user.id\n respond_to do |format|\n if @personal_profile.save\n format.html { redirect_to resume_path, notice: 'Personal profile was successfully created.' }\n format.json { render :show, status: :created, location: resume_path }\n else\n format.html { render :new }\n format.json { render json: @personal_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @skill_user_profile = SkillUserProfile.find(params[:id])\n\n if @skill_user_profile.update(skill_user_profile_params)\n head :no_content\n else\n render json: @skill_user_profile.errors, status: :unprocessable_entity\n end\n end", "def create\n @tag_pro_profile = current_user.build_tag_pro_profile(tag_pro_profile_params)\n if @tag_pro_profile.save\n flash[:notice] = 'Tag pro profile was successfully created.' if is_navigational_format?\n end\n respond_with(@tag_pro_profile, location: root_url)\n end", "def create\n @user = User.find(params[:user_id])\n @player_profile = PlayerProfile.new(player_profile_params)\n respond_to do |format|\n if @player_profile.save\n @user.update(player_profile: @player_profile)\n format.html { redirect_to user_player_profiles_path(@user, @player_profile), notice: 'Player profile was successfully created.' }\n format.json { render :show, status: :created, location: @player_profile }\n else\n byebug\n format.html { render :new }\n format.json { render json: @player_profile.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /skill_user_profiles/1 PATCH/PUT /skill_user_profiles/1.json
def update @skill_user_profile = SkillUserProfile.find(params[:id]) if @skill_user_profile.update(skill_user_profile_params) head :no_content else render json: @skill_user_profile.errors, status: :unprocessable_entity end end
[ "def update\n respond_to do |format|\n if @skills_to_profile.update(skills_to_profile_params)\n format.html { redirect_to @skills_to_profile, notice: 'Skills to profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @skills_to_profile }\n else\n format.html { render :edit }\n format.json { render json: @skills_to_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @skill = current_user.skills.find(params[:id])\n\n respond_to do |format|\n if @skill.update_attributes(params[:skill])\n format.html { redirect_to @skill, notice: 'Skill was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @skill.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @user_skill = UserSkill.find(params[:id])\n\n respond_to do |format|\n if @user_skill.update_attributes(params[:user_skill])\n format.html { redirect_to @user_skill, notice: 'User skill was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @user_skill.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @skill_profile = SkillProfile.find(params[:id])\n\n respond_to do |format|\n if @skill_profile.update_attributes(params[:skill_profile])\n format.html { redirect_to(@skill_profile, :notice => 'Skill profile was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @skill_profile.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @skills_user.update(skills_user_params)\n format.html { redirect_to @skills_user, notice: 'Skills user was successfully updated.' }\n format.json { render :show, status: :ok, location: @skills_user }\n else\n format.html { render :edit }\n format.json { render json: @skills_user.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @profile_sub_skill.update(profile_sub_skill_params)\n format.html { redirect_to @profile_sub_skill, notice: 'Profile sub skill was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile_sub_skill }\n else\n format.html { render :edit }\n format.json { render json: @profile_sub_skill.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_current_user_profile_data(user_profile_data)\n # PUT /d2l/api/lp/(version)/profile/myProfile\nend", "def update\n @skill = current_user.skills.find(params[:id])\n\n respond_to do |format|\n if @skill.update_attributes(params[:skill])\n flash[:notice] = 'Skill was successfully updated.'\n format.html { redirect_to(user_skills_path(current_user)) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @skill.errors, :status => :unprocessable_entity }\n end\n end\n end", "def json_update_users_profiles_tutorial_step_by_user_id_and_tutorial_step\n\n\n respond_to do |format|\n if UsersProfile.exists?(user_id:params[:user_id])\n @user_profile = UsersProfile.find_by_user_id(params[:user_id])\n\n if @user_profile.update_attributes(tutorial_step:params[:tutorial_step])\n\n format.json { render json: @user_profile.as_json(only: [:user_id, :tutorial_step]), status: :ok }\n\n else\n format.json { render json: @user_profile.errors, status: :unprocessable_entity }\n end\n\n\n end\n end\n end", "def update\n respond_to do |format|\n if @professional_skill.update(professional_skill_params)\n format.html { redirect_to profile_professional_skill_path, notice: 'Professional skill was successfully updated.' }\n format.json { render :show, status: :ok, location: @professional_skill }\n else\n format.html { render :edit }\n format.json { render json: @professional_skills.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @profiles = current_user.profiles.find(params[:id])\n\n respond_to do |format|\n if @profiles.update(profile_params)\n format.html { redirect_to profiles_path, notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profiles }\n else\n format.html { render :edit }\n format.json { render json: @profiles.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_users_profiles_by_user_id\n @users_profile = UsersProfile.find_all_by_user_id(params[:id]).first\n\n\n respond_to do |format|\n if @users_profile.update_attributes(params[:users_profile])\n format.html { redirect_to edit_users_profiles_by_user_id_path(@users_profile.user_id), notice: 'Users profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit_users_profiles_by_user_id\" }\n format.json { render json: @users_profile.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n # Retrieve user from db\n @user = User.find(params[:user_id])\n # Retrieve that user's profile\n @profile = @user.profile\n \n # Mass assign edited profile attributes from whitelisting below\n if @profile.update_attributes(profile_params)\n flash[:success] = \"Profile has been updated!\"\n redirect_to user_path(id: params[:user_id])\n else\n render action: :edit\n end\n \n end", "def update\n respond_to do |format|\n if @proffesional_skill.update(proffesional_skill_params)\n format.html { redirect_to user_proffesional_skills_path, notice: 'Proffesional skill was successfully updated.' }\n format.json { render :show, status: :ok, location: @proffesional_skill }\n else\n format.html { render :edit }\n format.json { render json: @proffesional_skill.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @profile = current_user.profiles.find(params[:id])\n\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n format.html { redirect_to(@profile, :notice => 'Profile was successfully updated.') }\n format.xml { head :ok }\n format.json { render :json => @profile }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @profile.errors, :status => :unprocessable_entity }\n format.json { render :json => {:error => @profile.errors.full_messages} }\n end\n end\n end", "def update\n @skill = Skill.find(params[:id])\n\n if @skill.update(skill_params)\n head :no_content\n else\n render json: @skill.errors, status: :unprocessable_entity\n end\n end", "def update\n if @skill.update(basic_params)\n render json: @skill\n else\n render json: @skill.errors, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @proficiency_skill.update(proficiency_skill_params)\n format.html { redirect_to @proficiency_skill, notice: 'Proficiency skill was successfully updated.' }\n format.json { render :show, status: :ok, location: @proficiency_skill }\n else\n format.html { render :edit }\n format.json { render json: @proficiency_skill.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @attorney_profile.update(attorney_profile_params)\n format.html { redirect_to @attorney_profile, notice: 'Attorney profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @attorney_profile }\n else\n format.html { render :edit }\n format.json { render json: @attorney_profile.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /skill_user_profiles/1 DELETE /skill_user_profiles/1.json
def destroy @skill_user_profile.destroy head :no_content end
[ "def destroy\n @user_skill = UserSkill.find(params[:id])\n @user_skill.destroy\n\n respond_to do |format|\n format.html { redirect_to user_skills_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @skills_to_profile.destroy\n respond_to do |format|\n format.html { redirect_to skills_to_profiles_url, notice: 'Skills to profile was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @skill_profile = SkillProfile.find(params[:id])\n @skill_profile.destroy\n\n respond_to do |format|\n format.html { redirect_to(skill_profiles_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @profile_sub_skill.destroy\n respond_to do |format|\n format.html { redirect_to profile_sub_skills_url, notice: 'Profile sub skill was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @userprofile = Userprofile.find(params[:id])\n @userprofile.destroy\n\n respond_to do |format|\n format.html { redirect_to userprofiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile = Profile.find(params[:id])\n @profile.user.destroy\n @profile.destroy\n\n\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.json { head :ok }\n end\n end", "def destroy\n @user_profile = UserProfile.find(params[:id])\n @user_profile.destroy\n\n respond_to do |format|\n format.html { redirect_to user_profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @skill = @user.skills.find(params[:id])\n @skill.destroy\n\n respond_to do |format|\n format.html { redirect_to(user_skills_url(@user)) }\n format.xml { head :ok }\n end\n end", "def destroy\n @skills_user.destroy\n respond_to do |format|\n format.html { redirect_to skills_users_url, notice: 'Skills user was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @user_skill = UserSkill.find(params[:id])\n @user_skill.destroy\n\n respond_to do |format|\n format.html { redirect_to(user_skills_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @profile = @user.profile\n @profile.destroy\n\n respond_to do |format|\n format.html { redirect_to profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @user_to_skill.destroy\n respond_to do |format|\n format.html { redirect_to user_to_skills_url, notice: 'User to skill was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @skill = current_user.skills.find(params[:id])\n @skill.destroy\n\n respond_to do |format|\n flash[:notice] = 'Skill deleted.'\n format.html { redirect_to(user_skills_path(current_user)) }\n format.xml { head :ok }\n end\n end", "def destroy\n @mma_user_profile.destroy\n respond_to do |format|\n format.html { redirect_to mma_user_profiles_url, notice: 'Mma user profile was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n # Delete profile\n @profil.destroy\n respond_to do |format|\n format.html { redirect_to profils_url, notice: 'Profil was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @user_prof.destroy\n respond_to do |format|\n format.html { redirect_to user_profs_url, notice: 'User prof was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @attorney_profile.destroy\n respond_to do |format|\n format.html { redirect_to attorney_profiles_url, notice: 'Attorney profile was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @official_profile = OfficialProfile.find(params[:id])\n @official_profile.destroy\n\n respond_to do |format|\n format.html { redirect_to official_profiles_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @profile_attribute = current_user.profile_attributes.find(params[:id])\n @profile_attribute.destroy\n\n respond_to do |format|\n format.html { redirect_to(profile_attributes_url) }\n format.xml { head :ok }\n format.json { render :json => {:profile_attribute => @profile_attribute} }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Invokes the view for the given model, passing the assigns as instance variables.
def view( model, view, assigns = {} ) self << Waves.main::Views[ model ].process( request ) do send( view, assigns ) end end
[ "def view(model_name, *args)\n orange[model_name].view(self, *args)\n end", "def evaluate\n @view.evaluate if @view\n end", "def _evaluate_assigns(object)\n view_assigns.each { |k,v| object.instance_variable_set(k, v) }\n end", "def method_missing(method, *args, &block)\n @view.send(method, @selector, *args, &block)\n self\n end", "def launch_my_view( for_download=false)\n begin\n id = params[:id]\n if id && @user_defined_report = UserDefinedReport.find(id)\n # report_state = @user_defined_report.report_state\n # report_state_hash = Marshal.load(report_state)\n report_state = @user_defined_report.view_state\n report_state_hash = YAML.load(report_state)\n\n clear_dm_session()\n\n dm_session[:search_fields] = report_state_hash[:search_fields]\n dm_session[:full_parameter_query] = report_state_hash[:full_parameter_query]\n dm_session[:parameter_fields_values] = report_state_hash[:parameter_fields_values]\n dm_session[:search_engine_or_values] = report_state_hash[:search_engine_or_values]\n dm_session[:search_engine_limit] = report_state_hash[:search_engine_limit]\n dm_session[:functions] = report_state_hash[:functions]\n dm_session[:search_engine_group_by_columns] = report_state_hash[:search_engine_group_by_columns]\n dm_session[:search_engine_order_by_columns] = report_state_hash[:search_engine_order_by_columns]\n dm_session[:main_table_name] = report_state_hash[:main_table_name]\n dm_session[:table_name] = report_state_hash[:table_name]\n dm_session[:report_name] = report_state_hash[:report_name]\n dm_session[:operator_signs] = report_state_hash[:operator_signs]\n dm_session[:columns_list] = report_state_hash[:columns_list]\n\n dm_session[:redirect_method] = nil\n dm_session[:redirect] = nil\n\n if @user_defined_report.show_parameters\n relaunch_search_form(@user_defined_report.user_defined_report_name)\n else\n parms = {}\n @user_defined_report.setup_params(parms, for_download)\n # logger.info \">>>> parms: #{parms.inspect}\"\n # logger.info \">>> PRE statement = #{@user_defined_report.sql_statement(report_state_hash)}\"\n statement = apply_functions(@user_defined_report.sql_statement(report_state_hash), parms)\n # logger.info \">>> POST statement = #{statement}\"\n #if statement.upcase.index(\" JOIN\") == nil\n if statement =~ / JOIN/i\n dm_session[:table_name] = @user_defined_report.value_from_report_hash(:main_table_name)\n else\n table_name = FieldParser.get_table_name(statement)\n dm_session[:table_name] = table_name\n end\n\n where_clause = ''\n if dm_session[:grid_type] == \"summary\"\n #if statement.upcase.index(\" WHERE\") != nil\n if statement =~ / WHERE/i\n where_clause = FieldParser.get_where_clause(statement).split(\"|splitter|\")[0].to_s\n end\n end\n\n #puts \"WHERE CLAUSE : #{where_clause} %%%\"\n dm_session[:search_engine_where_clause] = nil if dm_session[:search_engine_where_clause] != nil\n dm_session[:search_engine_where_clause] = where_clause\n # logger.info \">>> SQL: #{statement}\"\n dm_session[:search_engine_query_definition] = statement\n #dm_session[:search_engine_query_definition] = apply_functions(@user_defined_report.sql_statement(report_state_hash))\n dm_session[:search_engine_grid_action_columns] = []\n dm_session[:search_engine_multi_select] = nil\n\n if for_download\n dm_session[:csv_export_filename] = @user_defined_report.user_defined_report_name || @user_defined_report.report_name\n #render :text => \"TEST\"\n #@url_base = \"http://#{request.host_with_port}/development_tools/data/export_se_grid_to_csv\"\n #export_se_grid_to_csv\n redirect_to :controller => 'development_tools/data', :action => 'export_se_grid_to_csv'\n else\n if dm_session[:grid_type] == \"summary\"\n render_summary_grid(\"http://#{request.host_with_port}#{request.request_uri}\", @user_defined_report.user_defined_report_name)\n else \n render_generic_grid(\"http://#{request.host_with_port}#{request.request_uri}\", @user_defined_report.user_defined_report_name)\n end\n end \n end\n\n end\n rescue\n handle_error(\"The report view could not be launched, reason : \" + $!)\n end\n end", "def initialize model, app_or_controller_or_view\n @model = model\n @context = @controller = ContextExtractor.new(app_or_controller_or_view).extract\n end", "def apply\n @item.run_action(@action_name, *@action_args, current_intention: self)\n end", "def react!(model)\n reactor.react!(model, action, owner)\n end", "def update\n self.model = find_model\n model.update_attributes(params[model_slug])\n respond_with_contextual model\n end", "def render template, local_assigns\r\n title = (@view.assigns['page_title'] or local_assigns['page_title'])\r\n table(title) do\r\n test = self #to enable test.command\r\n\r\n assign_locals_code = ''\r\n local_assigns.each_key {|key| assign_locals_code << \"#{key} = local_assigns[#{key.inspect}];\"}\r\n\r\n eval assign_locals_code + \"\\n\" + template\r\n end\r\n end", "def exec_action_object(action)\n\t\t\taction.execute\n\t\tend", "def executed_by(agent_model, arguments = {})\n @execution_agent = [agent_model, arguments]\n end", "def bind\n raise ModelNotSetError.new(\"You must set the model before binding it.\") unless @model\n\n fields do |field|\n view_obj = self.view.viewWithTag(field.tag)\n @model.send(\"#{field.name}=\".to_sym, view_obj.text) if view_obj.respond_to?(:text)\n end\n end", "def apply_props()\n @view.apply_props(props)\n\n @view.populate_popup_menu_block = proc { |menu:| populate_popup_menu(menu: menu) }\n\n set_model( props.key?(:model) ? props[:model] : default_model )\n end", "def vm_show\n record = VmOrTemplate.find(params[:id])\n redirect_to(:action => 'show', :controller => record.class.base_model.to_s.underscore, :id => record.id)\n end", "def render(model, view)\n view.simple_form_for(model, self.args) do |builder|\n render_elements(builder, view)\n end\n end", "def call(vm)\r\n @block.call(self, vm)\r\n end", "def task_view\n @dataset = @user.datasets.find(params[:id])\n raise ActiveRecord::RecordNotFound unless @dataset\n \n @task = @dataset.analysis_tasks.find(params[:task_id])\n raise ActiveRecord::RecordNotFound unless @task\n \n raise ActiveRecord::RecordNotFound unless params[:view]\n \n klass = @task.job_class\n render :template => klass.view_path(params[:view])\n end", "def execute(block)\n model = @wrapper.object\n block.call model\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take a number of server/detail records for hosts, then format it into a data structure with standardized fields for display.
def convert_yaml(servers) serverdata = {} servers.each do |server| hostname = server.hostname # Initialize our root fields so that there won't be any surprises from # hosts that don't have data. serverdata[hostname] = {} fields = %w(general netdb puppetfacts puppetstatus advisories vmware upgrades managed) fields.each do |root| serverdata[hostname][root] = {} end server.details.each do |detail| category = detail.category field = detail.name value = format_value(category, field, detail.value) serverdata[hostname][category][field] = value end end serverdata end
[ "def hosts\n out = []\n out << \"group {\"\n out << ' filename \"deezy\";'\n Host.find_all_by_enabled(true).each do |host|\n out << [\n \" host #{host.hostname} { hardware ethernet #{host.mac}; \",\n \"#{\"fixed-address #{host.ip};\" unless host.ip.blank?}\",\n \"}\"\n ].join\n end\n out << \"}\"\n out << ''\n end", "def hosts_to_table(opts = {})\n tbl = Rex::Ui::Text::Table.new({'Columns' => ['address','mac','name','os_name','os_flavor','os_sp','purpose','info','comments']})\n tbl.header = 'Hosts'\n tbl.headeri = opts[:heading_size]\n framework.db.hosts.each do |host|\n unless opts[:hosts].nil? or opts[:hosts].empty?\n next unless opts[:hosts].include? host.address\n end\n unless opts[:ports].nil?\n next unless (host.services.map{|s| s[:port]}).any? {|p| opts[:ports].include? p}\n end\n address = host.address\n address = to_wikilink(address,opts[:namespace]) if opts[:links]\n row = [\n address,\n host.mac,\n host.name,\n host.os_name,\n host.os_flavor,\n host.os_sp,\n host.purpose,\n host.info,\n host.comments\n ]\n if opts[:search]\n tbl << row if row.any? {|r| /#{opts[:search]}/i.match r.to_s}\n else\n tbl << row\n end\n end\n return tbl\n end", "def hosts_to_opts(hosts)\n opts = {}\n \n hosts.each do |record|\n opts[:host] ||= record.hostName || ''\n opts[:domain] ||= record.domainName\n opts[:type] ||= record.recordType\n opts[:ttl] ||= record.tTL if record.tTL\n\n opts[:data] ||= []\n if opts[:type] =~ /MX/i\n opts[:data] << {:priority => record.priority, :value => record.data}\n else\n opts[:data] << record.data\n end\n end\n\n opts\n end", "def parse_servers\n tuples = config.scan(SERVER_REGEXP)\n hsh = {}\n tuples.map do |(vrf, host, prefer, minpoll, maxpoll, sourcei, key)|\n hsh[host] = {\n vrf: vrf,\n prefer: !prefer.nil?,\n minpoll: minpoll.nil? ? nil : minpoll.to_i,\n maxpoll: maxpoll.nil? ? nil : maxpoll.to_i,\n source_interface: sourcei,\n key: key.nil? ? nil : key.to_i\n }\n hsh[host]\n end\n\n { servers: hsh }\n end", "def parse_hosts\n entries = config.scan(\n /^logging(?:\\svrf\\s([^\\s]+))?\\shost\\s([^\\s]+)\\s(\\d+)\n \\sprotocol\\s([^\\s]+)/x\n )\n hosts = []\n entries.each do |vrf, address, port, proto|\n hosts << { address: address,\n vrf: vrf.nil? ? 'default' : vrf,\n port: port,\n protocol: proto }\n end\n { hosts: hosts }\n end", "def parse_servers\n tuples = config.scan(SERVER_REGEXP)\n tuples.map do |(host, vrf, authp, acctp, tout, tries, keyfm, key)|\n hsh = {}\n hsh[:hostname] = host\n hsh[:vrf] = vrf\n hsh[:auth_port] = authp.to_i\n hsh[:acct_port] = acctp.to_i\n hsh[:timeout] = tout.to_i\n hsh[:retransmit] = tries.to_i\n hsh[:key_format] = keyfm.to_i\n hsh[:key] = key\n hsh\n end\n end", "def servers\n tuples = config.scan(SERVER_REGEXP)\n tuples.map do |(host, mplex, vrf, port, tout, keyfm, key)|\n hsh = {}\n hsh[:hostname] = host\n hsh[:vrf] = vrf\n hsh[:port] = port.to_i\n hsh[:timeout] = tout.to_i\n hsh[:key_format] = keyfm.to_i\n hsh[:key] = key\n hsh[:multiplex] = mplex ? true : false\n hsh\n end\n end", "def simplify_hosts_2(e)\n name = e[\"name\"]\n comps = e[\"components\"]\n [name, comps]\nend", "def server_report\n get_resource_list('compute', 'servers', 'servers')\n @server_csv_array = []\n @server_print_array = []\n @resource_id_list.each do |serverid|\n server = rest_get(\"#{@resource_url}/servers/#{serverid}\", @token_id)\n server_array = JSON.parse(server)['server']\n server_name = server_array['name']\n server_lpar_name = server_array['OS-EXT-SRV-ATTR:instance_name']\n server_lpar_state = server_array['OS-EXT-STS:vm_state']\n server_state = server_array['status']\n server_health = server_array['health_status']['health_value']\n server_host = server_array['OS-EXT-SRV-ATTR:host']\n server_addresses = JSON.parse(server)['server']['addresses']\n @server_ipaddress = ''\n unless server_addresses.empty? || server_state != 'ACTIVE'\n @server_ipaddress = server_addresses.values[0][0]['addr']\n end\n server_flavor = server_array['flavor.original_name']\n server_cpus = server_array['cpus']\n server_memory = server_array['memory_mb']\n server_cpu_util = server_array['cpu_utilization']\n server_cpu_mode = server_array['vcpu_mode']\n server_os = server_array['operating_system']\n server_cpu_pool = server_array['shared_proc_pool_name']\n server_cpu_share_weight = server_array['shared_weight']\n server_compat_mode = server_array['desired_compatibility_mode']\n @server_csv_array << [server_name, server_lpar_name, server_lpar_state, server_state, server_host, server_health, @server_ipaddress, server_flavor, server_cpus, \\\n server_memory, server_cpu_util, server_cpu_mode, server_os, server_cpu_pool, server_cpu_share_weight, server_compat_mode]\n @server_print_headers = %w(Host_Name LPAR_Name LPAR_State OS_Status Machine_Name LPAR_Health IPaddress Template CPU Memory CPU_Util CPU_Mode CPU_Pool Share_Weight)\n @server_print_array << [server_name, server_lpar_name, server_lpar_state, server_state, server_host, server_health, @server_ipaddress, server_flavor, server_cpus, \\\n server_memory, server_cpu_util, server_cpu_mode, server_cpu_pool, server_cpu_share_weight]\n end\n end", "def zone(hosts, elbs)\n host_records = hosts.map do |id,info|\n name = \"#{id}.inst.\"\n priv = \"#{info[:priv]}.priv.\"\n [ Zonify::RR.cname(name, info[:dns], 86400), # Long TTLs for host records.\n Zonify::RR.cname(priv, info[:dns], 86400), # Long TTLs for host records.\n Zonify::RR.srv('inst.', name) ] +\n info[:tags].map do |tag|\n k, v = tag\n unless k.empty? or k.nil? or v.empty? or v.nil?\n tag_dn = \"#{Zonify.string_to_ldh(v)}.#{Zonify.string_to_ldh(k)}.tag.\"\n Zonify::RR.srv(tag_dn, name)\n end\n end.compact\n end.flatten\n elb_records = elbs.map do |elb|\n running = elb[:instances].select{|i| hosts[i] }\n name = \"#{elb[:prefix]}.elb.\"\n running.map{|host| Zonify::RR.srv(name, \"#{host}.inst.\") }\n end.flatten\n sg_records = hosts.inject({}) do |acc, kv|\n id, info = kv\n info[:sg].each do |sg|\n acc[sg] ||= []\n acc[sg] << id\n end\n acc\n end.map do |sg, ids|\n sg_ldh = Zonify.string_to_ldh(sg)\n name = \"#{sg_ldh}.sg.\"\n ids.map{|id| Zonify::RR.srv(name, \"#{id}.inst.\") }\n end.flatten\n [host_records, elb_records, sg_records].flatten\nend", "def live_hosts_to_stdout(host_type = :ip)\n if host_type == :ip\n if @xmlfi.scanner[\"arguments\"].include?(\"-Pn\")\n parse_live_hosts.each {|host| puts host.ip}\n else\n parse_up_hosts.each {|host| puts host.ip}\n end\n # if we want to print by name we need to check\n # if the host has a name otherwise still do by IP\n elsif host_type == :name\n if @xmlfi.scanner[\"arguments\"].include?(\"-Pn\")\n parse_live_hosts.each do |host|\n if host.hostname\n puts host.hostname\n else\n puts host.ip\n end\n end\n else\n parse_up_hosts.each do |host|\n if host.hostname\n puts host.hostname\n else\n puts host.ip\n end\n end\n end\n end\n end", "def parse_dns(raw)\n # Filtering Lines with Comments and Empty Lines\n dns_filter = raw.select {|x| x[0]!= \"#\" && x != \"\\n\" }\n\n # Creating a List with 3 Columns\n dns_filter_list = []\n dns_filter.each {|x| dns_filter_list.push(x.split(\", \"))}\n\n # Creating the List each DNS for Hash\n record_type_list = []\n source_list = []\n destination_list = []\n\n dns_filter_list.each do |x|\n record_type_list.push(x[0])\n source_list.push(x[1])\n destination_list.push(x[2])\n end\n\n # Building the Hash\n dns_hash = {\n \"RECORDTYPE\".to_sym => record_type_list,\n \"SOURCE\".to_sym => source_list,\n \"DESTINATION\".to_sym => destination_list,\n }\n return dns_hash\nend", "def collect_and_flatten(contents)\n contents.each do |line|\n entry = HostsFile::Entry.parse(line)\n next if entry.nil?\n\n append(\n ip_address: entry.ip_address,\n hostname: entry.hostname,\n aliases: entry.aliases,\n comment: entry.comment,\n priority: !entry.calculated_priority? && entry.priority\n )\n end\n end", "def parse_dns(raw)\n # Filtering Lines with Comments and Empty Lines\n dns_filter = raw.select { |x| x[0] != \"#\" && x != \"\\n\" }\n\n # Creating a List with 3 Columns\n dns_filter_list = []\n dns_filter.each { |x| dns_filter_list.push(x.split(\", \")) }\n\n # Creating the List each DNS for Hash\n record_type_list = []\n source_list = []\n destination_list = []\n\n dns_filter_list.each do |x|\n record_type_list.push(x[0])\n source_list.push(x[1])\n destination_list.push(x[2])\n end\n\n # Building the Hash\n dns_hash = {\n \"RECORDTYPE\".to_sym => record_type_list,\n \"SOURCE\".to_sym => source_list,\n \"DESTINATION\".to_sym => destination_list,\n }\n return dns_hash\nend", "def full_host_record(ip:)\n load_cnames\n \n @forward_host_record ||= {} # Global, as we want to do name lookups.\n return_record = []\n unless( (host_records = @infoblox.get_host_by_ip(ip_address: ip)).nil? )\n host_records.each do |hosts|\n hosts.each do |hn|\n # Assign an empty record, if we haven't seen this host before\n @forward_host_record[hn] ||= { hostname: hn, ip: '', aliases: [], cnames: [] }\n \n # Record the IP. There may be multiple IPs with one hostname.\n @forward_host_record[hn][:ip] = ip\n \n # The hostname might have CNAMES point to it\n unless @reverse_cnames[hn].nil?\n @reverse_cnames[hn].each do |cn| \n @forward_host_record[hn][:cnames] << cn \n end\n end\n \n # The hostname may have alternate hostname A records, stored in IPAM as ALIASES\n @infoblox.get_alias(hostname: hn) do |a| \n short_alias = a.split('.',2)[0]\n @forward_host_record[hn][:aliases] << short_alias\n \n # The ALIASes might have CNAME records pointing to it\n unless @reverse_cnames[a].nil?\n # Record the ALIAS CNAMES against the parent hostname.\n @reverse_cnames[a].each do |cn| \n @forward_host_record[hn][:cnames] << cn \n end\n end\n end\n return_record << @forward_host_record[hn]\n \n # Add forward lookup entries for each ALIAS\n host_domain = hn.split('.',2)[1]\n @forward_host_record[hn][:aliases].each do |a|\n @forward_host_record[\"#{a}.#{host_domain}\"] = @forward_host_record[hn]\n end\n \n # Add forward lookup entries for each CNAME\n @forward_host_record[hn][:cnames].each do |cn|\n @forward_host_record[cn] = @forward_host_record[hn]\n end\n \n end\n end\n end\n return return_record\nend", "def hosts\n h = []\n r = ('a'..'z')\n r.each do |i|\n r.each do |j|\n r.each do |k|\n h << i.to_s + j + k + \".com\"\n end\n end\n end\n h\n end", "def print_records(records)\n\tprint_status(\"Records found:\")\n\trecords.each do |r|\n\t\tprint_good(\"\\tHost: #{r[:host]}\")\n\t\tprint_good(\"\\tIP: #{r[:ip]}\")\n\t\tprint_good(\"\\tPort: #{r[:port]}\")\n\t\tprint_good(\"\\tService:#{r[:service]}\")\n\t\tprint_good(\"\\tText:#{r[:txt]}\")\n\t\tprint_good(\"\")\n\tend\nend", "def hosts\n @model.config['hosts'].map { |row|\n row.merge(@model.cpus[row['name']]).merge({\n openssl: @model.versions[row['name']],\n })\n }\n end", "def collectHosts(rf, db)\n\trf.childEntity.grep(RbVmomi::VIM::Datacenter).each do |dc|\n\t\tprogressbar = ProgressBar.create(:title => \"Hosts\", :format => '%t |%b>>%i| %p%% %a')\n\t\tprogressbar.total = counter(dc, \"h\")\n\t\tdc.hostFolder.childEntity.each do |cluster|\n\t\t\tcluster.host.each do |host|\n\t\t\t\tdb.select(2)\n\t\t\t\tdb.hset(\"#{host.name}\", \"Status\", \"#{host.summary.overallStatus}\")\n\t\t\t\tdb.hset(\"#{host.name}\", \"PowerStatus\", \"#{host.summary.runtime.powerState}\")\n\t\t\t\tdb.hset(\"#{host.name}\", \"Connection\", \"#{host.summary.runtime.connectionState}\")\n\t\t\t\tdb.hset(\"#{host.name}\", \"OverallCpu\", \"#{host.summary.quickStats.overallCpuUsage}\")\n\t\t\t\tdb.hset(\"#{host.name}\", \"OverallMem\", \"#{host.summary.quickStats.overallMemoryUsage}\") \n\t\t\t\t#db.hset(\"#{host.name}\", \"SystemSensor\", \"#{host.summary.runtime.healthSystemRuntime.systemHealthInfo.numericSensorInfo.name}\")\n\t\t\t\tprogressbar.increment\n\t\t\tend\n\t\tend\n\tend\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
converts a JDBC recordset to an array of hashes, with one hash per record
def rs_to_array(rs) # creates an array of hashes from a jdbc record set arr = [] # get basic metadata for the recordset meta = rs.getMetaData cols = meta.getColumnCount.to_i # loop through the records to add them into hash while rs.next do # r is a temporary hash for the row being processed r = {} # add each row to r (1..cols).each do |c| r[meta.get_column_name(c)] = rs.getObject(c) if convert_to_ruby_time_classes.include?(r[meta.get_column_name(c)].class) r[meta.get_column_name(c)] = Time.at(r[meta.get_column_name(c)].get_time / 1000).utc end end # each cols # append hash to array arr << r end # while # completed hash is returned return arr end
[ "def nicefy_resultset( resultset )\r\n array_of_hashes = []\r\n resultset.each_hash do |row_hash|\r\n array_of_hashes << row_hash\r\n end\r\n array_of_hashes\r\n end", "def resultset_to_hash(resultset)\n meta = resultset.meta_data\n rows = []\n\n while resultset.next\n row = {}\n\n (1..meta.column_count).each do |i|\n name = meta.column_name i\n row[name] = case meta.column_type(i)\n when -6, -5, 5, 4\n # TINYINT, BIGINT, INTEGER\n resultset.get_int(i).to_i\n when 41\n # Date\n resultset.get_date(i)\n when 92\n # Time\n resultset.get_time(i).to_i\n when 93\n # Timestamp\n resultset.get_timestamp(i)\n when 2, 3, 6\n # NUMERIC, DECIMAL, FLOAT\n case meta.scale(i)\n when 0\n resultset.get_long(i).to_i\n else\n BigDecimal.new(resultset.get_string(i).to_s)\n end\n when 1, -15, -9, 12\n # CHAR, NCHAR, NVARCHAR, VARCHAR\n resultset.get_string(i).to_s\n else\n resultset.get_string(i).to_s\n end\n end\n\n rows << row\n end\n rows\nend", "def to_hashed_array\n # Duplicate the rows so that we can modify it without losing data\n rows = @rows.dup\n\n # Use the header row's values as property keys\n keys = rows.shift.collect {|name| string_to_key(name) }\n\n # Collect the attributes\n rows.collect do |row|\n Hash[keys.collect {|n| [n, row[keys.index(n)]] }]\n end\n end", "def rs_to_hash(rs, index_key_field, multi_val)\n # setting default hash value is necessary for appending to arrays\n hash=Hash.new{ |h, k| h[k] = [] }\n\n # get basic metadata for the recordset\n meta = rs.getMetaData\n cols = meta.getColumnCount.to_i\n\n # loop through the records to add them into hash\n while rs.next do\n # if multi_val is not true... create new hash value as an empty hash if it doesn't already exist\n hash[rs.getString(index_key_field)]={} if (!hash[rs.getString(index_key_field)] and !multi_val)\n\n # if multi_val is true... create new hash value as an empty array if it doesn't already exist\n hash[rs.getString(index_key_field)]=[] if (!hash[rs.getString(index_key_field)] and multi_val)\n\n # r is a temporary hash for the row being processed\n r=Hash.new\n\n # add each row to r\n (1..cols).each do |c|\n r[meta.get_column_name(c)] = rs.getObject(c)\n if convert_to_ruby_time_classes.include?(r[meta.get_column_name(c)].class)\n r[meta.get_column_name(c)] = Time.at(r[meta.get_column_name(c)].get_time / 1000).utc\n end\n end # each cols\n\n # set hash value to r if not multi_val\n hash[rs.getString(index_key_field)] = r if !multi_val\n\n # append hash to r if multi_val\n hash[rs.getString(index_key_field)] << r if multi_val\n end # while\n\n # completed hash is returned\n return hash\n end", "def execute_as_array(sql)\n return_array = Array.new\n @db.results_as_hash = false\n self.execute(sql).each do |rec|\n return_array << rec[0]\n end\n @db.results_as_hash = true\n return_array\n end", "def table_to_array(input_table)\n table_of_hashes = []\n input_table.rows.each do |record|\n table_of_hashes << array_to_hash(record)\n end\n table_of_hashes\n end", "def to_ary\n hash_rows\n end", "def rows_to_array(rows)\n collection = BlocRecord::Collection.new\n rows.each {|row| collection << new(Hash[columns.zip(row)])}\n collection\n end", "def rows_to_array(rows)\n collection = BlocRecord::Collection.new\n rows.each { |row| collection << new(Hash[columns.zip(row)]) }\n collection # return an array\n end", "def read_records(table)\n hashes = []\n each(table) {|hash| hashes << hash}\n hashes\n end", "def to_a(schema = nil)\n schema ||= @schema\n raise \"No schema set\" unless schema\n a = schema.hash_to_row(@row) # don't need type conversion as sequel is doing this for us\n end", "def hash_to_array(record)\n\t\t\tarr = Array.new\n\t\t\trecord.map do |key, val |\n\t\t\t\tarr.push(val)\n\t\t\tend\t\t\t\n\t\t\tarr\n\t\tend", "def oracle_sql_results(sql, conn = VACOLS::Case.connection)\n result = conn.execute(sql)\n output = []\n while r = result.fetch_hash\n output << r\n end\n output\nend", "def to_a\r\n data_arr = []\r\n for i in 0...@df[@df.keys[0]].length\r\n data_arr << @df.keys.each_with_object({}) {|col, rhash| rhash[col] = @df[col][i]}\r\n end\r\n data_arr\r\n end", "def to_a\n @importer.data.rows.collect {|r| r[@key] }\n end", "def as_array\n row_names = []\n rows = [] \n if @db == @@sdb\n @@sdb.select('select * from `' + @table_name + '`')[:items].each do |row| \n row.each do |row_name, row_data| \n row_names << row_name\n rows << reassemble_sdb_items(row_data)\n end\n end\n elsif @db == @@google_storage\n row_names = as_name_array\n rows = get_rows_from_names(row_names)\n end\n return row_names, rows\n end", "def retrieve_csv_to_array_of_hashes(dataFileWithPath)\r\n data_file = \"#{dataFileWithPath}\"\r\n data = []\r\n CSV.foreach(data_file, headers: true) do |row|\r\n data << row.to_hash\r\n end\r\n return data\r\n end", "def select_all\n query { |db| return db.to_hash }\n end", "def array_of_hashes(file)\n csv = CSV.read(file)\n headers = csv.shift.map {|i| i.to_s }\n s_data = csv.map {|row| row.map {|cell| cell.to_s } }\n array_of_hashes = s_data.map {|row| Hash[*headers.zip(row).flatten] }\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
converts a JDBC recordset to an array of hashes, with one hash per record creates a hash from a jdbc record set index_key_field is the field you want to use as the top level hash key... and should exist in the record set multi_val=true will create an array below each index_key_filed, false will create a hash as the child
def rs_to_hash(rs, index_key_field, multi_val) # setting default hash value is necessary for appending to arrays hash=Hash.new{ |h, k| h[k] = [] } # get basic metadata for the recordset meta = rs.getMetaData cols = meta.getColumnCount.to_i # loop through the records to add them into hash while rs.next do # if multi_val is not true... create new hash value as an empty hash if it doesn't already exist hash[rs.getString(index_key_field)]={} if (!hash[rs.getString(index_key_field)] and !multi_val) # if multi_val is true... create new hash value as an empty array if it doesn't already exist hash[rs.getString(index_key_field)]=[] if (!hash[rs.getString(index_key_field)] and multi_val) # r is a temporary hash for the row being processed r=Hash.new # add each row to r (1..cols).each do |c| r[meta.get_column_name(c)] = rs.getObject(c) if convert_to_ruby_time_classes.include?(r[meta.get_column_name(c)].class) r[meta.get_column_name(c)] = Time.at(r[meta.get_column_name(c)].get_time / 1000).utc end end # each cols # set hash value to r if not multi_val hash[rs.getString(index_key_field)] = r if !multi_val # append hash to r if multi_val hash[rs.getString(index_key_field)] << r if multi_val end # while # completed hash is returned return hash end
[ "def build_record_set(records)\n \n #columns = {}\n record_set = {}\n \n records.each do |record|\n \n #If the record with the given id does not exsits, \n # create it\n record_set[record[:id]] = {} if !record_set[record[:id]]\n \n # Create the hash for the field if it does not exists.\n record_set[record[:id]][record[:name]] = {} if !record_set[record[:id]][record[:name]]\n record_set[record[:id]][:lock_version] = record[:instance_version]\n record_set[record[:id]][record[:name]][:detail_id] = record[:detail_id]\n record_set[record[:id]][record[:name]][:data_type] = record[:data_type]\n record_set[record[:id]][record[:name]][:display_order] = record[:display_order]\n # Create the array of values\n record_set[record[:id]][record[:name]][:values] = [] if !record_set[record[:id]][record[:name]][:values]\n record_set[record[:id]][record[:name]][:values].push({:id => record[:detail_value_id], :lock_version => record[:value_version], :value => record[:value]})\n end\n \n return record_set\n \n end", "def resultset_to_hash(resultset)\n meta = resultset.meta_data\n rows = []\n\n while resultset.next\n row = {}\n\n (1..meta.column_count).each do |i|\n name = meta.column_name i\n row[name] = case meta.column_type(i)\n when -6, -5, 5, 4\n # TINYINT, BIGINT, INTEGER\n resultset.get_int(i).to_i\n when 41\n # Date\n resultset.get_date(i)\n when 92\n # Time\n resultset.get_time(i).to_i\n when 93\n # Timestamp\n resultset.get_timestamp(i)\n when 2, 3, 6\n # NUMERIC, DECIMAL, FLOAT\n case meta.scale(i)\n when 0\n resultset.get_long(i).to_i\n else\n BigDecimal.new(resultset.get_string(i).to_s)\n end\n when 1, -15, -9, 12\n # CHAR, NCHAR, NVARCHAR, VARCHAR\n resultset.get_string(i).to_s\n else\n resultset.get_string(i).to_s\n end\n end\n\n rows << row\n end\n rows\nend", "def rs_to_array(rs)\n # creates an array of hashes from a jdbc record set\n arr = []\n\n # get basic metadata for the recordset\n meta = rs.getMetaData\n cols = meta.getColumnCount.to_i\n\n # loop through the records to add them into hash\n while rs.next do\n # r is a temporary hash for the row being processed\n r = {}\n\n # add each row to r\n (1..cols).each do |c|\n r[meta.get_column_name(c)] = rs.getObject(c)\n if convert_to_ruby_time_classes.include?(r[meta.get_column_name(c)].class)\n r[meta.get_column_name(c)] = Time.at(r[meta.get_column_name(c)].get_time / 1000).utc\n end\n end # each cols\n\n # append hash to array\n arr << r\n end # while\n\n # completed hash is returned\n return arr\n end", "def to_hashed_array\n # Duplicate the rows so that we can modify it without losing data\n rows = @rows.dup\n\n # Use the header row's values as property keys\n keys = rows.shift.collect {|name| string_to_key(name) }\n\n # Collect the attributes\n rows.collect do |row|\n Hash[keys.collect {|n| [n, row[keys.index(n)]] }]\n end\n end", "def nicefy_resultset( resultset )\r\n array_of_hashes = []\r\n resultset.each_hash do |row_hash|\r\n array_of_hashes << row_hash\r\n end\r\n array_of_hashes\r\n end", "def get_index_values\n hash = {}\n @db.connect\n @index_fields.each do |field|\n tname = table_name field\n sql = \"SELECT id,value FROM #{tname}\"\n res = @db.query(sql)\n res.each_hash do |row|\n hash[row['value']] = row['id']\n end\n end\n @db.close \n hash\n end", "def to_ary\n hash_rows\n end", "def execute_as_array(sql)\n return_array = Array.new\n @db.results_as_hash = false\n self.execute(sql).each do |rec|\n return_array << rec[0]\n end\n @db.results_as_hash = true\n return_array\n end", "def to_hash\n @data.map do |row|\n hsh = {}\n @field_names.each_with_index.map{ |fld, i| hsh[fld] = row[i] }\n hsh\n end\n end", "def map_to_hash_by_primary_key(result) \n hash = {}\n\n result.each do |record|\n hash[record[@primary_key]] = record\n end\n\n hash\n end", "def table_to_array(input_table)\n table_of_hashes = []\n input_table.rows.each do |record|\n table_of_hashes << array_to_hash(record)\n end\n table_of_hashes\n end", "def to_hash\n # flatten just one level of the internal Array\n Hash[*@row.inject(Array.new) { |ary, pair| ary.push(*pair) }]\n end", "def process_rows\n case self['rowset']\n when Hash\n normalize_hash_rowset\n when Array\n normalize_array_rowset\n end\n collapse_key\n end", "def to_a\r\n data_arr = []\r\n for i in 0...@df[@df.keys[0]].length\r\n data_arr << @df.keys.each_with_object({}) {|col, rhash| rhash[col] = @df[col][i]}\r\n end\r\n data_arr\r\n end", "def rows_to_array(rows)\n collection = BlocRecord::Collection.new\n rows.each {|row| collection << new(Hash[columns.zip(row)])}\n collection\n end", "def hash_to_array(record)\n\t\t\tarr = Array.new\n\t\t\trecord.map do |key, val |\n\t\t\t\tarr.push(val)\n\t\t\tend\t\t\t\n\t\t\tarr\n\t\tend", "def map_to_hash_of_arrays_by_key(result,key) \n res = {}\n\n result.each do |record|\n res[record[key]] = [] unless res.has_key?(record[key])\n res[record[key]].push record\n end\n\n res\n end", "def yale_nd_row_as_hash i\n yale_nd_row(i, :hash)\n end", "def rows_to_array(rows)\n collection = BlocRecord::Collection.new\n rows.each { |row| collection << new(Hash[columns.zip(row)]) }\n collection # return an array\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
outputs a JDBC result set to a formatted file formatter defaults to JSON output unless you provide your own proc
def rs_to_json_file(rs, file_object, formatter) # default formatter outputs json objects for each row formatter = json_formatter unless formatter # get basic metadata for the recordset meta = rs.getMetaData cols = meta.getColumnCount.to_i record_count = 0 # loop through the records to add them into hash while rs.next do # r is a temporary hash for the row being processed r = Hash.new # add each row to r (1..cols).each do |c| r[meta.get_column_name(c)] = rs.getObject(c) if convert_to_ruby_time_classes.include?(r[meta.get_column_name(c)].class) r[meta.get_column_name(c)] = Time.at(r[meta.get_column_name(c)].get_time / 1000).utc end end # each cols # formatter handles output of r to file formatter.call(file_object, r) record_count += 1 end # while return record_count end
[ "def print_query_result(result) \n puts result.columns.to_s\n result.each do |record|\n puts record.to_s\n end\nend", "def output_query_to_file(sql, fn, header = true)\n hdout = Hathidata::Data.new(fn).open('w');\n rows(sql) do |row|\n if header then\n hdout.file.puts(row.to_h.keys.join(\"\\t\"));\n header = false;\n end\n hdout.file.puts(row.to_a.join(\"\\t\"));\n end\n hdout.close();\n return hdout\n end", "def format_output(result, format)\n case format\n when /^jso?n?$/, nil\n JSON.pretty_generate(result)\n when /^ya?ml$/\n YAML.dump(result)\n when /^te?xt$/, /^sh(ell)?/, 'list'\n result = result.keys if result.respond_to?(:keys)\n result.join(\" \")\n else\n raise ArgumentError, \"Unknown output format #{format}\"\n end\n end", "def format_output(result, format)\n case format\n when :json\n JSON.pretty_generate(result)\n when :yaml\n YAML.dump(result)\n when :text\n result = result.keys if result.respond_to?(:keys)\n result.join(\" \")\n else\n raise ArgumentError, \"Unknown output format #{format}\"\n end\n end", "def print_result_set_iter(fw)\n @tables.each { |vt|\n vt.result_set_iter(fw)\n }\n wrap_result_set_iter(fw)\n end", "def export_results(opt)\n reclist = opt[:reclist]\n ofile = opt[:ofile]\n output_headers = opt[:output_headers]\n custom_headers = opt[:custom_headers]\n mode = 'w' unless opt[:mode] == 'a'\n headers = custom_headers + output_headers\n File.open(ofile, mode) do |outfile|\n outfile << headers.join(\"\\t\") + \"\\n\" if mode == 'w'\n i = 0\n reclist.each do |record|\n puts i += 1\n output = \"#{record.print_output(custom_headers)}\\n\"\n # _end = record.ss_match.first.most_recent.first\n # s = record.ss_match.first&.most_recent_data()\n begin\n outfile << output\n rescue\n puts record\n raise e\n end\n end\n end\nend", "def export_data_using_sql(table_or_report_uri, format, sql, config={})\n body = {'ZOHO_SQLQUERY' => sql}\n body = body.merge!(config) if config.present?\n\n options = {\n :query => {\n 'ZOHO_ACTION' => 'EXPORT',\n 'ZOHO_OUTPUT_FORMAT' => format,\n },\n :body => body\n }\n\n result = send_request get_uri(table_or_report_name), 'post', options\n result\n # TODO: Figure out to what to do with File objectsw response\n end", "def print output_formatter\n output_formatter.print({ \"Commits:\" => @commits, \"Affected lines churn:\" => @result})\n end", "def display_students_db\n all_students = @conn.exec(\"SELECT * FROM students_db;\")\n #usp[e exec to pretty much do everything\n all_students.each do |student|\n student.each do |k,v|\n puts \"#{k}: #{v}\"\n puts all_students\n end\n end\nend", "def process_result(out_dir, filename, keyset, tbls)\n filepath = append_filename(out_dir, filename)\n write_results(filepath, keyset, tbls)\n :ok\n end", "def write_results(outfile, results: self.results, headers: nil,\n include_headers: true, format: :tsv)\n Sierra::DB::Query.write_results(outfile,\n results: results, format: format,\n headers: headers,\n include_headers: include_headers)\n end", "def dbDumptoCsv(req,res)\n qs = req.query[\"select\"].split(\",\")\n @dbout = []\n qs.each do |q|\n @dbout = @dbout + @db.all(:url => q)\n end\n \n # Open the output csv file\n @oFile = File.new(\"#{$root_dir}/\" + $config.get_value('burpdotcsv'), 'w')\n \n @dbout.each do |entry|\n @oFile.syswrite(entry.ref + \",\" + entry.url + \"\\n\") if entry.ref.length > 0\n end\n \n @oFile.close\n end", "def output_sql(sql)\n return unless output = @opts[:output]\n sql << \" OUTPUT #{column_list(output[:select_list])}\"\n if into = output[:into]\n sql << \" INTO #{table_ref(into)}\"\n if column_list = output[:column_list]\n cl = []\n column_list.each { |k, v| cl << literal(String === k ? k.to_sym : k) }\n sql << \" (#{cl.join(COMMA_SEPARATOR)})\"\n end\n end\n end", "def result_set; end", "def to_json\n output = \"[\\n\"\n sep = \"\"\n next_result do |rec|\n output += sep\n output += rec.to_json\n sep = \",\\n\"\n end\n output += \"\\n]\\n\"\n end", "def print output_formatter\n output_formatter.print({ \"Commits:\" => @commits, \"Standard churn:\" => @result, \"Deletions:\" => @deletions, \"Insertions:\" => @insertions })\n end", "def dump(schemas, output_filename)\n\n # Redirect output to output_filename (or use stdout)\n\n if output_filename then\n begin\n $stdout = File.open(output_filename, 'w');\n rescue => ex\n $stderr.puts \"Error: output file: #{ex.message}\"\n exit 1\n end\n end\n\n # Dump schemas\n\n schemas.each do |s|\n puts \"#---\"\n puts s.to_dump()\n puts\n end\n\n # Close output\n\n if output_filename then\n $stdout.close\n end\n\nend", "def nicefy_resultset( resultset )\r\n array_of_hashes = []\r\n resultset.each_hash do |row_hash|\r\n array_of_hashes << row_hash\r\n end\r\n array_of_hashes\r\n end", "def export(table,fileout)\n klass = @db.const_get(table.singularize.camelize)\n columns = klass.column_names\n out = File.open(fileout,\"w\") \n out.write columns.join(\"\\t\")+\"\\n\"\n klass.find(:all).each do |output|\n records = output.attributes\n values = []\n columns.each {|c| values << records[c]}\n out.write values.join(\"\\t\")+\"\\n\"\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Input: (2 > 4 > 3) + (5 > 6 > 4) Output: 7 > 0 > 8 Input: (2 > 4 > 3) + (1 > 1) Output: (3 > 5 > 3) we want to traverse both input nodes as we traverse, we sum the values of node and have that be the value of a new node in the output list if the sum is greater than 9 we need to carry the 1 to the next node in the result initialize result head dummy set current to result head dummy set current1 and current2 to head1 and head2 initialize tens to 0 while current1 or current2 are not nil or tens is 1 add the values at current1 and current 2 and tens after adding, set tens to 0 if the sum is greater than 9 set tens to 1 set the current nodes next to a new node with value = sum % 10 current = current.next current1 = current1.next current2 = current2.next sum = 0 return result head dummy.next my solution beats 96% on leetcode!
def add_two_numbers(head1, head2) result_dummy = ListNode.new(nil) current, current1, current2 = result_dummy, head1, head2 tens = 0 while current1 && current2 sum = current1.val + current2.val + tens tens = sum > 9 ? 1 : 0 current.next = ListNode.new(sum % 10) current, current1, current2 = current.next, current1.next, current2.next end while current1 sum = current1.val + tens current.next = ListNode.new(sum % 10) tens = sum > 9 ? 1 : 0 current, current1 = current.next, current1.next end while current2 sum = current2.val + tens current.next = ListNode.new(sum % 10) tens = sum > 9 ? 1 : 0 current, current2 = current.next, current2.next end if tens == 1 current.next = ListNode.new(1) end result_dummy.next end
[ "def sum_lists(node1, node2)\n result = LinkedList.new\n carry = 0\n\n until node1.nil? && node2.nil?\n digit1, digit2 = ((!node1.nil? && node1.data) || 0), ((!node2.nil? && node2.data) || 0)\n\n sum_digits = digit1 + digit2 + carry\n result.append(sum_digits % 10)\n\n carry = sum_digits / 10\n node1 = node1.next\n node2 = node2.next\n end\n result.append(carry) if carry != 0\n\n result\nend", "def sum_lists(node1, node2)\n carry = 0\n total = LinkedList.new\n until node1.nil? && node2.nil?\n # If the numbers do not have the same number of digits, consider this digit\n # to be zero\n val1 = node1.nil? ? 0 : node1.data\n val2 = node2.nil? ? 0 : node2.data\n\n # Keep track of the carry value so that it may be used in calculating the\n # next digit\n sum = val1 + val2 + carry\n total.append(sum % 10)\n carry = sum / 10\n\n # Move to the next larger digit\n node1 = node1.next unless node1.nil?\n node2 = node2.next unless node2.nil?\n end\n # There may be an additional carry value left over\n total.append(carry) if carry.positive?\n total\nend", "def linked_list_add_two_integers(head_a, head_b)\n return head_b if head_a.nil?\n return head_a if head_b.nil?\n\n sum = head_a.value + head_b.value\n carry = 0\n if sum >= 10\n sum = sum % 10\n carry = 1\n end\n\n head_a = head_a.next\n head_b = head_b.next\n\n result_head = LinkedListNode.new(sum)\n result_tail = result_head\n\n until head_a.nil? && head_b.nil?\n digit_a = 0\n digit_b = 0\n\n unless head_a.nil?\n digit_a = head_a.value\n head_a = head_a.next\n end\n\n unless head_b.nil?\n digit_b = head_b.value\n head_b = head_b.next\n end\n\n sum = digit_a + digit_b + carry\n\n if sum >= 10\n sum = sum % 10\n carry = 1\n else\n carry = 0\n end\n\n result_tail.next = LinkedListNode.new(sum)\n result_tail = result_tail.next\n end\n\n if carry > 0\n result_tail.next = LinkedListNode.new(carry)\n result_tail = result_tail.next\n end\n\n return result_head\nend", "def plus(l2)\n result = LinkedList.new\n curr1 = @head\n curr2 = l2.head\n remember_number = 0\n\n while(curr1 || curr2)\n val1 = curr1 ? curr1.value : 0\n val2 = curr2 ? curr2.value : 0\n\n sum = val1 + val2 + remember_number\n\n if sum >= 10\n sum %= 10\n remember_number = 1\n end\n\n result.add(sum)\n\n curr1 = curr1.next\n curr2 = curr2.next\n end\n\n result\n end", "def add_reversed_digits(list1, list2)\n return false unless list1 && list2\n current1 = list1.head\n current2 = list2.head\n stack1 = []\n stack2 = []\n\n while current1.next\n stack1 << current1.value.to_i\n current1 = current1.next\n end\n stack1 << current1.value.to_i\n\n while current2.next\n stack2 << current2.value.to_i\n current2 = current2.next\n end\n stack2 << current2.value.to_i\n\n stack1 = stack1.reverse.join.to_i\n stack2 = stack2.reverse.join.to_i\n stack1 + stack2\nend", "def add_two_numbers(l1, l2)\n (linked_list_to_array(l1).map(&:to_s).join.to_i + linked_list_to_array(l2).map(&:to_s).join.to_i).to_s.reverse.chars.map(&:to_i)\nend", "def addTwoHugeNumbers(a, b)\n a_num = \"\"\n b_num = \"\"\n while a\n a_num += '%04d' % a.value\n a = a.next\n end\n puts a_num\n while b\n b_num += '%04d' % b.value\n b = b.next\n end\n puts b_num\n total = a_num.to_i + b_num.to_i\n result = []\n return [0] if total == 0\n while total > 0\n result.unshift(total%10000)\n total /= 10000\n end\n result\nend", "def two_list_merge node1, node2\n res = nil\n\n while node1 != nil or node2 != nil\n\n if node1 != nil and node2 != nil\n if node1.val < node2.val\n res == nil ? res = Node.new(node1.val) : res.add_next_node(Node.new(node1.val))\n node1 = node1.next_node\n else\n res == nil ? res = Node.new(node2.val) : res.add_next_node(Node.new(node2.val))\n node2 = node2.next_node\n end\n elsif node1 == nil\n res == nil ? res = Node.new(node2.val) : res.add_next_node(Node.new(node2.val))\n node2 = node2.next_node\n else\n res == nil ? res = Node.new(node1.val) : res.add_next_node(Node.new(node1.val))\n node1 = node1.next_node\n end\n end\nend", "def part1(numbers)\n stack = []\n stack.push([numbers[0], numbers[1]]) # [ n_child_nodes, n_metadata_entries ]\n curr = 2\n sum = 0\n while (parent = stack.pop) != nil && curr < numbers.length\n if parent[0] == 0\n while parent[1] > 0\n sum += numbers[curr]\n curr += 1\n parent[1] -= 1\n end\n else\n stack.push([parent[0] - 1, parent[1]])\n stack.push([numbers[curr], numbers[curr+1]])\n curr += 2\n end\n end\n \n puts \"part1 answer\"\n puts \"sum : #{sum}\"\nend", "def find_pair_to_sum(x)\n prep_sorted_lists # To prepared two sorted lists\n node1 = list1.head\n node2 = nil\n flag = false\n break_node = list2.end # Set the break node as end of secondlist\n while(node1.value < x && node1 != nil && flag == false)\n node2 = list2.head\n while(node2.value <= break_node.value && node2.value <= x-node1.value)\n if (node2.value + node1.value == x)\n flag = true\n break\n end\n break if node2.value + node1.value > x # All the following elements in List2 will be greater than sum anyways\n node2 = node2.next\n end\n break_node = node2 # Set the break point as this node for next iteration\n node1 = node1.next unless flag == true\n end\n if flag == true\n puts \"Pair to match sum as #{x} is Node1: #{node1.value} and Node2: #{node2.value}\"\n else\n puts \"Pair not found\"\n end\n end", "def mergeTwoLinkedLists(l1, l2)\n out = ListNode.new(0)\n head = out\n head1 = l1\n head2 = l2\n while head1 || head2\n if head1 && head2\n if head1.value <= head2.value\n head.next = ListNode.new(head1.value)\n head = head.next\n head1 = head1.next\n else\n head.next = ListNode.new(head2.value)\n head = head.next\n head2 = head2.next\n end\n elsif head1\n head.next = ListNode.new(head1.value)\n head = head.next\n head1 = head1.next\n else\n head.next = ListNode.new(head2.value)\n head = head.next\n head2 = head2.next\n end\n end\n out.next\nend", "def two_sum(numbers, target)\n\n numbers.each_with_index do |num, index|\n \n looking_for = target - num\n answer_2 = binary_search(numbers, index + 1, numbers.length - 1, looking_for)\n if !!answer_2\n return [index + 1, answer_2 + 1] \n end\n end\nend", "def sum_numbers(root, accumulator = {val: 0})\n return 0 if root.nil?\n\n accumulator[:val] = accumulator[:val] * 10 + root.val\n\n\n sum_numbers(root.left, accumulator) + sum_numbers(root.right, accumulator)\n accumulator[:val]\nend", "def add(lnum1, lnum2, offset)\n carry = 0\n result = []\n i = 0\n while i < offset\n if i < lnum1.size\n result.push lnum1[i]\n else\n result.push 0\n end\n i += 1\n end\n while i < lnum1.size and i-offset < lnum2.size\n tmp = lnum1[i] + lnum2[i-offset] + carry\n carry = tmp / 10\n result.push tmp % 10\n i += 1\n end\n while i < lnum1.size\n tmp = lnum1[i] + carry\n carry = tmp / 10\n result.push tmp % 10\n i += 1\n end\n while i-offset < lnum2.size\n tmp = lnum2[i-offset] + carry\n carry = tmp / 10\n result.push tmp % 10\n i += 1\n end\n while carry > 0\n result.push carry % 10\n carry /= 10\n end\n result\nend", "def digit_and_carry(num1, num2, carry)\n digit_sum = num1 + num2 + carry\n carry = digit_sum / 10\n digit_sum = digit_sum % 10\n\n [digit_sum, carry]\nend", "def merge(left_number, right_number)\n if left_number.empty?#if the left position is empty, put the\n right_number # number on the opposite side\n elsif right_number.empty?#if the right position is empty, put the\n left_number # number on the opposite side\n elsif left_number.first < right_number.first\n #if the first left is less than the first right then\n #put the first number on the left with the other numbers\n [left_number.first] + merge(left_number[1..-1], right_number)\n else#or put the first number on the right with the other numbers\n [right_number.first] + merge(left_number, right_number[1..-1])\n end\nend", "def merge_two_lists(l1, l2)\n\tdummy = ListNode.new(nil)\n\tacc = dummy\n\twhile l1 && l2\n\t\tcase l1.val <=> l2.val\n\t\twhen 1\n\t\t\tacc.next = l2\n\t\t\tl2 = l2.next\n\t\telse\n\t\t\tacc.next = l1\n\t\t\tl1 = l1.next\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \n\t\tend\n\t\tacc = acc.next\n\tend\n\tif l1\n\t\tacc.next = l1\n\telsif l2\n\t\tacc.next = l2\n\tend\n\n\tdummy.next\nend", "def addends\n\t\tluhn_array = @digit_array.reverse.map.with_index(1) do |value, idx|\n\t\t\tif idx.even?\n\t\t\t\tvalue = (value * 2 > 10) ? (value * 2 - 9) : (value * 2)\n\t\t\telse\n\t\t\t\tvalue\n\t\t\tend\n\t\tend\n\t\tluhn_array.reverse\n\tend", "def add_strings(num1, num2)\n i = num1.size - 1\n j = num2.size - 1\n carry = 0\n ans = ''\n while i >= 0 && j >= 0 do \n sum = (num1[i].ord) - (\"0\".ord) + num2[j].ord - (\"0\".ord) + carry\n ans = (sum % 10).to_s + ans\n carry = sum / 10\n i -= 1\n j -= 1\n end\n \n while i >= 0 do \n sum = num1[i].ord - '0'.ord + carry\n ans = (sum % 10).to_s + ans\n carry = sum / 10\n i -= 1\n end\n \n while j >= 0 do \n sum = num2[j].ord - '0'.ord + carry\n ans = (sum % 10).to_s + ans\n carry = sum / 10\n j -= 1\n end\n \n if carry > 0 \n ans = carry.to_s + ans\n end\n ans\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The Order Books channel allow you to keep track of the state of the Bitfinex order book. It is provided on a price aggregated basis, with customizable precision.
def books(symbol="btcusd", precision="P0", params = {}) check_params(params, %i{len}) get("book/#{symbol}/#{precision}", params: params).body end
[ "def apply_orderbook_snapshot\n client.orderbook(level: 3) do |resp|\n @bids = resp['bids'].map { |b| order_to_hash(*b) }\n @asks = resp['asks'].map { |a| order_to_hash(*a) }\n @snapshot_sequence = resp['sequence']\n @last_sequence = resp['sequence']\n end\n end", "def apply_orderbook_snapshot\n @client.orderbook(level: 3) do |resp|\n @bids = resp['bids'].map { |b| order_to_hash(*b) }\n @asks = resp['asks'].map { |a| order_to_hash(*a) }\n @snapshot_sequence = resp['sequence']\n @last_sequence = resp['sequence']\n end\n end", "def book_ticker(symbol:)\n PublicRequest.perform({\n request_method: :get,\n path: '/api/v3/ticker/bookTicker',\n params: {\n symbol: symbol,\n },\n })\n end", "def order_book(input, output)\n offers = []\n\n # Start at order book index\n # Stop after max order book quality\n tip_index = Indexes::order_book(input, output)\n book_end = Indexes::get_quality_next(tip_index)\n\n global_freeze = global_frozen?(output[:account]) ||\n global_frozen?(input[:account])\n\n # transfer rate multipled to offer output to pay issuer\n rate = transfer_rate(output[:account])\n\n balances = {}\n done = false # set true when we cannot traverse anymore\n direct = true # set true when we need to find next dir\n offer_dir = nil # current directory being travred\n dir_rate = nil # current directory quality\n offer_index = nil # index of current offer being processed\n book_entry = nil # index of next offer directory record\n until done\n if direct\n direct = false\n # Return first index after tip\n ledger_index = state_map.succ(tip_index, book_end)\n if ledger_index\n # retrieve offer_dir SLE from db\n offer_dir = state_map.read(ledger_index)\n else\n offer_dir = nil\n end\n\n if !offer_dir\n done = true\n else\n # Set new tip, get first offer at new tip\n tip_index = offer_dir.key\n dir_rate = STAmount.from_quality(Indexes::get_quality(tip_index))\n offer_index, offer_dir, book_entry = state_map.cdir_first(tip_index)\n end\n end\n\n if !done\n # Read offer from db and process\n sle_offer = state_map.read(offer_index)\n if sle_offer\n # Direct info from nodestore offer\n owner_id = sle_offer.account_id(:account)\n taker_gets = sle_offer.amount(:taker_gets)\n taker_pays = sle_offer.amount(:taker_pays)\n\n # Owner / Output Calculation\n owner_funds = nil # how much of offer output the owner has\n first_owner_offer = true # owner_funds returned w/ first owner offer\n\n # issuer is offering it's own IOU, fully funded\n if output[:account] == owner_id\n owner_funds = taker_gets\n\n # all offers not ours are unfunded\n elsif global_freeze\n owner_funds.clear(output)\n\n else\n # if we have owner funds cached\n if balances[owner_id]\n owner_funds = balances[owner_id]\n first_owner_offer = false\n\n # did not find balance in cache\n else\n # lookup from nodestore\n owner_funds = account_holds(owner_id, output)\n\n # treat negative funds as zero\n owner_funds.clear if owner_funds < STAmount.zero\n end\n end\n\n offer = Hash[sle_offer.fields] # copy the offer fields to return\n taker_gets_funded = nil # how much offer owner will actually be able to fund\n owner_funds_limit = owner_funds # how much the offer owner has limited by the output transfer fee\n offer_rate = Rate.parity # offer base output transfer rate\n\n # Check if transfer fee applies,\n if rate != Rate.parity && # transfer fee\n # TODO: provide support for 'taker_id' rpc param:\n #taker_id != output[:account] && # not taking offers of own IOUs\n output[:account] != owner_id # offer owner not issuing own funds\n # Need to charge a transfer fee to offer owner.\n offer_rate = rate\n owner_funds_limit = owner_funds / offer_rate.to_amount\n end\n\n # Check if owner has enough funds to pay it all\n if owner_funds_limit >= taker_gets\n # Sufficient funds no shenanigans.\n taker_gets_funded = taker_gets\n\n else\n # Only set these fields, if not fully funded.\n taker_gets_funded = owner_funds_limit\n offer[:taker_gets_funded] = taker_gets_funded\n\n # the account that takes the offer will need to\n # pay the 'gets' amount actually funded times the dir_rate (quality)\n offer[:taker_pays_funded] = [taker_pays,\n taker_gets_funded *\n dir_rate].min\n\n # XXX: done in multiply operation in rippled\n offer[:taker_pays_funded].issue = taker_pays.issue\n end\n\n # Calculate how much owner will pay after this offer,\n # if no transfer fee, then the amount funded,\n # else the minimum of what the owner has or the\n # amount funded w/ transfer fee\n owner_pays = (Rate.parity == offer_rate) ?\n taker_gets_funded :\n [owner_funds,\n taker_gets_funded *\n offer_rate.to_amount].min\n\n # Update balance cache w/ new owner balance\n balances[owner_id] = owner_funds - owner_pays\n\n # Set additional params and store the offer\n\n # include all offers funded and unfunded\n offer[:quality] = dir_rate\n offer[:owner_funds] = owner_funds if first_owner_offer\n offers << offer\n\n else\n puts \"missing offer\"\n end\n\n # Retrieve next offer in offer_dir,\n # updating offer_index, offer_dir, book_entry appropriately\n offer_index, offer_dir, book_entry = *state_map.cdir_next(tip_index, offer_dir, book_entry)\n\n # if next offer not retrieved find next record after tip\n direct = true if !offer_index\n end\n end\n\n return offers\n end", "def get_bid_count(order)\n return order.order_price_histories.count\n end", "def bids\n @order_book['bids'] || []\n end", "def trade(ticker, bar)\n # this bar's price\n price = account.broker.exchange.quote(ticker, bar)\n\n # try to buy the given ticker if we aren't holding any shares\n if account.portfolio[ticker] == 0 # we have zero holdings of the given ticker\n last_hold_time = if @last_purchase[ticker][:buy_bar] && @last_purchase[ticker][:sell_bar]\n @last_purchase[ticker][:buy_bar] - @last_purchase[ticker][:sell_bar] # compute the last hold-time\n else\n 0\n end\n \n # Wait for a time interval equal to gamma * HT to pass (cool-down period) OR Price < P to buy more:\n # if we have never purchased the given stock/ticker,\n # OR the current price is less than the price at which we last purchased this stock,\n # OR (the time elapsed since our last sell-date is greater than or equal to the minimum cool-down duration\n # AND the time elapsed since our last sell-date is greater than or equal to gamma * the last hold-time duration)\n if(!@last_purchase.key?(ticker) || \n price < @last_purchase[ticker][:price] || \n ((t = (@last_purchase[ticker][:sell_bar] - bar)) >= @min_cooldown && \n t >= @gamma * last_hold_time))\n \n s = account.buy_amap(ticker, bar, amount_per_company)\n @last_purchase[ticker] = {price: price, buy_bar: bar}\n puts \"bought #{s} shares of #{ticker} on #{account.broker.exchange.bar(ticker, bar).date}\" if $DEBUG\n end\n else # try to sell our holdings of the given ticker\n # compute t, the return multiplier, given the interval between now and last purchase of the given stock (ticker)\n t = @fn_t.call(@last_purchase[ticker][:buy_bar] - bar)\n\n # compute alpha, given the value t, to determine the percentage gain multiplier\n alpha = @fn_alpha.call(t)\n\n puts \"t = #{t}\", \"alpha = #{alpha}\" if $DEBUG\n\n puts \"price of #{ticker} on #{account.broker.exchange.bar(ticker, bar).date} is #{price}\" if $DEBUG\n \n # if trading price is above (1+alpha(i))*P, sell\n if(price > (1.0 + alpha) * @last_purchase[ticker][:price])\n s = account.sell_all(ticker, bar)\n @last_purchase[ticker][:sell_bar] = bar\n puts \"sold #{s} shares of #{ticker} on #{account.broker.exchange.bar(ticker, bar).date}\" if $DEBUG\n end\n end\n \n puts \"account: #{account.to_s(bar)}\" if $DEBUG\n end", "def pricebook\n pricebook = Pricebook.find_by_name 'Standard Price Book'\n end", "def borrow_book(book)\n @books << book\n end", "def bid(currency_code, price, amount, counter_currency_code = \"jpy\", comment = \"bot\")\n return trade(currency_code, price, amount, \"bid\", counter_currency_code, comment)\n end", "def exchange(from)\n # 실시간으로 패치에서 정보를 받아옴\n @bank.update_rates\n @bank.exchange(100, from, 'KRW')\nend", "def test_ebook_purchases_send_to_bookshelf\n puts \"test_ebook_purchases_send_to_bookshelf\"\n\n # Verify target bookshelf installation is in nibley mode\n\n # Log test user in to bookshelf\n bookshelf_token = login_bookshelf_user(\n 'tests@deseretbook.com',\n 'test123'\n )\n \n # Ensure the book isn't already in the test user's bookshelf account.\n remove_book_from_bookshelf_account(bookshelf_token, digital_product_book_id)\n\n # do the purchase\n clear_cookies\n login\n\n add_items_to_cart([:digital])\n\n begin_checkout\n\n select_addresses(allow_skip: true)\n\n select_payment(payment_type: :credit_card)\n\n confirm_order\n verify_successful_order\n verify_order_state([:digital])\n\n # Verify the book is now in the test user's bookshelf account.\n # It may take a while to get through the queue so do a timed retry here.\n # This loop will wait a total of 30 seconds.\n retries = 10\n until present = bookshelf_account_contains_book?(bookshelf_token, digital_product_book_id)\n puts \"Book #{digital_product_book_id} present yet? #{present.inspect}\"\n unless present\n retries -= 1\n puts \"#{retries} retries left. Trying again in 3 seconds.\"\n sleep(3)\n end\n end\n assert(present, \"Book #{digital_product_book_id} not in bookshelf account\")\n end", "def book\n response = request(:book, {\n \"currentInvoiceHandle\" => handle.to_hash\n })\n\n # Find the created Invoice\n session.invoices.find(response[:number])\n end", "def getbook\n \n end", "def conv_exchange_rate\n currency_exchange.exchange_rate\n end", "def buy_bot(percent_increase = 0.05, chunk = 0.006, prepump_buffer = 0.5)\n market_name = @market_name\n low_24_hr, last_price, ask_price, volume = get_market_summary(market_name)\n total_spent = 0.0\n p [low_24_hr, last_price, ask_price, volume]\n if volume < 100 and last_price < (1.0 + prepump_buffer) * low_24_hr #last_price is smaller than 50% increase since yerterday\n puts \"Coin is not prepumped\".blue\n order = buy_chunk(last_price, market_name, percent_increase, chunk)\n p [order, \"Units Bought : #{@units_bought}\"]\n end\nend", "def rebook item, book\n if (item.price > 0)\n # item represents new aggr_order with price\n item.order_book = book unless item.order_book\n book.add item # добавляем в стакан\n else\n # item clears previous aggr_order for given price\n item.order_book = nil\n end\n end", "def calc_profit_with_acc (order_books:[], accounts:{})\n return 0 if order_books.nil? or order_books.empty? or accounts.nil? or accounts.empty?\n\n obs = order_books\n acc = accounts\n\n #puts obs\n #puts acc\n\n bids = obs[0][\"bids\"].clone\n asks = obs[1][\"asks\"].clone\n if bids.empty? # || asks.empty\n return nil\n end\n\n base = obs[0][\"base\"]\n quote = obs[0][\"quote\"]\n max_fill_bid_volume = acc[obs[0][\"source\"]][quote] \n max_fill_ask_amount = acc[obs[1][\"source\"]][base]\n\n acfg = $MY_ACCOUNT_CONFIG\n\n #TODO do something if quote != bts\n #TODO fee calculation model needed\n #if obs[0][\"source\"] == \"chain\" and quote == \"bts\"\n # max_fill_bid_volume -= acfg[\"bts\"][\"min_balance\"]\n #end\n #if obs[\"buy_from\"] == \"chain\" and quote == \"bts\"\n # max_fill_ask_volume -= acfg[\"bts\"][\"min_balance\"]\n #end\n # Keep some balance\n max_fill_bid_volume -= acfg[quote][\"min_balance\"]\n max_fill_ask_amount -= acfg[base][\"min_balance\"]\n\n # adjust bid/ask price to make sure our order execute\n my_bid_price_adjust = 0\n my_ask_price_adjust = 0\n if obs[0][\"source\"] == \"chain\"\n my_ask_price_adjust = 0.000001\n end\n if obs[1][\"source\"] == \"chain\"\n my_bid_price_adjust = 0.000001\n end\n\n # in btc38, when we buy volume, we get (volume*0.999)\n my_bid_volume_adjust = 1\n if obs[1][\"source\"] == \"btc38\"\n my_bid_volume_adjust = 0.999\n end\n\n # in btc38, when we sell volume, we get (volume*price*0.999)\n my_ask_amount_adjust = 1\n if obs[0][\"source\"] == \"btc38\"\n my_ask_amount_adjust = 0.999\n end\n\n min_margin = $MY_TRADE_CONFIG[\"min_profit_margin\"]\n\n profit = 0\n volume = 0 #of quote\n amount = 0 #of base\n my_ask_volume = 0 #of quote\n my_bid_volume = 0 #of quote\n my_ask_amount = 0 #of base\n my_bid_amount = 0 #of base\n bid_index = 0\n ask_index = 0\n my_asks = []\n my_bids = []\n while bid_index < bids.size and ask_index < asks.size \n bid_price = bids[bid_index][\"price\"].to_f - my_ask_price_adjust\n ask_price = asks[ask_index][\"price\"].to_f + my_bid_price_adjust\n break if bid_price <= ask_price * (1+min_margin)\n\n bid_volume = bids[bid_index][\"volume\"].to_f # how many others want to buy\n ask_volume = asks[ask_index][\"volume\"].to_f # how many others want to sell\n\n my_fill_bid_volume = bid_volume # how many we will give out if fill the bid order\n my_fill_ask_volume = ask_volume * my_bid_volume_adjust # how many we will get if fill the ask order\n my_max_fill_bid_volume = max_fill_bid_volume - my_ask_volume # how many we can sell\n my_max_fill_ask_volume = (max_fill_ask_amount - my_bid_amount) / ask_price * my_bid_volume_adjust\n # how many we will get if we can buy all at current price\n\n # how many volume we will ask\n my_min_ask_volume = [my_fill_bid_volume, my_fill_ask_volume, my_max_fill_bid_volume, my_max_fill_ask_volume].each.min\n # how many volume we will bid. Remark: avoid precision loss\n my_min_bid_volume = 0\n if my_min_ask_volume == my_fill_ask_volume\n my_min_bid_volume = ask_volume\n elsif my_min_ask_volume == my_max_fill_ask_volume\n my_min_bid_volume = (max_fill_ask_amount - my_bid_amount) / ask_price\n else\n my_min_bid_volume = my_min_ask_volume / my_bid_volume_adjust\n end\n\n # calculate ask/bid volume and amount\n my_ask_volume += my_min_ask_volume\n my_bid_volume += my_min_bid_volume\n my_ask_amount += my_min_ask_volume * bid_price * my_ask_amount_adjust\n my_bid_amount += my_min_bid_volume * ask_price\n\n # build my orders\n my_ask_item = {\"type\"=>\"ask\",\"price\"=>bid_price,\"volume\"=>my_min_ask_volume}\n my_bid_item = {\"type\"=>\"bid\",\"price\"=>ask_price,\"volume\"=>my_min_bid_volume}\n my_asks.push my_ask_item\n my_bids.push my_bid_item\n\n # break if no more fund\n break if my_min_ask_volume < my_fill_bid_volume and my_min_ask_volume < my_fill_ask_volume\n\n # if still have fund\n if my_fill_ask_volume < my_fill_bid_volume\n asks[ask_index][\"volume\"] = ask_volume - my_min_bid_volume\n bid_index += 1\n elsif my_fill_ask_volume == my_fill_bid_volume\n ask_index += 1\n bid_index += 1\n else #if my_fill_ask_volume > my_fill_bid_volume\n ask_index += 1\n bids[bid_index][\"volume\"] = bid_volume - my_min_ask_volume\n end\n\n end #while\n\n # profit\n profit = my_ask_amount - my_bid_amount\n\n # hard code here to deal with min_margin limit. TODO optimize\n return nil if my_ask_volume == 0\n\n # hard code here to avoid too small orders, good practice not only for btc38. TODO optimize. \n return nil if my_ask_amount < 1.1\n\n #combine orders with same price\n # combine ask orders\n my_new_asks = []\n my_new_bids = []\n last_price = 0\n last_volume = 0\n my_asks.each { |o|\n if o[\"price\"] == last_price\n last_volume += o[\"volume\"]\n else\n if last_volume > 0\n last_amount = last_price * last_volume\n # hard code here to avoid btc38 one CNY limit. TODO optimize. \n # check every order \n if last_amount < 1.1 and obs[0][\"source\"] == \"btc38\"\n # if amount too small, add volume of this order to next order. do nothing here\n else\n my_ask_item = {\"type\"=>\"ask\",\"price\"=>last_price,\"volume\"=>last_volume}\n my_new_asks.push my_ask_item\n last_volume = 0\n end\n end\n last_price = o[\"price\"]\n last_volume += o[\"volume\"]\n end\n }\n ignore_ask_volume = 0\n if last_volume > 0\n last_amount = last_price * last_volume\n # hard code here to avoid btc38 one CNY limit. TODO optimize. \n # check every order \n if last_amount < 1.1 and obs[0][\"source\"] == \"btc38\"\n # if amount too small, and no more order, ignore this order\n ignore_ask_volume = last_volume\n else\n my_ask_item = {\"type\"=>\"ask\",\"price\"=>last_price,\"volume\"=>last_volume}\n my_new_asks.push my_ask_item\n end\n end\n # combine bid orders\n last_price = 0\n last_volume = 0\n my_bid_volume_combine_sum = 0\n my_bid_volume_combine_max = my_bid_volume - ignore_ask_volume / my_bid_volume_adjust\n my_bids.each { |o|\n bid_end = false\n if my_bid_volume_combine_sum + o[\"volume\"] >= my_bid_volume_combine_max\n bid_end = true\n o[\"volume\"] = my_bid_volume_combine_max - my_bid_volume_combine_sum\n end\n my_bid_volume_combine_sum += o[\"volume\"]\n if o[\"price\"] == last_price\n last_volume += o[\"volume\"]\n else\n if last_volume > 0\n last_amount = last_price * last_volume\n # hard code here to avoid btc38 one CNY limit. TODO optimize. \n # check every order \n if last_amount < 1.1 and obs[1][\"source\"] == \"btc38\"\n # if amount too small, add volume of this order to next order. do nothing here\n else\n my_bid_item = {\"type\"=>\"bid\",\"price\"=>last_price,\"volume\"=>last_volume}\n my_new_bids.push my_bid_item\n last_volume = 0\n end\n end\n last_price = o[\"price\"]\n last_volume += o[\"volume\"]\n end\n break if bid_end\n }\n ignore_bid_volume = 0\n if last_volume > 0\n last_amount = last_price * last_volume\n # hard code here to avoid btc38 one CNY limit. TODO optimize. \n # check every order \n if last_amount < 1.1 and obs[1][\"source\"] == \"btc38\"\n # if amount too small, and no more order, ignore this order\n ignore_bid_volume = last_volume\n else\n my_bid_item = {\"type\"=>\"bid\",\"price\"=>last_price,\"volume\"=>last_volume}\n my_new_bids.push my_bid_item\n end\n end\n # adjust ask orders again if ignored at least one bid order\n if ignore_bid_volume > 0\n ignore_ask_volume = ignore_bid_volume * my_bid_volume_adjust\n ask_volume_to_ignore = ignore_ask_volume \n for i in ((my_new_asks.length-1)..0)\n o = my_new_asks[i]\n if o[\"volume\"] > ask_volume_to_ignore\n o[\"volume\"] -= ask_volume_to_ignore\n break\n else\n ask_volume_to_ignore -= o[\"volume\"]\n my_new_asks.delete_at i\n end\n break if ask_volume_to_ignore <= 0\n end\n end\n\n return {\n \"volume\"=>(\"%.6f\" % (my_ask_volume - ignore_ask_volume) ),\n \"amount\"=>(\"%.6f\" % my_bid_amount), # TODO decuct ignored amount\n \"profit\"=>(\"%.6f\" % profit), # TODO deduct ignored amount\n \"buy_from\"=>obs[1][\"source\"],\n \"sell_to\"=>obs[0][\"source\"],\n \"orders\"=>[{\n \"source\"=>obs[1][\"source\"],\n \"base\"=>obs[1][\"base\"],\n \"quote\"=>obs[1][\"quote\"],\n \"bids\"=>my_new_bids,\n \"asks\"=>[]\n }, {\n \"source\"=>obs[0][\"source\"],\n \"base\"=>obs[0][\"base\"],\n \"quote\"=>obs[0][\"quote\"],\n \"bids\"=>[],\n \"asks\"=>my_new_asks\n }]\n }\n\nend", "def brokers\n {\n drive_wealth: 'DriveWealth'\n }\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get active positions return [Array]
def active_positions authenticated_post("auth/positions").body end
[ "def active_positions\n authenticated_post(\"auth/r/positions\").body\n end", "def get_available_positions\n @state.each.with_index(1).select { |mark, index| mark.nil? }.map { |mark, index| index }\n end", "def joined_positions()\n return [] unless defined?(@joined_positions)\n return @joined_positions\n end", "def get_all_positions\n\n positions = []\n POSITION_NUMBERS.each do |number|\n POSITION_LETTERS.each do |letter|\n positions << eval(\":#{letter}#{number}\")\n end\n end\n positions -= POSITIONS_NOT_ON_BOARD\n\n return positions\n\n end", "def consumed_positions\n return @ring_positions.keys\n end", "def sorted_positions\n self.positions.sort_by { |pos| pos.is_current? ? 0 : 1 }\n end", "def active\n c = self.current\n a = []\n while c\n a << c\n c = c[:outer_lspace]\n end\n a\n end", "def pos_to_a\r\n [ pos.x, pos.y ]\r\n end", "def get_position_list\n\n end", "def positions_of_agents\n positions = []\n @figures.each {|f| positions << f.position}\n positions.shift\n positions\n end", "def available_positions\n (0...cells.size).select{|i| cells[i].nil? }.map{|i| index2pos(i)}\n end", "def pos\n return [@x, @y]\n end", "def occupied_positions\n spaces.map{ |s| s.position unless s.pieces.empty? }.compact\n end", "def positions(passes) = passes.map { find_position(_1) }", "def collect_positions(tokens)\n\t\tboxes.select{|box| tokens.include? box.state.to_s }.map {|box| box.position}\n\tend", "def all_positions side=:white\n side==:white ? POSITIONS.flatten : POSITIONS.dup.reverse.map(&:reverse!)\n end", "def positions(value)\n result = []\n @mem.each do |y, row|\n row.each do |x, col|\n result << [x, y] if get(x, y) == value\n end\n end\n result\n end", "def positions\n Easybill::Api::Positions\n end", "def all_players_by_position\n all_players_by_position_hash = Hash.new([])\n\n all_positions.each do |position|\n all_players_by_position_hash[position] = active_players_by_position(position)\n end\n\n all_players_by_position_hash\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
array = [] if array.size == 1 return array[0] elsif array.size == 2 return array.join(" and ") else return array[0..2].join(", ") + ", and " + array[1] end end
def oxford_comma(array) case array.length when 1 "#{array[0]}" when 2 array[0..1].join(" and ") else array[0...-1].join(", ") << ", and #{array[-1]}" end end
[ "def format_comma_and(array)\n return array.join if array.length <= 1\n array[0..-2].join(', ') + \" and #{array[-1]}\"\nend", "def oxford_comma(array)\n if array.length == 1\n array.join\n elsif array.length == 2\n array.join(\" and \")\n else\n tempvar = array.pop\n returnvar = array.join(\", \") + \", and \" + tempvar\n returnvar\n end\nend", "def oxford_comma(array)\n if array.size <= 1\n array.join \n elsif array.size == 2\n array.join(\" and \")\n else\n array[-1] = \"and #{array[-1]}\"\n array.join(\", \")\n end\nend", "def format_comma_and(array)\n case array.size\n when 0 then ''\n when 1 then array[0]\n when 2 then \"#{array[0]} and #{array[1]}\"\n else \"#{array[0]}, #{format_comma_and(array[1..-1])}\"\n end\nend", "def oxford_comma(array)\n case array.size\n when 0\n \"\"\n when 1\n array.first\n when 2\n array.join(' and ')\n else\n [array[0..-2].join(', '), array.last].join(', and ')\n end\nend", "def convert_array_to_string(an_array)\n array_len = an_array.length\n combined_string = \"\"\n\n if array_len == 2\n combined_string << an_array[0] << \" and \" << an_array[1]\n return combined_string\n end\n\n an_array.each_with_index do |string, i|\n if i == 0\n combined_string << string\n elsif i == array_len - 1\n combined_string << \", and \" << string\n else\n combined_string << \", \" << string\n end\n end\n\n return combined_string\nend", "def commify_series(arr)\n return '' if not arr\n sepchar = arr.find { |p| p =~ /,/ } ? '; ' : ', '\n case arr.size\n when 0 then ''\n when 1 then arr[0]\n when 2 then arr.join(' and ')\n else arr[0..-2].join(sepchar) + sepchar + 'and ' + arr[-1]\n end\nend", "def join_with_and(list, seperator = ', ')\n return list.first if list.count == 1\n result = ''\n list.each do |item|\n result << item\n next if item == list.last\n result << if item == list[-2]\n ' and '\n else\n seperator\n end\n end\n result\n end", "def join_with_and list, seperator=\", \"\n return list.first if list.count==1\n result = \"\"\n list.each do |item|\n result << item\n unless item==list.last\n if item==list[-2]\n result << \" and \"\n else\n result << seperator\n end\n end\n end\n result\n end", "def join_artists(array)\n return \"\" if array.nil? or array.size<1\n return array.last if array.size==1\n\n rest = array.slice(0,array.size-1).join(', ')\n rest += \" and \" if (rest.size>0)\n return rest+array.last\n end", "def join_with_and\n x = self.pop\n return x if self.size == 0\n \"#{self.join(\", \")} and #{x}\"\n end", "def joinor(arr, delimiter = ', ', conjunction = 'or')\n return '' if arr.empty?\n arr.map!(&:to_s)\n return arr[0] if arr.size == 1\n str = arr.size > 2 ? arr[0..-2].join(delimiter) + delimiter : arr[0] + ' '\n # str = arr[0..-2].join(delimiter)\n # str << (arr.size > 2 ? delimiter : ' ')\n str << conjunction + ' ' + arr[-1]\nend", "def to_sentence(items)\n if items.size <= 2\n items.join(items.size == 2 ? \" and \" : \"\")\n else\n [items[0..-2].join(\", \"), items.last].join(\", and \")\n end\n end", "def to_sentence(items)\n if items.size <= 2\n items.join(items.size == 2 ? ' and ' : '')\n else\n [items[0..-2].join(\", \"), items.last].join(\", and \")\n end\n end", "def joinor(arr, delimiter = ', ', conjunction = 'or')\n array_of_strings = []\n if arr.size == 1\n arr[0].to_s\n elsif arr.size == 2\n arr.join(\" #{conjunction} \")\n else\n array_of_strings << arr[0..-3].join(\"#{delimiter}\")\n array_of_strings << arr[-2..-1].join(\"#{delimiter}#{conjunction} \")\n array_of_strings.join(\"#{delimiter}\")\n end\nend", "def to_string_with_commas(array, limit = nil) \n return \"\" if array.empty? \n return array[0] if array.length == 1\n \n if limit && limit > 0 && limit < array.length \n leftovers = array.length - limit \n return array[0..(limit-1)].join(', ') + ' and ' + leftovers.to_s + ' more'\n end \n\n\n array[0..-2].join(', ') + ' and ' + array[-1]\nend", "def english_list(array:, conjunction:)\n return '' if array.empty?\n return array.first if array.length == 1\n\n \"#{array[0..-2].join(', ')} #{conjunction} #{array.last}\"\n end", "def format_words(words)\n return \"\" if words.empty?\n return words.join if words.size <= 1\n words = words.join(\" \").split()\n ending = words.slice!(-2, 2).join(' and ')\n words.push(ending).join(', ')\nend", "def human_list(list)\n case list.length\n when 0\n \"\"\n when 1\n list[0]\n when 2\n \"#{list[0]} and #{list[1]}\"\n else\n \"#{list[0...-1].join(', ')}, and #{list[-1]}\"\n end\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns all nodes which the FE will identify as a metrics embed placeholder element Removes any nodes beyond the first 100
def nodes strong_memoize(:nodes) do nodes = doc.xpath(XPATH) nodes.drop(EMBED_LIMIT).each(&:remove) nodes end end
[ "def all_nodes_used_by_barclamp(role)\n role.elements.values.flatten.compact.uniq\n end", "def all_nodes\n get(\"/production/facts_search/search?facts.processorcount.ge=0\",false)\n end", "def free_nodes\n nodes.select(&:is_free?)\n end", "def generate_blank_nodes(amount)\n response = @resource.request_http(:post, path(:blankNodes),\n :parameters => { :amount => amount },\n :expected_status_code => 200)\n response.chomp.split(\"\\n\").map {|i| i.gsub(/^_:/, '') }\n end", "def test_get_node_range_no_features\n nodes = @container.get_nodes('1',12,27,0)\n assert_equal(4, nodes.length)\n assert_equal([11,15,0], [nodes[0].start, nodes[0].stop, nodes[0].count])\n assert_equal([16,20,0], [nodes[1].start, nodes[1].stop, nodes[1].count])\n assert_equal([21,25,1], [nodes[2].start, nodes[2].stop, nodes[2].count])\n assert_equal([26,28,0], [nodes[3].start, nodes[3].stop, nodes[3].count])\n end", "def unique_embeds\n embeds_by_node.values.uniq\n end", "def all_nodes\n nodes = []\n visit_nodes do |node|\n nodes.push node\n end\n nodes\n end", "def free_nodes\n nodes.select{ |n| n.free? }\n end", "def singleton_nodes\n all_node_ids = Node_Query.new(analysis_window: aw).run.first[:objects].collect{|n| n.id}.uniq\n all_nodes_in_ways = Way_Query.new(analysis_window: aw).run.first[:objects].collect{|w| w.nodes}.flatten.uniq\n # all_nodes_in_rels = Relation_Query.new(analysis_window: aw).run.first[:objects].collect{|r| r.nodes}.flatten.uniq\n nodes_not_in_ways_or_rels = (all_node_ids - all_nodes_in_ways).length\n puts \"Total Nodes: #{all_node_ids.length}, Nodes not in ways or relations: #{nodes_not_in_ways_or_rels}\"\n puts \"Percentage: #{nodes_not_in_ways_or_rels.to_f / all_node_ids.length.to_f}\"\n end", "def enabled_nodes\n @raw_data[\"properties\"][\"basic\"][\"nodes\"].reject(){|x| draining_nodes.include? x } \n end", "def nodesUsedByTest(name = \"iperfV\", jobId = 17476)\n headers[\"content-type\"]=\"text/html\";\n @node_data = []\n res = Result.find_by_name_and_jobid(name,jobId)\n res.nodes.each do |n| \n # Push the hash of values into the array\n @node_data<<{:node_name=>n.name,:node_id=>n.id}\n end\n\n end", "def node_ids; end", "def relevant_nodes\n nodeset = query_root_node(\"rdf:Description\", @@NAMESPACES)\n @items = []\n if !nodeset.nil?\n nodeset.each do |item|\n node_obj = SemanticCrawler::LinkedGeoData::RelevantNode.new(item)\n @items << node_obj\n end\n end\n @items\n end", "def item_nodes\n # different sorts of results have items in td.briefCitRow or tr.briefCitRow\n node_set = document.css(\".briefCitRow\")\n\n if configuration.max_results\n node_set = node_set.slice(0, configuration.max_results.to_i)\n end\n\n return node_set\n end", "def nodes # :nodoc:\n return @nodes if defined?(@nodes) \n node_ids = (1..Configuration.numbers['total_nodes'])\n @nodes = node_ids.map do |id| \n {\n id: id,\n host: \"node_#{id}_#{Worker::VERSION}\"\n }.to_struct\n end\n end", "def get_nodes\n @known_nodes\n end", "def get_registered_nodes\n update_nodes\n @registered_nodes\n end", "def get_nodes_undelete\n nds.collect do |n|\n node = Node.find(n)\n [node.lon, node.lat, n, node.version, node.tags_as_hash, node.visible]\n end\n end", "def nodes\n TestLab::Node.all\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Maps a node to key properties of an embed. Memoized so we only need to run the regex to get the project full path from the url once per node.
def embeds_by_node strong_memoize(:embeds_by_node) do nodes.each_with_object({}) do |node, embeds| embed = Embed.new url = node.attribute('data-dashboard-url').to_s permissions_by_route.each do |route| set_path_and_permission(embed, url, route.regex, route.permission) unless embed.permission end embeds[node] = embed if embed.permission end end end
[ "def key_to_node; end", "def prepare_key(node)\n node = node.name if node.is_a? Deployment::Node\n node.to_s.to_sym\n end", "def get_key_to_pmid(entry_node)\n hash = {}\n entry_node.xpath('./evidence').each do |node| \n pubmed_id = \n if att = node['attribute']\n if md = att.match(/^PubMed=(.*)/)\n Integer(md[1])\n end\n end\n evidence_key = node['key']\n hash[evidence_key] = pubmed_id\n end\n hash\nend", "def metadata_of(node, property = nil)\n if property.nil?\n @metadata[node] || {}\n else\n prefetch_metadata_of([node], property) unless @metadata.key?(node) && @metadata[node].key?(property)\n @metadata[node][property]\n end\n end", "def regenerate_node_lookup\n @nodes_hash = {}\n\n nodes.each do |node|\n @nodes_hash[node.key] = node\n end\n end", "def parse_embedded_properties(node,object)\n @embedded_properties.each do |property|\n unless parser = Object.full_const_get(property.class_name) rescue nil\n raise NokoParserError, \n \"Class #{property.class_name} not found for embed :#{property.name}\"\n end\n if match = node.xpath(property.xpath).first\n result = parser.parse(match.to_xml)\n result = result.first if property.single\n object.send(\"#{property.name}=\", result)\n end\n end\n end", "def stamp(node, uri, key)\n node.xpath(\"//*[@id]\").each { |node| node.remove_attribute \"id\" }\n node.attributes.each_pair { |name,_| node.remove_attribute name }\n node['data-embed-uri'] = uri\n node['data-embed-src'] = key\n end", "def generate_model_key(namespace, node_key)\n \"#{node_key}\"\n #\"#{namespace}::#{node_key}\"\n end", "def cache_node(node)\n cs = @c_start\n if cs.next_node != node\n remove_from(node,false,true)\n node2 = cs.next_node\n GeoTree.join_nodes(cs,node)\n GeoTree.join_nodes(node,node2)\n end\n @cache_dict[node.name] = node\n end", "def gen_node_key(num)\n \"node#{num}\".to_sym\nend", "def canonicalize(key, node)\n treecache.canonicalize(key, node)\n end", "def link node, to_path, key\n get node_name(node) + action(:link, :key => key, :toPath => to_path)\n end", "def js_node_key(node)\n node.id.to_s\n end", "def source_nodename_map\n map = {}\n @prometheus.query('max_over_time(node_uname_info[1d])').each do |result|\n source = result['metric']['instance']\n nodename = result['metric']['nodename'].split('.', 2)[0]\n log.info(\"[node_exporter] instance: '#{source}', nodename: '#{nodename}'\")\n map[source] = nodename\n end\n log.warn('Unable to query the node_exporter intances from Prometheus') \\\n if map.empty?\n map\n end", "def generate_key\n if self.key.blank? && !(self.node_id.blank? || self.timestamp.blank?)\n self.key = \"#{node_id}-#{timestamp.strftime('%Y%m%d%H%M%S')}\"\n end\n end", "def extract_hash(node); end", "def init_nodemap\n # map of key1 => node, key2 => node, ...\n @keynum = 1\n text_nodes = @doc.search(text_nodes_xpath, tm: TM_NS)\n text_nodes.each { |node| add_node(node) }\n end", "def map_info(node)\n h = {}\n for k,v in self.class.config.params\n h[k] = param(k)\n end\n h.update(node.node_info[:sitemap_info])\n return h\n end", "def node(key)\n node_hash[key]\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Attempts to determine the path and permission attributes of a url based on expected dashboard url formats and sets the attributes on an Embed object
def set_path_and_permission(embed, url, regex, permission) return unless path = regex.match(url) do |m| "#{$~[:namespace]}/#{$~[:project]}" end embed.project_path = path embed.permission = permission end
[ "def parse_url\n set_url_type_and_command\n generate_field\n set_domain\n end", "def set_embed\n if self.category == 'youtube'\n code = self.link.split('=')[1]\n self.embed = \"<iframe width='700' height='400' src='http://www.youtube.com/embed/#{code}' frameborder='0' allowfullscreen></iframe>\"\n elsif self.category == 'slideshare'\n url = 'http://www.slideshare.net/api/oembed/2?url=' + link + '&format=xml&maxwidth=700&maxheight=400'\n slideshare_iframe = open_xml(url).xpath(\"//html\").children.first.text.split('<div').first\n code = slideshare_iframe.split('/embed_code/')[1].split('\"').first\n self.embed = '<iframe src=\"http://www.slideshare.net/slideshow/embed_code/' + code + '\" width=\"700\" height=\"400\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\" style=\"border:1px solid #CCC;border-width:1px 1px 0;margin-bottom:5px\" allowfullscreen webkitallowfullscreen mozallowfullscreen> </iframe>'\n end\n end", "def metadata_url_pattern(action, str) \n url = compact_string(str);\n if (action == :create) then \n self[:create_url_pattern] = url;\n elsif (action == :update) then \n self[:update_url_pattern] = url;\n elsif (action == :show) then\n self[:show_url_pattern] = url;\n else \n raise \"unknow action #{action}\"; \n end \n end", "def saveurl\n url_str = link_params[:url]\n url_str.insert(0, 'http://') if url_str.match('^http').nil?\n \n annotations = get_annotations(url_str)\n \n url = Url.find_by_url(url_str)\n if url.nil?\n url = Url.new({:url => link_params[:url], :icon => annotations[:icon]})\n if !url.save\n render :status => 404\n end\n else\n Url.update(url.id, :icon => annotations[:icon]) if url.icon.nil? && annotations[:icon] != ''\n end\n\n @bookmark = Bookmark.new({:url => url, :title => annotations[:title], :description => annotations[:desc], :user => current_user})\n\n @share_with_group = Group.find(params[:id]) if params[:id]\n\n annotations[:keywords].each do |tag|\n if Tag.where(:tagname => tag.strip.gsub(' ', '-').downcase).size == 0\n @tag = Tag.new\n @tag.tagname = tag.strip.gsub(' ','-').downcase\n @bookmark.tags << @tag\n else\n @bookmark.tags << Tag.where(:tagname => tag.strip.gsub(' ', '-').downcase).first\n end\n end\n\n respond_to do |format|\n format.html { render action: 'bookmark_form' }\n format.js\n end\n end", "def embed_url\n video_url = params[:video_url]\n video = VideoInfo.get(video_url)\n if(video)\n embed_url = video.embed_url\n vid = Video.new(:embed_url=> embed_url)\n # check that the video is valid\n render :json => vid.as_json(:methods => :embed_code)\n else\n render :json => false\n end\n end", "def embed\n if youtube_url then youtube_embed\n # Uploads don't get put in the embed field on Kitsu\n elsif upload_url then nil\n elsif image then image_embed\n elsif link then link\n end\n end", "def ensure_uid_and_url\n unless self.uid && self.url\n self.uid = \"/activities/#{self.id}\"\n self.url = \"/activities/#{self.id}\"\n end\n end", "def convert_to_embedded_url\n youtube_id = youtube_video_id_from_link(url)\n self.url = youtube_embedded_url(youtube_id) if youtube_id\n end", "def link\n return unless @data['link']\n link = @data['link']\n # Aozora has embed data, we just need to restructure it a bit\n @link ||= {\n kind: link['type'],\n title: link['title'],\n description: link['description'],\n url: link['url'],\n site_name: link['siteName'],\n image: link['images'].first\n }\n end", "def embeds_by_node\n strong_memoize(:embeds_by_node) do\n nodes.each_with_object({}) do |node, embeds|\n embed = Embed.new\n url = node.attribute('data-dashboard-url').to_s\n\n permissions_by_route.each do |route|\n set_path_and_permission(embed, url, route.regex, route.permission) unless embed.permission\n end\n\n embeds[node] = embed if embed.permission\n end\n end\n end", "def embedded_link_available?(url_data)\n merged_params = merged_embedded(url_data)\n\n # test if embedded flag is in path or url parameter\n embedded_link = url_for(merged_params)\n embedded_link_params = Rails.application.routes.recognize_path(embedded_link)\n embedded_link_params[:embedded].present?\n end", "def image_url_embedly(link_url)\n response = http_get \"http://api.embed.ly/1/oembed?url=#{link_url}\"\n response['url'] if response\n end", "def add_href\n return if attributes.key?(\"href\")\n return unless attributes.key?(\"id\")\n attributes[\"href\"] = client.connection.api_path(\"#{collection.name}/#{attributes['id']}\")\n end", "def url_mobile_edit\n\t\t\t@data[\"content_urls\"][\"mobile\"][\"edit\"]\n\t\tend", "def embeddable_url\n\t\turl.sub('watch?v=', 'embed/')\n\tend", "def alter_url(url)\n facebook_link = Domainatrix.parse(url)\n if !facebook_link.nil? and facebook_link.path != \"\" and facebook_link.path.size != 1\n if facebook_link.path.include?(\"pages\")\n facebook_link.path.split(\"/\").each do |f| \n # Detect a facebook id numbder \n if f.to_i > 0 \n url = \"http://graph.facebook.com/\" + f.to_s\n end\n end\n else\n url = \"http://graph.facebook.com#{facebook_link.path}\"\n end\n else \n url = nil\n end \n url\n end", "def url=( url, type = :url)\n super( url )\n self.thumbnail = thumbshot( url )\n annotate( type => url )\n end", "def assign_social_site name, url\n User.social_site_attributes_keys.each do |key|\n if key.to_s[/#{name}/i]\n self[key] = url\n end\n end\n end", "def add_content_params\n begin\n url = self.url\n content = OpenGraph.fetch(url)\n content_params=nil \n if !content[\"video\"].blank? \n case content[\"site_name\"].downcase\n when \"soundcloud\"\n # change auto play to false\n content[\"video\"] = content[\"video\"].gsub(\"auto_play=true\",\"auto_play=false\")\n content[\"video\"] = content[\"video\"] + \"&default_width=75&default_height=90\"\n when \"youtube\"\n # do youtube stuff\n end\n # replace query string with ?wmode=opaque for all embedded content\n video_query = content[\"video\"].match(/[?].*/).to_s rescue \"\" # get query string\n vid_url_old_query = video_query.gsub(\"?\",\"\")\n vid_url_with_new_query=content[\"video\"].gsub(/[?].*/,\"?wmode=opaque&rel=0&\") # add our own params\n # rel=0 means no related vids at the end\n # opaque allows things to show ontop of embedded flash content\n video_url = vid_url_with_new_query+vid_url_old_query # replace video url with new query string + old query string\n # setup content object params from the opengraph info\n content_params={\n height: \"90\",\n width: \"75\",\n video_url: video_url,\n url: content[\"url\"],\n image: content[\"image\"],\n description: content[\"description\"],\n mime_type: content[\"video:type\"],\n title: content[\"title\"],\n site_name: content[\"site_name\"]\n }\n end # end if video blank and parsing\n #return content_params\n # trying to avoid recursion...\n #self.update_attributes(content_params)\n self.assign_attributes(content_params)\n puts.self.to_yaml\n rescue\n puts \"Error parsing!\"\n @song = nil\n end\n \n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }